diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..6fa15bb --- /dev/null +++ b/build.rs @@ -0,0 +1,8 @@ +// Nacre's patched libgstmse-1.0.so.0 (tools/gst-mse.sh) must win over the system copy: the binary's RUNPATH +// looks next to it first (`lib/`, the release layout), then in a dev tree's `target/gst-mse/lib`. +fn main() { + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("linux") { + println!("cargo:rustc-link-arg-bins=-Wl,-rpath,$ORIGIN/lib:$ORIGIN/../gst-mse/lib"); + } + println!("cargo:rerun-if-changed=build.rs"); +} diff --git a/src/main.rs b/src/main.rs index 6aca98d..9cbef01 100644 --- a/src/main.rs +++ b/src/main.rs @@ -99,6 +99,34 @@ fn choose_gl(settings: &store::settings::Settings) { } } +/// Points GStreamer at Nacre's patched MSE plugin (`msesrc`, docs/engine/gst-mse-patches.md) ahead of the +/// system one. The matching library, libgstmse-1.0.so.0, is found through the binary's RUNPATH (build.rs). +/// Release layout: `/lib/gstreamer-1.0`; a dev build: `target/gst-mse/gstreamer-1.0` (tools/gst-mse.sh). +fn use_own_gst_mse() { + let Some(dir) = std::env::current_exe().ok().and_then(|exe| exe.parent().map(|dir| dir.to_path_buf())) else { + return; + }; + let Some(plugins) = [dir.join("lib/gstreamer-1.0"), dir.join("../gst-mse/gstreamer-1.0")] + .into_iter() + .find(|plugins| plugins.join(if cfg!(windows) { "gstmse.dll" } else { "libgstmse.so" }).is_file()) + else { + eprintln!("nacre: gst-mse: no patched mse plugin next to the binary, using the system one"); + return; + }; + let mut paths = vec![plugins.clone()]; + paths.extend(std::env::var_os("GST_PLUGIN_PATH").iter().flat_map(std::env::split_paths)); + if let Ok(value) = std::env::join_paths(paths) { + // SAFETY: called on the main thread before any other thread exists. + unsafe { std::env::set_var("GST_PLUGIN_PATH", value) }; + } + let library = std::fs::read_to_string("/proc/self/maps") + .unwrap_or_default() + .lines() + .find_map(|line| line.split_whitespace().nth(5).filter(|path| path.contains("libgstmse-1.0")).map(str::to_owned)) + .unwrap_or_else(|| "not loaded".into()); + eprintln!("nacre: gst-mse: plugin {}, library {library}", plugins.display()); +} + fn main() { let launch = match parse_args() { Ok(launch) => launch, @@ -113,6 +141,7 @@ fn main() { return; } choose_gl(&store::settings::Settings::load(&paths.settings())); + use_own_gst_mse(); let event_loop = match EventLoop::::with_user_event().build() { Ok(event_loop) => event_loop, Err(error) => { diff --git a/tests/gst-mse/data/audio-aac.mp4 b/tests/gst-mse/data/audio-aac.mp4 new file mode 100644 index 0000000..cf6054b Binary files /dev/null and b/tests/gst-mse/data/audio-aac.mp4 differ diff --git a/tests/gst-mse/data/video-vp9.webm b/tests/gst-mse/data/video-vp9.webm new file mode 100644 index 0000000..6e75622 Binary files /dev/null and b/tests/gst-mse/data/video-vp9.webm differ diff --git a/tests/gst-mse/mse-fixes.c b/tests/gst-mse/mse-fixes.c new file mode 100644 index 0000000..fee824a --- /dev/null +++ b/tests/gst-mse/mse-fixes.c @@ -0,0 +1,333 @@ +/* Regression tests for Nacre's gst_mse patches (docs/engine/gst-mse-patches.md), one per defect of + * gst-plugins-bad 1.28.9's MSE library: + * /mse/update-end-after-parse bug 1: `buffered` is current at the first update-end of an append + * /mse/no-idle-updates bug 2: no update / update-end while nothing is appended + * /mse/split-audio-video bug 3: separate audio and video SourceBuffers, video appended 2 s + * before audio, expose no stream until both have an init segment, then play + * + * Built and run by `tools/gst-mse.sh test` against target/gst-mse (GST_PLUGIN_PATH, own registry). + * Clips in data/ (TESTS_DATA_DIR), made with ffmpeg: + * video-vp9.webm testsrc2 320x180 30 fps 5 s, libvpx-vp9, no audio + * audio-aac.mp4 sine 440 Hz 5 s, aac 64k, fragmented (frag_keyframe+empty_moov+default_base_moof, 1 s) + * Running the binary with LD_LIBRARY_PATH=/usr/lib and GST_PLUGIN_PATH unset tests the system copy instead + * (all three fail there). + */ + +#include +#include + +#define VIDEO_TYPE "video/webm; codecs=\"vp9\"" +#define AUDIO_TYPE "audio/mp4; codecs=\"mp4a.40.2\"" + +typedef struct +{ + GMutex lock; + GCond cond; + gint updates; + gint update_ends; + gint errors; + /* buffered ranges seen at each update-end */ + GArray *buffered_at_end; +} Counter; + +static void +counter_init (Counter * c) +{ + g_mutex_init (&c->lock); + g_cond_init (&c->cond); + c->updates = c->update_ends = c->errors = 0; + c->buffered_at_end = g_array_new (FALSE, TRUE, sizeof (guint)); +} + +static void +counter_clear (Counter * c) +{ + g_array_unref (c->buffered_at_end); + g_mutex_clear (&c->lock); + g_cond_clear (&c->cond); +} + +static void +on_update (GstSourceBuffer * buffer, Counter * c) +{ + g_mutex_lock (&c->lock); + c->updates++; + g_mutex_unlock (&c->lock); +} + +static void +on_update_end (GstSourceBuffer * buffer, Counter * c) +{ + GArray *ranges = gst_source_buffer_get_buffered (buffer, NULL); + guint n = ranges ? ranges->len : 0; + g_clear_pointer (&ranges, g_array_unref); + g_mutex_lock (&c->lock); + c->update_ends++; + g_array_append_val (c->buffered_at_end, n); + g_cond_broadcast (&c->cond); + g_mutex_unlock (&c->lock); +} + +static void +on_error (GstSourceBuffer * buffer, Counter * c) +{ + g_mutex_lock (&c->lock); + c->errors++; + g_cond_broadcast (&c->cond); + g_mutex_unlock (&c->lock); +} + +/* Waits up to @seconds for @n update-ends in total; returns whether they came. */ +static gboolean +wait_update_ends (Counter * c, gint n, gint seconds) +{ + gint64 deadline = g_get_monotonic_time () + seconds * G_TIME_SPAN_SECOND; + gboolean ok = TRUE; + g_mutex_lock (&c->lock); + while (c->update_ends < n && ok) { + ok = g_cond_wait_until (&c->cond, &c->lock, deadline); + } + ok = c->update_ends >= n; + g_mutex_unlock (&c->lock); + return ok; +} + +static void +watch (GstSourceBuffer * buffer, Counter * c) +{ + g_signal_connect (buffer, "on-update", G_CALLBACK (on_update), c); + g_signal_connect (buffer, "on-update-end", G_CALLBACK (on_update_end), c); + g_signal_connect (buffer, "on-error", G_CALLBACK (on_error), c); +} + +static GstBuffer * +clip (const gchar * name) +{ + gchar *path = g_build_filename (g_getenv ("TESTS_DATA_DIR"), name, NULL); + gchar *data; + gsize size; + GError *error = NULL; + g_file_get_contents (path, &data, &size, &error); + g_assert_no_error (error); + g_free (path); + return gst_buffer_new_wrapped (data, size); +} + +static void +sleep_seconds (gdouble seconds) +{ + g_usleep ((gulong) (seconds * G_USEC_PER_SEC)); +} + +/* A MediaSource attached to a lone msesrc (no pipeline), opened, with one SourceBuffer. */ +typedef struct +{ + GstElement *src; + GstMediaSource *source; + GstSourceBuffer *buffer; +} Lone; + +static void +lone_setup (Lone * lone, const gchar * type) +{ + lone->src = gst_element_factory_make ("msesrc", NULL); + g_assert_nonnull (lone->src); + gst_object_ref_sink (lone->src); + lone->source = gst_media_source_new (); + gst_media_source_attach (lone->source, GST_MSE_SRC (lone->src)); + g_assert_cmpint (gst_media_source_get_ready_state (lone->source), ==, + GST_MEDIA_SOURCE_READY_STATE_OPEN); + GError *error = NULL; + lone->buffer = gst_media_source_add_source_buffer (lone->source, type, &error); + g_assert_no_error (error); +} + +static void +lone_teardown (Lone * lone) +{ + gst_media_source_detach (lone->source); + gst_clear_object (&lone->buffer); + gst_clear_object (&lone->source); + gst_clear_object (&lone->src); +} + +static void +test_update_end_after_parse (void) +{ + Lone lone; + Counter c; + counter_init (&c); + lone_setup (&lone, VIDEO_TYPE); + watch (lone.buffer, &c); + + g_assert_true (gst_source_buffer_append_buffer (lone.buffer, + clip ("video-vp9.webm"), NULL)); + g_assert_true (wait_update_ends (&c, 1, 10)); + g_assert_cmpint (c.errors, ==, 0); + /* The whole clip (init segment and media) was in that append. */ + g_assert_cmpuint (g_array_index (c.buffered_at_end, guint, 0), >, 0); + + lone_teardown (&lone); + counter_clear (&c); +} + +static void +test_no_idle_updates (void) +{ + Lone lone; + Counter c; + counter_init (&c); + lone_setup (&lone, AUDIO_TYPE); + watch (lone.buffer, &c); + + sleep_seconds (3); + g_assert_cmpint (c.updates, ==, 0); + g_assert_cmpint (c.update_ends, ==, 0); + + g_assert_true (gst_source_buffer_append_buffer (lone.buffer, + clip ("audio-aac.mp4"), NULL)); + g_assert_true (wait_update_ends (&c, 1, 10)); + sleep_seconds (3); + g_assert_cmpint (c.updates, ==, 1); + g_assert_cmpint (c.update_ends, ==, 1); + g_assert_cmpint (c.errors, ==, 0); + + lone_teardown (&lone); + counter_clear (&c); +} + +/* playbin on mse://, both sinks fakesink (no audio device in test runs). */ +typedef struct +{ + GstElement *playbin; + GstMediaSource *source; + GstElement *src; + GMutex lock; + GCond cond; + gboolean opened; +} Player; + +static void +on_source_setup (GstElement * playbin, GstElement * src, Player * p) +{ + g_mutex_lock (&p->lock); + p->src = gst_object_ref (src); + g_mutex_unlock (&p->lock); + gst_media_source_attach (p->source, GST_MSE_SRC (src)); +} + +static void +on_source_open (GstMediaSource * source, Player * p) +{ + g_mutex_lock (&p->lock); + p->opened = TRUE; + g_cond_broadcast (&p->cond); + g_mutex_unlock (&p->lock); +} + +static GstClockTime +position (GstElement * playbin) +{ + gint64 pos = -1; + if (!gst_element_query_position (playbin, GST_FORMAT_TIME, &pos)) + return GST_CLOCK_TIME_NONE; + return pos; +} + +static void +test_split_audio_video (void) +{ + Player p = { 0 }; + g_mutex_init (&p.lock); + g_cond_init (&p.cond); + p.source = gst_media_source_new (); + g_signal_connect (p.source, "on-source-open", G_CALLBACK (on_source_open), &p); + p.playbin = gst_element_factory_make ("playbin", NULL); + g_assert_nonnull (p.playbin); + GstElement *vsink = gst_element_factory_make ("fakesink", NULL); + GstElement *asink = gst_element_factory_make ("fakesink", NULL); + g_object_set (vsink, "sync", TRUE, NULL); + g_object_set (asink, "sync", TRUE, NULL); + g_object_set (p.playbin, "uri", "mse://test", "video-sink", vsink, + "audio-sink", asink, NULL); + g_signal_connect (p.playbin, "source-setup", G_CALLBACK (on_source_setup), &p); + + gst_element_set_state (p.playbin, GST_STATE_PAUSED); + gint64 deadline = g_get_monotonic_time () + 5 * G_TIME_SPAN_SECOND; + g_mutex_lock (&p.lock); + while (!p.opened && g_cond_wait_until (&p.cond, &p.lock, deadline)); + g_assert_true (p.opened); + g_mutex_unlock (&p.lock); + + GError *error = NULL; + Counter cv, ca; + counter_init (&cv); + counter_init (&ca); + GstSourceBuffer *video = + gst_media_source_add_source_buffer (p.source, VIDEO_TYPE, &error); + g_assert_no_error (error); + GstSourceBuffer *audio = + gst_media_source_add_source_buffer (p.source, AUDIO_TYPE, &error); + g_assert_no_error (error); + watch (video, &cv); + watch (audio, &ca); + + /* Video first, then 2 s with only one init segment, like YouTube's separate buffers. */ + g_assert_true (gst_source_buffer_append_buffer (video, clip ("video-vp9.webm"), + NULL)); + g_assert_true (wait_update_ends (&cv, 1, 10)); + sleep_seconds (2); + guint n_video = 0, n_audio = 0; + GstMseSrcReadyState ready; + g_object_get (p.src, "n-video", &n_video, "n-audio", &n_audio, "ready-state", + &ready, NULL); + g_assert_cmpuint (n_video, ==, 0); + g_assert_cmpuint (n_audio, ==, 0); + g_assert_cmpint (ready, ==, GST_MSE_SRC_READY_STATE_HAVE_NOTHING); + + g_assert_true (gst_source_buffer_append_buffer (audio, clip ("audio-aac.mp4"), + NULL)); + g_assert_true (wait_update_ends (&ca, 1, 10)); + g_assert_true (gst_media_source_end_of_stream (p.source, + GST_MEDIA_SOURCE_EOS_ERROR_NONE, &error)); + g_assert_no_error (error); + g_object_get (p.src, "n-video", &n_video, "n-audio", &n_audio, NULL); + g_assert_cmpuint (n_video, ==, 1); + g_assert_cmpuint (n_audio, ==, 1); + + gst_element_set_state (p.playbin, GST_STATE_PLAYING); + GstClockTime pos = GST_CLOCK_TIME_NONE; + for (gint i = 0; i < 100; i++) { + sleep_seconds (0.1); + pos = position (p.playbin); + if (GST_CLOCK_TIME_IS_VALID (pos) && pos > GST_SECOND) + break; + } + g_test_message ("position after play: %" GST_TIME_FORMAT, GST_TIME_ARGS (pos)); + g_assert_true (GST_CLOCK_TIME_IS_VALID (pos) && pos > GST_SECOND); + g_object_get (p.src, "ready-state", &ready, NULL); + g_assert_cmpint (ready, >=, GST_MSE_SRC_READY_STATE_HAVE_CURRENT_DATA); + g_assert_cmpint (cv.errors + ca.errors, ==, 0); + + gst_element_set_state (p.playbin, GST_STATE_NULL); + gst_clear_object (&video); + gst_clear_object (&audio); + gst_clear_object (&p.src); + gst_clear_object (&p.playbin); + gst_clear_object (&p.source); + counter_clear (&cv); + counter_clear (&ca); + g_mutex_clear (&p.lock); + g_cond_clear (&p.cond); +} + +int +main (int argc, char **argv) +{ + g_test_init (&argc, &argv, NULL); + gst_init (&argc, &argv); + g_test_add_func ("/mse/update-end-after-parse", test_update_end_after_parse); + g_test_add_func ("/mse/no-idle-updates", test_no_idle_updates); + g_test_add_func ("/mse/split-audio-video", test_split_audio_video); + return g_test_run (); +} diff --git a/tools/gst-mse.sh b/tools/gst-mse.sh new file mode 100755 index 0000000..0b67fa9 --- /dev/null +++ b/tools/gst-mse.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +# Builds Nacre's patched copy of GStreamer's MSE library and plugin (vendor/gst-mse, gst-plugins-bad 1.28.9, LGPL) +# into target/gst-mse/: +# lib/libgstmse-1.0.so.0 the library (same soname as the system one; Nacre's RUNPATH finds this first) +# gstreamer-1.0/libgstmse.so the `mse` plugin (msesrc), found through GST_PLUGIN_PATH (src/main.rs) +# and, with `test`, builds and runs the C tests in tests/gst-mse/ against that library. +# +# Usage: tools/gst-mse.sh [test] +# Needs: cc, pkg-config, gstreamer-1.0, gstreamer-base-1.0, gstreamer-app-1.0. +set -eu + +root=$(cd "$(dirname "$0")/.." && pwd) +src=$root/vendor/gst-mse +out=$root/target/gst-mse +mkdir -p "$out/obj" "$out/lib" "$out/gstreamer-1.0" + +cflags="-O2 -g -fPIC -fvisibility=hidden -std=gnu11 -Wall -Wno-unused-function + -DGST_USE_UNSTABLE_API -DHAVE_CONFIG_H + -I$src/gen -I$src/gen/gst/mse -I$src/gst-libs -I$src/gst-libs/gst/mse + $(pkg-config --cflags gstreamer-1.0 gstreamer-base-1.0 gstreamer-app-1.0)" +libs=$(pkg-config --libs gstreamer-1.0 gstreamer-base-1.0 gstreamer-app-1.0) + +objs=() +for c in "$src"/gst-libs/gst/mse/*.c "$src"/gen/gst/mse/mse-enumtypes.c; do + o=$out/obj/$(basename "$c" .c).o + if [ ! -f "$o" ] || [ "$c" -nt "$o" ] || [ -n "$(find "$src/gst-libs" "$src/gen" -name '*.h' -newer "$o")" ]; then + # shellcheck disable=SC2086 + cc $cflags -DBUILDING_GST_MSE -DG_LOG_DOMAIN='"GStreamer-MSE"' -c "$c" -o "$o" + fi + objs+=("$o") +done +# shellcheck disable=SC2086 +cc -shared -Wl,-soname,libgstmse-1.0.so.0 -Wl,--no-undefined -o "$out/lib/libgstmse-1.0.so.0" "${objs[@]}" $libs +ln -sf libgstmse-1.0.so.0 "$out/lib/libgstmse-1.0.so" + +# The plugin links our library; its RUNPATH points at ../lib so it never pulls in the system copy. +# shellcheck disable=SC2086 +cc $cflags -shared -Wl,--no-undefined -Wl,-rpath,'$ORIGIN/../lib' -o "$out/gstreamer-1.0/libgstmse.so" \ + "$src/gst/mse/gstmse.c" -L"$out/lib" -lgstmse-1.0 $libs +echo "gst-mse: built $out/lib/libgstmse-1.0.so.0 and $out/gstreamer-1.0/libgstmse.so" + +[ "${1:-}" = test ] || exit 0 + +# C tests: each tests/gst-mse/*.c is a GLib test program run against our library and plugin only. +tcflags="-O0 -g -std=gnu11 -Wall -DGST_USE_UNSTABLE_API -I$src/gen -I$src/gst-libs + $(pkg-config --cflags gstreamer-1.0)" +tlibs="-L$out/lib -lgstmse-1.0 $(pkg-config --libs gstreamer-1.0)" +mkdir -p "$out/tests" +status=0 +for t in "$root"/tests/gst-mse/*.c; do + bin=$out/tests/$(basename "$t" .c) + # shellcheck disable=SC2086 + cc $tcflags -Wl,-rpath,"$out/lib" -o "$bin" "$t" $tlibs + echo "gst-mse: running $(basename "$bin")" + GST_PLUGIN_PATH=$out/gstreamer-1.0 GST_REGISTRY=$out/tests/registry.bin \ + TESTS_DATA_DIR=$root/tests/gst-mse/data "$bin" || status=1 +done +exit $status diff --git a/vendor/gst-mse/COPYING b/vendor/gst-mse/COPYING new file mode 100644 index 0000000..4362b49 --- /dev/null +++ b/vendor/gst-mse/COPYING @@ -0,0 +1,502 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/vendor/gst-mse/gen/config.h b/vendor/gst-mse/gen/config.h new file mode 100644 index 0000000..93d2fa3 --- /dev/null +++ b/vendor/gst-mse/gen/config.h @@ -0,0 +1,8 @@ +/* Nacre patch: the few config.h macros the gst_mse sources use (normally written by meson). */ +#pragma once +#define PACKAGE "gst-plugins-bad" +#define VERSION "1.28.9" +#define GST_LICENSE "LGPL" +#define GST_PACKAGE_NAME "GStreamer Bad Plug-ins (Nacre patched gst_mse)" +#define GST_PACKAGE_ORIGIN "https://archlinux.tail7c4f5e.ts.net/git/astar76/Nacre" +#define GST_API_VERSION "1.0" diff --git a/vendor/gst-mse/gen/gst/mse/mse-enumtypes-private.h b/vendor/gst-mse/gen/gst/mse/mse-enumtypes-private.h new file mode 100644 index 0000000..0a2dc3d --- /dev/null +++ b/vendor/gst-mse/gen/gst/mse/mse-enumtypes-private.h @@ -0,0 +1,16 @@ +/* Nacre patch: written by hand in place of the glib-mkenums output (no meson build here). */ + +#pragma once + +#include +#include + +G_BEGIN_DECLS + +/* enumerations from "gstmediasourcetrack-private.h" */ + +GST_MSE_PRIVATE +GType gst_media_source_track_type_get_type (void); +#define GST_TYPE_MEDIA_SOURCE_TRACK_TYPE (gst_media_source_track_type_get_type()) + +G_END_DECLS diff --git a/vendor/gst-mse/gen/gst/mse/mse-enumtypes.c b/vendor/gst-mse/gen/gst/mse/mse-enumtypes.c new file mode 100644 index 0000000..4f1d19b --- /dev/null +++ b/vendor/gst-mse/gen/gst/mse/mse-enumtypes.c @@ -0,0 +1,43 @@ +/* Nacre patch: written by hand in place of the glib-mkenums output (no meson build here). + * Value nicks follow glib-mkenums: the common prefix removed, lower case, '-' for '_'. */ + +#include "gstmediasource.h" +#include "gstmsesrc.h" +#include "gstsourcebuffer.h" +#include "gstmediasourcetrack-private.h" +#include +#include + +G_DEFINE_ENUM_TYPE (GstMediaSourceReadyState, gst_media_source_ready_state, + G_DEFINE_ENUM_VALUE (GST_MEDIA_SOURCE_READY_STATE_CLOSED, "closed"), + G_DEFINE_ENUM_VALUE (GST_MEDIA_SOURCE_READY_STATE_OPEN, "open"), + G_DEFINE_ENUM_VALUE (GST_MEDIA_SOURCE_READY_STATE_ENDED, "ended")); + +G_DEFINE_ENUM_TYPE (GstMediaSourceError, gst_media_source_error, + G_DEFINE_ENUM_VALUE (GST_MEDIA_SOURCE_ERROR_INVALID_STATE, "invalid-state"), + G_DEFINE_ENUM_VALUE (GST_MEDIA_SOURCE_ERROR_TYPE, "type"), + G_DEFINE_ENUM_VALUE (GST_MEDIA_SOURCE_ERROR_NOT_SUPPORTED, "not-supported"), + G_DEFINE_ENUM_VALUE (GST_MEDIA_SOURCE_ERROR_NOT_FOUND, "not-found"), + G_DEFINE_ENUM_VALUE (GST_MEDIA_SOURCE_ERROR_QUOTA_EXCEEDED, "quota-exceeded")); + +G_DEFINE_ENUM_TYPE (GstMediaSourceEOSError, gst_media_source_eos_error, + G_DEFINE_ENUM_VALUE (GST_MEDIA_SOURCE_EOS_ERROR_NONE, "none"), + G_DEFINE_ENUM_VALUE (GST_MEDIA_SOURCE_EOS_ERROR_NETWORK, "network"), + G_DEFINE_ENUM_VALUE (GST_MEDIA_SOURCE_EOS_ERROR_DECODE, "decode")); + +G_DEFINE_ENUM_TYPE (GstMseSrcReadyState, gst_mse_src_ready_state, + G_DEFINE_ENUM_VALUE (GST_MSE_SRC_READY_STATE_HAVE_NOTHING, "nothing"), + G_DEFINE_ENUM_VALUE (GST_MSE_SRC_READY_STATE_HAVE_METADATA, "metadata"), + G_DEFINE_ENUM_VALUE (GST_MSE_SRC_READY_STATE_HAVE_CURRENT_DATA, "current-data"), + G_DEFINE_ENUM_VALUE (GST_MSE_SRC_READY_STATE_HAVE_FUTURE_DATA, "future-data"), + G_DEFINE_ENUM_VALUE (GST_MSE_SRC_READY_STATE_HAVE_ENOUGH_DATA, "enough-data")); + +G_DEFINE_ENUM_TYPE (GstSourceBufferAppendMode, gst_source_buffer_append_mode, + G_DEFINE_ENUM_VALUE (GST_SOURCE_BUFFER_APPEND_MODE_SEGMENTS, "segments"), + G_DEFINE_ENUM_VALUE (GST_SOURCE_BUFFER_APPEND_MODE_SEQUENCE, "sequence")); + +G_DEFINE_ENUM_TYPE (GstMediaSourceTrackType, gst_media_source_track_type, + G_DEFINE_ENUM_VALUE (GST_MEDIA_SOURCE_TRACK_TYPE_AUDIO, "audio"), + G_DEFINE_ENUM_VALUE (GST_MEDIA_SOURCE_TRACK_TYPE_VIDEO, "video"), + G_DEFINE_ENUM_VALUE (GST_MEDIA_SOURCE_TRACK_TYPE_TEXT, "text"), + G_DEFINE_ENUM_VALUE (GST_MEDIA_SOURCE_TRACK_TYPE_OTHER, "other")); diff --git a/vendor/gst-mse/gen/gst/mse/mse-enumtypes.h b/vendor/gst-mse/gen/gst/mse/mse-enumtypes.h new file mode 100644 index 0000000..bc7e153 --- /dev/null +++ b/vendor/gst-mse/gen/gst/mse/mse-enumtypes.h @@ -0,0 +1,40 @@ +/* Nacre patch: written by hand in place of the glib-mkenums output (no meson build here). */ +/* This file is generated by glib-mkenums, do not modify it. This code is licensed under the same license as the containing project. Note that it links to GLib, so must comply with the LGPL linking clauses. */ + +#pragma once + +#include +#include + +G_BEGIN_DECLS + +/* enumerations from "gstmediasource.h" */ + +GST_MSE_API +GType gst_media_source_ready_state_get_type (void); +#define GST_TYPE_MEDIA_SOURCE_READY_STATE (gst_media_source_ready_state_get_type()) + +GST_MSE_API +GType gst_media_source_error_get_type (void); +#define GST_TYPE_MEDIA_SOURCE_ERROR (gst_media_source_error_get_type()) + +GST_MSE_API +GType gst_media_source_eos_error_get_type (void); +#define GST_TYPE_MEDIA_SOURCE_EOS_ERROR (gst_media_source_eos_error_get_type()) + +/* enumerations from "gstmsesrc.h" */ + +GST_MSE_API +GType gst_mse_src_ready_state_get_type (void); +#define GST_TYPE_MSE_SRC_READY_STATE (gst_mse_src_ready_state_get_type()) + +/* enumerations from "gstsourcebuffer.h" */ + +GST_MSE_API +GType gst_source_buffer_append_mode_get_type (void); +#define GST_TYPE_SOURCE_BUFFER_APPEND_MODE (gst_source_buffer_append_mode_get_type()) + +G_END_DECLS + +/* Generated data ends here */ + diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstappendpipeline-private.h b/vendor/gst-mse/gst-libs/gst/mse/gstappendpipeline-private.h new file mode 100644 index 0000000..c44a344 --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstappendpipeline-private.h @@ -0,0 +1,102 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2016, 2017 Metrological Group B.V. + * Copyright (C) 2016, 2017 Igalia S.L + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#pragma once + +#include +#include +#include +#include + +G_BEGIN_DECLS + +#define GST_TYPE_APPEND_PIPELINE (gst_append_pipeline_get_type()) + +GST_MSE_PRIVATE +G_DECLARE_FINAL_TYPE (GstAppendPipeline, gst_append_pipeline, GST, + APPEND_PIPELINE, GstObject); + +typedef struct +{ + void (*received_init_segment) (GstAppendPipeline * self, + gpointer user_data); + void (*duration_changed) (GstAppendPipeline * self, + gpointer user_data); + void (*new_sample) (GstAppendPipeline * self, + GstMediaSourceTrack * track, + GstSample * sample, + gpointer user_data); + void (*eos) (GstAppendPipeline * self, + GstMediaSourceTrack * track, + gpointer user_data); + void (*error) (GstAppendPipeline * self, + gpointer user_data); +} GstAppendPipelineCallbacks; + +GST_MSE_PRIVATE +GstAppendPipeline * gst_append_pipeline_new ( + GstAppendPipelineCallbacks * callbacks, gpointer user_data, + GError ** error); + +GST_MSE_PRIVATE +GstFlowReturn gst_append_pipeline_append (GstAppendPipeline * self, + GstBuffer * buffer); + +GST_MSE_PRIVATE +GstFlowReturn gst_append_pipeline_eos (GstAppendPipeline * self); + +GST_MSE_PRIVATE +gboolean gst_append_pipeline_stop (GstAppendPipeline * self); + +GST_MSE_PRIVATE +gboolean gst_append_pipeline_reset (GstAppendPipeline * self); + +GST_MSE_PRIVATE +gsize gst_append_pipeline_n_tracks (GstAppendPipeline * self); + +GST_MSE_PRIVATE +gboolean gst_append_pipeline_has_init_segment (GstAppendPipeline * self); + +GST_MSE_PRIVATE +GstClockTime gst_append_pipeline_get_duration (GstAppendPipeline * self); + +GST_MSE_PRIVATE +GPtrArray *gst_append_pipeline_get_audio_tracks (GstAppendPipeline * self); + +GST_MSE_PRIVATE +GPtrArray *gst_append_pipeline_get_text_tracks (GstAppendPipeline * self); + +GST_MSE_PRIVATE +GPtrArray *gst_append_pipeline_get_video_tracks (GstAppendPipeline * self); + +GST_MSE_PRIVATE +gboolean gst_append_pipeline_get_eos (GstAppendPipeline * self); + +GST_MSE_PRIVATE +void gst_append_pipeline_fail (GstAppendPipeline * self); + +GST_MSE_PRIVATE +gboolean gst_append_pipeline_get_failed (GstAppendPipeline * self); + +G_END_DECLS diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstappendpipeline.c b/vendor/gst-mse/gst-libs/gst/mse/gstappendpipeline.c new file mode 100644 index 0000000..008e828 --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstappendpipeline.c @@ -0,0 +1,1044 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2016, 2017 Metrological Group B.V. + * Copyright (C) 2016, 2017 Igalia S.L + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "gstappendpipeline-private.h" + +#include "mse.h" + +#include "gstmselogging-private.h" +#include "gstmsemediatype-private.h" +#include "gstmediasourcetrack-private.h" + +#include +#include +#include + +typedef enum +{ + PARSE_ERROR, + IGNORED, + ADDED, +} AddTrackResult; + +typedef struct +{ + GstAppendPipeline *pipeline; + GstTask *task; + GRecMutex mutex; + GstBus *bus; +} BackgroundTask; + +typedef struct +{ + GstAppendPipelineCallbacks callbacks; + gpointer user_data; +} Callbacks; + +typedef struct +{ + GstAppendPipeline *parent; + GstPad *src_pad; + GstAppSink *sink; + GstMediaSourceTrack *mse_track; + GstStream *stream; + GstClockTime previous_pts; +} Track; + +typedef struct +{ + GstClockTime duration; + GPtrArray *video_tracks; + GPtrArray *audio_tracks; + GPtrArray *text_tracks; +} InitSegment; + +struct _GstAppendPipeline +{ + GstObject parent_instance; + + GstPipeline *pipeline; + GstAppSrc *src; + GstElement *parsebin; + GstBus *bus; + + GstStreamCollection *streams; + GArray *tracks; + + gboolean received_init_segment; + gboolean have_outstanding_samples; + InitSegment init_segment; + + gboolean encountered_error; + + /* Nacre patch: appends pushed and appends whose end-of-append marker the + * background task has handled (samples handed to the source buffer), so + * gst_append_pipeline_append() can return only once its data is parsed. */ + GMutex append_lock; + GCond append_cond; + guint64 appends_sent; + guint64 appends_done; + + BackgroundTask *task; + + Callbacks callbacks; +}; + +G_DEFINE_TYPE (GstAppendPipeline, gst_append_pipeline, GST_TYPE_OBJECT); + +#define END_OF_APPEND "end-of-append" +#define ABORT "abort" +#define SHUTDOWN "shutdown" + +static void process_init_segment (GstAppendPipeline *); + +/* Nacre patch: one more append is fully processed, or (all) every append is + * settled because the pipeline stopped, failed or was reset. */ +static void +finish_appends (GstAppendPipeline * self, gboolean all) +{ + g_mutex_lock (&self->append_lock); + if (all) { + self->appends_done = self->appends_sent; + } else if (self->appends_done < self->appends_sent) { + self->appends_done++; + } + g_cond_broadcast (&self->append_cond); + g_mutex_unlock (&self->append_lock); +} + +static gboolean +send_abort (GstAppendPipeline * self) +{ + return gst_bus_post (self->bus, gst_message_new_application (NULL, + gst_structure_new_empty (ABORT))); +} + +static gboolean +send_shutdown (GstAppendPipeline * self) +{ + return gst_bus_post (self->bus, gst_message_new_application (NULL, + gst_structure_new_empty (SHUTDOWN))); +} + +static GstEvent * +new_end_of_append_event (void) +{ + GstStructure *structure = gst_structure_new_empty (END_OF_APPEND); + return gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM, structure); +} + +static gboolean +is_end_of_append_event (GstEvent * event) +{ + return GST_EVENT_TYPE (event) == GST_EVENT_CUSTOM_DOWNSTREAM + && gst_event_has_name (event, END_OF_APPEND); +} + +static inline guint +n_tracks (GstAppendPipeline * self) +{ + return self->tracks->len; +} + +static inline Track * +index_track (GstAppendPipeline * self, guint i) +{ + return &g_array_index (self->tracks, Track, i); +} + +static inline void +call_parse_error (GstAppendPipeline * self) +{ + GstAppendPipelineCallbacks *callbacks = &self->callbacks.callbacks; + gpointer user_data = self->callbacks.user_data; + + if (callbacks->error) { + callbacks->error (self, user_data); + GST_TRACE_OBJECT (self, "done"); + } else { + GST_TRACE_OBJECT (self, "dropping"); + } +} + +static inline void +call_received_init_segment (GstAppendPipeline * self) +{ + GstAppendPipelineCallbacks *callbacks = &self->callbacks.callbacks; + gpointer user_data = self->callbacks.user_data; + + if (callbacks->received_init_segment) { + callbacks->received_init_segment (self, user_data); + GST_TRACE_OBJECT (self, "done"); + } else { + GST_TRACE_OBJECT (self, "dropping"); + } +} + +static inline void +call_new_sample (GstAppendPipeline * self, GstMediaSourceTrack * track, + GstSample * sample) +{ + GstAppendPipelineCallbacks *callbacks = &self->callbacks.callbacks; + gpointer user_data = self->callbacks.user_data; + + if (callbacks->new_sample) { + callbacks->new_sample (self, track, sample, user_data); + GST_TRACE_OBJECT (self, "done"); + } else { + GST_TRACE_OBJECT (self, "dropping"); + } +} + +static inline void +call_duration_changed (GstAppendPipeline * self) +{ + GstAppendPipelineCallbacks *callbacks = &self->callbacks.callbacks; + gpointer user_data = self->callbacks.user_data; + + if (callbacks->duration_changed) { + callbacks->duration_changed (self, user_data); + GST_TRACE_OBJECT (self, "done"); + } else { + GST_TRACE_OBJECT (self, "dropping"); + } +} + +static inline void +call_eos (GstAppendPipeline * self, GstMediaSourceTrack * track) +{ + GstAppendPipelineCallbacks *callbacks = &self->callbacks.callbacks; + gpointer user_data = self->callbacks.user_data; + + if (callbacks->eos) { + callbacks->eos (self, track, user_data); + GST_TRACE_OBJECT (self, "done"); + } else { + GST_TRACE_OBJECT (self, "dropping"); + } +} + +static inline GstSample * +patch_missing_duration (GstAppendPipeline * self, GstSample * sample) +{ + GstBuffer *buffer = gst_sample_get_buffer (sample); + if (!GST_BUFFER_DURATION_IS_VALID (buffer)) { + GST_BUFFER_DURATION (buffer) = GST_SECOND / 60; + GST_TRACE_OBJECT (self, "sample is missing duration, patched to %" + GST_TIMEP_FORMAT, &buffer->duration); + } + return sample; +} + +static inline GstSample * +patch_missing_pts (GstAppendPipeline * self, GstSample * sample, GstClockTime + fallback) +{ + GstBuffer *buffer = gst_sample_get_buffer (sample); + if (!GST_BUFFER_PTS_IS_VALID (buffer) && GST_CLOCK_TIME_IS_VALID (fallback)) { + GST_TRACE_OBJECT (self, "sample is missing pts, patching with %" + GST_TIMEP_FORMAT, &fallback); + GST_BUFFER_PTS (buffer) = fallback; + } + return sample; +} + +static inline GstSample * +patch_missing_dts (GstAppendPipeline * self, GstSample * sample) +{ + GstBuffer *buffer = gst_sample_get_buffer (sample); + if (!GST_BUFFER_DTS_IS_VALID (buffer) && GST_BUFFER_PTS_IS_VALID (buffer)) { + GST_TRACE_OBJECT (self, "sample is missing dts, patching with pts %" + GST_TIMEP_FORMAT, &buffer->pts); + GST_BUFFER_DTS (buffer) = GST_BUFFER_PTS (buffer); + } + return sample; +} + +static gboolean +consume_sample_from_track (GstAppendPipeline * self, Track * track) +{ + GstSample *sample = gst_app_sink_try_pull_sample (track->sink, 0); + if (sample == NULL) { + return FALSE; + } + GstBuffer *buffer = gst_sample_get_buffer (sample); + if (!GST_IS_BUFFER (buffer)) { + GST_WARNING_OBJECT (self, "got null buffer in sample"); + goto done; + } + sample = patch_missing_pts (self, sample, track->previous_pts); + sample = patch_missing_duration (self, sample); + sample = patch_missing_dts (self, sample); + track->previous_pts = GST_BUFFER_PTS (buffer); + call_new_sample (self, track->mse_track, sample); + +done: + gst_clear_sample (&sample); + return TRUE; +} + +static void +consume_all_samples (GstAppendPipeline * self) +{ + if (!self->received_init_segment) { + GST_DEBUG_OBJECT (self, "not all tracks are available, delaying"); + self->have_outstanding_samples = TRUE; + return; + } + guint track_count = n_tracks (self); + while (TRUE) { + gboolean sample_consumed = FALSE; + for (guint i = 0; i < track_count; i++) { + Track *track = index_track (self, i); + sample_consumed |= consume_sample_from_track (self, track); + } + if (!sample_consumed) { + break; + } + } + call_duration_changed (self); + self->have_outstanding_samples = FALSE; +} + +static void +handle_shutdown (BackgroundTask * task) +{ + gst_task_stop (task->task); + GstAppendPipeline *self = task->pipeline; + guint track_count = n_tracks (self); + for (guint i = 0; i < track_count; i++) { + Track *track = index_track (self, i); + call_eos (self, track->mse_track); + } + call_eos (self, NULL); + finish_appends (self, TRUE); +} + +static void +handle_abort (BackgroundTask * task) +{ + gst_task_stop (task->task); + finish_appends (task->pipeline, TRUE); +} + +static void +task_function (gpointer user_data) +{ + BackgroundTask *task = (BackgroundTask *) user_data; + GstAppendPipeline *self = task->pipeline; + GstMessage *message = gst_bus_timed_pop (task->bus, GST_CLOCK_TIME_NONE); + switch (GST_MESSAGE_TYPE (message)) { + case GST_MESSAGE_APPLICATION:{ + if (gst_message_has_name (message, END_OF_APPEND)) { + GST_TRACE_OBJECT (self, "end of append"); + consume_all_samples (self); + finish_appends (self, FALSE); + goto done; + } + if (gst_message_has_name (message, SHUTDOWN)) { + GST_DEBUG_OBJECT (self, "shutdown"); + handle_shutdown (task); + goto done; + } + if (gst_message_has_name (message, ABORT)) { + GST_DEBUG_OBJECT (self, "abort"); + handle_abort (task); + goto done; + } + g_error ("received unsupported application message"); + } + case GST_MESSAGE_STREAM_COLLECTION:{ + GST_DEBUG_OBJECT (self, "stream collection"); + GstStreamCollection *streams; + gst_message_parse_stream_collection (message, &streams); + gst_clear_object (&self->streams); + self->streams = streams; + process_init_segment (self); + goto done; + } + case GST_MESSAGE_EOS: + GST_DEBUG_OBJECT (self, "end of stream"); + if (self->have_outstanding_samples) { + GST_DEBUG_OBJECT (self, "consuming remaining samples before EOS"); + consume_all_samples (self); + } + handle_shutdown (task); + goto done; + case GST_MESSAGE_ERROR: + GST_DEBUG_OBJECT (self, "error: %" GST_PTR_FORMAT, message); + self->encountered_error = TRUE; + call_parse_error (self); + handle_shutdown (task); + goto done; + default: + GST_TRACE_OBJECT (self, "ignoring message %" GST_PTR_FORMAT, message); + goto done; + } +done: + gst_message_unref (message); +} + +static inline GstAppSink * +new_appsink (GstAppendPipeline * self, GstStreamType type) +{ + const gchar *type_name = gst_stream_type_get_name (type); + gchar *name = g_strdup_printf ("%s-%u", type_name, n_tracks (self)); + GstAppSink *appsink = + GST_APP_SINK (gst_element_factory_make ("appsink", name)); + gst_base_sink_set_sync (GST_BASE_SINK (appsink), FALSE); + gst_base_sink_set_async_enabled (GST_BASE_SINK (appsink), FALSE); + gst_base_sink_set_drop_out_of_segment (GST_BASE_SINK (appsink), FALSE); + gst_base_sink_set_last_sample_enabled (GST_BASE_SINK (appsink), FALSE); + g_free (name); + return appsink; +} + +static GstPadProbeReturn +black_hole_probe (GstPad * pad, GstPadProbeInfo * info, gpointer user_data) +{ + g_return_val_if_fail (GST_PAD_PROBE_INFO_TYPE (info) & + GST_PAD_PROBE_TYPE_BUFFER, GST_PAD_PROBE_DROP); + return GST_PAD_PROBE_DROP; +} + +static GstPadProbeReturn +event_probe (GstPad * pad, GstPadProbeInfo * info, gpointer user_data) +{ + GstAppendPipeline *self = GST_APPEND_PIPELINE (user_data); + GstEvent *event = GST_PAD_PROBE_INFO_EVENT (info); + + if (is_end_of_append_event (event)) { + GST_TRACE_OBJECT (self, "end of append event"); + if (gst_bus_post (self->bus, gst_message_new_application (NULL, + gst_structure_new_empty (END_OF_APPEND)))) { + return GST_PAD_PROBE_DROP; + } else { + GST_ERROR_OBJECT (self, "failed to post end of append"); + goto error; + } + } + + if (GST_EVENT_TYPE (event) == GST_EVENT_EOS) { + GST_DEBUG_OBJECT (self, "eos event"); + if (send_shutdown (self)) { + return GST_PAD_PROBE_OK; + } else { + GST_ERROR_OBJECT (self, "failed to post shutdown"); + goto error; + } + } + + return GST_PAD_PROBE_OK; + +error: + GST_PAD_PROBE_INFO_FLOW_RETURN (info) = GST_FLOW_ERROR; + gst_event_unref (event); + return GST_PAD_PROBE_HANDLED; +} + +static AddTrackResult +add_track (GstAppendPipeline * self, GstPad * pad, GstStream * stream, + GstCaps * caps, Track * added_track) +{ + GstStreamType type = gst_stream_get_stream_type (stream); + GstMediaSourceTrackType track_type = + gst_media_source_track_type_from_stream_type (type); + + switch (type) { + case GST_STREAM_TYPE_AUDIO: + case GST_STREAM_TYPE_TEXT: + case GST_STREAM_TYPE_VIDEO: + break; + default:{ + GST_DEBUG_OBJECT (self, "unexpected caps %" GST_PTR_FORMAT + ", using black hole probe", caps); + gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_BUFFER, black_hole_probe, self, + NULL); + return IGNORED; + } + } + + if (type != GST_STREAM_TYPE_TEXT && + !gst_media_source_media_type_is_caps_supported (caps)) { + GST_ERROR_OBJECT (self, "unsupported caps: %" GST_PTR_FORMAT, caps); + return PARSE_ERROR; + } + + GstAppSink *appsink = new_appsink (self, type); + gst_bin_add (GST_BIN (self->pipeline), GST_ELEMENT (appsink)); + gst_element_sync_state_with_parent (GST_ELEMENT (appsink)); + + GstPad *appsink_pad = + gst_element_get_static_pad (GST_ELEMENT (appsink), "sink"); + GstPadLinkReturn link_result = gst_pad_link (pad, appsink_pad); + gst_clear_object (&appsink_pad); + if (GST_PAD_LINK_FAILED (link_result)) { + g_error ("failed to link parser to appsink: %s", + gst_pad_link_get_name (link_result)); + } + + Track track_template = { + .parent = self, + .sink = gst_object_ref (appsink), + .src_pad = gst_object_ref (pad), + .stream = gst_object_ref (stream), + .mse_track = gst_media_source_track_new_with_initial_caps (track_type, + GST_OBJECT_NAME (appsink), caps), + .previous_pts = GST_CLOCK_TIME_NONE, + }; + g_array_append_val (self->tracks, track_template); + + GST_TRACE_OBJECT (self, "added appsink %s to pad %s", + GST_OBJECT_NAME (appsink), GST_OBJECT_NAME (pad)); + + *added_track = track_template; + + return ADDED; +} + +static void +clear_track (Track * track) +{ + gst_clear_object (&track->sink); + gst_clear_object (&track->src_pad); + gst_clear_object (&track->mse_track); + gst_clear_object (&track->stream); +} + +static inline GPtrArray * +init_segment_tracks_for (InitSegment * self, GstStreamType type) +{ + switch (type) { + case GST_STREAM_TYPE_AUDIO: + return self->audio_tracks; + case GST_STREAM_TYPE_TEXT: + return self->text_tracks; + case GST_STREAM_TYPE_VIDEO: + return self->video_tracks; + default: + g_assert_not_reached (); + return NULL; + } +} + +static void +process_init_segment_track (GstPad * pad, GstAppendPipeline * self) +{ + GST_OBJECT_LOCK (self); + InitSegment *init_segment = &self->init_segment; + GstStream *stream = gst_pad_get_stream (pad); + GstCaps *caps = gst_stream_get_caps (stream); + GST_DEBUG_OBJECT (self, "%" GST_PTR_FORMAT " got caps %" GST_PTR_FORMAT, pad, + caps); + + if (gst_pad_is_linked (pad)) { + GST_TRACE_OBJECT (self, "%" GST_PTR_FORMAT " is already linked, skipping", + pad); + goto done; + } + + if (!GST_IS_CAPS (caps)) { + GST_ERROR_OBJECT (self, "no caps on %" GST_PTR_FORMAT + " after stream collection", pad); + call_parse_error (self); + goto done; + } + + Track track; + AddTrackResult result = add_track (self, pad, stream, caps, &track); + GstMediaSourceTrack *mse_track = track.mse_track; + switch (result) { + case ADDED:{ + GstStreamType type = gst_stream_get_stream_type (stream); + GPtrArray *tracks = init_segment_tracks_for (init_segment, type); + if (tracks->len < 1) { + gst_media_source_track_set_active (mse_track, TRUE); + } + g_ptr_array_add (tracks, gst_object_ref (mse_track)); + break; + } + case IGNORED: + break; + case PARSE_ERROR: + call_parse_error (self); + break; + } + +done: + gst_clear_object (&stream); + gst_clear_caps (&caps); + GST_OBJECT_UNLOCK (self); +} + +static void +on_pad_added (GstElement * parsebin, GstPad * pad, gpointer user_data) +{ + GstAppendPipeline *self = GST_APPEND_PIPELINE (user_data); + process_init_segment_track (pad, self); + process_init_segment (self); +} + +static gboolean +has_track_for_stream (GstAppendPipeline * self, GstStream * stream) +{ + guint track_count = n_tracks (self); + for (guint i = 0; i < track_count; i++) { + Track *track = index_track (self, i); + if (track->stream == stream) { + return TRUE; + } + } + return FALSE; +} + +static gboolean +has_all_tracks (GstAppendPipeline * self) +{ + if (!GST_IS_STREAM_COLLECTION (self->streams)) { + return FALSE; + } + for (guint i = 0; i < gst_stream_collection_get_size (self->streams); i++) { + GstStream *stream = gst_stream_collection_get_stream (self->streams, i); + switch (gst_stream_get_stream_type (stream)) { + case GST_STREAM_TYPE_AUDIO: + case GST_STREAM_TYPE_VIDEO: + case GST_STREAM_TYPE_TEXT: + break; + default: + continue; + } + if (!has_track_for_stream (self, stream)) { + return FALSE; + } + } + return TRUE; +} + +static void +process_init_segment (GstAppendPipeline * self) +{ + gint64 duration; + InitSegment *init_segment = &self->init_segment; + + GST_OBJECT_LOCK (self); + + if (!has_all_tracks (self)) { + goto done; + } + + if (gst_element_query_duration (self->parsebin, GST_FORMAT_TIME, &duration)) { + init_segment->duration = MAX (0, duration); + } else { + init_segment->duration = GST_CLOCK_TIME_NONE; + } + + GST_DEBUG_OBJECT (self, "init segment says duration=%" GST_TIME_FORMAT, + GST_TIME_ARGS ((GstClockTime) duration)); + + self->received_init_segment = TRUE; + + call_received_init_segment (self); + +done: + GST_OBJECT_UNLOCK (self); +} + +static inline void +init_segment_init (InitSegment * self) +{ + self->audio_tracks = g_ptr_array_new_with_free_func (gst_object_unref); + self->text_tracks = g_ptr_array_new_with_free_func (gst_object_unref); + self->video_tracks = g_ptr_array_new_with_free_func (gst_object_unref); + self->duration = GST_CLOCK_TIME_NONE; +} + +static inline void +init_segment_finalize (InitSegment * self) +{ + g_ptr_array_free (self->audio_tracks, TRUE); + g_ptr_array_free (self->text_tracks, TRUE); + g_ptr_array_free (self->video_tracks, TRUE); +} + +static GArray * +new_tracks_array (void) +{ + GArray *tracks = g_array_new (TRUE, TRUE, sizeof (Track)); + g_array_set_clear_func (tracks, (GDestroyNotify) clear_track); + return tracks; +} + +static BackgroundTask * +background_task_new (GstAppendPipeline * pipeline) +{ + BackgroundTask *task = g_new0 (BackgroundTask, 1); + g_rec_mutex_init (&task->mutex); + task->task = gst_task_new (task_function, task, NULL); + task->pipeline = pipeline; + task->bus = gst_object_ref (pipeline->bus); + gst_task_set_lock (task->task, &task->mutex); + return task; +} + +static gboolean +background_task_start (BackgroundTask * task) +{ + gst_bus_set_flushing (task->bus, FALSE); + gchar *name = g_strdup_printf ("%s:bg", GST_OBJECT_NAME (task->pipeline)); + g_object_set (task->task, "name", name, NULL); + g_clear_pointer (&name, g_free); + return gst_task_start (task->task); +} + +static gboolean +background_task_stop (BackgroundTask * task) +{ + send_abort (task->pipeline); + gst_task_join (task->task); + gst_bus_set_flushing (task->bus, TRUE); + return TRUE; +} + +static void +background_task_cleanup (gpointer ptr) +{ + BackgroundTask *task = (BackgroundTask *) ptr; + background_task_stop (task); + task->pipeline = NULL; + gst_clear_object (&task->task); + gst_clear_object (&task->bus); + g_rec_mutex_clear (&task->mutex); + g_free (task); +} + +static void +gst_append_pipeline_init (GstAppendPipeline * self) +{ + GstElement *appsrc = GST_ELEMENT (gst_element_factory_make ("appsrc", "src")); + GstElement *parsebin = + GST_ELEMENT (gst_element_factory_make ("parsebin", "parse")); + GstElement *pipeline = gst_pipeline_new ("append-pipeline"); + + GstPad *appsrc_pad = GST_PAD (gst_element_get_static_pad (appsrc, "src")); + gst_pad_add_probe (appsrc_pad, GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM, + event_probe, self, NULL); + gst_object_unref (appsrc_pad); + + gst_bin_add_many (GST_BIN (pipeline), appsrc, parsebin, NULL); + if (!gst_element_link (appsrc, parsebin)) { + g_error ("failed to link appsrc to parsebin"); + } + + self->bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); + self->pipeline = gst_object_ref_sink (GST_PIPELINE (pipeline)); + self->src = GST_APP_SRC (appsrc); + self->parsebin = parsebin; + + self->task = background_task_new (self); + + g_signal_connect_object (parsebin, "pad-added", G_CALLBACK (on_pad_added), + self, 0); + + self->received_init_segment = FALSE; + self->encountered_error = FALSE; + self->tracks = new_tracks_array (); + init_segment_init (&self->init_segment); + + g_mutex_init (&self->append_lock); + g_cond_init (&self->append_cond); + self->appends_sent = 0; + self->appends_done = 0; +} + +static void +gst_append_pipeline_dispose (GObject * object) +{ + GstAppendPipeline *self = (GstAppendPipeline *) object; + + send_shutdown (self); + g_clear_pointer (&self->task, background_task_cleanup); + + gst_element_set_state (GST_ELEMENT (self->pipeline), GST_STATE_NULL); + + G_OBJECT_CLASS (gst_append_pipeline_parent_class)->dispose (object); +} + +static void +gst_append_pipeline_finalize (GObject * object) +{ + GstAppendPipeline *self = (GstAppendPipeline *) object; + + gst_clear_object (&self->pipeline); + gst_clear_object (&self->bus); + + init_segment_finalize (&self->init_segment); + + g_array_free (self->tracks, TRUE); + gst_clear_object (&self->streams); + + g_mutex_clear (&self->append_lock); + g_cond_clear (&self->append_cond); + + G_OBJECT_CLASS (gst_append_pipeline_parent_class)->finalize (object); +} + +static void +gst_append_pipeline_class_init (GstAppendPipelineClass * klass) +{ + GObjectClass *oclass = G_OBJECT_CLASS (klass); + + oclass->dispose = GST_DEBUG_FUNCPTR (gst_append_pipeline_dispose); + oclass->finalize = GST_DEBUG_FUNCPTR (gst_append_pipeline_finalize); +} + +GstAppendPipeline * +gst_append_pipeline_new (GstAppendPipelineCallbacks * callbacks, + gpointer user_data, GError ** error) +{ + gst_mse_init_logging (); + GstAppendPipeline *self = g_object_new (GST_TYPE_APPEND_PIPELINE, NULL); + GstStateChangeReturn started = + gst_element_set_state (GST_ELEMENT (self->pipeline), GST_STATE_PLAYING); + if (started != GST_STATE_CHANGE_SUCCESS) { + GST_ERROR_OBJECT (self, "failed to start: %s", + gst_state_change_return_get_name (started)); + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_INVALID_STATE, + "failed to start append pipeline"); + goto error; + } + if (callbacks) { + self->callbacks.callbacks = *callbacks; + self->callbacks.user_data = user_data; + } + if (!background_task_start (self->task)) { + GST_ERROR_OBJECT (self, "failed to start background task"); + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_INVALID_STATE, + "failed to start append pipeline's background task"); + goto error; + } + return gst_object_ref_sink (self); +error: + gst_clear_object (&self); + return NULL; +} + +/* Nacre patch: an append that never settles (a stuck parser) would leave the + * source buffer updating forever; give up waiting after this long. */ +#define APPEND_TIMEOUT (10 * G_TIME_SPAN_SECOND) + +/* Nacre patch: blocks until the background task has handled this append's + * end-of-append marker, i.e. every sample parsed from @buffer has been handed + * to the source buffer (consume_all_samples), so `buffered` is current when the + * caller signals update-end. Upstream returned once the bytes were queued in + * appsrc. Must be called without locks the new-sample callback takes. */ +GstFlowReturn +gst_append_pipeline_append (GstAppendPipeline * self, GstBuffer * buffer) +{ + g_return_val_if_fail (GST_IS_APPEND_PIPELINE (self), GST_FLOW_ERROR); + + g_mutex_lock (&self->append_lock); + guint64 ticket = ++self->appends_sent; + g_mutex_unlock (&self->append_lock); + + GstFlowReturn push_result = gst_app_src_push_buffer (self->src, buffer); + if (push_result != GST_FLOW_OK) { + finish_appends (self, FALSE); + return push_result; + } + + if (!gst_element_send_event (GST_ELEMENT_CAST (self->src), + new_end_of_append_event ())) { + GST_ERROR_OBJECT (self, "failed to push end-of-append event"); + finish_appends (self, FALSE); + return GST_FLOW_ERROR; + } + + gint64 deadline = g_get_monotonic_time () + APPEND_TIMEOUT; + g_mutex_lock (&self->append_lock); + while (self->appends_done < ticket) { + if (!g_cond_wait_until (&self->append_cond, &self->append_lock, deadline)) { + GST_WARNING_OBJECT (self, "append %" G_GUINT64_FORMAT " not processed " + "after %" G_GINT64_FORMAT " s, giving up waiting", ticket, + APPEND_TIMEOUT / G_TIME_SPAN_SECOND); + break; + } + } + g_mutex_unlock (&self->append_lock); + return GST_FLOW_OK; +} + +GstFlowReturn +gst_append_pipeline_eos (GstAppendPipeline * self) +{ + g_return_val_if_fail (GST_IS_APPEND_PIPELINE (self), GST_FLOW_ERROR); + return gst_app_src_end_of_stream (self->src); +} + +gboolean +gst_append_pipeline_stop (GstAppendPipeline * self) +{ + g_return_val_if_fail (GST_IS_APPEND_PIPELINE (self), FALSE); + + GstElement *pipeline = GST_ELEMENT (self->pipeline); + + GstStateChangeReturn stopped = + gst_element_set_state (pipeline, GST_STATE_NULL); + if (stopped != GST_STATE_CHANGE_SUCCESS) { + GST_ERROR_OBJECT (self, "failed to stop: %s", + gst_state_change_return_get_name (stopped)); + return FALSE; + } + self->received_init_segment = FALSE; + self->encountered_error = FALSE; + + return TRUE; +} + +gboolean +gst_append_pipeline_reset (GstAppendPipeline * self) +{ + g_return_val_if_fail (GST_IS_APPEND_PIPELINE (self), FALSE); + + GstElement *pipeline = GST_ELEMENT (self->pipeline); + + GstStateChangeReturn stopped = + gst_element_set_state (pipeline, GST_STATE_READY); + if (stopped != GST_STATE_CHANGE_SUCCESS) { + GST_ERROR_OBJECT (self, "failed to stop: %s", + gst_state_change_return_get_name (stopped)); + return FALSE; + } + + background_task_stop (self->task); + + init_segment_finalize (&self->init_segment); + gst_clear_object (&self->streams); + g_array_free (self->tracks, TRUE); + + self->received_init_segment = FALSE; + self->have_outstanding_samples = FALSE; + self->encountered_error = FALSE; + self->tracks = new_tracks_array (); + init_segment_init (&self->init_segment); + + if (!background_task_start (self->task)) { + GST_ERROR_OBJECT (self, "failed to start background task"); + return FALSE; + } + + GstStateChangeReturn started = + gst_element_set_state (pipeline, GST_STATE_PLAYING); + if (started == GST_STATE_CHANGE_SUCCESS) { + return TRUE; + } else { + GST_ERROR_OBJECT (self, "failed to start: %s", + gst_state_change_return_get_name (started)); + return FALSE; + } +} + +gsize +gst_append_pipeline_n_tracks (GstAppendPipeline * self) +{ + g_return_val_if_fail (GST_IS_APPEND_PIPELINE (self), 0); + return n_tracks (self); +} + +gboolean +gst_append_pipeline_has_init_segment (GstAppendPipeline * self) +{ + g_return_val_if_fail (GST_IS_APPEND_PIPELINE (self), FALSE); + return self->received_init_segment; +} + +GstClockTime +gst_append_pipeline_get_duration (GstAppendPipeline * self) +{ + g_return_val_if_fail (GST_IS_APPEND_PIPELINE (self), GST_CLOCK_TIME_NONE); + if (self->received_init_segment) { + return self->init_segment.duration; + } else { + return GST_CLOCK_TIME_NONE; + } +} + +GPtrArray * +gst_append_pipeline_get_audio_tracks (GstAppendPipeline * self) +{ + g_return_val_if_fail (GST_IS_APPEND_PIPELINE (self), NULL); + if (self->received_init_segment) { + return self->init_segment.audio_tracks; + } else { + return NULL; + } +} + +GPtrArray * +gst_append_pipeline_get_text_tracks (GstAppendPipeline * self) +{ + g_return_val_if_fail (GST_IS_APPEND_PIPELINE (self), NULL); + if (self->received_init_segment) { + return self->init_segment.text_tracks; + } else { + return NULL; + } +} + +GPtrArray * +gst_append_pipeline_get_video_tracks (GstAppendPipeline * self) +{ + g_return_val_if_fail (GST_IS_APPEND_PIPELINE (self), NULL); + if (self->received_init_segment) { + return self->init_segment.video_tracks; + } else { + return NULL; + } +} + +gboolean +gst_append_pipeline_get_eos (GstAppendPipeline * self) +{ + g_return_val_if_fail (GST_IS_APPEND_PIPELINE (self), FALSE); + return gst_task_get_state (self->task->task) != GST_TASK_STARTED; +} + +void +gst_append_pipeline_fail (GstAppendPipeline * self) +{ + g_return_if_fail (GST_IS_APPEND_PIPELINE (self)); + gst_bus_post (self->bus, gst_message_new_error (NULL, NULL, NULL)); +} + +gboolean +gst_append_pipeline_get_failed (GstAppendPipeline * self) +{ + g_return_val_if_fail (GST_IS_APPEND_PIPELINE (self), FALSE); + return self->encountered_error; +} diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstmediasource-private.h b/vendor/gst-mse/gst-libs/gst/mse/gstmediasource-private.h new file mode 100644 index 0000000..0b4e1d0 --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstmediasource-private.h @@ -0,0 +1,58 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#pragma once + +#include "gstmediasource.h" +#include "gstmseeventqueue-private.h" + +G_BEGIN_DECLS + +GST_MSE_PRIVATE +gboolean gst_media_source_is_attached (GstMediaSource * self); + +GST_MSE_PRIVATE +void gst_media_source_open (GstMediaSource * self); + +GST_MSE_PRIVATE +GstMseSrc * gst_media_source_get_source_element (GstMediaSource * self); + +GST_MSE_PRIVATE +void gst_media_source_seek (GstMediaSource * self, GstClockTime time); + +struct _GstMediaSource +{ + GstObject parent_instance; + + GstMseSrc *element; + GstMseEventQueue *event_queue; + + GstSourceBufferList *buffers; + GstSourceBufferList *active_buffers; + + GstMediaSourceRange live_seekable_range; + + GstClockTime duration; + GstMediaSourceReadyState ready_state; +}; + +G_END_DECLS diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstmediasource.c b/vendor/gst-mse/gst-libs/gst/mse/gstmediasource.c new file mode 100644 index 0000000..04a817d --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstmediasource.c @@ -0,0 +1,1160 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013 Orange + * Copyright (C) 2013-2017 Apple Inc. All rights reserved. + * Copyright (C) 2014 Sebastian Dröge + * Copyright (C) 2015, 2016 Igalia, S.L + * Copyright (C) 2015, 2016 Metrological Group B.V. + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +/** + * SECTION:gstmediasource + * @title: GstMediaSource + * @short_description: Media Source + * @symbols: + * - GstMediaSource + * + * #GstMediaSource is the entry point into the W3C Media Source API. It offers + * functionality similar to #GstAppSrc for client-side web or JavaScript + * applications decoupling the source of media from its processing and playback. + * + * To interact with a Media Source, connect it to a #GstMseSrc that is in some + * #GstPipeline using gst_media_source_attach(). Then create at least one + * #GstSourceBuffer using gst_media_source_add_source_buffer(). Finally, feed + * some media data to the Source Buffer(s) using + * gst_source_buffer_append_buffer() and play the pipeline. + * + * Since: 1.24 + */ + +/** + * GstMediaSource: + * Since: 1.24 + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include "gstmediasource.h" +#include "gstmediasource-private.h" + +#include "gstmselogging-private.h" +#include "gstmsemediatype-private.h" +#include "gstsourcebuffer-private.h" +#include "gstsourcebufferlist-private.h" + +#include "gstmsesrc.h" +#include "gstmsesrc-private.h" + +G_DEFINE_TYPE (GstMediaSource, gst_media_source, GST_TYPE_OBJECT); +G_DEFINE_QUARK (gst_media_source_error_quark, gst_media_source_error); + +enum +{ + PROP_0, + + PROP_SOURCE_BUFFERS, + PROP_ACTIVE_SOURCE_BUFFERS, + PROP_READY_STATE, + PROP_POSITION, + PROP_DURATION, + + N_PROPS, +}; + +typedef enum +{ + ON_SOURCE_OPEN, + ON_SOURCE_ENDED, + ON_SOURCE_CLOSE, + + N_SIGNALS, +} MediaSourceEvent; + +typedef struct +{ + GstDataQueueItem item; + MediaSourceEvent event; +} MediaSourceEventItem; + +static GParamSpec *properties[N_PROPS]; +static guint signals[N_SIGNALS]; + +#define DEFAULT_READY_STATE GST_MEDIA_SOURCE_READY_STATE_CLOSED +#define DEFAULT_POSITION GST_CLOCK_TIME_NONE +#define DEFAULT_DURATION GST_CLOCK_TIME_NONE + +static void rebuild_active_source_buffers_unlocked (GstMediaSource * self); +static void detach_unlocked (GstMediaSource * self); +static void set_duration_unlocked (GstMediaSource * self, + GstClockTime duration); + +/** + * gst_media_source_is_type_supported: + * @type: (transfer none): A MIME type value + * + * Determines whether the current Media Source configuration can process media + * of the supplied @type. + * + * Returns: `TRUE` when supported, `FALSE` otherwise + * + * Since: 1.24 + */ +gboolean +gst_media_source_is_type_supported (const gchar * type) +{ + gst_mse_init_logging (); + g_return_val_if_fail (type != NULL, FALSE); + + if (g_strcmp0 (type, "") == 0) { + return FALSE; + } + + GstMediaSourceMediaType media_type = GST_MEDIA_SOURCE_MEDIA_TYPE_INIT; + if (!gst_media_source_media_type_parse (&media_type, type)) { + return FALSE; + } + + gboolean supported = gst_media_source_media_type_is_supported (&media_type); + + gst_media_source_media_type_reset (&media_type); + + return supported; +} + +/** + * gst_media_source_new: + * + * Creates a new #GstMediaSource instance. The instance is in the + * %GST_MEDIA_SOURCE_READY_STATE_CLOSED state and is not associated with any + * media player. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-mediasource-constructor) + * + * Returns: (transfer full): a new #GstMediaSource instance + * Since: 1.24 + */ +GstMediaSource * +gst_media_source_new (void) +{ + gst_mse_init_logging (); + return g_object_ref_sink (g_object_new (GST_TYPE_MEDIA_SOURCE, NULL)); +} + +static inline void +empty_buffers (GstMediaSource * self) +{ + for (guint i = 0;; i++) { + GstSourceBuffer *buf = gst_source_buffer_list_index (self->buffers, i); + if (buf == NULL) { + break; + } + gst_object_unparent (GST_OBJECT_CAST (buf)); + gst_object_unref (buf); + } + gst_source_buffer_list_remove_all (self->buffers); +} + +static void +gst_media_source_dispose (GObject * object) +{ + GstMediaSource *self = (GstMediaSource *) object; + + detach_unlocked (self); + + g_clear_object (&self->active_buffers); + + if (self->buffers) { + empty_buffers (self); + } + gst_clear_object (&self->buffers); + + gst_clear_object (&self->event_queue); + + G_OBJECT_CLASS (gst_media_source_parent_class)->dispose (object); +} + +static void +gst_media_source_get_property (GObject * object, guint prop_id, GValue * value, + GParamSpec * pspec) +{ + GstMediaSource *self = GST_MEDIA_SOURCE (object); + + switch (prop_id) { + case PROP_SOURCE_BUFFERS: + g_value_take_object (value, gst_media_source_get_source_buffers (self)); + break; + case PROP_ACTIVE_SOURCE_BUFFERS: + g_value_take_object (value, + gst_media_source_get_active_source_buffers (self)); + break; + case PROP_READY_STATE: + g_value_set_enum (value, gst_media_source_get_ready_state (self)); + break; + case PROP_POSITION: + g_value_set_uint64 (value, gst_media_source_get_position (self)); + break; + case PROP_DURATION: + g_value_set_uint64 (value, gst_media_source_get_duration (self)); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + } +} + +static void +gst_media_source_set_property (GObject * object, guint prop_id, + const GValue * value, GParamSpec * pspec) +{ + GstMediaSource *self = GST_MEDIA_SOURCE (object); + + switch (prop_id) { + case PROP_DURATION:{ + GstClockTime duration = (GstClockTime) g_value_get_uint64 (value); + gst_media_source_set_duration (self, duration, NULL); + break; + } + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + } +} + +static void +gst_media_source_class_init (GstMediaSourceClass * klass) +{ + GObjectClass *oclass = G_OBJECT_CLASS (klass); + + oclass->dispose = GST_DEBUG_FUNCPTR (gst_media_source_dispose); + oclass->get_property = GST_DEBUG_FUNCPTR (gst_media_source_get_property); + oclass->set_property = GST_DEBUG_FUNCPTR (gst_media_source_set_property); + + /** + * GstMediaSource:source-buffers: + * + * A #GstSourceBufferList of every #GstSourceBuffer in this Media Source + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-mediasource-sourcebuffers) + * + * Since: 1.24 + */ + properties[PROP_SOURCE_BUFFERS] = g_param_spec_object ("source-buffers", + "Source Buffers", + "A SourceBufferList of all SourceBuffers in this Media Source", + GST_TYPE_SOURCE_BUFFER_LIST, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS); + + /** + * GstMediaSource:active-source-buffers: + * + * A #GstSourceBufferList of every #GstSourceBuffer in this Media Source that + * is considered active + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-mediasource-activesourcebuffers) + * + * Since: 1.24 + */ + properties[PROP_ACTIVE_SOURCE_BUFFERS] = + g_param_spec_object ("active-source-buffers", "Active Source Buffers", + "A SourceBufferList of all SourceBuffers that are active in this Media Source", + GST_TYPE_SOURCE_BUFFER_LIST, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS); + + /** + * GstMediaSource:ready-state: + * + * The Ready State of the Media Source + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-mediasource-readystate) + * + * Since: 1.24 + */ + properties[PROP_READY_STATE] = g_param_spec_enum ("ready-state", + "Ready State", + "The Ready State of the Media Source", + GST_TYPE_MEDIA_SOURCE_READY_STATE, DEFAULT_READY_STATE, G_PARAM_READABLE | + G_PARAM_STATIC_STRINGS); + + /** + * GstMediaSource:position: + * + * The position of the player consuming from the Media Source + * + * Since: 1.24 + */ + properties[PROP_POSITION] = g_param_spec_uint64 ("position", + "Position", + "The Position of the Media Source as a GstClockTime", + GST_CLOCK_TIME_NONE, G_MAXUINT64, DEFAULT_DURATION, G_PARAM_READWRITE | + G_PARAM_STATIC_STRINGS); + + /** + * GstMediaSource:duration: + * + * The Duration of the Media Source as a #GstClockTime + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-mediasource-duration) + * + * Since: 1.24 + */ + properties[PROP_DURATION] = g_param_spec_uint64 ("duration", + "Duration", + "The Duration of the Media Source as a GstClockTime", + GST_CLOCK_TIME_NONE, G_MAXUINT64, DEFAULT_DURATION, G_PARAM_READWRITE | + G_PARAM_STATIC_STRINGS); + + g_object_class_install_properties (oclass, N_PROPS, properties); + + /** + * GstMediaSource::on-source-open: + * @self: The #GstMediaSource that has just opened + * + * Emitted when @self has been opened. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-mediasource-onsourceopen) + * + * Since: 1.24 + */ + signals[ON_SOURCE_OPEN] = g_signal_new ("on-source-open", + G_TYPE_FROM_CLASS (klass), + G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 0); + + /** + * GstMediaSource::on-source-ended: + * @self: The #GstMediaSource that has just ended + * + * Emitted when @self has ended, normally through + * gst_media_source_end_of_stream(). + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-mediasource-onsourceended) + * + * Since: 1.24 + */ + signals[ON_SOURCE_ENDED] = g_signal_new ("on-source-ended", + G_TYPE_FROM_CLASS (klass), + G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 0); + + /** + * GstMediaSource::on-source-closed: + * @self: The #GstMediaSource that has just closed + * + * Emitted when @self has closed, normally when detached from a #GstMseSrc. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-mediasource-onsourceclose) + * + * Since: 1.24 + */ + signals[ON_SOURCE_CLOSE] = g_signal_new ("on-source-close", + G_TYPE_FROM_CLASS (klass), + G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 0); + +} + +static inline void +reset_live_seekable_range (GstMediaSource * self) +{ + self->live_seekable_range.start = 0; + self->live_seekable_range.end = 0; +} + +static inline gboolean +is_updating (GstMediaSource * self) +{ + for (guint i = 0;; i++) { + GstSourceBuffer *buf = gst_source_buffer_list_index (self->buffers, i); + if (buf == NULL) + break; + gboolean updating = gst_source_buffer_get_updating (buf); + gst_object_unref (buf); + if (updating) { + return TRUE; + } + } + return FALSE; +} + +static inline gboolean +is_attached (GstMediaSource * self) +{ + return GST_IS_MSE_SRC (self->element); +} + +static inline void +network_error (GstMediaSource * self) +{ + if (is_attached (self)) { + gst_mse_src_network_error (self->element); + } +} + +static inline void +decode_error (GstMediaSource * self) +{ + if (is_attached (self)) { + gst_mse_src_decode_error (self->element); + } +} + +static inline void +update_duration (GstMediaSource * self) +{ + if (is_attached (self)) { + gst_mse_src_set_duration (self->element, self->duration); + } +} + +static void +schedule_event (GstMediaSource * self, MediaSourceEvent event) +{ + MediaSourceEventItem item = { + .item = {.destroy = g_free,.visible = TRUE,.size = 1,.object = NULL}, + .event = event, + }; + + gst_mse_event_queue_push (self->event_queue, g_memdup2 (&item, + sizeof (MediaSourceEventItem))); +} + +static void +dispatch_event (MediaSourceEventItem * item, GstMediaSource * self) +{ + g_signal_emit (self, signals[item->event], 0); +} + +static void +gst_media_source_init (GstMediaSource * self) +{ + self->buffers = gst_source_buffer_list_new (); + self->active_buffers = gst_source_buffer_list_new (); + self->ready_state = DEFAULT_READY_STATE; + self->duration = DEFAULT_DURATION; + reset_live_seekable_range (self); + self->element = NULL; + self->event_queue = + gst_mse_event_queue_new ((GstMseEventQueueCallback) dispatch_event, self); +} + +/** + * gst_media_source_attach: + * @self: #GstMediaSource instance + * @element: (transfer none): #GstMseSrc source Element + * + * Associates @self with @element. + * Normally, the Element will be part of a #GstPipeline that plays back the data + * submitted to the Media Source's Source Buffers. + * + * #GstMseSrc is a special source element that is designed to consume media from + * a #GstMediaSource. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dfn-attaching-to-a-media-element) + * + * Since: 1.24 + */ +void +gst_media_source_attach (GstMediaSource * self, GstMseSrc * element) +{ + g_return_if_fail (GST_IS_MEDIA_SOURCE (self)); + g_return_if_fail (GST_IS_MSE_SRC (element)); + + GST_OBJECT_LOCK (self); + if (is_attached (self)) { + detach_unlocked (self); + } + + self->element = gst_object_ref (element); + gst_mse_src_attach (element, self); + + self->ready_state = GST_MEDIA_SOURCE_READY_STATE_OPEN; + GST_OBJECT_UNLOCK (self); + + schedule_event (self, ON_SOURCE_OPEN); +} + +static void +detach_unlocked (GstMediaSource * self) +{ + self->ready_state = GST_MEDIA_SOURCE_READY_STATE_CLOSED; + set_duration_unlocked (self, GST_CLOCK_TIME_NONE); + + gst_source_buffer_list_remove_all (self->active_buffers); + empty_buffers (self); + + if (is_attached (self)) { + gst_mse_src_detach (self->element); + gst_clear_object (&self->element); + } + + schedule_event (self, ON_SOURCE_CLOSE); +} + +/** + * gst_media_source_detach: + * @self: #GstMediaSource instance + * + * Detaches @self from any #GstMseSrc element that it may be associated with. + * + * Since: 1.24 + */ +void +gst_media_source_detach (GstMediaSource * self) +{ + g_return_if_fail (GST_IS_MEDIA_SOURCE (self)); + + GST_OBJECT_LOCK (self); + detach_unlocked (self); + GST_OBJECT_UNLOCK (self); +} + +/** + * gst_media_source_get_source_element: + * @self: #GstMediaSource instance + * + * Gets the #GstMseSrc currently attached to @self or `NULL` if there is none. + * + * Returns: (transfer full) (nullable): a #GstMseSrc instance or `NULL` + */ +GstMseSrc * +gst_media_source_get_source_element (GstMediaSource * self) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE (self), NULL); + GST_OBJECT_LOCK (self); + GstMseSrc *element = self->element == NULL ? NULL + : gst_object_ref (self->element); + GST_OBJECT_UNLOCK (self); + return element; +} + +void +gst_media_source_open (GstMediaSource * self) +{ + g_return_if_fail (GST_IS_MEDIA_SOURCE (self)); + if (self->ready_state != GST_MEDIA_SOURCE_READY_STATE_OPEN) { + self->ready_state = GST_MEDIA_SOURCE_READY_STATE_OPEN; + schedule_event (self, ON_SOURCE_OPEN); + } +} + +/** + * gst_media_source_get_source_buffers: + * @self: #GstMediaSource instance + * + * Gets a #GstSourceBufferList containing all the Source Buffers currently + * associated with this Media Source. This object will reflect any future + * changes to the parent Media Source as well. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-mediasource-sourcebuffers) + * + * Returns: (transfer full): a #GstSourceBufferList instance + * Since: 1.24 + */ +GstSourceBufferList * +gst_media_source_get_source_buffers (GstMediaSource * self) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE (self), NULL); + return g_object_ref (self->buffers); +} + +/** + * gst_media_source_get_active_source_buffers: + * @self: #GstMediaSource instance + * + * Gets a #GstSourceBufferList containing all the Source Buffers currently + * associated with this Media Source that are considered "active." + * For a Source Buffer to be considered active, either its video track is + * selected, its audio track is enabled, or its text track is visible or hidden. + * This object will reflect any future changes to the parent Media Source as + * well. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-mediasource-activesourcebuffers) + * + * Returns: (transfer full): a new #GstSourceBufferList instance + * Since: 1.24 + */ +GstSourceBufferList * +gst_media_source_get_active_source_buffers (GstMediaSource * self) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE (self), NULL); + return g_object_ref (self->active_buffers); +} + +/** + * gst_media_source_get_ready_state: + * @self: #GstMediaSource instance + * + * Gets the current Ready State of the Media Source. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-mediasource-readystate) + * + * Returns: the current #GstMediaSourceReadyState value + * Since: 1.24 + */ +GstMediaSourceReadyState +gst_media_source_get_ready_state (GstMediaSource * self) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE (self), DEFAULT_READY_STATE); + + GST_OBJECT_LOCK (self); + GstMediaSourceReadyState ready_state = self->ready_state; + GST_OBJECT_UNLOCK (self); + + return ready_state; +} + +/** + * gst_media_source_get_position: + * @self: #GstMediaSource instance + * + * Gets the current playback position of the Media Source. + * + * Returns: the current playback position as a #GstClockTime + * Since: 1.24 + */ +GstClockTime +gst_media_source_get_position (GstMediaSource * self) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE (self), DEFAULT_POSITION); + + GST_OBJECT_LOCK (self); + GstClockTime position = + is_attached (self) ? gst_mse_src_get_position (self->element) : + DEFAULT_POSITION; + GST_OBJECT_UNLOCK (self); + + return position; +} + +/** + * gst_media_source_get_duration: + * @self: #GstMediaSource instance + * + * Gets the current duration of @self. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-mediasource-duration) + * + * Returns: the current duration as a #GstClockTime + * Since: 1.24 + */ +GstClockTime +gst_media_source_get_duration (GstMediaSource * self) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE (self), DEFAULT_DURATION); + + GST_OBJECT_LOCK (self); + GstClockTime duration = + self->ready_state == + GST_MEDIA_SOURCE_READY_STATE_CLOSED ? GST_CLOCK_TIME_NONE : + self->duration; + GST_OBJECT_UNLOCK (self); + + return duration; +} + +static void +set_duration_unlocked (GstMediaSource * self, GstClockTime duration) +{ + self->duration = duration; + update_duration (self); +} + +/** + * gst_media_source_set_duration: + * @self: #GstMediaSource instance + * @duration: The new duration to apply to @self. + * @error: (out) (optional) (nullable) (transfer full): the resulting error or `NULL` + * + * Sets the duration of @self. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-mediasource-duration) + * + * Returns: `TRUE` on success, `FALSE` otherwise + * Since: 1.24 + */ +gboolean +gst_media_source_set_duration (GstMediaSource * self, GstClockTime duration, + GError ** error) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE (self), FALSE); + + GST_OBJECT_LOCK (self); + self->duration = duration; + update_duration (self); + GST_OBJECT_UNLOCK (self); + + g_object_notify_by_pspec (G_OBJECT (self), properties[PROP_DURATION]); + return TRUE; +} + +static void +on_received_init_segment (G_GNUC_UNUSED GstSourceBuffer * source_buffer, + gpointer user_data) +{ + GstMediaSource *self = GST_MEDIA_SOURCE (user_data); + + GST_OBJECT_LOCK (self); + + if (!is_attached (self)) { + GST_DEBUG_OBJECT (self, "received init segment while detached, ignoring"); + GST_OBJECT_UNLOCK (self); + return; + } + + GPtrArray *all_tracks = g_ptr_array_new (); + + for (guint i = 0;; i++) { + GstSourceBuffer *buf = gst_source_buffer_list_index (self->buffers, i); + if (buf == NULL) { + break; + } + GPtrArray *tracks = gst_source_buffer_get_all_tracks (buf); + g_ptr_array_extend (all_tracks, tracks, NULL, NULL); + g_ptr_array_unref (tracks); + gst_object_unref (buf); + } + + GST_OBJECT_UNLOCK (self); + + gst_mse_src_emit_streams (self->element, + (GstMediaSourceTrack **) all_tracks->pdata, all_tracks->len); + + g_ptr_array_unref (all_tracks); +} + +static void +on_duration_changed (G_GNUC_UNUSED GstSourceBuffer * source_buffer, + gpointer user_data) +{ + GstMediaSource *self = GST_MEDIA_SOURCE (user_data); + GstClockTime current = self->duration; + GstClockTime max = 0; + for (guint i = 0;; i++) { + GstSourceBuffer *buf = gst_source_buffer_list_index (self->buffers, i); + if (buf == NULL) { + break; + } + GstClockTime duration = gst_source_buffer_get_duration (buf); + if (GST_CLOCK_TIME_IS_VALID (duration)) { + max = MAX (max, duration); + } + gst_object_unref (buf); + } + if (current == max) { + return; + } + GST_DEBUG_OBJECT (self, "updating %" GST_TIMEP_FORMAT "=>%" GST_TIMEP_FORMAT, + ¤t, &max); + gst_media_source_set_duration (self, max, NULL); +} + +static GHashTable * +source_buffer_list_as_set (GstSourceBufferList * list) +{ + GHashTable *buffers = g_hash_table_new_full (g_direct_hash, g_direct_equal, + gst_object_unref, NULL); + for (guint i = 0;; i++) { + GstSourceBuffer *buf = gst_source_buffer_list_index (list, i); + if (buf == NULL) { + break; + } + g_hash_table_add (buffers, buf); + } + return buffers; +} + +static void +rebuild_active_source_buffers_unlocked (GstMediaSource * self) +{ + GST_DEBUG_OBJECT (self, "rebuilding active source buffers"); + GHashTable *previously_active = + source_buffer_list_as_set (self->active_buffers); + + gst_source_buffer_list_notify_freeze (self->active_buffers); + gst_source_buffer_list_remove_all (self->active_buffers); + + gboolean added = FALSE; + gboolean removed = FALSE; + + for (guint i = 0;; i++) { + GstSourceBuffer *buf = gst_source_buffer_list_index (self->buffers, i); + if (buf == NULL) { + break; + } + if (gst_source_buffer_get_active (buf)) { + gst_source_buffer_list_append (self->active_buffers, buf); + added |= !g_hash_table_contains (previously_active, buf); + } else { + gst_source_buffer_list_append (self->active_buffers, buf); + removed |= g_hash_table_contains (previously_active, buf); + } + gst_object_unref (buf); + } + g_hash_table_unref (previously_active); + + gst_source_buffer_list_notify_cancel (self->active_buffers); + gst_source_buffer_list_notify_thaw (self->active_buffers); + + if (added) { + GST_DEBUG_OBJECT (self, "notifying active source buffer added"); + gst_source_buffer_list_notify_added (self->active_buffers); + } + if (removed) { + GST_DEBUG_OBJECT (self, "notifying active source buffer removed"); + gst_source_buffer_list_notify_removed (self->active_buffers); + } +} + +static void +on_active_state_changed (GstSourceBuffer * source_buffer, gpointer user_data) +{ + GstMediaSource *self = GST_MEDIA_SOURCE (user_data); + + GST_OBJECT_LOCK (self); + rebuild_active_source_buffers_unlocked (self); + GST_OBJECT_UNLOCK (self); +} + +/** + * gst_media_source_add_source_buffer: + * @self: #GstMediaSource instance + * @type: (transfer none): A MIME type describing the format of the incoming media + * @error: (out) (optional) (nullable) (transfer full): the resulting error or `NULL` + * + * Add a #GstSourceBuffer to this #GstMediaSource of the specified media type. + * The Media Source must be in the #GstMediaSourceReadyState %GST_MEDIA_SOURCE_READY_STATE_OPEN. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-mediasource-addsourcebuffer) + * + * Returns: (transfer full): a new #GstSourceBuffer instance on success, otherwise `NULL` + * Since: 1.24 + */ +GstSourceBuffer * +gst_media_source_add_source_buffer (GstMediaSource * self, const gchar * type, + GError ** error) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE (self), NULL); + g_return_val_if_fail (type != NULL, NULL); + + if (g_strcmp0 (type, "") == 0) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_TYPE, + "supplied content type is empty"); + return NULL; + } + + if (!gst_media_source_is_type_supported (type)) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_NOT_SUPPORTED, + "unsupported content type"); + return NULL; + } + + GST_OBJECT_LOCK (self); + + if (self->ready_state != GST_MEDIA_SOURCE_READY_STATE_OPEN) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_INVALID_STATE, + "media source is not open"); + goto error; + } + + GstSourceBufferCallbacks callbacks = { + .duration_changed = on_duration_changed, + .received_init_segment = on_received_init_segment, + .active_state_changed = on_active_state_changed, + }; + + GError *source_buffer_error = NULL; + GstSourceBuffer *buf = gst_source_buffer_new_with_callbacks (type, + GST_OBJECT (self), &callbacks, self, &source_buffer_error); + if (source_buffer_error) { + g_propagate_prefixed_error (error, source_buffer_error, + "failed to create source buffer"); + gst_clear_object (&buf); + goto error; + } + + gst_source_buffer_list_append (self->buffers, buf); + + GST_OBJECT_UNLOCK (self); + + return buf; + +error: + GST_OBJECT_UNLOCK (self); + return NULL; +} + +/** + * gst_media_source_remove_source_buffer: + * @self: #GstMediaSource instance + * @buffer: (transfer none): #GstSourceBuffer instance + * @error: (out) (optional) (nullable) (transfer full): the resulting error or `NULL` + * + * Remove @buffer from @self. + * + * @buffer must have been created as a child of @self and @self must be in the + * #GstMediaSourceReadyState %GST_MEDIA_SOURCE_READY_STATE_OPEN. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-mediasource-removesourcebuffer) + * + * Returns: `TRUE` on success, `FALSE` otherwise + * Since: 1.24 + */ +gboolean +gst_media_source_remove_source_buffer (GstMediaSource * self, + GstSourceBuffer * buffer, GError ** error) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE (self), FALSE); + g_return_val_if_fail (GST_IS_SOURCE_BUFFER (buffer), FALSE); + + GST_OBJECT_LOCK (self); + + if (!gst_source_buffer_list_contains (self->buffers, buffer)) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_NOT_FOUND, + "the supplied source buffer was not found in this media source"); + goto error; + } + + if (gst_source_buffer_get_updating (buffer)) + gst_source_buffer_teardown (buffer); + + gst_source_buffer_list_remove (self->active_buffers, buffer); + + gst_object_unparent (GST_OBJECT (buffer)); + gst_source_buffer_list_remove (self->buffers, buffer); + + GST_OBJECT_UNLOCK (self); + + return TRUE; + +error: + GST_OBJECT_UNLOCK (self); + return FALSE; +} + +static void +abort_all_source_buffers (GstMediaSource * self) +{ + for (guint i = 0;; i++) { + GstSourceBuffer *buf = gst_source_buffer_list_index (self->buffers, i); + if (buf == NULL) { + return; + } + GST_LOG_OBJECT (self, "shutting down %" GST_PTR_FORMAT, buf); + gst_source_buffer_abort (buf, NULL); + gst_object_unref (buf); + } +} + +/** + * gst_media_source_end_of_stream: + * @self: #GstMediaSource instance + * @eos_error: The error type, if any + * @error: (out) (optional) (nullable) (transfer full): the resulting error or `NULL` + * + * Mark @self as reaching the end of stream, disallowing new data inputs. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-mediasource-endofstream) + * + * Returns: `TRUE` on success, `FALSE` otherwise + * Since: 1.24 + */ +gboolean +gst_media_source_end_of_stream (GstMediaSource * self, + GstMediaSourceEOSError eos_error, GError ** error) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE (self), FALSE); + + GST_OBJECT_LOCK (self); + + if (self->ready_state != GST_MEDIA_SOURCE_READY_STATE_OPEN) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_INVALID_STATE, + "media source is not open"); + goto error; + } + + if (is_updating (self)) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_INVALID_STATE, + "some buffers are still updating"); + goto error; + } + + self->ready_state = GST_MEDIA_SOURCE_READY_STATE_ENDED; + schedule_event (self, ON_SOURCE_ENDED); + + GST_OBJECT_UNLOCK (self); + + switch (eos_error) { + case GST_MEDIA_SOURCE_EOS_ERROR_NETWORK: + network_error (self); + break; + case GST_MEDIA_SOURCE_EOS_ERROR_DECODE: + decode_error (self); + break; + default: + update_duration (self); + abort_all_source_buffers (self); + break; + } + + return TRUE; + +error: + GST_OBJECT_UNLOCK (self); + return FALSE; +} + +/** + * gst_media_source_set_live_seekable_range: + * @self: #GstMediaSource instance + * @start: The earliest point in the stream considered seekable + * @end: The latest point in the stream considered seekable + * @error: (out) (optional) (nullable) (transfer full): the resulting error or `NULL` + * + * Set the live seekable range for @self. This range informs the component + * playing this Media Source what it can allow the user to seek through. + * + * If the ready state is not %GST_MEDIA_SOURCE_READY_STATE_OPEN, or the supplied + * @start time is later than @end it will fail and set an error. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-mediasource-setliveseekablerange) + * + * Returns: `TRUE` on success, `FALSE` otherwise + * Since: 1.24 + */ +gboolean +gst_media_source_set_live_seekable_range (GstMediaSource * self, + GstClockTime start, GstClockTime end, GError ** error) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE (self), FALSE); + + GST_OBJECT_LOCK (self); + + if (self->ready_state != GST_MEDIA_SOURCE_READY_STATE_OPEN) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_INVALID_STATE, + "media source is not open"); + goto error; + } + + if (start > end) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_TYPE, + "bad time range: start must be earlier than end"); + goto error; + } + + self->live_seekable_range.start = start; + self->live_seekable_range.end = end; + + GST_OBJECT_UNLOCK (self); + + return TRUE; + +error: + GST_OBJECT_UNLOCK (self); + return FALSE; +} + +/** + * gst_media_source_clear_live_seekable_range: + * @self: #GstMediaSource instance + * @error: (out) (optional) (nullable) (transfer full): the resulting error or `NULL` + * + * Clear the live seekable range for @self. This will inform the component + * playing this Media Source that there is no seekable time range. + * + * If the ready state is not %GST_MEDIA_SOURCE_READY_STATE_OPEN, it will fail + * and set an error. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-mediasource-clearliveseekablerange) + * + * Returns: `TRUE` on success, `FALSE` otherwise + * Since: 1.24 + */ +gboolean +gst_media_source_clear_live_seekable_range (GstMediaSource * self, + GError ** error) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE (self), FALSE); + + GST_OBJECT_LOCK (self); + + if (self->ready_state != GST_MEDIA_SOURCE_READY_STATE_OPEN) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_INVALID_STATE, + "media source is not open"); + goto error; + } + + reset_live_seekable_range (self); + + GST_OBJECT_UNLOCK (self); + + return TRUE; + +error: + GST_OBJECT_UNLOCK (self); + return FALSE; +} + +/** + * gst_media_source_get_live_seekable_range: + * @self: #GstMediaSource instance + * @range: (out caller-allocates) (transfer none): time range + * + * Get the live seekable range of @self. Will fill in the supplied @range with + * the current live seekable range. + * + * Since: 1.24 + */ +void +gst_media_source_get_live_seekable_range (GstMediaSource * self, + GstMediaSourceRange * range) +{ + g_return_if_fail (GST_IS_MEDIA_SOURCE (self)); + g_return_if_fail (range != NULL); + + GST_OBJECT_LOCK (self); + range->start = self->live_seekable_range.start; + range->end = self->live_seekable_range.end; + GST_OBJECT_UNLOCK (self); +} + +void +gst_media_source_seek (GstMediaSource * self, GstClockTime time) +{ + g_return_if_fail (GST_IS_MEDIA_SOURCE (self)); + + GST_OBJECT_LOCK (self); + for (guint i = 0;; i++) { + GstSourceBuffer *buf = gst_source_buffer_list_index (self->buffers, i); + if (buf == NULL) { + goto done; + } + gst_source_buffer_seek (buf, time); + gst_object_unref (buf); + } +done: + GST_OBJECT_UNLOCK (self); +} diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstmediasource.h b/vendor/gst-mse/gst-libs/gst/mse/gstmediasource.h new file mode 100644 index 0000000..15df96e --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstmediasource.h @@ -0,0 +1,203 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013 Orange + * Copyright (C) 2013-2017 Apple Inc. All rights reserved. + * Copyright (C) 2014 Sebastian Dröge + * Copyright (C) 2015, 2016 Igalia, S.L + * Copyright (C) 2015, 2016 Metrological Group B.V. + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#pragma once + +#include +#include +#include + +#include "gstsourcebufferlist.h" + +G_BEGIN_DECLS + +/** + * GstMediaSourceReadyState: + * @GST_MEDIA_SOURCE_READY_STATE_CLOSED: The #GstMediaSource is not connected to + * any playback element. + * @GST_MEDIA_SOURCE_READY_STATE_OPEN: The #GstMediaSource is connected to a + * playback element and ready to append data to its #GstSourceBuffer (s). + * @GST_MEDIA_SOURCE_READY_STATE_ENDED: gst_media_source_end_of_stream() has + * been called on the current #GstMediaSource + * + * Describes the possible states of the Media Source. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-readystate) + * + * Since: 1.24 + */ +typedef enum +{ + GST_MEDIA_SOURCE_READY_STATE_CLOSED, + GST_MEDIA_SOURCE_READY_STATE_OPEN, + GST_MEDIA_SOURCE_READY_STATE_ENDED, +} GstMediaSourceReadyState; + +/** + * GstMediaSourceError: + * @GST_MEDIA_SOURCE_ERROR_INVALID_STATE: + * @GST_MEDIA_SOURCE_ERROR_TYPE: + * @GST_MEDIA_SOURCE_ERROR_NOT_SUPPORTED: + * @GST_MEDIA_SOURCE_ERROR_NOT_FOUND: + * @GST_MEDIA_SOURCE_ERROR_QUOTA_EXCEEDED: + * + * Any error that can occur within #GstMediaSource or #GstSourceBuffer APIs. + * These values correspond directly to those in the Web IDL specification. + * + * [Specification](https://webidl.spec.whatwg.org/#idl-DOMException-error-names) + * + * Since: 1.24 + */ +typedef enum +{ + GST_MEDIA_SOURCE_ERROR_INVALID_STATE, + GST_MEDIA_SOURCE_ERROR_TYPE, + GST_MEDIA_SOURCE_ERROR_NOT_SUPPORTED, + GST_MEDIA_SOURCE_ERROR_NOT_FOUND, + GST_MEDIA_SOURCE_ERROR_QUOTA_EXCEEDED, +} GstMediaSourceError; + +/** + * GstMediaSourceEOSError: + * @GST_MEDIA_SOURCE_EOS_ERROR_NONE: End the stream successfully + * @GST_MEDIA_SOURCE_EOS_ERROR_NETWORK: End the stream due to a networking error + * @GST_MEDIA_SOURCE_EOS_ERROR_DECODE: End the stream due to a decoding error + * + * Reasons for ending a #GstMediaSource using gst_media_source_end_of_stream(). + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-endofstreamerror) + * + * Since: 1.24 + */ +typedef enum +{ + GST_MEDIA_SOURCE_EOS_ERROR_NONE, + GST_MEDIA_SOURCE_EOS_ERROR_NETWORK, + GST_MEDIA_SOURCE_EOS_ERROR_DECODE, +} GstMediaSourceEOSError; + +/** + * GstMediaSourceRange: + * @start: The start of this range. + * @end: The end of this range. + * + * A structure describing a simplified version of the TimeRanges concept in the + * HTML specification, only representing a single @start and @end time. + * + * [Specification](https://html.spec.whatwg.org/multipage/media.html#timeranges) + * + * Since: 1.24 + */ +typedef struct +{ + GstClockTime start; + GstClockTime end; +} GstMediaSourceRange; + +GST_MSE_API +gboolean gst_media_source_is_type_supported (const gchar * type); + +#define GST_TYPE_MEDIA_SOURCE (gst_media_source_get_type()) +#define GST_MEDIA_SOURCE_ERROR (gst_media_source_error_quark()) + +/** + * gst_media_source_error_quark: + * + * Any error type that can be reported by the Media Source API. + * + * Since: 1.24 + */ +GST_MSE_API +GQuark gst_media_source_error_quark (void); + +GST_MSE_API +G_DECLARE_FINAL_TYPE (GstMediaSource, gst_media_source, GST, MEDIA_SOURCE, + GstObject); + +GST_MSE_API +GstMediaSource *gst_media_source_new (void) G_GNUC_WARN_UNUSED_RESULT; + +GST_MSE_API +void gst_media_source_attach (GstMediaSource * self, GstMseSrc * element); + +GST_MSE_API +void gst_media_source_detach (GstMediaSource * self); + +GST_MSE_API +GstSourceBufferList * gst_media_source_get_source_buffers ( + GstMediaSource * self) G_GNUC_WARN_UNUSED_RESULT; + +GST_MSE_API +GstSourceBufferList * gst_media_source_get_active_source_buffers ( + GstMediaSource * self) G_GNUC_WARN_UNUSED_RESULT; + +GST_MSE_API +GstMediaSourceReadyState gst_media_source_get_ready_state ( + GstMediaSource * self); + +GST_MSE_API +GstClockTime gst_media_source_get_position (GstMediaSource * self); + +GST_MSE_API +GstClockTime gst_media_source_get_duration (GstMediaSource * self); + +GST_MSE_API +gboolean gst_media_source_set_duration (GstMediaSource * self, + GstClockTime duration, + GError ** error); + +GST_MSE_API +GstSourceBuffer * gst_media_source_add_source_buffer (GstMediaSource * self, + const gchar * type, + GError ** error) G_GNUC_WARN_UNUSED_RESULT; + +GST_MSE_API +gboolean gst_media_source_remove_source_buffer (GstMediaSource * self, + GstSourceBuffer * buffer, + GError ** error); + +GST_MSE_API +gboolean gst_media_source_end_of_stream (GstMediaSource * self, + GstMediaSourceEOSError eos_error, + GError ** error); + +GST_MSE_API +gboolean gst_media_source_set_live_seekable_range (GstMediaSource * self, + GstClockTime start, + GstClockTime end, + GError ** error); + +GST_MSE_API +gboolean gst_media_source_clear_live_seekable_range (GstMediaSource * self, + GError ** error); + +GST_MSE_API +void gst_media_source_get_live_seekable_range (GstMediaSource * self, + GstMediaSourceRange * range); + +G_END_DECLS diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstmediasourcesamplemap-private.h b/vendor/gst-mse/gst-libs/gst/mse/gstmediasourcesamplemap-private.h new file mode 100644 index 0000000..096d0ce --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstmediasourcesamplemap-private.h @@ -0,0 +1,108 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#pragma once + +#include +#include + +G_BEGIN_DECLS + +#define GST_TYPE_MEDIA_SOURCE_SAMPLE_MAP \ + (gst_media_source_sample_map_get_type()) + +#define GST_TYPE_MEDIA_SOURCE_CODED_FRAME_GROUP \ + (gst_media_source_coded_frame_group_get_type()) + +#define gst_value_get_media_source_coded_frame_group(v) \ + (GstMediaSourceCodedFrameGroup *)(g_value_get_boxed (v)) + +#define gst_value_take_media_source_coded_frame_group(v, g) \ + g_value_take_boxed ((v), (g)) + +typedef struct { + GstClockTime start; + GstClockTime end; + gsize size; + GList *samples; +} GstMediaSourceCodedFrameGroup; + +GST_MSE_PRIVATE +G_DECLARE_FINAL_TYPE (GstMediaSourceSampleMap, gst_media_source_sample_map, GST, + MEDIA_SOURCE_SAMPLE_MAP, GstObject); + +GST_MSE_PRIVATE +GstMediaSourceSampleMap *gst_media_source_sample_map_new (void); + +GST_MSE_PRIVATE +void gst_media_source_sample_map_add (GstMediaSourceSampleMap * self, + GstSample * sample); + +GST_MSE_PRIVATE +void gst_media_source_sample_map_remove (GstMediaSourceSampleMap * self, + GstSample * sample); + +GST_MSE_PRIVATE +gsize gst_media_source_sample_map_remove_range (GstMediaSourceSampleMap * self, + GstClockTime earliest, GstClockTime latest); + +GST_MSE_PRIVATE +gboolean gst_media_source_sample_map_contains (GstMediaSourceSampleMap * self, + GstSample * sample); + +GST_MSE_PRIVATE +GSequenceIter * gst_media_source_sample_map_get_begin_iter_by_pts ( + GstMediaSourceSampleMap * self); + +GST_MSE_PRIVATE +GstClockTime gst_media_source_sample_map_get_highest_end_time ( + GstMediaSourceSampleMap * self); + +GST_MSE_PRIVATE +guint gst_media_source_sample_map_get_size (GstMediaSourceSampleMap * self); + +GST_MSE_PRIVATE +gsize gst_media_source_sample_map_get_storage_size ( + GstMediaSourceSampleMap * self); + +GST_MSE_PRIVATE +GstIterator * +gst_media_source_sample_map_iter_samples_by_dts (GstMediaSourceSampleMap * self, + GMutex * lock, guint32 * master_cookie); + +GST_MSE_PRIVATE +GstIterator * +gst_media_source_sample_map_iter_samples_by_pts (GstMediaSourceSampleMap * self, + GMutex * lock, guint32 * master_cookie); + +GST_MSE_PRIVATE +GType gst_media_source_coded_frame_group_get_type (void); + +GST_MSE_PRIVATE +GstMediaSourceCodedFrameGroup * +gst_media_source_coded_frame_group_copy (GstMediaSourceCodedFrameGroup * group); + +GST_MSE_PRIVATE +void +gst_media_source_coded_frame_group_free (GstMediaSourceCodedFrameGroup * group); + +G_END_DECLS diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstmediasourcesamplemap.c b/vendor/gst-mse/gst-libs/gst/mse/gstmediasourcesamplemap.c new file mode 100644 index 0000000..3047c2d --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstmediasourcesamplemap.c @@ -0,0 +1,552 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "gstmediasourcesamplemap-private.h" +#include "gstmselogging-private.h" + +G_DEFINE_BOXED_TYPE (GstMediaSourceCodedFrameGroup, + gst_media_source_coded_frame_group, + gst_media_source_coded_frame_group_copy, + gst_media_source_coded_frame_group_free); + +#define TIME_RANGE_FORMAT \ + "[%" GST_TIMEP_FORMAT "..%" GST_TIMEP_FORMAT ")" +#define TIME_RANGE_ARGS(a, b) &(a), &(b) +#define CODED_FRAME_GROUP_ARGS(g) TIME_RANGE_ARGS ((g)->start, (g)->end) + +struct _GstMediaSourceSampleMap +{ + GstObject parent_instance; + + GHashTable *samples; + GSequence *samples_by_dts; + GSequence *samples_by_pts; + + gsize storage_size; +}; + +G_DEFINE_TYPE (GstMediaSourceSampleMap, gst_media_source_sample_map, + GST_TYPE_OBJECT); + +static GstMediaSourceCodedFrameGroup *new_coded_frame_group_from_memory (const + GstMediaSourceCodedFrameGroup * src); +static gint compare_pts (GstSample * a, GstSample * b, gpointer user_data); +static GSequenceIter *next_coded_frame_group (GSequenceIter * it, GValue * val); + +static inline GstClockTime +sample_duration (GstSample * sample) +{ + return GST_BUFFER_DURATION (gst_sample_get_buffer (sample)); +} + +static inline GstClockTime +sample_dts (GstSample * sample) +{ + return GST_BUFFER_DTS (gst_sample_get_buffer (sample)); +} + +static inline GstClockTime +sample_dts_end (GstSample * sample) +{ + return sample_dts (sample) + sample_duration (sample); +} + +static inline GstClockTime +sample_pts (GstSample * sample) +{ + return GST_BUFFER_PTS (gst_sample_get_buffer (sample)); +} + +static gsize +sample_buffer_size (GstSample * sample) +{ + return gst_buffer_get_size (gst_sample_get_buffer (sample)); +} + +static inline gboolean +sample_is_key_unit (GstSample * sample) +{ + GstBuffer *buffer = gst_sample_get_buffer (sample); + return !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT); +} + +static gint +compare_dts (GstSample * a, GstSample * b, gpointer user_data) +{ + GstClockTime a_dts = sample_dts (a); + GstClockTime b_dts = sample_dts (b); + if (a_dts == b_dts) { + return compare_pts (a, b, user_data); + } + return a_dts > b_dts ? +1 : -1; +} + +static gint +compare_pts (GstSample * a, GstSample * b, gpointer user_data) +{ + GstClockTime a_pts = sample_pts (a); + GstClockTime b_pts = sample_pts (b); + if (a_pts == b_pts) { + return 0; + } + return a_pts > b_pts ? +1 : -1; +} + +static inline void +remove_sample (GSequence * sequence, GCompareDataFunc compare, + GstSample * sample, GstMediaSourceSampleMap * self) +{ + GSequenceIter *match = g_sequence_lookup (sequence, sample, compare, self); + if (match == NULL) { + return; + } + g_sequence_remove (match); +} + +GstMediaSourceSampleMap * +gst_media_source_sample_map_new (void) +{ + gst_mse_init_logging (); + return gst_object_ref_sink (g_object_new (GST_TYPE_MEDIA_SOURCE_SAMPLE_MAP, + NULL)); +} + +static void +gst_media_source_sample_map_finalize (GObject * object) +{ + GstMediaSourceSampleMap *self = GST_MEDIA_SOURCE_SAMPLE_MAP (object); + g_sequence_free (self->samples_by_dts); + g_sequence_free (self->samples_by_pts); + g_hash_table_unref (self->samples); + G_OBJECT_CLASS (gst_media_source_sample_map_parent_class)->finalize (object); +} + +static void +gst_media_source_sample_map_class_init (GstMediaSourceSampleMapClass * klass) +{ + GObjectClass *oclass = G_OBJECT_CLASS (klass); + + oclass->finalize = GST_DEBUG_FUNCPTR (gst_media_source_sample_map_finalize); +} + +static void +gst_media_source_sample_map_init (GstMediaSourceSampleMap * self) +{ + self->samples = g_hash_table_new_full (g_direct_hash, g_direct_equal, + (GDestroyNotify) gst_sample_unref, NULL); + self->samples_by_dts = g_sequence_new ((GDestroyNotify) gst_sample_unref); + self->samples_by_pts = g_sequence_new ((GDestroyNotify) gst_sample_unref); +} + +void +gst_media_source_sample_map_add (GstMediaSourceSampleMap * self, + GstSample * sample) +{ + g_return_if_fail (GST_IS_MEDIA_SOURCE_SAMPLE_MAP (self)); + g_return_if_fail (GST_IS_SAMPLE (sample)); + GstBuffer *buffer = gst_sample_get_buffer (sample); + g_return_if_fail (GST_BUFFER_DTS_IS_VALID (buffer)); + g_return_if_fail (GST_BUFFER_PTS_IS_VALID (buffer)); + g_return_if_fail (GST_BUFFER_DURATION_IS_VALID (buffer)); + + if (g_hash_table_contains (self->samples, sample)) { + return; + } + + g_hash_table_add (self->samples, gst_sample_ref (sample)); + g_sequence_insert_sorted (self->samples_by_dts, gst_sample_ref (sample), + (GCompareDataFunc) compare_dts, self); + g_sequence_insert_sorted (self->samples_by_pts, gst_sample_ref (sample), + (GCompareDataFunc) compare_pts, self); + self->storage_size += gst_buffer_get_size (buffer); + GST_TRACE_OBJECT (self, "new storage size=%" G_GSIZE_FORMAT, + self->storage_size); +} + +void +gst_media_source_sample_map_remove (GstMediaSourceSampleMap * self, + GstSample * sample) +{ + g_return_if_fail (GST_IS_MEDIA_SOURCE_SAMPLE_MAP (self)); + g_return_if_fail (GST_IS_SAMPLE (sample)); + + if (!g_hash_table_contains (self->samples, sample)) { + return; + } + + gsize buffer_size = sample_buffer_size (sample); + remove_sample (self->samples_by_dts, (GCompareDataFunc) compare_dts, sample, + self); + remove_sample (self->samples_by_pts, (GCompareDataFunc) compare_pts, sample, + self); + g_hash_table_remove (self->samples, sample); + self->storage_size -= MIN (buffer_size, self->storage_size); +} + +gboolean +gst_media_source_sample_map_contains (GstMediaSourceSampleMap * self, + GstSample * sample) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE_SAMPLE_MAP (self), FALSE); + return g_hash_table_contains (self->samples, sample); +} + +static GSequenceIter * +next_key_unit (GSequenceIter * it) +{ + for (; !g_sequence_iter_is_end (it); it = g_sequence_iter_next (it)) { + GstSample *sample = g_sequence_get (it); + if (sample_is_key_unit (sample)) { + break; + } + } + return it; +} + +static GSequenceIter * +next_coded_frame_group (GSequenceIter * it, GValue * val) +{ + it = next_key_unit (it); + if (g_sequence_iter_is_end (it)) { + return it; + } + GstSample *head = g_sequence_get (it); + g_return_val_if_fail (sample_is_key_unit (head), NULL); + GstMediaSourceCodedFrameGroup group = { + .start = sample_dts (head), + .end = sample_dts_end (head), + .samples = g_list_prepend (NULL, gst_sample_ref (head)), + .size = 1, + }; + it = g_sequence_iter_next (it); + for (; !g_sequence_iter_is_end (it); it = g_sequence_iter_next (it)) { + GstSample *sample = g_sequence_get (it); + if (sample_is_key_unit (sample)) { + goto done; + } + group.end = sample_dts_end (sample), group.size++; + group.samples = g_list_prepend (group.samples, gst_sample_ref (sample)); + } +done: + group.samples = g_list_reverse (group.samples); + GstMediaSourceCodedFrameGroup *box = + new_coded_frame_group_from_memory (&group); + gst_value_take_media_source_coded_frame_group (val, box); + return it; +} + +static GSequenceIter * +find_start_point (GstMediaSourceSampleMap * self, GSequenceIter * it, + GList ** to_remove, GstClockTime earliest, GstClockTime latest) +{ + while (TRUE) { + GValue value = G_VALUE_INIT; + g_value_init (&value, GST_TYPE_MEDIA_SOURCE_CODED_FRAME_GROUP); + it = next_coded_frame_group (it, &value); + GstMediaSourceCodedFrameGroup *group = + gst_value_get_media_source_coded_frame_group (&value); + if (group == NULL) { + GST_TRACE_OBJECT (self, + "reached end of coded frames before finding start point"); + goto done; + } + + if (group->start >= earliest && group->end <= latest) { + GST_TRACE_OBJECT (self, "found start point for %" GST_TIMEP_FORMAT ": " + TIME_RANGE_FORMAT, &earliest, CODED_FRAME_GROUP_ARGS (group)); + *to_remove = g_list_prepend (*to_remove, + gst_media_source_coded_frame_group_copy (group)); + goto done; + } + + g_value_unset (&value); + continue; + done: + g_value_unset (&value); + return it; + } + return it; +} + +static GSequenceIter * +find_end_point (GstMediaSourceSampleMap * self, GSequenceIter * it, GList ** + to_remove, GstClockTime latest) +{ + while (TRUE) { + GValue value = G_VALUE_INIT; + g_value_init (&value, GST_TYPE_MEDIA_SOURCE_CODED_FRAME_GROUP); + it = next_coded_frame_group (it, &value); + GstMediaSourceCodedFrameGroup *group = + gst_value_get_media_source_coded_frame_group (&value); + if (group == NULL) { + GST_TRACE_OBJECT (self, + "reached end of coded frames before finding end point"); + goto done; + } + if (group->end >= latest) { + GST_TRACE_OBJECT (self, "found end point for %" GST_TIMEP_FORMAT ": " + TIME_RANGE_FORMAT, &latest, CODED_FRAME_GROUP_ARGS (group)); + goto done; + } + *to_remove = g_list_prepend (*to_remove, + gst_media_source_coded_frame_group_copy (group)); + g_value_unset (&value); + continue; + + done: + g_value_unset (&value); + return it; + } + return it; +} + +gsize +gst_media_source_sample_map_remove_range (GstMediaSourceSampleMap * self, + GstClockTime earliest, GstClockTime latest) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE_SAMPLE_MAP (self), 0); + g_return_val_if_fail (earliest <= latest, 0); + + GST_TRACE_OBJECT (self, "request remove range " TIME_RANGE_FORMAT, + TIME_RANGE_ARGS (earliest, latest)); + + GSequenceIter *it = g_sequence_get_begin_iter (self->samples_by_dts); + + GList *to_remove = NULL; + + it = find_start_point (self, it, &to_remove, earliest, latest); + + if (to_remove == NULL) { + return 0; + } + + it = find_end_point (self, it, &to_remove, latest); + + to_remove = g_list_reverse (to_remove); + + gsize bytes_removed = 0; + for (GList * group_iter = to_remove; group_iter != NULL; + group_iter = g_list_next (group_iter)) { + GstMediaSourceCodedFrameGroup *group = group_iter->data; + for (GList * sample_iter = group->samples; sample_iter != NULL; + sample_iter = g_list_next (sample_iter)) { + GstSample *sample = sample_iter->data; + bytes_removed += sample_buffer_size (sample); + gst_media_source_sample_map_remove (self, sample); + } + } + + g_list_free_full (to_remove, + (GDestroyNotify) gst_media_source_coded_frame_group_free); + + GST_TRACE_OBJECT (self, "removed=%" G_GSIZE_FORMAT "B, latest=%" + GST_TIMEP_FORMAT, bytes_removed, &latest); + return bytes_removed; +} + +GstClockTime +gst_media_source_sample_map_get_highest_end_time (GstMediaSourceSampleMap * + self) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE_SAMPLE_MAP (self), + GST_CLOCK_TIME_NONE); + GSequenceIter *iter = g_sequence_get_end_iter (self->samples_by_pts); + iter = g_sequence_iter_prev (iter); + if (g_sequence_iter_is_begin (iter)) { + return GST_CLOCK_TIME_NONE; + } + GstSample *sample = g_sequence_get (iter); + GstBuffer *buffer = gst_sample_get_buffer (sample); + g_return_val_if_fail (GST_BUFFER_PTS_IS_VALID (buffer), GST_CLOCK_TIME_NONE); + g_return_val_if_fail (GST_BUFFER_DURATION_IS_VALID (buffer), + GST_CLOCK_TIME_NONE); + return GST_BUFFER_PTS (buffer) + GST_BUFFER_DURATION (buffer); +} + +guint +gst_media_source_sample_map_get_size (GstMediaSourceSampleMap * self) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE_SAMPLE_MAP (self), 0); + return g_hash_table_size (self->samples); +} + +gsize +gst_media_source_sample_map_get_storage_size (GstMediaSourceSampleMap * self) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE_SAMPLE_MAP (self), 0); + return self->storage_size; +} + +typedef struct _SampleMapIterator SampleMapIterator; + +struct _SampleMapIterator +{ + GstIterator iterator; + GstMediaSourceSampleMap *map; + GSequenceIter *(*reset_func) (SampleMapIterator *); + + GSequenceIter *current_iter; +}; + +static void +iter_copy (const SampleMapIterator * it, SampleMapIterator * copy) +{ + copy->map = gst_object_ref (it->map); + copy->reset_func = it->reset_func; + + copy->current_iter = it->current_iter; +} + +static GSequenceIter * +iter_reset_by_dts (SampleMapIterator * it) +{ + return g_sequence_get_begin_iter (it->map->samples_by_dts); +} + +static GSequenceIter * +iter_reset_by_pts (SampleMapIterator * it) +{ + return g_sequence_get_begin_iter (it->map->samples_by_pts); +} + +static GstIteratorResult +iter_next_sample (SampleMapIterator * it, GValue * result) +{ + + if (g_sequence_iter_is_end (it->current_iter)) { + return GST_ITERATOR_DONE; + } + + GstSample *sample = g_sequence_get (it->current_iter); + + it->current_iter = g_sequence_iter_next (it->current_iter); + + gst_value_set_sample (result, sample); + + return GST_ITERATOR_OK; +} + +static GstIteratorResult +iter_next_group (SampleMapIterator * it, GValue * result) +{ + if (g_sequence_iter_is_end (it->current_iter)) { + return GST_ITERATOR_DONE; + } + + it->current_iter = next_coded_frame_group (it->current_iter, result); + + return GST_ITERATOR_OK; +} + +static void +iter_resync (SampleMapIterator * it) +{ + GST_TRACE_OBJECT (it->map, "resync"); + it->current_iter = it->reset_func (it); +} + +static void +iter_free (SampleMapIterator * it) +{ + gst_clear_object (&it->map); +} + +GstIterator * +gst_media_source_sample_map_iter_samples_by_dts (GstMediaSourceSampleMap * self, + GMutex * lock, guint32 * master_cookie) +{ +/* *INDENT-OFF* */ + SampleMapIterator *it = (SampleMapIterator *) gst_iterator_new ( + sizeof (SampleMapIterator), + GST_TYPE_MEDIA_SOURCE_CODED_FRAME_GROUP, + lock, + master_cookie, + (GstIteratorCopyFunction) iter_copy, + (GstIteratorNextFunction) iter_next_group, + (GstIteratorItemFunction) NULL, + (GstIteratorResyncFunction) iter_resync, + (GstIteratorFreeFunction) iter_free + ); +/* *INDENT-ON* */ + + it->map = gst_object_ref (self); + it->reset_func = iter_reset_by_dts; + it->current_iter = iter_reset_by_dts (it); + + return GST_ITERATOR (it); +} + +GstIterator * +gst_media_source_sample_map_iter_samples_by_pts (GstMediaSourceSampleMap * self, + GMutex * lock, guint32 * master_cookie) +{ +/* *INDENT-OFF* */ + SampleMapIterator *it = (SampleMapIterator *) gst_iterator_new ( + sizeof (SampleMapIterator), + GST_TYPE_SAMPLE, + lock, + master_cookie, + (GstIteratorCopyFunction) iter_copy, + (GstIteratorNextFunction) iter_next_sample, + (GstIteratorItemFunction) NULL, + (GstIteratorResyncFunction) iter_resync, + (GstIteratorFreeFunction) iter_free + ); +/* *INDENT-ON* */ + + it->map = gst_object_ref (self); + it->reset_func = iter_reset_by_pts; + it->current_iter = iter_reset_by_pts (it); + + return GST_ITERATOR (it); +} + +static GstMediaSourceCodedFrameGroup * +new_coded_frame_group_from_memory (const GstMediaSourceCodedFrameGroup * src) +{ + GstMediaSourceCodedFrameGroup *box = + g_atomic_rc_box_new0 (GstMediaSourceCodedFrameGroup); + memcpy (box, src, sizeof (GstMediaSourceCodedFrameGroup)); + return box; +} + +GstMediaSourceCodedFrameGroup * +gst_media_source_coded_frame_group_copy (GstMediaSourceCodedFrameGroup * self) +{ + return g_atomic_rc_box_acquire (self); +} + +static void +free_group_inner (GstMediaSourceCodedFrameGroup * self) +{ + g_list_free_full (self->samples, (GDestroyNotify) gst_sample_unref); +} + +void +gst_media_source_coded_frame_group_free (GstMediaSourceCodedFrameGroup * self) +{ + g_atomic_rc_box_release_full (self, (GDestroyNotify) free_group_inner); +} diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstmediasourcetrack-private.h b/vendor/gst-mse/gst-libs/gst/mse/gstmediasourcetrack-private.h new file mode 100644 index 0000000..a83e6f1 --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstmediasourcetrack-private.h @@ -0,0 +1,106 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#pragma once + +#include +#include + +G_BEGIN_DECLS + +typedef enum +{ + GST_MEDIA_SOURCE_TRACK_TYPE_AUDIO, + GST_MEDIA_SOURCE_TRACK_TYPE_VIDEO, + GST_MEDIA_SOURCE_TRACK_TYPE_TEXT, + GST_MEDIA_SOURCE_TRACK_TYPE_OTHER, +} GstMediaSourceTrackType; + +#define GST_TYPE_MEDIA_SOURCE_TRACK (gst_media_source_track_get_type()) + +GST_MSE_PRIVATE +G_DECLARE_FINAL_TYPE (GstMediaSourceTrack, gst_media_source_track, GST, + MEDIA_SOURCE_TRACK, GstObject); + +GST_MSE_PRIVATE +GstMediaSourceTrackType gst_media_source_track_get_track_type ( + GstMediaSourceTrack * self); + +GST_MSE_PRIVATE +const gchar * +gst_media_source_track_get_id (GstMediaSourceTrack * self); + +GST_MSE_PRIVATE +gboolean gst_media_source_track_get_active (GstMediaSourceTrack * self); + +GST_MSE_PRIVATE +GstMediaSourceTrack *gst_media_source_track_new (GstMediaSourceTrackType type, + const gchar * track_id); + +GST_MSE_PRIVATE +GstMediaSourceTrack * +gst_media_source_track_new_with_initial_caps (GstMediaSourceTrackType type, + const gchar * track_id, GstCaps * initial_caps); + +GST_MSE_PRIVATE +GstMediaSourceTrack * gst_media_source_track_new_with_size ( + GstMediaSourceTrackType type, const gchar * track_id, gsize size); + +GST_MSE_PRIVATE +GstCaps *gst_media_source_track_get_initial_caps (GstMediaSourceTrack * self); + +GST_MSE_PRIVATE +GstStreamType +gst_media_source_track_get_stream_type (GstMediaSourceTrack * self); + +GST_MSE_API +void gst_media_source_track_set_active (GstMediaSourceTrack * self, + gboolean active); + +GST_MSE_PRIVATE +GstMiniObject *gst_media_source_track_pop (GstMediaSourceTrack * self); + +GST_MSE_PRIVATE +gboolean gst_media_source_track_push (GstMediaSourceTrack * self, + GstSample * sample); + +GST_MSE_PRIVATE +gboolean gst_media_source_track_push_eos (GstMediaSourceTrack * self); + +GST_MSE_PRIVATE +void gst_media_source_track_flush (GstMediaSourceTrack * self); + +GST_MSE_PRIVATE +void gst_media_source_track_resume (GstMediaSourceTrack * self); + +GST_MSE_PRIVATE +gboolean gst_media_source_track_is_empty (GstMediaSourceTrack * self); + +GST_MSE_PRIVATE +GstStreamType gst_media_source_track_type_to_stream_type ( + GstMediaSourceTrackType type); + +GST_MSE_PRIVATE +GstMediaSourceTrackType gst_media_source_track_type_from_stream_type ( + GstStreamType type); + +G_END_DECLS diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstmediasourcetrack.c b/vendor/gst-mse/gst-libs/gst/mse/gstmediasourcetrack.c new file mode 100644 index 0000000..e0dcfe4 --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstmediasourcetrack.c @@ -0,0 +1,446 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include "gstmediasourcetrack-private.h" + +#include "gstmselogging-private.h" + +#include + +struct _GstMediaSourceTrack +{ + GstObject parent_instance; + + GstMediaSourceTrackType track_type; + gchar *track_id; + gboolean active; + GstCaps *initial_caps; + + gsize queue_size; + GstDataQueue *samples; +}; + +G_DEFINE_TYPE (GstMediaSourceTrack, gst_media_source_track, GST_TYPE_OBJECT); + +#define DEFAULT_QUEUE_SIZE (1 << 10) + +enum +{ + PROP_0, + + PROP_TRACK_TYPE, + PROP_TRACK_ID, + PROP_ACTIVE, + PROP_INITIAL_CAPS, + PROP_QUEUE_SIZE, + + N_PROPS, +}; + +enum +{ + ON_NOT_EMPTY, + + N_SIGNALS, +}; + +static GParamSpec *properties[N_PROPS]; +static guint signals[N_SIGNALS]; + +static GstMediaSourceTrack * +_gst_media_source_track_new_full (GstMediaSourceTrackType type, + const gchar * track_id, gsize size, GstCaps * initial_caps) +{ + g_return_val_if_fail (type >= 0, NULL); + g_return_val_if_fail (type <= GST_MEDIA_SOURCE_TRACK_TYPE_OTHER, NULL); + + gst_mse_init_logging (); + + GstMediaSourceTrack *self = g_object_new (GST_TYPE_MEDIA_SOURCE_TRACK, + "track-type", type, "track-id", track_id, "queue-size", size, + "initial-caps", initial_caps, NULL); + + return gst_object_ref_sink (self); +} + +GstMediaSourceTrack * +gst_media_source_track_new_with_size (GstMediaSourceTrackType type, + const gchar * track_id, gsize size) +{ + return _gst_media_source_track_new_full (type, track_id, size, NULL); +} + +GstMediaSourceTrack * +gst_media_source_track_new (GstMediaSourceTrackType type, + const gchar * track_id) +{ + return _gst_media_source_track_new_full (type, track_id, DEFAULT_QUEUE_SIZE, + NULL); +} + +GstMediaSourceTrack * +gst_media_source_track_new_with_initial_caps (GstMediaSourceTrackType type, + const gchar * track_id, GstCaps * initial_caps) +{ + g_return_val_if_fail (GST_IS_CAPS (initial_caps), NULL); + return _gst_media_source_track_new_full (type, track_id, DEFAULT_QUEUE_SIZE, + initial_caps); +} + +static void +gst_media_source_track_finalize (GObject * object) +{ + GstMediaSourceTrack *self = (GstMediaSourceTrack *) object; + + g_free (self->track_id); + gst_clear_caps (&self->initial_caps); + g_object_unref (self->samples); + + G_OBJECT_CLASS (gst_media_source_track_parent_class)->finalize (object); +} + +static void +gst_media_source_track_get_property (GObject * object, guint prop_id, + GValue * value, GParamSpec * pspec) +{ + GstMediaSourceTrack *self = GST_MEDIA_SOURCE_TRACK (object); + + switch (prop_id) { + case PROP_TRACK_TYPE: + g_value_set_enum (value, gst_media_source_track_get_track_type (self)); + break; + case PROP_TRACK_ID: + g_value_set_static_string (value, gst_media_source_track_get_id (self)); + break; + case PROP_ACTIVE: + g_value_set_boolean (value, gst_media_source_track_get_active (self)); + break; + case PROP_INITIAL_CAPS: + g_value_take_boxed (value, + gst_media_source_track_get_initial_caps (self)); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + } +} + +static void +gst_media_source_track_set_property (GObject * object, guint prop_id, + const GValue * value, GParamSpec * pspec) +{ + GstMediaSourceTrack *self = GST_MEDIA_SOURCE_TRACK (object); + + switch (prop_id) { + case PROP_TRACK_TYPE: + self->track_type = g_value_get_enum (value); + break; + case PROP_TRACK_ID: + /* G_PARAM_CONSTRUCT_ONLY */ + self->track_id = g_value_dup_string (value); + break; + case PROP_ACTIVE: + gst_media_source_track_set_active (self, g_value_get_boolean (value)); + break; + case PROP_INITIAL_CAPS:{ + const GstCaps *caps = gst_value_get_caps (value); + self->initial_caps = caps == NULL ? NULL : gst_caps_copy (caps); + break; + } + case PROP_QUEUE_SIZE:{ + self->queue_size = g_value_get_ulong (value); + break; + } + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + } +} + +static void +gst_media_source_track_class_init (GstMediaSourceTrackClass * klass) +{ + GObjectClass *oclass = G_OBJECT_CLASS (klass); + + oclass->finalize = GST_DEBUG_FUNCPTR (gst_media_source_track_finalize); + oclass->get_property = + GST_DEBUG_FUNCPTR (gst_media_source_track_get_property); + oclass->set_property = + GST_DEBUG_FUNCPTR (gst_media_source_track_set_property); + + signals[ON_NOT_EMPTY] = g_signal_new ("on-not-empty", + G_TYPE_FROM_CLASS (klass), + G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 0); + + properties[PROP_TRACK_TYPE] = + g_param_spec_enum ("track-type", "Track Type", + "Type of media in this Track, either Audio, Video, Text, or Other.", + GST_TYPE_MEDIA_SOURCE_TRACK_TYPE, GST_MEDIA_SOURCE_TRACK_TYPE_OTHER, + G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS); + + properties[PROP_TRACK_ID] = + g_param_spec_string ("track-id", "Track ID", + "Identifier for this Track that must be unique within a Source Buffer.", + "", G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS); + + properties[PROP_ACTIVE] = + g_param_spec_boolean ("active", "Active", + "Whether this Track requires its parent Source Buffer to be in its " + "parent Media Source's Active Source Buffers list", FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); + + properties[PROP_INITIAL_CAPS] = + g_param_spec_boxed ("initial-caps", "Initial Caps", + "GstCaps discovered in the first Initialization Segment", + GST_TYPE_CAPS, G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | + G_PARAM_STATIC_STRINGS); + + properties[PROP_QUEUE_SIZE] = + g_param_spec_ulong ("queue-size", "Queue Size", + "Maximum Track Queue size", + 0, G_MAXULONG, DEFAULT_QUEUE_SIZE, + G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS); + + g_object_class_install_properties (oclass, N_PROPS, properties); +} + +static gboolean +check_queue_depth (GstDataQueue * queue, guint visible, guint bytes, + guint64 time, gpointer checkdata) +{ + GstMediaSourceTrack *self = GST_MEDIA_SOURCE_TRACK (checkdata); + return visible >= self->queue_size; +} + +static void +gst_media_source_track_init (GstMediaSourceTrack * self) +{ + self->samples = gst_data_queue_new (check_queue_depth, NULL, NULL, self); +} + +GstMediaSourceTrackType +gst_media_source_track_get_track_type (GstMediaSourceTrack * self) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE_TRACK (self), + GST_MEDIA_SOURCE_TRACK_TYPE_OTHER); + return self->track_type; +} + +GstStreamType +gst_media_source_track_get_stream_type (GstMediaSourceTrack * self) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE_TRACK (self), + GST_STREAM_TYPE_UNKNOWN); + return gst_media_source_track_type_to_stream_type (self->track_type); +} + +const gchar * +gst_media_source_track_get_id (GstMediaSourceTrack * self) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE_TRACK (self), NULL); + return self->track_id; +} + +GstCaps * +gst_media_source_track_get_initial_caps (GstMediaSourceTrack * self) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE_TRACK (self), NULL); + if (GST_IS_CAPS (self->initial_caps)) { + return self->initial_caps; + } else { + return NULL; + } +} + +gboolean +gst_media_source_track_get_active (GstMediaSourceTrack * self) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE_TRACK (self), FALSE); + return self->active; +} + +void +gst_media_source_track_set_active (GstMediaSourceTrack * self, gboolean active) +{ + g_return_if_fail (GST_IS_MEDIA_SOURCE_TRACK (self)); + self->active = active; + g_object_notify_by_pspec (G_OBJECT (self), properties[PROP_ACTIVE]); +} + +GstMiniObject * +gst_media_source_track_pop (GstMediaSourceTrack * self) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE_TRACK (self), NULL); + GstDataQueueItem *item = NULL; + if (!gst_data_queue_pop (self->samples, &item)) { + return NULL; + } + GstMiniObject *object = item->object; + item->object = NULL; + item->destroy (item); + return object; +} + +static inline gsize +sample_size (GstSample * sample) +{ + GstBuffer *buffer = gst_sample_get_buffer (sample); + return gst_buffer_get_size (buffer); +} + +static inline GstClockTime +sample_duration (GstSample * sample) +{ + GstBuffer *buffer = gst_sample_get_buffer (sample); + return GST_BUFFER_DURATION (buffer); +} + +static void +destroy_item (GstDataQueueItem * item) +{ + gst_clear_mini_object (&item->object); + g_free (item); +} + +static inline GstDataQueueItem * +wrap_sample (GstSample * sample) +{ + GstDataQueueItem item = { + .object = GST_MINI_OBJECT (sample), + .size = sample_size (sample), + .duration = sample_duration (sample), + .destroy = (GDestroyNotify) destroy_item, + .visible = TRUE, + }; + return g_memdup2 (&item, sizeof (GstDataQueueItem)); +} + +gboolean +gst_media_source_track_push (GstMediaSourceTrack * self, GstSample * sample) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE_TRACK (self), FALSE); + g_return_val_if_fail (GST_IS_SAMPLE (sample), FALSE); + + gboolean was_empty = gst_media_source_track_is_empty (self); + + GstDataQueueItem *item = wrap_sample (gst_sample_ref (sample)); + + gboolean result = gst_data_queue_push (self->samples, item); + + if (result) { + if (was_empty) { + g_signal_emit (self, signals[ON_NOT_EMPTY], 0); + } + return TRUE; + } else { + item->destroy (item); + return FALSE; + } +} + +static inline GstDataQueueItem * +wrap_eos (void) +{ + GstEvent *event = gst_event_ref (gst_event_new_eos ()); + + GstDataQueueItem item = { + .object = GST_MINI_OBJECT (event), + .size = 0, + .duration = 0, + .destroy = (GDestroyNotify) destroy_item, + .visible = TRUE, + }; + return g_memdup2 (&item, sizeof (GstDataQueueItem)); +} + +gboolean +gst_media_source_track_push_eos (GstMediaSourceTrack * self) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE_TRACK (self), FALSE); + + GstDataQueueItem *item = wrap_eos (); + + gboolean result = gst_data_queue_push (self->samples, item); + + if (result) { + return TRUE; + } else { + item->destroy (item); + return FALSE; + } +} + +void +gst_media_source_track_flush (GstMediaSourceTrack * self) +{ + g_return_if_fail (GST_IS_MEDIA_SOURCE_TRACK (self)); + gst_data_queue_set_flushing (self->samples, TRUE); + gst_data_queue_flush (self->samples); +} + +void +gst_media_source_track_resume (GstMediaSourceTrack * self) +{ + g_return_if_fail (GST_IS_MEDIA_SOURCE_TRACK (self)); + gst_data_queue_set_flushing (self->samples, FALSE); +} + +gboolean +gst_media_source_track_is_empty (GstMediaSourceTrack * self) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE_TRACK (self), FALSE); + return gst_data_queue_is_empty (self->samples); +} + +GstStreamType +gst_media_source_track_type_to_stream_type (GstMediaSourceTrackType type) +{ + switch (type) { + case GST_MEDIA_SOURCE_TRACK_TYPE_AUDIO: + return GST_STREAM_TYPE_AUDIO; + case GST_MEDIA_SOURCE_TRACK_TYPE_TEXT: + return GST_STREAM_TYPE_TEXT; + case GST_MEDIA_SOURCE_TRACK_TYPE_VIDEO: + return GST_STREAM_TYPE_VIDEO; + default: + return GST_STREAM_TYPE_UNKNOWN; + } +} + +GstMediaSourceTrackType +gst_media_source_track_type_from_stream_type (GstStreamType type) +{ + switch (type) { + case GST_STREAM_TYPE_AUDIO: + return GST_MEDIA_SOURCE_TRACK_TYPE_AUDIO; + case GST_STREAM_TYPE_TEXT: + return GST_MEDIA_SOURCE_TRACK_TYPE_TEXT; + case GST_STREAM_TYPE_VIDEO: + return GST_MEDIA_SOURCE_TRACK_TYPE_VIDEO; + default: + return GST_MEDIA_SOURCE_TRACK_TYPE_OTHER; + } +} diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstmediasourcetrackbuffer-private.h b/vendor/gst-mse/gst-libs/gst/mse/gstmediasourcetrackbuffer-private.h new file mode 100644 index 0000000..a6beb1a --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstmediasourcetrackbuffer-private.h @@ -0,0 +1,92 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#pragma once + +#include +#include +#include + +G_BEGIN_DECLS + +#define GST_TYPE_MEDIA_SOURCE_TRACK_BUFFER \ + (gst_media_source_track_buffer_get_type()) + +GST_MSE_PRIVATE +G_DECLARE_FINAL_TYPE (GstMediaSourceTrackBuffer, gst_media_source_track_buffer, + GST, MEDIA_SOURCE_TRACK_BUFFER, GstObject); + +GST_MSE_PRIVATE +GstMediaSourceTrackBuffer *gst_media_source_track_buffer_new (void); + +GST_MSE_PRIVATE +gboolean gst_media_source_track_buffer_is_empty ( + GstMediaSourceTrackBuffer * self); + +GST_MSE_PRIVATE +gint gst_media_source_track_buffer_get_size (GstMediaSourceTrackBuffer * self); + +GST_MSE_PRIVATE +GstClockTime gst_media_source_track_buffer_get_highest_end_time ( + GstMediaSourceTrackBuffer * self); + +GST_MSE_PRIVATE +GArray * gst_media_source_track_buffer_get_ranges ( + GstMediaSourceTrackBuffer * self); + +GST_MSE_PRIVATE +void gst_media_source_track_buffer_set_group_start (GstMediaSourceTrackBuffer + * self, GstClockTime group_start); + +GST_MSE_PRIVATE +void gst_media_source_track_buffer_process_init_segment ( + GstMediaSourceTrackBuffer * self, gboolean sequence_mode); + +GST_MSE_PRIVATE +void gst_media_source_track_buffer_add (GstMediaSourceTrackBuffer * self, + GstSample * sample); + +GST_MSE_PRIVATE +gsize +gst_media_source_track_buffer_remove_range (GstMediaSourceTrackBuffer * self, + GstClockTime start, GstClockTime end); + +GST_MSE_PRIVATE +void gst_media_source_track_buffer_eos (GstMediaSourceTrackBuffer * self); + +GST_MSE_PRIVATE +gboolean gst_media_source_track_buffer_is_eos ( + GstMediaSourceTrackBuffer * self); + +GST_MSE_PRIVATE +void gst_media_source_track_buffer_await_new_data_until ( + GstMediaSourceTrackBuffer * self, gint64 deadline); + +GST_MSE_PRIVATE +gsize gst_media_source_track_buffer_get_storage_size ( + GstMediaSourceTrackBuffer * self); + +GST_MSE_PRIVATE +GstIterator * gst_media_source_track_buffer_iter_samples ( + GstMediaSourceTrackBuffer * self); + +G_END_DECLS diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstmediasourcetrackbuffer.c b/vendor/gst-mse/gst-libs/gst/mse/gstmediasourcetrackbuffer.c new file mode 100644 index 0000000..f121e64 --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstmediasourcetrackbuffer.c @@ -0,0 +1,362 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "gstmediasourcetrackbuffer-private.h" +#include "gstmediasourcesamplemap-private.h" +#include "gstmediasource.h" +#include "gstmselogging-private.h" + +typedef struct +{ + gboolean enabled; + GstClockTime group_start; + GstClockTime group_end; + GstClockTimeDiff offset; + + GstClockTime last_dts; + GstClockTime last_duration; +} Timestamps; + +struct _GstMediaSourceTrackBuffer +{ + GstObject parent_instance; + + GstMediaSourceSampleMap *samples; + Timestamps timestamps; + guint eos; + + guint32 master_cookie; + + GCond new_data_cond; + GMutex new_data_mutex; +}; + +#define g_array_new_ranges() \ + (g_array_new (TRUE, FALSE, sizeof (GstMediaSourceRange))) + +#define NEW_DATA_LOCK(a) (g_mutex_lock (&a->new_data_mutex)) +#define NEW_DATA_UNLOCK(a) (g_mutex_unlock (&a->new_data_mutex)) +#define NEW_DATA_SIGNAL(a) (g_cond_signal (&a->new_data_cond)) +#define NEW_DATA_WAIT(a) (g_cond_wait (&a->new_data_cond, &a->new_data_mutex)) +#define NEW_DATA_WAIT_UNTIL(a, d) \ + (g_cond_wait_until (&a->new_data_cond, &a->new_data_mutex, d)) + +static void timestamps_init (Timestamps * self, gboolean enabled); +static void timestamps_process (Timestamps * self, GstSample * sample); + +G_DEFINE_TYPE (GstMediaSourceTrackBuffer, gst_media_source_track_buffer, + GST_TYPE_OBJECT); + +static void +invalidate_cookie (GstMediaSourceTrackBuffer * self) +{ + self->master_cookie++; +} + +GstMediaSourceTrackBuffer * +gst_media_source_track_buffer_new (void) +{ + return gst_object_ref_sink (g_object_new (GST_TYPE_MEDIA_SOURCE_TRACK_BUFFER, + NULL)); +} + +static void +gst_media_source_track_buffer_finalize (GObject * object) +{ + GstMediaSourceTrackBuffer *self = GST_MEDIA_SOURCE_TRACK_BUFFER (object); + gst_object_unref (self->samples); + g_cond_clear (&self->new_data_cond); + g_mutex_clear (&self->new_data_mutex); + G_OBJECT_CLASS (gst_media_source_track_buffer_parent_class)->finalize + (object); +} + +static void +gst_media_source_track_buffer_class_init (GstMediaSourceTrackBufferClass * + klass) +{ + GObjectClass *oclass = G_OBJECT_CLASS (klass); + + oclass->finalize = GST_DEBUG_FUNCPTR (gst_media_source_track_buffer_finalize); +} + +static void +gst_media_source_track_buffer_init (GstMediaSourceTrackBuffer * self) +{ + self->samples = gst_media_source_sample_map_new (); + self->eos = FALSE; + self->master_cookie = 0; + timestamps_init (&self->timestamps, FALSE); + g_cond_init (&self->new_data_cond); + g_mutex_init (&self->new_data_mutex); +} + +void +gst_media_source_track_buffer_process_init_segment (GstMediaSourceTrackBuffer + * self, gboolean sequence_mode) +{ + NEW_DATA_LOCK (self); + + timestamps_init (&self->timestamps, sequence_mode); + + NEW_DATA_UNLOCK (self); +} + +void +gst_media_source_track_buffer_set_group_start (GstMediaSourceTrackBuffer + * self, GstClockTime group_start) +{ + g_return_if_fail (GST_IS_MEDIA_SOURCE_TRACK_BUFFER (self)); + if (self->timestamps.enabled) { + self->timestamps.group_start = group_start; + } +} + +void +gst_media_source_track_buffer_add (GstMediaSourceTrackBuffer * self, + GstSample * sample) +{ + g_return_if_fail (GST_IS_MEDIA_SOURCE_TRACK_BUFFER (self)); + g_return_if_fail (GST_IS_SAMPLE (sample)); + + NEW_DATA_LOCK (self); + + timestamps_process (&self->timestamps, sample); + gst_media_source_sample_map_add (self->samples, sample); + invalidate_cookie (self); + + NEW_DATA_SIGNAL (self); + NEW_DATA_UNLOCK (self); +} + +gsize +gst_media_source_track_buffer_remove_range (GstMediaSourceTrackBuffer * self, + GstClockTime earliest, GstClockTime latest) +{ + NEW_DATA_LOCK (self); + gsize size = gst_media_source_sample_map_remove_range (self->samples, + earliest, latest); + invalidate_cookie (self); + NEW_DATA_SIGNAL (self); + NEW_DATA_UNLOCK (self); + return size; +} + +static gboolean +is_eos (GstMediaSourceTrackBuffer * self) +{ + return g_atomic_int_get (&self->eos); +} + +void +gst_media_source_track_buffer_eos (GstMediaSourceTrackBuffer * self) +{ + g_return_if_fail (GST_IS_MEDIA_SOURCE_TRACK_BUFFER (self)); + NEW_DATA_LOCK (self); + g_atomic_int_set (&self->eos, TRUE); + NEW_DATA_SIGNAL (self); + NEW_DATA_UNLOCK (self); +} + +gboolean +gst_media_source_track_buffer_is_eos (GstMediaSourceTrackBuffer * self) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE_TRACK_BUFFER (self), FALSE); + return is_eos (self); +} + +void +gst_media_source_track_buffer_await_new_data_until (GstMediaSourceTrackBuffer * + self, gint64 deadline) +{ + NEW_DATA_LOCK (self); + NEW_DATA_WAIT_UNTIL (self, deadline); + NEW_DATA_UNLOCK (self); +} + +gint +gst_media_source_track_buffer_get_size (GstMediaSourceTrackBuffer * self) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE_TRACK_BUFFER (self), 0); + return gst_media_source_sample_map_get_size (self->samples); +} + +GstClockTime +gst_media_source_track_buffer_get_highest_end_time (GstMediaSourceTrackBuffer + * self) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE_TRACK_BUFFER (self), + GST_CLOCK_TIME_NONE); + return gst_media_source_sample_map_get_highest_end_time (self->samples); +} + +typedef struct +{ + GArray *ranges; + GstMediaSourceRange current_range; + GstClockTime max_duration; +} GetRangesAccumulator; + +static gboolean +get_ranges_fold (const GValue * item, GetRangesAccumulator * acc, + gpointer user_data) +{ + GstSample *sample = gst_value_get_sample (item); + GstBuffer *buffer = gst_sample_get_buffer (sample); + GstClockTime start = GST_BUFFER_PTS (buffer); + GstClockTime end = start + GST_BUFFER_DURATION (buffer); + + if (GST_BUFFER_DURATION_IS_VALID (buffer)) { + acc->max_duration = MAX (acc->max_duration, GST_BUFFER_DURATION (buffer)); + } + + GstMediaSourceRange *range = &acc->current_range; + + if (!GST_CLOCK_TIME_IS_VALID (acc->current_range.start)) { + acc->current_range.start = start; + } + if (!GST_CLOCK_TIME_IS_VALID (acc->current_range.end)) { + acc->current_range.end = end; + } + + GstClockTime gap_tolerance = MAX (GST_SECOND / 10, acc->max_duration * 2); + GstClockTime gap = MAX (0, GST_CLOCK_DIFF (range->end, start)); + + if (range->end == 0 || gap <= gap_tolerance) { + range->end = end; + return TRUE; + } + g_array_append_val (acc->ranges, *range); + + range->start = start; + range->end = end; + + return TRUE; +} + +GArray * +gst_media_source_track_buffer_get_ranges (GstMediaSourceTrackBuffer * self) +{ + GetRangesAccumulator acc = { + .ranges = g_array_new_ranges (), + .max_duration = 0, + .current_range = {.start = GST_CLOCK_TIME_NONE,.end = GST_CLOCK_TIME_NONE}, + }; + + /* *INDENT-OFF* */ + GstIterator *iter = gst_media_source_sample_map_iter_samples_by_pts ( + self->samples, + &self->new_data_mutex, + &self->master_cookie + ); + /* *INDENT-ON* */ + while (gst_iterator_fold (iter, (GstIteratorFoldFunction) get_ranges_fold, + (GValue *) & acc, NULL) == GST_ITERATOR_RESYNC) { + gst_iterator_resync (iter); + g_clear_pointer (&acc.ranges, g_array_unref); + acc.ranges = g_array_new_ranges (); + acc.max_duration = 0; + acc.current_range.start = GST_CLOCK_TIME_NONE; + acc.current_range.end = GST_CLOCK_TIME_NONE; + } + gst_iterator_free (iter); + + if (!GST_CLOCK_TIME_IS_VALID (acc.current_range.start)) { + acc.current_range.start = 0; + } + if (!GST_CLOCK_TIME_IS_VALID (acc.current_range.end)) { + acc.current_range.end = 0; + } + if (acc.current_range.end > 0) { + g_array_append_val (acc.ranges, acc.current_range); + } + + return acc.ranges; +} + +static void +timestamps_init (Timestamps * self, gboolean enabled) +{ + self->enabled = enabled; + self->group_start = GST_CLOCK_TIME_NONE; + self->group_end = GST_CLOCK_TIME_NONE; + self->offset = 0; + self->last_dts = 0; + self->last_duration = 0; +} + +static void +timestamps_process (Timestamps * self, GstSample * sample) +{ + if (!self->enabled) { + return; + } + + GstBuffer *buffer = gst_sample_get_buffer (sample); + GstClockTime duration = GST_BUFFER_DURATION (buffer); + + GstClockTime pts = 0; + GstClockTime dts = 0; + + if (GST_CLOCK_TIME_IS_VALID (self->group_start)) { + self->offset = self->group_start - pts; + self->group_end = self->group_start; + self->group_start = GST_CLOCK_TIME_NONE; + } + + if (self->offset != 0) { + pts += self->offset; + dts += self->offset; + } + + GstClockTime end_pts = pts + duration; + + self->last_dts = dts; + self->last_duration = duration; + + if (GST_CLOCK_TIME_IS_VALID (self->group_end)) { + self->group_end = MAX (self->group_end, end_pts); + } + self->offset = end_pts; + + GST_BUFFER_PTS (buffer) = pts; + GST_BUFFER_DTS (buffer) = dts; +} + +gsize +gst_media_source_track_buffer_get_storage_size (GstMediaSourceTrackBuffer * + self) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE_TRACK_BUFFER (self), 0); + return gst_media_source_sample_map_get_storage_size (self->samples); +} + +GstIterator * +gst_media_source_track_buffer_iter_samples (GstMediaSourceTrackBuffer * self) +{ + return gst_media_source_sample_map_iter_samples_by_dts (self->samples, + &self->new_data_mutex, &self->master_cookie); +} diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstmseeventqueue-private.h b/vendor/gst-mse/gst-libs/gst/mse/gstmseeventqueue-private.h new file mode 100644 index 0000000..9b0c9bb --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstmseeventqueue-private.h @@ -0,0 +1,46 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#pragma once + +#include +#include +#include + +G_BEGIN_DECLS + +typedef void (*GstMseEventQueueCallback) (GstDataQueueItem *, gpointer); + +#define GST_TYPE_MSE_EVENT_QUEUE (gst_mse_event_queue_get_type()) + +G_DECLARE_FINAL_TYPE (GstMseEventQueue, gst_mse_event_queue, GST, + MSE_EVENT_QUEUE, GstObject); + +GST_MSE_PRIVATE +GstMseEventQueue * gst_mse_event_queue_new (GstMseEventQueueCallback callback, + gpointer user_data); + +GST_MSE_PRIVATE +gboolean gst_mse_event_queue_push (GstMseEventQueue * self, + GstDataQueueItem * item); + +G_END_DECLS diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstmseeventqueue.c b/vendor/gst-mse/gst-libs/gst/mse/gstmseeventqueue.c new file mode 100644 index 0000000..b49e09c --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstmseeventqueue.c @@ -0,0 +1,133 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include + +#include "gstmseeventqueue-private.h" + +struct _GstMseEventQueue +{ + GstObject parent_instance; + + GstMseEventQueueCallback callback; + gpointer user_data; + + GstTask *task; + GRecMutex lock; + GstDataQueue *queue; +}; + +G_DEFINE_TYPE (GstMseEventQueue, gst_mse_event_queue, GST_TYPE_OBJECT); + +GstMseEventQueue * +gst_mse_event_queue_new (GstMseEventQueueCallback callback, gpointer user_data) +{ + g_return_val_if_fail (callback != NULL, NULL); + + GstMseEventQueue *self = g_object_new (GST_TYPE_MSE_EVENT_QUEUE, NULL); + + self->callback = callback; + self->user_data = user_data; + + gst_task_start (self->task); + + return g_object_ref_sink (self); +} + +static void +gst_mse_background_event_queue_dispose (GObject * obj) +{ + GstMseEventQueue *self = GST_MSE_EVENT_QUEUE (obj); + + gst_data_queue_set_flushing (self->queue, TRUE); + gst_data_queue_flush (self->queue); + + G_OBJECT_CLASS (gst_mse_event_queue_parent_class)->dispose (obj); +} + +static void +gst_mse_background_event_queue_finalize (GObject * obj) +{ + GstMseEventQueue *self = GST_MSE_EVENT_QUEUE (obj); + + gst_task_join (self->task); + g_rec_mutex_clear (&self->lock); + gst_clear_object (&self->task); + gst_clear_object (&self->queue); + + G_OBJECT_CLASS (gst_mse_event_queue_parent_class)->finalize (obj); +} + +void +gst_mse_event_queue_class_init (GstMseEventQueueClass * klass) +{ + GObjectClass *oclass = G_OBJECT_CLASS (klass); + + oclass->dispose = GST_DEBUG_FUNCPTR (gst_mse_background_event_queue_dispose); + oclass->finalize = + GST_DEBUG_FUNCPTR (gst_mse_background_event_queue_finalize); +} + +static void +task_func (GstMseEventQueue * self) +{ + GstTask *task = self->task; + GstDataQueue *queue = self->queue; + GstDataQueueItem *item = NULL; + if (!gst_data_queue_pop (queue, &item)) { + gst_task_stop (task); + return; + } + self->callback (item, self->user_data); + if (item->destroy) { + item->destroy (item); + } +} + +static gboolean +never_full (GstDataQueue * queue, guint visible, guint bytes, guint64 time, + gpointer user_data) +{ + return FALSE; +} + +void +gst_mse_event_queue_init (GstMseEventQueue * self) +{ + self->queue = gst_data_queue_new (never_full, NULL, NULL, NULL); + self->task = gst_task_new ((GstTaskFunction) task_func, self, NULL); + g_rec_mutex_init (&self->lock); + gst_task_set_lock (self->task, &self->lock); +} + +gboolean +gst_mse_event_queue_push (GstMseEventQueue * self, GstDataQueueItem * item) +{ + g_return_val_if_fail (GST_IS_MSE_EVENT_QUEUE (self), FALSE); + g_return_val_if_fail (item != NULL, FALSE); + return gst_data_queue_push (self->queue, item); +} diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstmselogging-private.h b/vendor/gst-mse/gst-libs/gst/mse/gstmselogging-private.h new file mode 100644 index 0000000..1ff2662 --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstmselogging-private.h @@ -0,0 +1,36 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#pragma once + +#include + +#define GST_CAT_DEFAULT gst_mse_debug + +G_GNUC_INTERNAL +GST_DEBUG_CATEGORY_EXTERN (gst_mse_debug); + +G_GNUC_INTERNAL +void gst_mse_init_logging (void); + +G_GNUC_INTERNAL +const gchar * gst_mse_enum_value_nick (GType enum_type, gint mse_enum_value); diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstmselogging.c b/vendor/gst-mse/gst-libs/gst/mse/gstmselogging.c new file mode 100644 index 0000000..82c5c7c --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstmselogging.c @@ -0,0 +1,45 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "gstmselogging-private.h" + +GST_DEBUG_CATEGORY (gst_mse_debug); + +void +gst_mse_init_logging (void) +{ + GST_DEBUG_CATEGORY_INIT (gst_mse_debug, "gst-mse", 0, "GstMse"); +} + +const gchar * +gst_mse_enum_value_nick (GType enum_type, gint mse_enum_value) +{ + GEnumClass *enum_class = (GEnumClass *) g_type_class_ref (enum_type); + GEnumValue *enum_value = g_enum_get_value (enum_class, mse_enum_value); + const gchar *nick = enum_value->value_nick; + g_type_class_unref (enum_class); + return nick; +} diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstmsemediatype-private.h b/vendor/gst-mse/gst-libs/gst/mse/gstmsemediatype-private.h new file mode 100644 index 0000000..dfdb537 --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstmsemediatype-private.h @@ -0,0 +1,60 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#pragma once + +#include +#include +#include + +G_BEGIN_DECLS + +typedef struct +{ + gchar *mime_type; + GStrv codecs; +} GstMediaSourceMediaType; + +#define GST_MEDIA_SOURCE_MEDIA_TYPE_INIT { 0 } + +GST_MSE_PRIVATE +gboolean gst_media_source_media_type_parse (GstMediaSourceMediaType * self, + const gchar * type); + +GST_MSE_PRIVATE +gboolean gst_media_source_media_type_is_caps_supported (const GstCaps * caps); + +GST_MSE_PRIVATE +gboolean gst_media_source_media_type_is_supported ( + GstMediaSourceMediaType * self); + +GST_MSE_PRIVATE +gboolean gst_media_source_media_type_generates_timestamp ( + GstMediaSourceMediaType * self); + +GST_MSE_PRIVATE +void gst_media_source_media_type_reset (GstMediaSourceMediaType * self); + +GST_MSE_PRIVATE +void gst_media_source_media_type_free (GstMediaSourceMediaType * self); + +G_END_DECLS diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstmsemediatype.c b/vendor/gst-mse/gst-libs/gst/mse/gstmsemediatype.c new file mode 100644 index 0000000..b80f2b0 --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstmsemediatype.c @@ -0,0 +1,538 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2019 Igalia S.L. + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include + +#include "gstmsemediatype-private.h" + +static const gchar tspecials[] = { + '(', ')', '<', '>', '@', ',', ';', ':', + '\\', '"', '/', '[', ']', '?', '=', + 0, +}; + +static gboolean +is_tspecial (const gchar c) +{ + for (const gchar * tspecial = tspecials; *tspecial != 0; tspecial++) { + if (*tspecial == c) { + return TRUE; + } + } + return FALSE; +} + +static gboolean +is_token_character (const gchar c) +{ + if (g_ascii_iscntrl (c) || is_tspecial (c)) { + return FALSE; + } + return g_ascii_isgraph (c); +} + +static gboolean +is_eos (const gchar c) +{ + return c == '\0'; +} + +static void +ignore_whitespace (const gchar ** input) +{ + g_return_if_fail (input != NULL); + + const gchar *output; + for (output = *input; g_ascii_isspace (*output); output++) { + } + *input = output; +} + +static gboolean +any_of (const gchar ** input, const gchar ** choices, gchar ** value) +{ + g_return_val_if_fail (input != NULL, FALSE); + g_return_val_if_fail (choices != NULL, FALSE); + g_return_val_if_fail (value != NULL, FALSE); + + for (const gchar ** choice = choices; *choice != NULL; choice++) { + gulong prefix_length = strlen (*choice); + if (g_str_has_prefix (*input, *choice)) { + *value = g_strndup (*input, prefix_length); + *input += prefix_length; + return TRUE; + } + } + return FALSE; +} + +static gboolean +literal (const gchar ** input, const gchar * value) +{ + g_return_val_if_fail (input != NULL, FALSE); + g_return_val_if_fail (value != NULL, FALSE); + + if (!g_str_has_prefix (*input, value)) { + return FALSE; + } + *input += strlen (value); + return TRUE; +} + +static gboolean +token (const gchar ** input, gchar ** value) +{ + g_return_val_if_fail (input != NULL, FALSE); + g_return_val_if_fail (value != NULL, FALSE); + + const gchar *unparsed = *input; + for (; is_token_character (unparsed[0]); unparsed++) { + } + gsize length = unparsed - *input; + if (length < 1) { + return FALSE; + } + *value = g_strndup (*input, length); + *input = unparsed; + return TRUE; +} + +static gboolean +quoted_string_char (const gchar ** input, gchar * value) +{ + g_return_val_if_fail (input != NULL, FALSE); + g_return_val_if_fail (value != NULL, FALSE); + + const gchar *unparsed = *input; + gchar c = unparsed[0]; + if (!g_ascii_isprint (c)) { + return FALSE; + } + + if (c == '"' || c == '\\' || c == '\r') { + return FALSE; + } + + *value = c; + (*input)++; + return TRUE; +} + +static gboolean +escaped_ascii_char (const gchar ** input, gchar * value) +{ + g_return_val_if_fail (input != NULL, FALSE); + g_return_val_if_fail (value != NULL, FALSE); + + if (!literal (input, "\\")) { + return FALSE; + } + + gchar c = (*input)[0]; + if (!g_ascii_isprint (c)) { + return FALSE; + } + + *value = c; + (*input)++; + return TRUE; +} + +static gboolean +quoted_string (const gchar ** input, gchar ** value) +{ + g_return_val_if_fail (input != NULL, FALSE); + g_return_val_if_fail (value != NULL, FALSE); + + const gchar *unparsed = *input; + if (!literal (&unparsed, "\"")) { + return FALSE; + } + + GString *string_value = g_string_new (NULL); + for (;;) { + if (literal (&unparsed, "\"")) { + *input = unparsed; + *value = g_string_free (string_value, FALSE); + return TRUE; + } + + if (is_eos (unparsed[0])) { + goto error; + } + + gchar c; + + if (quoted_string_char (&unparsed, &c)) { + g_string_append_c (string_value, c); + continue; + } + + if (escaped_ascii_char (&unparsed, &c)) { + g_string_append_c (string_value, c); + continue; + } + + goto error; + } +error: + g_string_free (string_value, TRUE); + return FALSE; +} + +static const gchar *discrete_media_types[] = { + "text", + "image", + "audio", + "video", + "application", + NULL, +}; + +static gboolean +discrete_media_type (const gchar ** input, gchar ** value) +{ + return any_of (input, discrete_media_types, value); +} + +static gboolean +composite_media_type (const gchar ** input, gchar ** value) +{ + return token (input, value); +} + +static gboolean +media_type_parameter (const gchar ** input, gchar ** param_name, + gchar ** param_value) +{ + g_return_val_if_fail (input != NULL, FALSE); + g_return_val_if_fail (param_name != NULL, FALSE); + g_return_val_if_fail (param_value != NULL, FALSE); + + ignore_whitespace (input); + if (!token (input, param_name)) { + return FALSE; + } + if (!literal (input, "=")) { + return FALSE; + } + if (!token (input, param_value)) { + if (!quoted_string (input, param_value)) { + return FALSE; + } + } + ignore_whitespace (input); + return TRUE; +} + +static gboolean +media_type (const gchar ** input, gchar ** value) +{ + g_return_val_if_fail (input != NULL, FALSE); + g_return_val_if_fail (value != NULL, FALSE); + + gchar *discrete = NULL; + gchar *composite = NULL; + + if (!discrete_media_type (input, &discrete)) { + goto error; + } + if (!literal (input, "/")) { + goto error; + } + if (!composite_media_type (input, &composite)) { + goto error; + } + + *value = g_strdup_printf ("%s/%s", discrete, composite); + g_clear_pointer (&discrete, g_free); + g_clear_pointer (&composite, g_free); + return TRUE; + +error: + g_clear_pointer (&discrete, g_free); + g_clear_pointer (&composite, g_free); + return FALSE; +} + +static gboolean +media_type_codecs (const gchar ** input, gchar *** codecs) +{ + g_return_val_if_fail (input != NULL, FALSE); + g_return_val_if_fail (codecs != NULL, FALSE); + + gchar *param_name = NULL; + gchar *codecs_value = NULL; + while (!is_eos (*input[0]) + && media_type_parameter (input, ¶m_name, &codecs_value)) { + gboolean is_codecs = g_strcmp0 (param_name, "codecs") == 0; + g_clear_pointer (¶m_name, g_free); + if (is_codecs) { + break; + } + g_clear_pointer (&codecs_value, g_free); + } + if (codecs_value == NULL) { + return TRUE; + } + + gchar **codec_names = g_strsplit (codecs_value, ",", 0); + guint n_codecs = g_strv_length (codec_names); + GPtrArray *codecs_array = g_ptr_array_new_full (n_codecs, NULL); + for (guint i = 0; i < n_codecs; i++) { + gchar *codec = g_strstrip (g_strdup (codec_names[i])); + if (g_strcmp0 (codec, "") != 0) { + g_ptr_array_add (codecs_array, g_strdup (codec)); + } + g_clear_pointer (&codec, g_free); + } + g_ptr_array_add (codecs_array, NULL); + *codecs = (gchar **) g_ptr_array_free (codecs_array, FALSE); + + g_clear_pointer (&codecs_value, g_free); + g_strfreev (codec_names); + + return TRUE; +} + +gboolean +gst_media_source_media_type_parse (GstMediaSourceMediaType * self, + const gchar * type) +{ + g_return_val_if_fail (self != NULL, FALSE); + g_return_val_if_fail (type != NULL, FALSE); + + gchar *lowercase = g_ascii_strdown (type, -1); + const gchar *input = lowercase; + + ignore_whitespace (&input); + if (!media_type (&input, &self->mime_type)) { + g_free (lowercase); + return FALSE; + } + self->codecs = NULL; + ignore_whitespace (&input); + if (is_eos (input[0])) { + g_free (lowercase); + return TRUE; + } + if (!literal (&input, ";")) { + g_free (lowercase); + return TRUE; + } + ignore_whitespace (&input); + media_type_codecs (&input, &self->codecs); + g_free (lowercase); + return TRUE; +} + +static inline gboolean +has_any_prefix (const gchar * str, const gchar * prefix, ...) +{ + if (g_str_has_prefix (str, prefix)) { + return TRUE; + } + + va_list varargs; + + va_start (varargs, prefix); + for (const gchar * arg = va_arg (varargs, const gchar *); arg != NULL; + arg = va_arg (varargs, const gchar *)) + { + if (g_str_has_prefix (str, arg)) { + va_end (varargs); + return TRUE; + } + } + va_end (varargs); + return FALSE; +} + +static const gchar * +patch_media_type (const gchar * media_type) +{ + if (g_strcmp0 (media_type, "video/mp4") == 0) { + return "video/quicktime"; + } + if (g_strcmp0 (media_type, "audio/mp4") == 0 || + g_strcmp0 (media_type, "audio/aac") == 0) { + return "audio/x-m4a"; + } + if (!has_any_prefix (media_type, "audio/", "video/", NULL)) { + return NULL; + } + return media_type; +} + +static GstStaticCaps h264_caps = GST_STATIC_CAPS ("video/x-h264"); +static GstStaticCaps h265_caps = GST_STATIC_CAPS ("video/x-h265"); +static GstStaticCaps av1_caps = GST_STATIC_CAPS ("video/x-av1"); +static GstStaticCaps vp8_caps = GST_STATIC_CAPS ("video/x-vp8"); +static GstStaticCaps vp9_caps = GST_STATIC_CAPS ("video/x-vp9"); + +static GstStaticCaps vorbis_caps = GST_STATIC_CAPS ("audio/x-vorbis"); +static GstStaticCaps opus_caps = GST_STATIC_CAPS ("audio/x-opus"); +static GstStaticCaps flac_caps = GST_STATIC_CAPS ("audio/x-flac"); +static GstStaticCaps mp3_caps = +GST_STATIC_CAPS ("audio/mpeg, mpegversion=(int)1, layer=(int)3"); +static GstStaticCaps aac_caps = +GST_STATIC_CAPS ("audio/mpeg, mpegversion=(int)4"); + +static inline GstStaticCaps * +mse_codec_id_to_static_caps (const gchar * codec_id) +{ + if (has_any_prefix (codec_id, "avc", "x-h264", "mp4v", NULL)) { + return &h264_caps; + } + if (has_any_prefix (codec_id, "hvc1", "hev1", "x-h265", NULL)) { + return &h265_caps; + } + if (has_any_prefix (codec_id, "av01", "av1", "x-av1", NULL)) { + return &av1_caps; + } + if (has_any_prefix (codec_id, "vp8", "x-vp8", NULL)) { + return &vp8_caps; + } + if (has_any_prefix (codec_id, "vp9", "vp09", "x-vp9", NULL)) { + return &vp9_caps; + } + + if (has_any_prefix (codec_id, "mpeg", "mp4a", NULL)) { + return &aac_caps; + } + if (has_any_prefix (codec_id, "vorbis", "x-vorbis", NULL)) { + return &vorbis_caps; + } + if (has_any_prefix (codec_id, "opus", "x-opus", NULL)) { + return &opus_caps; + } + if (has_any_prefix (codec_id, "flac", "x-flac", NULL)) { + return &flac_caps; + } + if (has_any_prefix (codec_id, "mp3", "audio/mp3", NULL)) { + return &mp3_caps; + } + + return NULL; +} + +static gboolean +is_supported (const GstCaps * caps, GList * elements) +{ + GList *supporting_elements = gst_element_factory_list_filter (elements, caps, + GST_PAD_SINK, FALSE); + gboolean supported = supporting_elements != NULL; + gst_plugin_feature_list_free (supporting_elements); + return supported; +} + +static gboolean +is_codec_supported (const gchar * codec_id, GList * elements) +{ + GstStaticCaps *static_caps = mse_codec_id_to_static_caps (codec_id); + if (static_caps == NULL) { + return FALSE; + } + GstCaps *codec_caps = gst_static_caps_get (static_caps); + gboolean supported = is_supported (codec_caps, elements); + gst_clear_caps (&codec_caps); + return supported; +} + +static inline GList * +get_srcpad_elements (void) +{ + return gst_element_factory_list_get_elements (GST_ELEMENT_FACTORY_TYPE_DEMUXER + | GST_ELEMENT_FACTORY_TYPE_DECODER | GST_ELEMENT_FACTORY_TYPE_DECRYPTOR | + GST_ELEMENT_FACTORY_TYPE_DEPAYLOADER | GST_ELEMENT_FACTORY_TYPE_SINK | + GST_ELEMENT_FACTORY_TYPE_PARSER, GST_RANK_MARGINAL); +} + +gboolean +gst_media_source_media_type_is_caps_supported (const GstCaps * caps) +{ + GList *elements = get_srcpad_elements (); + gboolean supported = is_supported (caps, elements); + gst_plugin_feature_list_free (elements); + return supported; +} + +gboolean +gst_media_source_media_type_is_supported (GstMediaSourceMediaType * self) +{ + g_return_val_if_fail (self != NULL, FALSE); + g_return_val_if_fail (self->mime_type != NULL, FALSE); + + const gchar *mime_type = patch_media_type (self->mime_type); + if (mime_type == NULL) { + return FALSE; + } + + GList *elements = get_srcpad_elements (); + GstCaps *caps = gst_caps_from_string (mime_type); + + gboolean supported = is_supported (caps, elements); + for (gchar ** codec_id = self->codecs; + supported && codec_id && *codec_id; codec_id++) { + supported &= is_codec_supported (*codec_id, elements); + } + + gst_plugin_feature_list_free (elements); + gst_clear_caps (&caps); + + return supported; +} + +static const gchar *generate_timestamps_formats[] = { + "audio/mpeg", + "audio/aac", + NULL, +}; + +gboolean +gst_media_source_media_type_generates_timestamp (GstMediaSourceMediaType * self) +{ + g_return_val_if_fail (self != NULL, FALSE); + g_return_val_if_fail (self->mime_type != NULL, FALSE); + return g_strv_contains (generate_timestamps_formats, self->mime_type); +} + +void +gst_media_source_media_type_reset (GstMediaSourceMediaType * self) +{ + g_return_if_fail (self != NULL); + g_clear_pointer (&self->mime_type, g_free); + g_clear_pointer (&self->codecs, g_strfreev); +} + +void +gst_media_source_media_type_free (GstMediaSourceMediaType * self) +{ + gst_media_source_media_type_reset (self); + g_free (self); +} diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstmsesrc-private.h b/vendor/gst-mse/gst-libs/gst/mse/gstmsesrc-private.h new file mode 100644 index 0000000..b0d5099 --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstmsesrc-private.h @@ -0,0 +1,52 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#pragma once + +#include +#include +#include "gstmsesrc.h" +#include "gstmediasource.h" +#include "gstmediasourcetrack-private.h" + +G_BEGIN_DECLS + +GST_MSE_PRIVATE +void gst_mse_src_set_duration (GstMseSrc * self, GstClockTime duration); + +GST_MSE_PRIVATE +void gst_mse_src_network_error (GstMseSrc * self); + +GST_MSE_PRIVATE +void gst_mse_src_decode_error (GstMseSrc * self); + +GST_MSE_PRIVATE +void gst_mse_src_emit_streams (GstMseSrc * self, GstMediaSourceTrack ** tracks, + gsize n_tracks); + +GST_MSE_PRIVATE +void gst_mse_src_attach (GstMseSrc * self, GstMediaSource * media_source); + +GST_MSE_PRIVATE +void gst_mse_src_detach (GstMseSrc * self); + +G_END_DECLS diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstmsesrc.c b/vendor/gst-mse/gst-libs/gst/mse/gstmsesrc.c new file mode 100644 index 0000000..add0716 --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstmsesrc.c @@ -0,0 +1,1502 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2009, 2010 Sebastian Dröge + * Copyright (C) 2013, 2022, 2023 Collabora Ltd. + * Copyright (C) 2013 Orange + * Copyright (C) 2014, 2015 Sebastian Dröge + * Copyright (C) 2015, 2016, 2018, 2019, 2020, 2021 Igalia, S.L + * Copyright (C) 2015, 2016, 2018, 2019, 2020, 2021 Metrological Group B.V. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +/** + * SECTION:gstmsesrc + * @title: GstMseSrc + * @short_description: Source Element for Media Source playback + * + * #GstMseSrc is a source Element that interacts with a #GstMediaSource to + * consume #GstSamples processed by the Media Source and supplies them + * to the containing #GstPipeline. In the perspective of the Media Source API, + * this element fulfills the basis of the Media Element's role relating to + * working with a Media Source. The remaining responsibilities are meant to be + * fulfilled by the application and #GstPlay can be used to satisfy many of + * them. + * + * Once added to a Pipeline, this element should be attached to a Media Source + * using gst_media_source_attach(). + * + * Since: 1.24 + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include + +#include +#include "gstmsesrc.h" +#include "gstmsesrc-private.h" + +#include "gstmselogging-private.h" + +#include "gstmediasource.h" +#include "gstmediasource-private.h" +#include "gstmediasourcetrack-private.h" +#include "gstsourcebuffer.h" +#include "gstsourcebuffer-private.h" + +#define DEFAULT_POSITION 0 +#define DEFAULT_DURATION GST_CLOCK_TIME_NONE +#define DEFAULT_READY_STATE GST_MSE_SRC_READY_STATE_HAVE_NOTHING +#define DECODE_ERROR "decode error" +#define NETWORK_ERROR "network error" + +enum +{ + PROP_0, + + PROP_POSITION, + PROP_DURATION, + PROP_READY_STATE, + + PROP_N_AUDIO, + PROP_N_TEXT, + PROP_N_VIDEO, + + N_PROPS, +}; + +enum +{ + THRESHOLD_FUTURE_DATA = GST_SECOND * 5, + THRESHOLD_ENOUGH_DATA = GST_SECOND * 50, +}; + +static GParamSpec *properties[N_PROPS]; + +static GstStaticPadTemplate gst_mse_src_template = +GST_STATIC_PAD_TEMPLATE ("src_%s", GST_PAD_SRC, GST_PAD_SOMETIMES, + GST_STATIC_CAPS_ANY); + +typedef struct +{ + GWeakRef parent; + GstTask *task; + GRecMutex mutex; +} ReadyStateUpdateTask; + +/** + * GstMseSrcPad: + * + * Since: 1.24 + */ +struct _GstMseSrcPad +{ + GstPad base; + + GstStream *stream; + GstMediaSourceTrack *track; + GstCaps *most_recent_caps; + GstSegment segment; + + gboolean sent_stream_collection; + gboolean sent_stream_start; + gboolean sent_initial_caps; + gboolean does_need_segment; + + GCond linked_or_flushing_cond; + GMutex linked_or_flushing_lock; + gboolean flushing; +}; + +#define MEDIA_SOURCE_LOCK(a) g_mutex_lock (&(a)->media_source_lock) +#define MEDIA_SOURCE_UNLOCK(a) g_mutex_unlock (&(a)->media_source_lock) + +#define STREAMS_LOCK(a) (g_mutex_lock (&a->streams_lock)) +#define STREAMS_UNLOCK(a) (g_mutex_unlock (&a->streams_lock)) + +#define LINKED_OR_FLUSHING_LOCK(a) (g_mutex_lock (&a->linked_or_flushing_lock)) +#define LINKED_OR_FLUSHING_UNLOCK(a) (g_mutex_unlock (&a->linked_or_flushing_lock)) +#define LINKED_OR_FLUSHING_SIGNAL(a) (g_cond_signal (&a->linked_or_flushing_cond)) +#define LINKED_OR_FLUSHING_WAIT(a) \ + (g_cond_wait (&a->linked_or_flushing_cond, &a->linked_or_flushing_lock)) + +#define FLOW_COMBINER_LOCK(a) (g_mutex_lock (&a->flow_combiner_lock)) +#define FLOW_COMBINER_UNLOCK(a) (g_mutex_unlock (&a->flow_combiner_lock)) + +G_DEFINE_TYPE (GstMseSrcPad, gst_mse_src_pad, GST_TYPE_PAD); + +static gboolean pad_activate_mode (GstMseSrcPad * pad, GstObject * parent, + GstPadMode mode, gboolean active); + +static GstPadLinkReturn pad_linked (GstMseSrcPad * pad, GstMseSrc * parent, + GstPad * sink); +static gboolean pad_event (GstMseSrcPad * pad, GstMseSrc * parent, + GstEvent * event); +static gboolean pad_query (GstMseSrcPad * pad, GstObject * parent, + GstQuery * query); +static void pad_task (GstMseSrcPad * pad); + +static ReadyStateUpdateTask *ready_state_update_task_new (GstMseSrc * parent); +static void ready_state_update_task_free (ReadyStateUpdateTask * task); +static void ready_state_update_task_func (ReadyStateUpdateTask * task); +static void ready_state_update_task_start (ReadyStateUpdateTask * task); +static void ready_state_update_task_stop (ReadyStateUpdateTask * task); +static void ready_state_update_task_join (ReadyStateUpdateTask * task); + +static const gchar * +mse_src_ready_state_name (GstMseSrcReadyState state) +{ + return gst_mse_enum_value_nick (gst_mse_src_ready_state_get_type (), state); +} + +static GstPad * +gst_mse_src_pad_new (GstMediaSourceTrack * track, GstStream * stream, + guint id, GstClockTime start, gdouble rate) +{ + gchar *name = g_strdup_printf ("src_%u", id); + GstMseSrcPad *self = g_object_new (GST_TYPE_MSE_SRC_PAD, "name", name, + "direction", GST_PAD_SRC, NULL); + g_free (name); + self->stream = stream; + self->track = track; + self->segment.start = start; + self->segment.rate = rate; + + return GST_PAD (self); +} + +static void +gst_mse_src_pad_init (GstMseSrcPad * self) +{ + gst_segment_init (&self->segment, GST_FORMAT_TIME); + self->sent_stream_collection = FALSE; + self->sent_stream_start = FALSE; + self->sent_initial_caps = FALSE; + self->does_need_segment = TRUE; + self->flushing = FALSE; + g_mutex_init (&self->linked_or_flushing_lock); + g_cond_init (&self->linked_or_flushing_cond); + + gst_pad_set_activatemode_function (GST_PAD (self), + (GstPadActivateModeFunction) pad_activate_mode); + gst_pad_set_link_function (GST_PAD (self), (GstPadLinkFunction) pad_linked); + gst_pad_set_event_function (GST_PAD (self), (GstPadEventFunction) pad_event); + gst_pad_set_query_function (GST_PAD (self), (GstPadQueryFunction) pad_query); +} + +static void +gst_mse_src_pad_finalize (GObject * object) +{ + GstMseSrcPad *self = GST_MSE_SRC_PAD (object); + + gst_clear_caps (&self->most_recent_caps); + g_mutex_clear (&self->linked_or_flushing_lock); + g_cond_clear (&self->linked_or_flushing_cond); + + G_OBJECT_CLASS (gst_mse_src_pad_parent_class)->finalize (object); +} + +static void +gst_mse_src_pad_class_init (GstMseSrcPadClass * klass) +{ + GObjectClass *oclass = G_OBJECT_CLASS (klass); + oclass->finalize = GST_DEBUG_FUNCPTR (gst_mse_src_pad_finalize); +} + +// TODO: Check if this struct is even necessary. +// The custom pad should be able to keep track of information for each track. +typedef struct +{ + GstMediaSourceTrack *track; + GstPad *pad; + GstStream *info; +} Stream; + +/** + * GstMseSrc: + * + * Since: 1.24 + */ +struct _GstMseSrc +{ + GstElement base; + + GstMediaSource *media_source; + GMutex media_source_lock; + + guint group_id; + GstStreamCollection *collection; + GHashTable *streams; + GMutex streams_lock; + + GstClockTime duration; + GstClockTime start_time; + gdouble rate; + GstMseSrcReadyState ready_state; + + ReadyStateUpdateTask *ready_state_update_task; + + GstFlowCombiner *flow_combiner; + GMutex flow_combiner_lock; + + gchar *uri; +}; + +static void gst_mse_src_uri_handler_init (gpointer g_iface, + gpointer iface_data); +static GstStateChangeReturn gst_mse_src_change_state (GstElement * element, + GstStateChange transition); +static gboolean gst_mse_src_send_event (GstElement * element, GstEvent * event); +static gboolean update_ready_state_for_init_segment (GstMseSrc * self); +static void update_ready_state (GstMseSrc * self); + +G_DEFINE_TYPE_WITH_CODE (GstMseSrc, gst_mse_src, GST_TYPE_ELEMENT, + G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER, gst_mse_src_uri_handler_init)); + +static void +gst_mse_src_constructed (GObject * object) +{ + GstMseSrc *self = GST_MSE_SRC (object); + + G_OBJECT_CLASS (gst_mse_src_parent_class)->constructed (object); + GST_OBJECT_FLAG_SET (self, GST_ELEMENT_FLAG_SOURCE); +} + +static void +gst_mse_src_dispose (GObject * object) +{ + GstMseSrc *self = GST_MSE_SRC (object); + g_clear_pointer (&self->ready_state_update_task, + ready_state_update_task_free); + gst_clear_object (&self->media_source); + g_mutex_clear (&self->media_source_lock); + gst_clear_object (&self->collection); + g_clear_pointer (&self->streams, g_hash_table_unref); + g_mutex_clear (&self->streams_lock); + g_clear_pointer (&self->flow_combiner, gst_flow_combiner_free); + g_mutex_clear (&self->flow_combiner_lock); + G_OBJECT_CLASS (gst_mse_src_parent_class)->dispose (object); +} + +static void +gst_mse_src_finalize (GObject * object) +{ + GstMseSrc *self = GST_MSE_SRC (object); + + g_clear_pointer (&self->uri, g_free); + + G_OBJECT_CLASS (gst_mse_src_parent_class)->finalize (object); +} + +static void +gst_mse_src_get_property (GObject * object, guint prop_id, GValue * value, + GParamSpec * pspec) +{ + GstMseSrc *self = GST_MSE_SRC (object); + + switch (prop_id) { + case PROP_DURATION: + g_value_set_uint64 (value, gst_mse_src_get_duration (self)); + break; + case PROP_POSITION: + g_value_set_uint64 (value, gst_mse_src_get_position (self)); + break; + case PROP_READY_STATE: + g_value_set_enum (value, gst_mse_src_get_ready_state (self)); + break; + case PROP_N_AUDIO: + g_value_set_uint (value, gst_mse_src_get_n_audio (self)); + break; + case PROP_N_TEXT: + g_value_set_uint (value, gst_mse_src_get_n_text (self)); + break; + case PROP_N_VIDEO: + g_value_set_uint (value, gst_mse_src_get_n_video (self)); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +static void +gst_mse_src_set_property (GObject * object, guint prop_id, + const GValue * value, GParamSpec * pspec) +{ + GstMseSrc *self = GST_MSE_SRC (object); + + switch (prop_id) { + case PROP_DURATION: + gst_mse_src_set_duration (self, g_value_get_uint64 (value)); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +static void +gst_mse_src_class_init (GstMseSrcClass * klass) +{ + GObjectClass *oclass = (GObjectClass *) klass; + GstElementClass *eclass = (GstElementClass *) klass; + + oclass->constructed = GST_DEBUG_FUNCPTR (gst_mse_src_constructed); + oclass->finalize = GST_DEBUG_FUNCPTR (gst_mse_src_finalize); + oclass->dispose = GST_DEBUG_FUNCPTR (gst_mse_src_dispose); + oclass->get_property = GST_DEBUG_FUNCPTR (gst_mse_src_get_property); + oclass->set_property = GST_DEBUG_FUNCPTR (gst_mse_src_set_property); + + eclass->change_state = GST_DEBUG_FUNCPTR (gst_mse_src_change_state); + eclass->send_event = GST_DEBUG_FUNCPTR (gst_mse_src_send_event); + + /** + * GstMseSrc:position: + * + * The playback position as a #GstClockTime + * + * [Specification](https://html.spec.whatwg.org/multipage/media.html#current-playback-position) + * + * Since: 1.24 + */ + properties[PROP_POSITION] = g_param_spec_uint64 ("position", + "Position", + "The playback position as a GstClockTime", + 0, G_MAXUINT64, DEFAULT_POSITION, G_PARAM_READABLE | + G_PARAM_STATIC_STRINGS); + + /** + * GstMseSrc:duration: + * + * The duration of the stream as a #GstClockTime + * + * [Specification](https://html.spec.whatwg.org/multipage/media.html#dom-media-duration) + * + * Since: 1.24 + */ + properties[PROP_DURATION] = g_param_spec_uint64 ("duration", + "Duration", + "The duration of the stream as a GstClockTime", + 0, G_MAXUINT64, DEFAULT_DURATION, G_PARAM_READWRITE | + G_PARAM_STATIC_STRINGS); + + /** + * GstMseSrc:ready-state: + * + * The Ready State of this element, describing to what level it can supply + * content for the current #GstMseSrc:position. This is a separate concept + * from #GstMediaSource:ready-state: and corresponds to the HTML Media + * Element's Ready State. + * + * [Specification](https://html.spec.whatwg.org/multipage/media.html#ready-states) + * + * Since: 1.24 + */ + properties[PROP_READY_STATE] = g_param_spec_enum ("ready-state", + "Ready State", + "The Ready State of this Element", + GST_TYPE_MSE_SRC_READY_STATE, + DEFAULT_READY_STATE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS); + + /** + * GstMseSrc:n-audio: + * + * The number of audio tracks in the Media Source + * + * Since: 1.24 + */ + properties[PROP_N_AUDIO] = g_param_spec_uint ("n-audio", + "Number of Audio Tracks", + "The number of audio tracks in the Media Source", + 0, G_MAXINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS); + + /** + * GstMseSrc:n-text: + * + * The number of text tracks in the Media Source + * + * Since: 1.24 + */ + properties[PROP_N_TEXT] = g_param_spec_uint ("n-text", + "Number of Text Tracks", + "The number of text tracks in the Media Source", + 0, G_MAXINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS); + + /** + * GstMseSrc:n-video: + * + * The number of video tracks in the Media Source + * + * Since: 1.24 + */ + properties[PROP_N_VIDEO] = g_param_spec_uint ("n-video", + "Number of Video Tracks", + "The number of video tracks in the Media Source", + 0, G_MAXINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS); + + g_object_class_install_properties (oclass, N_PROPS, properties); + + gst_element_class_set_static_metadata (eclass, "MseSrc", + "Generic/Source", + "Implements a GStreamer Source for the gstreamer-mse API", "Collabora"); + gst_element_class_add_static_pad_template (eclass, &gst_mse_src_template); + + gst_mse_init_logging (); +} + +static void +clear_stream (Stream * stream) +{ + gst_clear_object (&stream->track); + gst_clear_object (&stream->info); + g_free (stream); +} + +static GHashTable * +streams_init (const GstMseSrc * self) +{ + return g_hash_table_new_full (g_direct_hash, g_direct_equal, + NULL, (GDestroyNotify) clear_stream); +} + +static GstStreamCollection * +collection_init (const GstMseSrc * self) +{ + return gst_stream_collection_new (G_OBJECT_TYPE_NAME (self)); +} + +static ReadyStateUpdateTask * +ready_state_update_task_new (GstMseSrc * parent) +{ + ReadyStateUpdateTask *task = g_new0 (ReadyStateUpdateTask, 1); + g_rec_mutex_init (&task->mutex); + g_weak_ref_init (&task->parent, parent); + task->task = + gst_task_new ((GstTaskFunction) ready_state_update_task_func, task, NULL); + gst_task_set_lock (task->task, &task->mutex); + return task; +} + +static void +ready_state_update_task_free (ReadyStateUpdateTask * task) +{ + g_weak_ref_set (&task->parent, NULL); + gst_task_join (task->task); + gst_clear_object (&task->task); + g_weak_ref_clear (&task->parent); + g_rec_mutex_clear (&task->mutex); + g_free (task); +} + +static void +ready_state_update_task_start (ReadyStateUpdateTask * task) +{ + GstMseSrc *parent = g_weak_ref_get (&task->parent); + if (parent) { + gchar *name = g_strdup_printf ("%s:ready-state", GST_OBJECT_NAME (parent)); + g_object_set (task->task, "name", name, NULL); + g_clear_pointer (&name, g_free); + } + gst_clear_object (&parent); + gst_task_start (task->task); +} + +static void +ready_state_update_task_stop (ReadyStateUpdateTask * task) +{ + gst_task_stop (task->task); +} + +static void +ready_state_update_task_join (ReadyStateUpdateTask * task) +{ + gst_task_join (task->task); +} + +static void +ready_state_update_task_func (ReadyStateUpdateTask * task) +{ + GstMseSrc *self = (GstMseSrc *) g_weak_ref_get (&task->parent); + + if (self == NULL) { + GST_ERROR_OBJECT (task->task, "parent object is gone, stopping"); + gst_task_stop (task->task); + return; + } + + update_ready_state (self); + gst_object_unref (self); + g_usleep (G_TIME_SPAN_SECOND); +} + +static void +gst_mse_src_init (GstMseSrc * self) +{ + self->group_id = gst_util_group_id_next (); + self->streams = streams_init (self); + self->collection = collection_init (self); + self->uri = NULL; + self->start_time = 0; + self->rate = 1; + self->media_source = NULL; + g_mutex_init (&self->media_source_lock); + g_mutex_init (&self->streams_lock); + self->flow_combiner = gst_flow_combiner_new (); + g_mutex_init (&self->flow_combiner_lock); + self->ready_state_update_task = ready_state_update_task_new (self); +} + +/** + * gst_mse_src_get_position: + * @self: #GstMseSrc instance + * + * Gets the current playback position of @self. + * + * [Specification](https://html.spec.whatwg.org/multipage/media.html#current-playback-position) + * + * Returns: The playback position of this Element as a #GstClockTime + * Since: 1.24 + */ +GstClockTime +gst_mse_src_get_position (GstMseSrc * self) +{ + g_return_val_if_fail (GST_IS_MSE_SRC (self), GST_CLOCK_TIME_NONE); + gint64 position; + gboolean success = gst_element_query_position (GST_ELEMENT (self), + GST_FORMAT_TIME, &position); + if (success) + return (GstClockTime) position; + else + return DEFAULT_POSITION; +} + +static void +update_pad_duration (GstMseSrc * self, GstMseSrcPad * pad) +{ + pad->segment.duration = self->duration; + pad->does_need_segment = TRUE; +} + +void +gst_mse_src_set_duration (GstMseSrc * self, GstClockTime duration) +{ + g_return_if_fail (GST_IS_MSE_SRC (self)); + + self->duration = duration; + + gst_element_foreach_src_pad (GST_ELEMENT (self), + (GstElementForeachPadFunc) update_pad_duration, NULL); + + gst_element_post_message (GST_ELEMENT (self), + gst_message_new_duration_changed (GST_OBJECT (self))); +} + +/** + * gst_mse_src_get_duration: + * @self: #GstMseSrc instance + * + * Gets the duration of @self. + * + * [Specification](https://html.spec.whatwg.org/multipage/media.html#dom-media-duration) + * + * Returns: The duration of this stream as a #GstClockTime + * Since: 1.24 + */ +GstClockTime +gst_mse_src_get_duration (GstMseSrc * self) +{ + g_return_val_if_fail (GST_IS_MSE_SRC (self), DEFAULT_DURATION); + return self->duration; +} + +/** + * gst_mse_src_get_ready_state: + * @self: #GstMseSrc instance + * + * The Ready State of @self, describing to what level it can supply content for + * the current #GstMseSrc:position. This is a separate concept from + * #GstMediaSource:ready-state: and corresponds to the HTML Media Element's + * Ready State. + * + * [Specification](https://html.spec.whatwg.org/multipage/media.html#ready-states) + * + * Returns: the current #GstMseSrcReadyState + * Since: 1.24 + */ +GstMseSrcReadyState +gst_mse_src_get_ready_state (GstMseSrc * self) +{ + g_return_val_if_fail (GST_IS_MSE_SRC (self), DEFAULT_READY_STATE); + return self->ready_state; +} + +static guint +n_streams_by_type (GstMseSrc * self, GstMediaSourceTrackType type) +{ + guint count = 0; + GHashTableIter iter; + g_hash_table_iter_init (&iter, self->streams); + for (gpointer key; g_hash_table_iter_next (&iter, &key, NULL);) { + GstMediaSourceTrack *track = GST_MEDIA_SOURCE_TRACK (key); + GstMediaSourceTrackType stream_type = + gst_media_source_track_get_track_type (track); + if (type == stream_type) { + count++; + } + } + return count; +} + +/** + * gst_mse_src_get_n_audio: + * @self: #GstMseSrc instance + * + * Returns: the number of audio tracks available from this source + * Since: 1.24 + */ +guint +gst_mse_src_get_n_audio (GstMseSrc * self) +{ + g_return_val_if_fail (GST_IS_MSE_SRC (self), 0); + return n_streams_by_type (self, GST_MEDIA_SOURCE_TRACK_TYPE_AUDIO); +} + +/** + * gst_mse_src_get_n_text: + * @self: #GstMseSrc instance + * + * Returns: the number of text tracks available from this source + * Since: 1.24 + */ +guint +gst_mse_src_get_n_text (GstMseSrc * self) +{ + g_return_val_if_fail (GST_IS_MSE_SRC (self), 0); + return n_streams_by_type (self, GST_MEDIA_SOURCE_TRACK_TYPE_TEXT); +} + +/** + * gst_mse_src_get_n_video: + * @self: #GstMseSrc instance + * + * Returns: the number of video tracks available from this source + * Since: 1.24 + */ +guint +gst_mse_src_get_n_video (GstMseSrc * self) +{ + g_return_val_if_fail (GST_IS_MSE_SRC (self), 0); + return n_streams_by_type (self, GST_MEDIA_SOURCE_TRACK_TYPE_VIDEO); +} + +void +gst_mse_src_decode_error (GstMseSrc * self) +{ + g_return_if_fail (GST_IS_MSE_SRC (self)); + GstMseSrcReadyState ready_state = g_atomic_int_get (&self->ready_state); + if (ready_state == GST_MSE_SRC_READY_STATE_HAVE_NOTHING) { + GST_ELEMENT_ERROR (self, STREAM, DECODE, (DECODE_ERROR), + ("the necessary decoder may be missing from this installation")); + } else { + GST_ELEMENT_ERROR (self, STREAM, DECODE, (DECODE_ERROR), + ("the stream may be corrupt")); + } +} + +void +gst_mse_src_network_error (GstMseSrc * self) +{ + g_return_if_fail (GST_IS_MSE_SRC (self)); + GstMseSrcReadyState ready_state = g_atomic_int_get (&self->ready_state); + if (ready_state == GST_MSE_SRC_READY_STATE_HAVE_NOTHING) { + GST_ELEMENT_ERROR (self, RESOURCE, OPEN_READ, (NETWORK_ERROR), + ("an error occurred before any media was read")); + } else { + GST_ELEMENT_ERROR (self, RESOURCE, READ, (NETWORK_ERROR), + ("an error occurred while reading media")); + } +} + +static inline gboolean +is_streamable (GstMediaSourceTrack * track) +{ + switch (gst_media_source_track_get_track_type (track)) { + case GST_MEDIA_SOURCE_TRACK_TYPE_AUDIO: + case GST_MEDIA_SOURCE_TRACK_TYPE_TEXT: + case GST_MEDIA_SOURCE_TRACK_TYPE_VIDEO: + return TRUE; + default: + return FALSE; + } +} + +static GstStream * +create_gst_stream (GstMediaSourceTrack * track) +{ + gchar *stream_id = g_strdup_printf ("%s-%s", + GST_OBJECT_NAME (track), gst_media_source_track_get_id (track)); + GstStream *stream = gst_stream_new (stream_id, + gst_media_source_track_get_initial_caps (track), + gst_media_source_track_get_stream_type (track), GST_STREAM_FLAG_SELECT); + g_free (stream_id); + return stream; +} + +static void +set_flushing_and_signal (GstMseSrcPad * pad) +{ + GST_TRACE_OBJECT (pad, "locking"); + LINKED_OR_FLUSHING_LOCK (pad); + g_atomic_int_set (&pad->flushing, TRUE); + LINKED_OR_FLUSHING_SIGNAL (pad); + LINKED_OR_FLUSHING_UNLOCK (pad); + GST_TRACE_OBJECT (pad, "done"); +} + +static void +clear_flushing (GstMseSrcPad * pad) +{ + GST_TRACE_OBJECT (pad, "locking"); + LINKED_OR_FLUSHING_LOCK (pad); + g_atomic_int_set (&pad->flushing, FALSE); + LINKED_OR_FLUSHING_UNLOCK (pad); + GST_TRACE_OBJECT (pad, "done"); +} + +static void +flush_stream (GstMseSrc * self, Stream * stream, gboolean is_seek) +{ + GstMseSrcPad *pad = GST_MSE_SRC_PAD (stream->pad); + gst_pad_push_event (GST_PAD (pad), gst_event_new_flush_start ()); + + if (is_seek) { + GST_DEBUG_OBJECT (pad, "flushing for seek to %" GST_TIMEP_FORMAT, + &self->start_time); + set_flushing_and_signal (pad); + gst_media_source_track_flush (stream->track); + gst_pad_stop_task (GST_PAD (pad)); + GST_DEBUG_OBJECT (pad, "stopped task"); + GstSegment *segment = &(pad->segment); + segment->base = 0; + segment->start = self->start_time; + segment->position = self->start_time; + segment->time = self->start_time; + segment->rate = self->rate; + } else { + gst_media_source_track_flush (stream->track); + } + + g_atomic_int_set (&pad->does_need_segment, TRUE); + + gst_pad_push_event (GST_PAD (pad), gst_event_new_flush_stop (is_seek)); +} + +static void +flush_all_streams (GstMseSrc * self, gboolean is_seek) +{ + GHashTableIter iter; + g_hash_table_iter_init (&iter, self->streams); + for (gpointer value; g_hash_table_iter_next (&iter, NULL, &value);) { + flush_stream (self, (Stream *) value, is_seek); + } +} + +static void +resume_all_streams (GstMseSrc * self) +{ + GstState state; + gst_element_get_state (GST_ELEMENT (self), &state, NULL, 0); + gboolean active = state > GST_STATE_READY; + + GHashTableIter iter; + g_hash_table_iter_init (&iter, self->streams); + for (gpointer value; g_hash_table_iter_next (&iter, NULL, &value);) { + Stream *stream = value; + GstPad *pad = GST_PAD (stream->pad); + if (active) { + clear_flushing (GST_MSE_SRC_PAD (pad)); + gst_pad_start_task (pad, (GstTaskFunction) pad_task, pad, NULL); + } + } +} + +static void +tear_down_stream (GstMseSrc * self, Stream * stream) +{ + GST_DEBUG_OBJECT (self, "tearing down stream %s", + gst_media_source_track_get_id (stream->track)); + + flush_stream (self, stream, FALSE); + gst_pad_set_active (stream->pad, FALSE); + + if (gst_stream_collection_get_size (self->collection) > 0) { + gst_element_remove_pad (GST_ELEMENT (self), stream->pad); + FLOW_COMBINER_LOCK (self); + gst_flow_combiner_remove_pad (self->flow_combiner, stream->pad); + FLOW_COMBINER_UNLOCK (self); + } +} + + +static void +tear_down_all_streams (GstMseSrc * self) +{ + GHashTableIter iter; + g_hash_table_iter_init (&iter, self->streams); + for (gpointer value; g_hash_table_iter_next (&iter, NULL, &value);) { + tear_down_stream (self, (Stream *) value); + g_hash_table_iter_remove (&iter); + } +} + +static GstStateChangeReturn +gst_mse_src_change_state (GstElement * element, GstStateChange transition) +{ + GstMseSrc *self = GST_MSE_SRC (element); + switch (transition) { + case GST_STATE_CHANGE_PAUSED_TO_READY: + ready_state_update_task_stop (self->ready_state_update_task); + tear_down_all_streams (self); + break; + case GST_STATE_CHANGE_READY_TO_NULL: + ready_state_update_task_join (self->ready_state_update_task); + gst_mse_src_detach (self); + break; + case GST_STATE_CHANGE_READY_TO_PAUSED: + ready_state_update_task_start (self->ready_state_update_task); + break; + default: + break; + } + return GST_ELEMENT_CLASS (gst_mse_src_parent_class)->change_state (element, + transition); +} + +static void +gst_mse_src_seek (GstMseSrc * self, GstClockTime start_time, gdouble rate) +{ + GST_OBJECT_LOCK (self); + self->start_time = start_time; + self->rate = rate; + GST_OBJECT_UNLOCK (self); + + MEDIA_SOURCE_LOCK (self); + flush_all_streams (self, TRUE); + if (self->media_source) { + GST_DEBUG_OBJECT (self, "seeking on media source %" GST_PTR_FORMAT, + self->media_source); + gst_media_source_seek (self->media_source, start_time); + } else { + GST_DEBUG_OBJECT (self, "detached, not seeking on media source"); + } + MEDIA_SOURCE_UNLOCK (self); + resume_all_streams (self); +} + +static gboolean +gst_mse_src_send_event (GstElement * element, GstEvent * event) +{ + if (GST_EVENT_TYPE (event) != GST_EVENT_SEEK) { + return GST_ELEMENT_CLASS (gst_mse_src_parent_class)->send_event (element, + event); + } + + GstMseSrc *self = GST_MSE_SRC (element); + + gdouble rate; + GstFormat format; + GstSeekType seek_type; + gint64 start; + gst_event_parse_seek (event, &rate, &format, NULL, &seek_type, &start, NULL, + NULL); + + gst_event_unref (event); + + if (format != GST_FORMAT_TIME || seek_type != GST_SEEK_TYPE_SET || rate < 0) { + GST_ERROR_OBJECT (self, + "Rejecting unsupported seek event: %" GST_PTR_FORMAT, event); + return FALSE; + } + + GST_DEBUG_OBJECT (self, "handling %" GST_PTR_FORMAT, event); + gst_mse_src_seek (self, start, rate); + return TRUE; +} + +static inline gboolean +is_flushing (GstMseSrcPad * pad) +{ + return g_atomic_int_get (&pad->flushing) || GST_PAD_IS_FLUSHING (pad); +} + +static gboolean +await_pad_linked_or_flushing (GstMseSrcPad * pad) +{ + GST_TRACE_OBJECT (pad, "waiting for link"); + LINKED_OR_FLUSHING_LOCK (pad); + gboolean flushing = FALSE; + while (!gst_pad_is_linked (GST_PAD_CAST (pad)) && !is_flushing (pad)) { + LINKED_OR_FLUSHING_WAIT (pad); + } + flushing = is_flushing (pad); + LINKED_OR_FLUSHING_UNLOCK (pad); + GST_TRACE_OBJECT (pad, "linked"); + return flushing; +} + +static void +pad_task (GstMseSrcPad * pad) +{ + GstMseSrc *self = NULL; + gboolean flushing = await_pad_linked_or_flushing (pad); + if (flushing) { + GST_TRACE_OBJECT (pad, "pad is flushing"); + goto pause; + } + + self = GST_MSE_SRC (gst_pad_get_parent_element (GST_PAD (pad))); + + GstMediaSourceTrack *track = pad->track; + + GstMiniObject *object = gst_media_source_track_pop (track); + + if (object == NULL) { + GST_DEBUG_OBJECT (pad, "nothing was popped from track, must be flushing"); + gst_media_source_track_flush (track); + goto pause; + } + + if (!g_atomic_int_get (&pad->sent_stream_start)) { + const gchar *track_id = gst_media_source_track_get_id (track); + GstEvent *event = gst_event_new_stream_start (track_id); + gst_event_set_group_id (event, self->group_id); + gst_event_set_stream (event, pad->stream); + if (!gst_pad_push_event (GST_PAD (pad), event)) { + GST_ERROR_OBJECT (pad, "failed to push stream start"); + goto pause; + } + GST_TRACE_OBJECT (pad, "stream start"); + g_atomic_int_set (&pad->sent_stream_start, TRUE); + } + + GstCaps *caps = gst_media_source_track_get_initial_caps (track); + if (!g_atomic_int_get (&pad->sent_initial_caps) && GST_IS_CAPS (caps)) { + GST_DEBUG_OBJECT (pad, "sending initial caps"); + gst_caps_replace (&pad->most_recent_caps, caps); + GstEvent *event = gst_event_new_caps (caps); + if (!gst_pad_push_event (GST_PAD (pad), event)) { + GST_ERROR_OBJECT (pad, "failed to push caps update"); + goto pause; + } + GST_TRACE_OBJECT (pad, "initial caps %" GST_PTR_FORMAT, caps); + g_atomic_int_set (&pad->sent_initial_caps, TRUE); + } + + if (g_atomic_int_get (&pad->does_need_segment)) { + GST_DEBUG_OBJECT (pad, "sending new segment starting@%" GST_TIMEP_FORMAT, + &pad->segment.time); + GstEvent *event = gst_event_new_segment (&pad->segment); + if (!gst_pad_push_event (GST_PAD (pad), event)) { + GST_ERROR_OBJECT (pad, "failed to push new segment"); + goto pause; + } + GST_TRACE_OBJECT (pad, "segment"); + g_atomic_int_set (&pad->does_need_segment, FALSE); + } + + if (!g_atomic_int_get (&pad->sent_stream_collection)) { + GstEvent *event = gst_event_new_stream_collection (self->collection); + if (!gst_pad_push_event (GST_PAD (pad), event)) { + GST_ERROR_OBJECT (pad, "failed to push stream collection"); + goto pause; + } + GST_TRACE_OBJECT (pad, "stream collection"); + g_atomic_int_set (&pad->sent_stream_collection, TRUE); + } + + if (GST_IS_SAMPLE (object)) { + GstSample *sample = GST_SAMPLE (object); + GstCaps *sample_caps = gst_sample_get_caps (sample); + + if (!gst_caps_is_equal (pad->most_recent_caps, sample_caps)) { + gst_caps_replace (&pad->most_recent_caps, sample_caps); + GstEvent *event = gst_event_new_caps (gst_caps_ref (sample_caps)); + if (!gst_pad_push_event (GST_PAD (pad), event)) { + GST_ERROR_OBJECT (pad, "failed to push new caps"); + goto pause; + } + GST_TRACE_OBJECT (pad, "new caps %" GST_PTR_FORMAT, sample_caps); + } + + GstBuffer *buffer = gst_buffer_copy (gst_sample_get_buffer (sample)); + if (GST_BUFFER_DTS_IS_VALID (buffer)) { + GstClockTime duration = + GST_BUFFER_DURATION_IS_VALID (buffer) ? GST_BUFFER_DURATION (buffer) : + 1; + GstClockTime buffer_end = GST_BUFFER_DTS (buffer) + duration; + pad->segment.position = MAX (pad->segment.position, buffer_end); + } + + GstFlowReturn push_result = gst_pad_push (GST_PAD (pad), buffer); + + FLOW_COMBINER_LOCK (self); + GstFlowReturn combined_result = + gst_flow_combiner_update_pad_flow (self->flow_combiner, + GST_PAD_CAST (pad), push_result); + FLOW_COMBINER_UNLOCK (self); + + switch (combined_result) { + case GST_FLOW_OK: + break; + case GST_FLOW_FLUSHING: + goto pause; + default: + GST_ELEMENT_ERROR (self, CORE, PAD, ("failed to push data downstream"), + ("pad result: %s, combined result %s", + gst_flow_get_name (push_result), + gst_flow_get_name (combined_result))); + goto pause; + } + } else if (GST_IS_EVENT (object)) { + GstEvent *event = GST_EVENT (g_steal_pointer (&object)); + if (GST_EVENT_TYPE (event) == GST_EVENT_EOS) { + GST_LOG_OBJECT (self, "EOS"); + } + if (!gst_pad_push_event (GST_PAD (pad), event)) { + GST_ERROR_OBJECT (self, "failed to push enqueued event"); + goto pause; + } + } else { + GST_ERROR_OBJECT (self, "unexpected object on track queue" + ", only samples and events are supported"); + g_assert_not_reached (); + } + + gst_clear_object (&self); + return; + +pause: + if (!g_atomic_int_get (&pad->flushing)) { + gst_pad_pause_task (GST_PAD (pad)); + } + gst_clear_object (&self); +} + +static gboolean +pad_activate_mode (GstMseSrcPad * pad, GstObject * parent, GstPadMode mode, + gboolean active) +{ + if (mode != GST_PAD_MODE_PUSH) { + GST_ERROR_OBJECT (parent, "msesrc only supports push mode"); + return FALSE; + } + + if (active) { + gst_pad_start_task (GST_PAD (pad), (GstTaskFunction) pad_task, pad, NULL); + } else { + set_flushing_and_signal (pad); + gst_media_source_track_flush (pad->track); + gst_pad_stop_task (GST_PAD (pad)); + clear_flushing (pad); + } + + return TRUE; +} + +static GstPadLinkReturn +pad_linked (GstMseSrcPad * pad, GstMseSrc * parent, GstPad * sink) +{ + GST_DEBUG_OBJECT (pad, "pad is linked to %" GST_PTR_FORMAT ", resuming task", + sink); + LINKED_OR_FLUSHING_LOCK (pad); + LINKED_OR_FLUSHING_SIGNAL (pad); + LINKED_OR_FLUSHING_UNLOCK (pad); + return GST_PAD_LINK_OK; +} + +static gboolean +pad_event (GstMseSrcPad * pad, GstMseSrc * parent, GstEvent * event) +{ + switch (GST_EVENT_TYPE (event)) { + case GST_EVENT_SEEK: + return gst_element_send_event (GST_ELEMENT (parent), event); + default: + return gst_pad_event_default (GST_PAD (pad), GST_OBJECT (parent), event); + } +} + +static gboolean +pad_query (GstMseSrcPad * pad, GstObject * parent, GstQuery * query) +{ + GstMseSrc *self = GST_MSE_SRC (parent); + switch (GST_QUERY_TYPE (query)) { + case GST_QUERY_POSITION:{ + GstClockTime position = pad->segment.position; + GstFormat fmt; + gst_query_parse_position (query, &fmt, NULL); + if (fmt == GST_FORMAT_TIME && GST_CLOCK_TIME_IS_VALID (position)) { + GST_TRACE_OBJECT (pad, "position query returning %" GST_TIMEP_FORMAT, + &position); + gst_query_set_position (query, GST_FORMAT_TIME, position); + return TRUE; + } + break; + } + case GST_QUERY_DURATION:{ + GstFormat fmt; + gst_query_parse_duration (query, &fmt, NULL); + if (fmt == GST_FORMAT_TIME) { + gst_query_set_duration (query, GST_FORMAT_TIME, self->duration); + return TRUE; + } else { + return FALSE; + } + } + case GST_QUERY_SEEKING:{ + GstFormat fmt; + gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL); + if (fmt != GST_FORMAT_TIME) { + return FALSE; + } + gst_query_set_seeking (query, GST_FORMAT_TIME, TRUE, 0, self->duration); + return TRUE; + } + default: + break; + } + return gst_pad_query_default (GST_PAD (pad), parent, query); +} + +static void +append_stream (GstMseSrc * self, GstMediaSourceTrack * track) +{ + if (g_hash_table_contains (self->streams, track)) { + GST_DEBUG_OBJECT (self, "skipping processed %" GST_PTR_FORMAT, track); + return; + } + GST_DEBUG_OBJECT (self, "creating stream for %" GST_PTR_FORMAT, track); + guint pad_index = g_hash_table_size (self->streams); + GstStream *info = create_gst_stream (track); + Stream stream = { + .info = gst_object_ref (info), + .track = gst_object_ref (track), + .pad = gst_mse_src_pad_new (track, info, pad_index, + self->start_time, self->rate), + }; + g_hash_table_insert (self->streams, track, + g_memdup2 (&stream, sizeof (Stream))); + gst_stream_collection_add_stream (self->collection, stream.info); +} + +void +gst_mse_src_emit_streams (GstMseSrc * self, GstMediaSourceTrack ** tracks, + gsize n_tracks) +{ + g_return_if_fail (GST_IS_MSE_SRC (self)); + + GstElement *element = GST_ELEMENT (self); + GstObject *object = GST_OBJECT (self); + + /* Nacre patch: expose no stream until every SourceBuffer of the attached + * MediaSource has received its first init segment (MSE "init segment + * received" step 5 / HAVE_METADATA). Exposing the first buffer's tracks alone + * made playbin preroll on them and never take the later ones, so separate + * audio and video SourceBuffers stalled at HAVE_NOTHING. */ + if (!update_ready_state_for_init_segment (self)) { + GST_DEBUG_OBJECT (self, "waiting for every source buffer's init segment"); + return; + } + + STREAMS_LOCK (self); + + for (gsize i = 0; i < n_tracks; i++) { + GstMediaSourceTrack *track = tracks[i]; + if (!is_streamable (track)) { + continue; + } + append_stream (self, track); + } + + GstState state; + gst_element_get_state (element, &state, NULL, 0); + gboolean active = state > GST_STATE_READY; + + GHashTableIter iter; + g_hash_table_iter_init (&iter, self->streams); + for (gpointer value; g_hash_table_iter_next (&iter, NULL, &value);) { + Stream *stream = value; + GstPad *pad = stream->pad; + if (active) { + gst_pad_set_active (pad, TRUE); + } + GstElement *parent = gst_pad_get_parent_element (pad); + if (parent) { + GST_DEBUG_OBJECT (self, "skipping parented pad %" GST_PTR_FORMAT, pad); + gst_object_unref (parent); + continue; + } + gst_element_add_pad (element, pad); + FLOW_COMBINER_LOCK (self); + gst_flow_combiner_add_pad (self->flow_combiner, pad); + FLOW_COMBINER_UNLOCK (self); + } + STREAMS_UNLOCK (self); + + gst_element_no_more_pads (element); + gst_element_post_message (element, gst_message_new_stream_collection (object, + self->collection)); +} + +static GstURIType +gst_mse_src_uri_get_type (GType type) +{ + return GST_URI_SRC; +} + +static const gchar *const * +gst_mse_src_uri_get_protocols (GType type) +{ + static const gchar *protocols[] = { "mse", NULL }; + return protocols; +} + +static gchar * +gst_mse_src_uri_get_uri (GstURIHandler * handler) +{ + GstMseSrc *self = GST_MSE_SRC (handler); + GST_OBJECT_LOCK (self); + gchar *uri = g_strdup (self->uri); + GST_OBJECT_UNLOCK (self); + return uri; +} + +static gboolean +gst_mse_src_uri_set_uri (GstURIHandler * handler, const gchar * uri, + GError ** error) +{ + GstMseSrc *self = GST_MSE_SRC (handler); + GST_OBJECT_LOCK (self); + g_free (self->uri); + self->uri = g_strdup (uri); + GST_OBJECT_UNLOCK (self); + return TRUE; +} + +static void +gst_mse_src_uri_handler_init (gpointer g_iface, gpointer iface_data) +{ + GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface; + iface->get_type = gst_mse_src_uri_get_type; + iface->get_protocols = gst_mse_src_uri_get_protocols; + iface->get_uri = gst_mse_src_uri_get_uri; + iface->set_uri = gst_mse_src_uri_set_uri; +} + +void +gst_mse_src_attach (GstMseSrc * self, GstMediaSource * media_source) +{ + g_return_if_fail (GST_IS_MSE_SRC (self)); + g_return_if_fail (GST_IS_MEDIA_SOURCE (media_source)); + + MEDIA_SOURCE_LOCK (self); + g_set_object (&self->media_source, media_source); + MEDIA_SOURCE_UNLOCK (self); +} + +void +gst_mse_src_detach (GstMseSrc * self) +{ + g_return_if_fail (GST_IS_MSE_SRC (self)); + + MEDIA_SOURCE_LOCK (self); + gst_clear_object (&self->media_source); + MEDIA_SOURCE_UNLOCK (self); +} + +static void +set_ready_state (GstMseSrc * self, GstMseSrcReadyState ready_state) +{ + if (ready_state == self->ready_state) { + return; + } + GST_DEBUG_OBJECT (self, "ready state %s=>%s", + mse_src_ready_state_name (self->ready_state), + mse_src_ready_state_name (ready_state)); + self->ready_state = ready_state; + g_object_notify_by_pspec (G_OBJECT (self), properties[PROP_READY_STATE]); +} + +/* Nacre patch: returns whether every source buffer has received an init + * segment (TRUE once past HAVE_NOTHING, or when detached), and no longer leaves + * media_source_lock held on the "not yet" path, which deadlocked the ready + * state task and anything else taking that lock. */ +static gboolean +update_ready_state_for_init_segment (GstMseSrc * self) +{ + gboolean all_received_init_segment = TRUE; + + MEDIA_SOURCE_LOCK (self); + + if (self->media_source == NULL) { + goto done; + } + if (self->ready_state != GST_MSE_SRC_READY_STATE_HAVE_NOTHING) { + goto done; + } + GstSourceBufferList *buffers = gst_media_source_get_source_buffers + (self->media_source); + for (guint i = 0; all_received_init_segment; i++) { + GstSourceBuffer *buf = gst_source_buffer_list_index (buffers, i); + if (buf == NULL) { + break; + } + all_received_init_segment &= gst_source_buffer_has_init_segment (buf); + gst_object_unref (buf); + } + gst_object_unref (buffers); + if (!all_received_init_segment) { + goto done; + } + set_ready_state (self, MAX (self->ready_state, + GST_MSE_SRC_READY_STATE_HAVE_METADATA)); + +done: + MEDIA_SOURCE_UNLOCK (self); + return all_received_init_segment; +} + +static gboolean +has_current_data (GstMseSrc * self, GstClockTime position, + GstClockTime duration) +{ + if (!GST_CLOCK_TIME_IS_VALID (position)) { + return FALSE; + } + GstSourceBufferList *active = + gst_media_source_get_active_source_buffers (self->media_source); + gboolean has_data = TRUE; + for (guint i = 0; has_data; i++) { + GstSourceBuffer *buf = gst_source_buffer_list_index (active, i); + if (buf == NULL) { + if (i == 0) { + has_data = FALSE; + GST_DEBUG_OBJECT (self, + "no active source buffers, nothing is buffered"); + } + break; + } + has_data = gst_source_buffer_is_buffered (buf, position); + gst_object_unref (buf); + } + g_object_unref (active); + return has_data; +} + +static gboolean +has_future_data (GstMseSrc * self, GstClockTime position, GstClockTime duration) +{ + if (!GST_CLOCK_TIME_IS_VALID (position) + || !GST_CLOCK_TIME_IS_VALID (duration)) { + return FALSE; + } + GstClockTime target_position = MIN (position + THRESHOLD_FUTURE_DATA, + duration); + GstSourceBufferList *active = + gst_media_source_get_active_source_buffers (self->media_source); + gboolean has_data = TRUE; + for (guint i = 0; has_data; i++) { + GstSourceBuffer *buf = gst_source_buffer_list_index (active, i); + if (buf == NULL) { + if (i == 0) { + has_data = FALSE; + GST_DEBUG_OBJECT (self, + "no active source buffers, nothing is buffered"); + } + break; + } + has_data = gst_source_buffer_is_range_buffered (buf, position, + target_position); + gst_object_unref (buf); + } + g_object_unref (active); + return has_data; +} + +static gboolean +has_enough_data (GstMseSrc * self, GstClockTime position, GstClockTime duration) +{ + if (!GST_CLOCK_TIME_IS_VALID (position) + || !GST_CLOCK_TIME_IS_VALID (duration)) { + return FALSE; + } + GstClockTime target_position = MIN (position + THRESHOLD_ENOUGH_DATA, + duration); + GstSourceBufferList *active = + gst_media_source_get_active_source_buffers (self->media_source); + gboolean has_data = TRUE; + for (guint i = 0; has_data; i++) { + GstSourceBuffer *buf = gst_source_buffer_list_index (active, i); + if (buf == NULL) { + if (i == 0) { + has_data = FALSE; + GST_DEBUG_OBJECT (self, + "no active source buffers, nothing is buffered"); + } + break; + } + has_data = gst_source_buffer_is_range_buffered (buf, position, + target_position); + gst_object_unref (buf); + } + g_object_unref (active); + return has_data; +} + +static void +update_ready_state (GstMseSrc * self) +{ + MEDIA_SOURCE_LOCK (self); + + if (self->media_source == NULL) { + goto done; + } + + if (self->ready_state < GST_MSE_SRC_READY_STATE_HAVE_METADATA) { + goto done; + } + + GstClockTime position = gst_mse_src_get_position (self); + GstClockTime duration = self->duration; + + if (has_enough_data (self, position, duration)) { + set_ready_state (self, GST_MSE_SRC_READY_STATE_HAVE_ENOUGH_DATA); + } else if (has_future_data (self, position, duration)) { + set_ready_state (self, GST_MSE_SRC_READY_STATE_HAVE_FUTURE_DATA); + } else if (has_current_data (self, position, duration)) { + set_ready_state (self, GST_MSE_SRC_READY_STATE_HAVE_CURRENT_DATA); + } else { + set_ready_state (self, GST_MSE_SRC_READY_STATE_HAVE_METADATA); + } + +done: + MEDIA_SOURCE_UNLOCK (self); +} diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstmsesrc.h b/vendor/gst-mse/gst-libs/gst/mse/gstmsesrc.h new file mode 100644 index 0000000..1a7ff14 --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstmsesrc.h @@ -0,0 +1,94 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2009, 2010 Sebastian Dröge + * Copyright (C) 2013, 2022, 2023 Collabora Ltd. + * Copyright (C) 2013 Orange + * Copyright (C) 2014, 2015 Sebastian Dröge + * Copyright (C) 2015, 2016, 2018, 2019, 2020, 2021 Igalia, S.L + * Copyright (C) 2015, 2016, 2018, 2019, 2020, 2021 Metrological Group B.V. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#pragma once + +#include +#include + +G_BEGIN_DECLS + +/** + * GstMseSrcReadyState: + * @GST_MSE_SRC_READY_STATE_HAVE_NOTHING: No information is available about the + * stream + * @GST_MSE_SRC_READY_STATE_HAVE_METADATA: The duration is available and video + * dimensions are available if the stream contains video + * @GST_MSE_SRC_READY_STATE_HAVE_CURRENT_DATA: The current playback position can + * be presented but future information is not available + * @GST_MSE_SRC_READY_STATE_HAVE_FUTURE_DATA: There is data for the current + * position and some amount in the future and any text tracks are ready. + * @GST_MSE_SRC_READY_STATE_HAVE_ENOUGH_DATA: Either there is enough data to + * play the stream through at the current playback and input rate or the input + * buffer is full. + * + * Describes how much information a #GstMseSrc has about the media it is playing + * back at the current playback #GstMseSrc:position. This type corresponds + * directly to the ready state of a HTML Media Element and is a separate concept + * from #GstMediaSourceReadyState. + * + * [Specification](https://html.spec.whatwg.org/multipage/media.html#ready-states) + * + * Since: 1.24 + */ +typedef enum +{ + GST_MSE_SRC_READY_STATE_HAVE_NOTHING, + GST_MSE_SRC_READY_STATE_HAVE_METADATA, + GST_MSE_SRC_READY_STATE_HAVE_CURRENT_DATA, + GST_MSE_SRC_READY_STATE_HAVE_FUTURE_DATA, + GST_MSE_SRC_READY_STATE_HAVE_ENOUGH_DATA, +} GstMseSrcReadyState; + +#define GST_TYPE_MSE_SRC (gst_mse_src_get_type()) +#define GST_TYPE_MSE_SRC_PAD (gst_mse_src_pad_get_type()) + +GST_MSE_API +G_DECLARE_FINAL_TYPE (GstMseSrc, gst_mse_src, GST, MSE_SRC, GstElement); + +GST_MSE_API +G_DECLARE_FINAL_TYPE (GstMseSrcPad, gst_mse_src_pad, GST, MSE_SRC_PAD, GstPad); + +GST_MSE_API +GstClockTime gst_mse_src_get_position (GstMseSrc * self); + +GST_MSE_API +GstClockTime gst_mse_src_get_duration (GstMseSrc * self); + +GST_MSE_API +GstMseSrcReadyState gst_mse_src_get_ready_state (GstMseSrc * self); + +GST_MSE_API +guint gst_mse_src_get_n_audio (GstMseSrc * self); + +GST_MSE_API +guint gst_mse_src_get_n_text (GstMseSrc * self); + +GST_MSE_API +guint gst_mse_src_get_n_video (GstMseSrc * self); + +G_END_DECLS diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstsourcebuffer-private.h b/vendor/gst-mse/gst-libs/gst/mse/gstsourcebuffer-private.h new file mode 100644 index 0000000..17ae1af --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstsourcebuffer-private.h @@ -0,0 +1,72 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#pragma once + +#include +#include "gstsourcebuffer.h" + +G_BEGIN_DECLS + +typedef struct +{ + void (*duration_changed) (GstSourceBuffer * self, gpointer user_data); + void (*received_init_segment) (GstSourceBuffer * self, gpointer user_data); + void (*active_state_changed) (GstSourceBuffer * self, gpointer user_data); +} GstSourceBufferCallbacks; + +GST_MSE_PRIVATE +GstSourceBuffer * gst_source_buffer_new (const gchar * content_type, + GstObject * parent, GError ** error); + +GST_MSE_PRIVATE +GstSourceBuffer * gst_source_buffer_new_with_callbacks ( + const gchar * content_type, GstObject * parent, + GstSourceBufferCallbacks *callbacks, gpointer user_data, GError ** error); + +GST_MSE_PRIVATE +void gst_source_buffer_teardown (GstSourceBuffer * self); + +GST_MSE_PRIVATE +gboolean gst_source_buffer_has_init_segment (GstSourceBuffer * self); + +GST_MSE_PRIVATE +gboolean gst_source_buffer_is_buffered (GstSourceBuffer * self, GstClockTime + time); + +GST_MSE_PRIVATE +gboolean gst_source_buffer_is_range_buffered (GstSourceBuffer * self, + GstClockTime start, GstClockTime end); + +GST_MSE_PRIVATE +GstClockTime gst_source_buffer_get_duration (GstSourceBuffer * self); + +GST_MSE_PRIVATE +GPtrArray * gst_source_buffer_get_all_tracks (GstSourceBuffer * self); + +GST_MSE_PRIVATE +void gst_source_buffer_seek (GstSourceBuffer * self, GstClockTime time); + +GST_MSE_PRIVATE +gboolean gst_source_buffer_get_active (GstSourceBuffer * self); + +G_END_DECLS diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstsourcebuffer.c b/vendor/gst-mse/gst-libs/gst/mse/gstsourcebuffer.c new file mode 100644 index 0000000..1dbca9a --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstsourcebuffer.c @@ -0,0 +1,2256 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013 Orange + * Copyright (C) 2013-2020 Apple Inc. All rights reserved. + * Copyright (C) 2014 Sebastian Dröge + * Copyright (C) 2015, 2016, 2017 Igalia, S.L + * Copyright (C) 2015, 2016, 2017 Metrological Group B.V. + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +/** + * SECTION:gstsourcebuffer + * @title: GstSourceBuffer + * @short_description: Source Buffer + * @include: mse/mse.h + * @symbols: + * - GstSourceBuffer + * + * The Source Buffer is the primary means of data flow between an application + * and the Media Source API. It represents a single timeline of media, + * containing some combination of audio, video, and text tracks. + * An application is responsible for feeding raw data into the Source Buffer + * using gst_source_buffer_append_buffer() and the Source Buffer will + * asynchronously process the data into tracks of time-coded multimedia samples. + * + * The application as well as the associated playback component can then select + * to play media from any subset of tracks across all Source Buffers of a Media + * Source. + * + * A few control points are also provided to customize the behavior. + * + * - #GstSourceBuffer:append-mode controls how timestamps of processed samples are + * interpreted. They are either inserted in the timeline directly where the + * decoded media states they should, or inserted directly after the previously + * encountered sample. + * + * - #GstSourceBuffer:append-window-start / #GstSourceBuffer:append-window-end + * control the planned time window where media from appended data can be added + * to the current timeline. Any samples outside that range may be ignored. + * + * - #GstSourceBuffer:timestamp-offset is added to the start time of any sample + * processed. + * + * Since: 1.24 + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include "gstsourcebuffer.h" +#include "gstsourcebuffer-private.h" + +#include "gstmselogging-private.h" +#include "gstmsemediatype-private.h" +#include "gstmseeventqueue-private.h" + +#include "gstappendpipeline-private.h" +#include "gstmediasource.h" +#include "gstmediasource-private.h" +#include "gstmediasourcesamplemap-private.h" +#include "gstmediasourcetrack-private.h" +#include "gstmediasourcetrackbuffer-private.h" +#include "gstsourcebufferlist-private.h" +#include "gstmsesrc.h" +#include "gstmsesrc-private.h" + +#define g_array_new_ranges() \ + (g_array_new (TRUE, FALSE, sizeof (GstMediaSourceRange))) + +typedef struct +{ + GstSourceBufferCallbacks callbacks; + gpointer user_data; +} Callbacks; + +typedef struct +{ + GstSourceBuffer *parent; + GstTask *task; + GRecMutex lock; + gboolean cancelled; +} AppendToBufferTask; + +typedef struct +{ + GWeakRef parent; + + GstMediaSourceTrack *track; + GstMediaSourceTrackBuffer *buffer; + + GstTask *task; + GRecMutex lock; + + gboolean cancelled; +} TrackFeedTask; + +typedef struct +{ + GstSourceBuffer *parent; + GHashTable *processed_samples; + gboolean push_failed; +} TrackFeedAccumulator; + +typedef struct +{ + const GstClockTime time; + gboolean buffered; +} IsBufferedAccumulator; + +typedef struct +{ + const GstClockTime start; + const GstClockTime end; + gboolean start_buffered; + gboolean end_buffered; +} IsRangeBufferedAccumulator; + +/** + * GstSourceBuffer: + * Since: 1.24 + */ +struct _GstSourceBuffer +{ + GstObject parent_instance; + + GstSourceBufferAppendMode append_mode; + GstClockTime append_window_start; + GstClockTime append_window_end; + gchar *content_type; + gboolean generate_timestamps; + GstClockTime timestamp_offset; + gboolean updating; + gboolean errored; + gsize size_limit; + gsize size; + GstBuffer *pending_data; + GCond pending_data_cond; + AppendToBufferTask *append_to_buffer_task; + GstAppendPipeline *append_pipeline; + GstMseEventQueue *event_queue; + + GMutex tracks_lock; + GstClockTime seek_time; + gboolean processed_init_segment; + GHashTable *track_buffers; + GHashTable *track_feeds; + + Callbacks callbacks; +}; + +G_DEFINE_TYPE (GstSourceBuffer, gst_source_buffer, GST_TYPE_OBJECT); + +enum +{ + PROP_0, + + PROP_APPEND_MODE, + PROP_APPEND_WINDOW_START, + PROP_APPEND_WINDOW_END, + PROP_BUFFERED, + PROP_CONTENT_TYPE, + PROP_TIMESTAMP_OFFSET, + PROP_UDPATING, + + N_PROPS, +}; + +typedef enum +{ + ON_UPDATE_START, + ON_UPDATE, + ON_UPDATE_END, + ON_ERROR, + ON_ABORT, + + N_SIGNALS, +} SourceBufferEvent; + +typedef struct +{ + GstDataQueueItem item; + SourceBufferEvent event; +} SourceBufferEventItem; + +#define DEFAULT_BUFFER_SIZE 1 << 24 +#define DEFAULT_APPEND_MODE GST_SOURCE_BUFFER_APPEND_MODE_SEGMENTS + +static GParamSpec *properties[N_PROPS]; +static guint signals[N_SIGNALS]; + +static void call_received_init_segment (GstSourceBuffer * self); +static void call_duration_changed (GstSourceBuffer * self); +static void call_active_state_changed (GstSourceBuffer * self); + +static GArray *get_buffered_unlocked (GstSourceBuffer * self); +static inline gboolean is_removed_unlocked (GstSourceBuffer * self); +static void reset_parser_state_unlocked (GstSourceBuffer * self); +static void append_error_unlocked (GstSourceBuffer * self); + +static void seek_track_buffer_unlocked (GstMediaSourceTrack * track, + GstMediaSourceTrackBuffer * buffer, GstSourceBuffer * self); +static void dispatch_event (SourceBufferEventItem * item, GstSourceBuffer * + self); +static void schedule_event_unlocked (GstSourceBuffer * self, + SourceBufferEvent event); +static void append_to_buffer_task_func (AppendToBufferTask * task); +static void append_to_buffer_task_start (AppendToBufferTask * task); +static void append_to_buffer_task_stop (AppendToBufferTask * task); +static AppendToBufferTask *append_to_buffer_task_new (GstSourceBuffer * parent); +static void append_to_buffer_task_free (AppendToBufferTask * task); +static void track_feed_task (TrackFeedTask * feed); +static void clear_track_feed (TrackFeedTask * feed); +static void stop_track_feed (TrackFeedTask * feed); +static void start_track_feed (TrackFeedTask * feed); +static void reset_track_feed (TrackFeedTask * feed); +static TrackFeedTask *get_track_feed_unlocked (GstSourceBuffer * self, + GstMediaSourceTrack * track); +static GstMediaSourceTrackBuffer *get_track_buffer_unlocked (GstSourceBuffer * + self, GstMediaSourceTrack * track); +static void add_track_feed_unlocked (GstMediaSourceTrack * track, + GstMediaSourceTrackBuffer * track_buffer, GstSourceBuffer * self); +static void add_track_buffer_unlocked (GstMediaSourceTrack * track, + GstSourceBuffer * self); + +static void on_duration_changed (GstAppendPipeline * pipeline, + gpointer user_data); +static void on_eos (GstAppendPipeline * pipeline, GstMediaSourceTrack * track, + gpointer user_data); +static void on_error (GstAppendPipeline * pipeline, gpointer user_data); +static void on_new_sample (GstAppendPipeline * pipeline, + GstMediaSourceTrack * track, GstSample * sample, gpointer user_data); +static void on_received_init_segment (GstAppendPipeline * pipeline, + gpointer user_data); + +#define TRACKS_LOCK(b) g_mutex_lock(&(b)->tracks_lock) +#define TRACKS_UNLOCK(b) g_mutex_unlock(&(b)->tracks_lock) + +static inline GstMediaSource * +get_media_source_unlocked (GstSourceBuffer * self) +{ + GstObject *parent = GST_OBJECT_PARENT (self); + if (parent == NULL) { + return NULL; + } + return GST_MEDIA_SOURCE (gst_object_ref (parent)); +} + +static inline GstMediaSource * +get_media_source (GstSourceBuffer * self) +{ + return GST_MEDIA_SOURCE (gst_object_get_parent (GST_OBJECT (self))); +} + +static void +clear_pending_data_unlocked (GstSourceBuffer * self) +{ + gst_clear_buffer (&self->pending_data); +} + +static GstBuffer * +take_pending_data_unlocked (GstSourceBuffer * self) +{ + return g_steal_pointer (&self->pending_data); +} + +static void +set_pending_data_unlocked (GstSourceBuffer * self, GstBuffer * buffer) +{ + clear_pending_data_unlocked (self); + self->pending_data = buffer; +} + +GstSourceBuffer * +gst_source_buffer_new (const gchar * content_type, GstObject * parent, + GError ** error) +{ + g_return_val_if_fail (GST_IS_MEDIA_SOURCE (parent), NULL); + g_return_val_if_fail (content_type != NULL, NULL); + + gst_mse_init_logging (); + + GstMediaSourceMediaType media_type = GST_MEDIA_SOURCE_MEDIA_TYPE_INIT; + gst_media_source_media_type_parse (&media_type, content_type); + + gboolean generate_timestamps = gst_media_source_media_type_generates_timestamp + (&media_type); + gst_media_source_media_type_reset (&media_type); + + GstSourceBufferAppendMode append_mode = generate_timestamps + ? GST_SOURCE_BUFFER_APPEND_MODE_SEQUENCE + : GST_SOURCE_BUFFER_APPEND_MODE_SEGMENTS; + + GstSourceBuffer *self = g_object_new (GST_TYPE_SOURCE_BUFFER, NULL); + + gst_object_set_parent (GST_OBJECT_CAST (self), parent); + self->generate_timestamps = generate_timestamps; + self->append_mode = append_mode; + self->content_type = g_strdup (content_type); + + GstAppendPipelineCallbacks callbacks = { + .duration_changed = on_duration_changed, + .eos = on_eos, + .error = on_error, + .new_sample = on_new_sample, + .received_init_segment = on_received_init_segment, + }; + GError *append_pipeline_error = NULL; + self->append_pipeline = + gst_append_pipeline_new (&callbacks, self, &append_pipeline_error); + if (append_pipeline_error) { + g_propagate_prefixed_error (error, append_pipeline_error, + "failed to create source buffer"); + goto error; + } + + return gst_object_ref_sink (self); +error: + gst_clear_object (&self); + return NULL; +} + +GstSourceBuffer * +gst_source_buffer_new_with_callbacks (const gchar * content_type, + GstObject * parent, GstSourceBufferCallbacks * callbacks, + gpointer user_data, GError ** error) +{ + g_return_val_if_fail (callbacks, NULL); + + GError *source_buffer_error = NULL; + GstSourceBuffer *self = + gst_source_buffer_new (content_type, parent, &source_buffer_error); + if (source_buffer_error) { + g_propagate_error (error, source_buffer_error); + gst_clear_object (&self); + return NULL; + } + self->callbacks.callbacks = *callbacks; + self->callbacks.user_data = user_data; + + return self; +} + +static void +gst_source_buffer_constructed (GObject * object) +{ + GstSourceBuffer *self = GST_SOURCE_BUFFER (object); + + append_to_buffer_task_start (self->append_to_buffer_task); + + G_OBJECT_CLASS (gst_source_buffer_parent_class)->constructed (object); +} + +static void +gst_source_buffer_dispose (GObject * object) +{ + GstSourceBuffer *self = (GstSourceBuffer *) object; + + g_clear_pointer (&self->append_to_buffer_task, append_to_buffer_task_free); + + gst_clear_object (&self->append_pipeline); + + g_hash_table_remove_all (self->track_feeds); + + if (!is_removed_unlocked (self)) { + GstMediaSource *parent = get_media_source (self); + gst_media_source_remove_source_buffer (parent, self, NULL); + gst_object_unref (parent); + } + + gst_clear_object (&self->event_queue); + + G_OBJECT_CLASS (gst_source_buffer_parent_class)->dispose (object); +} + +static void +gst_source_buffer_finalize (GObject * object) +{ + GstSourceBuffer *self = (GstSourceBuffer *) object; + + g_clear_pointer (&self->content_type, g_free); + + g_hash_table_unref (self->track_buffers); + g_hash_table_unref (self->track_feeds); + g_mutex_clear (&self->tracks_lock); + + G_OBJECT_CLASS (gst_source_buffer_parent_class)->finalize (object); +} + +static void +gst_source_buffer_get_property (GObject * object, guint prop_id, GValue * value, + GParamSpec * pspec) +{ + GstSourceBuffer *self = GST_SOURCE_BUFFER (object); + + switch (prop_id) { + case PROP_APPEND_MODE: + g_value_set_enum (value, gst_source_buffer_get_append_mode (self)); + break; + case PROP_APPEND_WINDOW_START: + g_value_set_uint64 (value, + gst_source_buffer_get_append_window_start (self)); + break; + case PROP_APPEND_WINDOW_END: + g_value_set_uint64 (value, + gst_source_buffer_get_append_window_end (self)); + break; + case PROP_BUFFERED: + g_value_take_boxed (value, gst_source_buffer_get_buffered (self, NULL)); + break; + case PROP_CONTENT_TYPE: + g_value_take_string (value, gst_source_buffer_get_content_type (self)); + break; + case PROP_TIMESTAMP_OFFSET: + g_value_set_int64 (value, gst_source_buffer_get_timestamp_offset (self)); + break; + case PROP_UDPATING: + g_value_set_boolean (value, gst_source_buffer_get_updating (self)); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + } +} + +static void +gst_source_buffer_set_property (GObject * object, guint prop_id, + const GValue * value, GParamSpec * pspec) +{ + GstSourceBuffer *self = GST_SOURCE_BUFFER (object); + + switch (prop_id) { + case PROP_APPEND_MODE: + gst_source_buffer_set_append_mode (self, g_value_get_enum (value), NULL); + break; + case PROP_CONTENT_TYPE: + gst_source_buffer_change_content_type (self, + g_value_get_string (value), NULL); + break; + case PROP_TIMESTAMP_OFFSET: + gst_source_buffer_set_timestamp_offset (self, + g_value_get_int64 (value), NULL); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + } +} + +static void +gst_source_buffer_class_init (GstSourceBufferClass * klass) +{ + GObjectClass *oclass = G_OBJECT_CLASS (klass); + + oclass->constructed = GST_DEBUG_FUNCPTR (gst_source_buffer_constructed); + oclass->dispose = GST_DEBUG_FUNCPTR (gst_source_buffer_dispose); + oclass->finalize = GST_DEBUG_FUNCPTR (gst_source_buffer_finalize); + oclass->get_property = GST_DEBUG_FUNCPTR (gst_source_buffer_get_property); + oclass->set_property = GST_DEBUG_FUNCPTR (gst_source_buffer_set_property); + + /** + * GstSourceBuffer:append-mode: + * + * Affects how timestamps of processed media segments are interpreted. + * In %GST_SOURCE_BUFFER_APPEND_MODE_SEGMENTS, the start timestamp of a + * processed media segment is used directly along with + * #GstSourceBuffer:timestamp-offset . + * In %GST_SOURCE_BUFFER_APPEND_MODE_SEQUENCE, the timestamp of a + * processed media segment is ignored and replaced with the end time of the + * most recently appended segment. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebuffer-mode) + * + * Since: 1.24 + */ + properties[PROP_APPEND_MODE] = g_param_spec_enum ("append-mode", + "Append Mode", + "Either Segments or Sequence", + GST_TYPE_SOURCE_BUFFER_APPEND_MODE, DEFAULT_APPEND_MODE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); + + /** + * GstSourceBuffer:append-window-start: + * + * Any segments processed which end before this value will be ignored by this + * Source Buffer. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebuffer-appendwindowstart) + * + * Since: 1.24 + */ + properties[PROP_APPEND_WINDOW_START] = + g_param_spec_uint64 ("append-window-start", "Append Window Start", + "The timestamp representing the start of the append window", 0, + GST_CLOCK_TIME_NONE, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS); + + /** + * GstSourceBuffer:append-window-end: + * + * Any segments processed which have a start time greater than this value will + * be ignored by this Source Buffer. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebuffer-appendwindowend) + * + * Since: 1.24 + */ + properties[PROP_APPEND_WINDOW_END] = g_param_spec_uint64 ("append-window-end", + "Append Window End", + "The timestamp representing the end of the append window", + 0, GST_CLOCK_TIME_NONE, GST_CLOCK_TIME_NONE, G_PARAM_READABLE | + G_PARAM_STATIC_STRINGS); + + /** + * GstSourceBuffer:buffered: + * + * The set of Time Intervals that have been loaded into the current Source + * Buffer + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebuffer-buffered) + * + * Since: 1.24 + */ + properties[PROP_BUFFERED] = g_param_spec_boxed ("buffered", + "Buffered Time Intervals", + "The set of Time Intervals that have been loaded into" + " the current Source Buffer", G_TYPE_ARRAY, G_PARAM_READABLE | + G_PARAM_STATIC_STRINGS); + + /** + * GstSourceBuffer:content-type: + * + * The MIME content-type of the data stream + * + * Since: 1.24 + */ + properties[PROP_CONTENT_TYPE] = g_param_spec_string ("content-type", + "Content Type", + "The MIME content-type of the data stream", NULL, + G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS); + + /** + * GstSourceBuffer:timestamp-offset: + * + * The next media segment appended to the current Source Buffer will have its + * start timestamp increased by this amount. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebuffer-timestampoffset) + * + * Since: 1.24 + */ + properties[PROP_TIMESTAMP_OFFSET] = g_param_spec_int64 ("timestamp-offset", + "Timestamp Offset", + "The next media segment appended to the current Source Buffer" + " will have its start timestamp increased by this amount", + 0, G_MAXINT64, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); + + /** + * GstSourceBuffer:updating: + * + * Whether the current source buffer is still asynchronously processing + * previously issued commands. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebuffer-updating) + * + * Since: 1.24 + */ + properties[PROP_UDPATING] = g_param_spec_boolean ("updating", + "Updating", + "Whether the current Source Buffer is still" + " asynchronously processing previously issued commands", + FALSE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS); + + g_object_class_install_properties (oclass, N_PROPS, properties); + + /** + * GstSourceBuffer::on-update-start: + * @self: The #GstSourceBuffer that has just started updating + * + * Emitted when @self has begun to process data after a call to + * gst_source_buffer_append_buffer(). + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebuffer-onupdatestart) + * + * Since: 1.24 + */ + signals[ON_UPDATE_START] = g_signal_new ("on-update-start", + G_TYPE_FROM_CLASS (klass), + G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 0); + + /** + * GstSourceBuffer::on-update: + * @self: The #GstSourceBuffer that has just updated + * + * Emitted when @self has successfully processed data after a call to + * gst_source_buffer_append_buffer(). + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebuffer-onupdate) + * + * Since: 1.24 + */ + signals[ON_UPDATE] = g_signal_new ("on-update", + G_TYPE_FROM_CLASS (klass), + G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 0); + + /** + * GstSourceBuffer::on-update-end: + * @self: The #GstSourceBuffer that is no longer updating + * + * Emitted when @self is no longer in the updating state after a call to + * gst_source_buffer_append_buffer(). This can happen after a successful or + * unsuccessful append. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebuffer-onupdateend) + * + * Since: 1.24 + */ + signals[ON_UPDATE_END] = g_signal_new ("on-update-end", + G_TYPE_FROM_CLASS (klass), + G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 0); + + /** + * GstSourceBuffer::on-error: + * @self: The #GstSourceBuffer that has encountered an error + * + * Emitted when @self has encountered an error after a call to + * gst_source_buffer_append_buffer(). + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebuffer-onerror) + * + * Since: 1.24 + */ + signals[ON_ERROR] = g_signal_new ("on-error", + G_TYPE_FROM_CLASS (klass), + G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 0); + + /** + * GstSourceBuffer::on-abort: + * @self: The #GstSourceBuffer that has been aborted. + * + * Emitted when @self was aborted after a call to gst_source_buffer_abort(). + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebuffer-onabort) + * + * Since: 1.24 + */ + signals[ON_ABORT] = g_signal_new ("on-abort", + G_TYPE_FROM_CLASS (klass), + G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 0); +} + +static void +on_duration_changed (GstAppendPipeline * pipeline, gpointer user_data) +{ + GstSourceBuffer *self = GST_SOURCE_BUFFER (user_data); + + GST_OBJECT_LOCK (self); + gboolean removed = is_removed_unlocked (self); + GST_OBJECT_UNLOCK (self); + + if (removed) { + return; + } + + call_duration_changed (self); +} + +static void +on_eos (GstAppendPipeline * pipeline, GstMediaSourceTrack * track, + gpointer user_data) +{ + GstSourceBuffer *self = GST_SOURCE_BUFFER (user_data); + + if (GST_IS_MEDIA_SOURCE_TRACK (track)) { + TRACKS_LOCK (self); + GST_DEBUG_OBJECT (self, "got EOS event on %" GST_PTR_FORMAT, track); + GstMediaSourceTrackBuffer *buffer = get_track_buffer_unlocked (self, track); + gst_media_source_track_buffer_eos (buffer); + TRACKS_UNLOCK (self); + } +} + +static void +on_error (GstAppendPipeline * pipeline, gpointer user_data) +{ + GstSourceBuffer *self = GST_SOURCE_BUFFER (user_data); + + GST_OBJECT_LOCK (self); + append_error_unlocked (self); + GST_OBJECT_UNLOCK (self); +} + +static GstMediaSourceTrackBuffer * +get_track_buffer_unlocked (GstSourceBuffer * self, GstMediaSourceTrack * track) +{ + g_return_val_if_fail (g_hash_table_contains (self->track_buffers, track), + NULL); + return g_hash_table_lookup (self->track_buffers, track); +} + +static inline TrackFeedTask * +get_track_feed_unlocked (GstSourceBuffer * self, GstMediaSourceTrack * track) +{ + g_return_val_if_fail (g_hash_table_contains (self->track_feeds, track), NULL); + return g_hash_table_lookup (self->track_feeds, track); +} + +static void +add_track_buffer_unlocked (GstMediaSourceTrack * track, GstSourceBuffer * self) +{ + const gchar *id = gst_media_source_track_get_id (track); + if (g_hash_table_contains (self->track_buffers, track)) { + GST_DEBUG_OBJECT (self, "already have a track buffer for track %s", id); + return; + } + GstMediaSourceTrackBuffer *buf = gst_media_source_track_buffer_new (); + g_hash_table_insert (self->track_buffers, track, buf); + GST_DEBUG_OBJECT (self, "added track buffer for track %s", id); + + add_track_feed_unlocked (track, buf, self); +} + +static void +add_track_feed_unlocked (GstMediaSourceTrack * track, + GstMediaSourceTrackBuffer * track_buffer, GstSourceBuffer * self) +{ + TrackFeedTask *feed = g_new0 (TrackFeedTask, 1); + GstTask *task = gst_task_new ((GstTaskFunction) track_feed_task, feed, NULL); + g_rec_mutex_init (&feed->lock); + gst_task_set_lock (task, &feed->lock); + const gchar *track_id = gst_media_source_track_get_id (track); + gchar *name = g_strdup_printf ("%s:%s", GST_OBJECT_NAME (self), track_id); + g_object_set (task, "name", name, NULL); + g_clear_pointer (&name, g_free); + feed->task = task; + feed->buffer = track_buffer; + feed->track = gst_object_ref (track); + g_weak_ref_init (&feed->parent, self); + feed->cancelled = FALSE; + g_hash_table_insert (self->track_feeds, track, feed); +} + +static void +clear_track_feed (TrackFeedTask * feed) +{ + gst_object_unref (feed->task); + g_rec_mutex_clear (&feed->lock); + gst_object_unref (feed->track); + g_weak_ref_clear (&feed->parent); + g_free (feed); +} + +static void +stop_track_feed (TrackFeedTask * feed) +{ + g_return_if_fail (feed != NULL); + gst_media_source_track_flush (feed->track); + g_atomic_int_set (&feed->cancelled, TRUE); + gst_task_join (feed->task); +} + +static void +start_track_feed (TrackFeedTask * feed) +{ + g_return_if_fail (feed != NULL); + g_atomic_int_set (&feed->cancelled, FALSE); + gst_media_source_track_resume (feed->track); + gst_task_start (feed->task); +} + +static void +reset_track_feed (TrackFeedTask * feed) +{ + stop_track_feed (feed); + start_track_feed (feed); +} + +static gboolean +is_within_append_window_unlocked (GstSourceBuffer * self, GstSample * sample) +{ + GstBuffer *buffer = gst_sample_get_buffer (sample); + GstClockTime start = GST_BUFFER_PTS (buffer); + GstClockTime end = start + GST_BUFFER_DURATION (buffer); + + if (start < self->append_window_start) { + return FALSE; + } + + if (!GST_CLOCK_TIME_IS_VALID (self->append_window_end)) { + return TRUE; + } + + return end <= self->append_window_end; +} + +static void +on_new_sample (GstAppendPipeline * pipeline, GstMediaSourceTrack * track, + GstSample * sample, gpointer user_data) +{ + GstSourceBuffer *self = GST_SOURCE_BUFFER (user_data); + +#ifndef G_DISABLE_CHECKS + gboolean processed_init_segment = + g_atomic_int_get (&self->processed_init_segment); + g_return_if_fail (processed_init_segment); +#endif + + GST_OBJECT_LOCK (self); + gboolean is_within_window = is_within_append_window_unlocked (self, sample); + GST_OBJECT_UNLOCK (self); + + TRACKS_LOCK (self); + if (is_within_window) { + GstMediaSourceTrackBuffer *track_buffer = + get_track_buffer_unlocked (self, track); + GST_TRACE_OBJECT (self, "new sample on %s with %" GST_PTR_FORMAT, + gst_media_source_track_get_id (track), gst_sample_get_buffer (sample)); + gst_media_source_track_buffer_add (track_buffer, sample); + TrackFeedTask *feed = get_track_feed_unlocked (self, track); + start_track_feed (feed); + } + TRACKS_UNLOCK (self); +} + +static void +call_received_init_segment (GstSourceBuffer * self) +{ + GstSourceBufferCallbacks *callbacks = &self->callbacks.callbacks; + if (callbacks->received_init_segment) { + callbacks->received_init_segment (self, self->callbacks.user_data); + } +} + +static void +call_duration_changed (GstSourceBuffer * self) +{ + GstSourceBufferCallbacks *callbacks = &self->callbacks.callbacks; + if (callbacks->duration_changed) { + callbacks->duration_changed (self, self->callbacks.user_data); + } +} + +static void +call_active_state_changed (GstSourceBuffer * self) +{ + GstSourceBufferCallbacks *callbacks = &self->callbacks.callbacks; + if (callbacks->active_state_changed) { + callbacks->active_state_changed (self, self->callbacks.user_data); + } +} + +static void +update_track_buffer_modes (GstSourceBuffer * self) +{ + GHashTableIter iter; + g_hash_table_iter_init (&iter, self->track_buffers); + gboolean enabled = + self->append_mode == GST_SOURCE_BUFFER_APPEND_MODE_SEQUENCE; + for (gpointer value; g_hash_table_iter_next (&iter, NULL, &value);) { + GstMediaSourceTrackBuffer *buffer = GST_MEDIA_SOURCE_TRACK_BUFFER (value); + gst_media_source_track_buffer_process_init_segment (buffer, enabled); + gst_media_source_track_buffer_set_group_start (buffer, + self->timestamp_offset); + } +} + +static void +on_received_init_segment (GstAppendPipeline * pipeline, gpointer user_data) +{ + GstSourceBuffer *self = GST_SOURCE_BUFFER (user_data); + GST_DEBUG_OBJECT (self, "got init segment, have duration %" GST_TIME_FORMAT, + GST_TIME_ARGS (gst_append_pipeline_get_duration (pipeline))); + + TRACKS_LOCK (self); + + if (g_atomic_int_compare_and_exchange (&self->processed_init_segment, FALSE, + TRUE)) { + GST_DEBUG_OBJECT (self, "processing first init segment"); + + GPtrArray *audio_tracks = gst_append_pipeline_get_audio_tracks (pipeline); + GPtrArray *text_tracks = gst_append_pipeline_get_text_tracks (pipeline); + GPtrArray *video_tracks = gst_append_pipeline_get_video_tracks (pipeline); + + g_ptr_array_foreach (audio_tracks, (GFunc) add_track_buffer_unlocked, self); + g_ptr_array_foreach (text_tracks, (GFunc) add_track_buffer_unlocked, self); + g_ptr_array_foreach (video_tracks, (GFunc) add_track_buffer_unlocked, self); + } + + update_track_buffer_modes (self); + + TRACKS_UNLOCK (self); + + call_received_init_segment (self); + call_active_state_changed (self); +} + +static guint +track_buffer_hash (GstMediaSourceTrack * track) +{ + return g_str_hash (gst_media_source_track_get_id (track)); +} + +static gboolean +track_buffer_equal (GstMediaSourceTrack * a, GstMediaSourceTrack * b) +{ + return g_str_equal (gst_media_source_track_get_id (a), + gst_media_source_track_get_id (b)); +} + +static void +gst_source_buffer_init (GstSourceBuffer * self) +{ + + self->append_mode = DEFAULT_APPEND_MODE; + self->append_window_start = 0; + self->append_window_end = GST_CLOCK_TIME_NONE; + self->content_type = NULL; + self->timestamp_offset = 0; + self->updating = FALSE; + self->errored = FALSE; + self->size_limit = DEFAULT_BUFFER_SIZE; + self->size = 0; + self->pending_data = NULL; + g_cond_init (&self->pending_data_cond); + self->processed_init_segment = FALSE; + self->event_queue = + gst_mse_event_queue_new ((GstMseEventQueueCallback) dispatch_event, self); + + self->append_to_buffer_task = append_to_buffer_task_new (self); + self->track_buffers = g_hash_table_new_full ((GHashFunc) track_buffer_hash, + (GEqualFunc) track_buffer_equal, NULL, gst_object_unref); + g_mutex_init (&self->tracks_lock); + + self->track_feeds = g_hash_table_new_full (g_direct_hash, g_direct_equal, + NULL, (GDestroyNotify) clear_track_feed); + self->seek_time = 0; + self->callbacks.callbacks.duration_changed = NULL; + self->callbacks.user_data = NULL; +} + +static inline gboolean +is_removed_unlocked (GstSourceBuffer * self) +{ + GstObject *parent = GST_OBJECT_PARENT (self); + if (parent == NULL) { + return TRUE; + } + + GstMediaSource *source = GST_MEDIA_SOURCE (parent); + GstSourceBufferList *buffers = gst_media_source_get_source_buffers (source); + gboolean removed = !gst_source_buffer_list_contains (buffers, self); + + gst_object_unref (buffers); + + return removed; +} + +static inline gboolean +is_updating (GstSourceBuffer * self) +{ + return g_atomic_int_get (&self->updating); +} + +static inline void +set_updating (GstSourceBuffer * self) +{ + g_atomic_int_set (&self->updating, TRUE); +} + +static inline void +clear_updating (GstSourceBuffer * self) +{ + g_atomic_int_set (&self->updating, FALSE); +} + +static inline gboolean +is_errored (GstSourceBuffer * self) +{ + return g_atomic_int_get (&self->errored); +} + +static inline void +set_errored (GstSourceBuffer * self) +{ + g_atomic_int_set (&self->errored, TRUE); +} + +static inline void +clear_errored (GstSourceBuffer * self) +{ + g_atomic_int_set (&self->errored, FALSE); +} + +static inline gboolean +is_ended_unlocked (GstSourceBuffer * self) +{ + if (is_removed_unlocked (self)) { + return TRUE; + } + + GstMediaSource *source = get_media_source_unlocked (self); + gboolean ended = gst_media_source_get_ready_state (source) == + GST_MEDIA_SOURCE_READY_STATE_ENDED; + + gst_object_unref (source); + + return ended; +} + +static void +open_parent_unlocked (GstSourceBuffer * self) +{ + g_return_if_fail (!is_removed_unlocked (self)); + GstMediaSource *source = get_media_source_unlocked (self); + gst_media_source_open (source); + gst_object_unref (source); +} + +/** + * gst_source_buffer_get_append_mode: + * @self: #GstSourceBuffer instance + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebuffer-mode) + * + * Returns: The current #GstSourceBufferAppendMode + * Since: 1.24 + */ +GstSourceBufferAppendMode +gst_source_buffer_get_append_mode (GstSourceBuffer * self) +{ + g_return_val_if_fail (GST_IS_SOURCE_BUFFER (self), DEFAULT_APPEND_MODE); + GST_OBJECT_LOCK (self); + GstSourceBufferAppendMode append_mode = self->append_mode; + GST_OBJECT_UNLOCK (self); + + return append_mode; +} + +/** + * gst_source_buffer_set_append_mode: + * @self: #GstSourceBuffer instance + * @mode: #GstSourceBufferAppendMode the desired Append Mode + * @error: (out) (optional) (nullable) (transfer full): the resulting error or `NULL` + * + * Changes the Append Mode of @self. This influences what timestamps will be + * assigned to media processed by this Source Buffer. In Segment mode, the + * timestamps in each segment determine the position of each sample after it + * is processed. In Sequence mode, the timestamp of each processed sample is + * generated based on the end of the most recently processed segment. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebuffer-mode) + * + * Returns: `TRUE` on success, `FALSE` otherwise + * Since: 1.24 + */ +gboolean +gst_source_buffer_set_append_mode (GstSourceBuffer * self, + GstSourceBufferAppendMode mode, GError ** error) +{ + g_return_val_if_fail (GST_IS_SOURCE_BUFFER (self), FALSE); + + GST_OBJECT_LOCK (self); + + if (is_removed_unlocked (self)) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_INVALID_STATE, + "buffer is removed"); + goto error; + } + + if (is_updating (self)) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_INVALID_STATE, + "buffer is still updating"); + goto error; + } + + if (self->generate_timestamps && mode == + GST_SOURCE_BUFFER_APPEND_MODE_SEGMENTS) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_TYPE, + "cannot change to segments mode while generate timestamps is active"); + goto error; + } + + if (is_ended_unlocked (self)) { + open_parent_unlocked (self); + } + + self->append_mode = mode; + + GST_OBJECT_UNLOCK (self); + + g_object_notify_by_pspec (G_OBJECT (self), properties[PROP_APPEND_MODE]); + + return TRUE; + +error: + GST_OBJECT_UNLOCK (self); + return FALSE; +} + +/** + * gst_source_buffer_get_append_window_start: + * @self: #GstSourceBuffer instance + * + * Returns the current append window start time. Any segment processed that ends + * earlier than this value will be ignored. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebuffer-appendwindowstart) + * + * Returns: The current Append Window start time as a #GstClockTime + * Since: 1.24 + */ +GstClockTime +gst_source_buffer_get_append_window_start (GstSourceBuffer * self) +{ + g_return_val_if_fail (GST_IS_SOURCE_BUFFER (self), GST_CLOCK_TIME_NONE); + + GST_OBJECT_LOCK (self); + GstClockTime append_window_start = self->append_window_start; + GST_OBJECT_UNLOCK (self); + + return append_window_start; +} + +/** + * gst_source_buffer_set_append_window_start: + * @self: #GstSourceBuffer instance + * @start: the append window start + * @error: (out) (optional) (nullable) (transfer full): the resulting error or `NULL` + * + * Modifies the current append window start of @self. If successful, samples + * processed after setting this value that end before this point will be + * ignored. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebuffer-appendwindowstart) + * + * Returns: `TRUE` on success, `FALSE` otherwise + * Since: 1.24 + */ +gboolean +gst_source_buffer_set_append_window_start (GstSourceBuffer * self, + GstClockTime start, GError ** error) +{ + g_return_val_if_fail (GST_IS_SOURCE_BUFFER (self), FALSE); + + GST_OBJECT_LOCK (self); + + if (is_removed_unlocked (self)) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_INVALID_STATE, + "append window start cannot be set on source buffer " + "with no media source"); + goto error; + } + + if (is_updating (self)) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_INVALID_STATE, + "append window start cannot be set on source buffer while updating"); + goto error; + } + + if (!GST_CLOCK_TIME_IS_VALID (start) || start <= self->append_window_end) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_TYPE, + "append window start must be between zero and append window end"); + goto error; + } + + self->append_window_start = start; + + GST_OBJECT_UNLOCK (self); + + g_object_notify_by_pspec (G_OBJECT (self), + properties[PROP_APPEND_WINDOW_START]); + + return TRUE; + +error: + GST_OBJECT_UNLOCK (self); + return FALSE; +} + +/** + * gst_source_buffer_get_append_window_end: + * @self: #GstSourceBuffer instance + * + * Returns the current append window end time. Any segment processed that starts + * after this value will be ignored. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebuffer-appendwindowend) + * + * Returns: The current Append Window end time as a #GstClockTime + * Since: 1.24 + */ +GstClockTime +gst_source_buffer_get_append_window_end (GstSourceBuffer * self) +{ + g_return_val_if_fail (GST_IS_SOURCE_BUFFER (self), GST_CLOCK_TIME_NONE); + + GST_OBJECT_LOCK (self); + GstClockTime append_window_end = self->append_window_end; + GST_OBJECT_UNLOCK (self); + + return append_window_end; +} + +/** + * gst_source_buffer_set_append_window_end: + * @self: #GstSourceBuffer instance + * @end: the append window end + * @error: (out) (optional) (nullable) (transfer full): the resulting error or `NULL` + * + * Modifies the current append window end of @self. If successful, samples + * processed after setting this value that start after this point will be + * ignored. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebuffer-appendwindowend) + * + * Returns: `TRUE` on success, `FALSE` otherwise + * Since: 1.24 + */ +gboolean +gst_source_buffer_set_append_window_end (GstSourceBuffer * self, + GstClockTime end, GError ** error) +{ + g_return_val_if_fail (GST_IS_SOURCE_BUFFER (self), FALSE); + + GST_OBJECT_LOCK (self); + + if (is_removed_unlocked (self)) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_INVALID_STATE, + "append window end cannot be set on source buffer " + "with no media source"); + goto error; + } + + if (is_updating (self)) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_INVALID_STATE, + "append window end cannot be set on source buffer while updating"); + goto error; + } + + if (end <= self->append_window_start) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_TYPE, + "append window end must be after append window start"); + goto error; + } + + self->append_window_end = end; + + GST_OBJECT_UNLOCK (self); + + g_object_notify_by_pspec (G_OBJECT (self), + properties[PROP_APPEND_WINDOW_END]); + + return TRUE; + +error: + GST_OBJECT_UNLOCK (self); + return FALSE; +} + +static gboolean +get_intersection (GstMediaSourceRange * a, GstMediaSourceRange * b, + GstMediaSourceRange * intersection) +{ + g_return_val_if_fail (a != NULL, FALSE); + g_return_val_if_fail (b != NULL, FALSE); + g_return_val_if_fail (intersection != NULL, FALSE); + GstMediaSourceRange range = { + .start = MAX (a->start, b->start), + .end = MIN (a->end, b->end), + }; + if (range.start >= range.end) { + return FALSE; + } + *intersection = range; + return TRUE; +} + +static GArray * +intersect_ranges (GstMediaSourceRange * a, GstMediaSourceRange * a_end, + GstMediaSourceRange * b, GstMediaSourceRange * b_end) +{ + GArray *intersection = g_array_new_ranges (); + while (a < a_end && b < b_end) { + GstMediaSourceRange range; + if (!get_intersection (a, b, &range)) { + if (a->end < b->end) { + a++; + } else { + b++; + } + continue; + } + + if (a->end < b->end) { + a++; + } else { + b++; + } + + g_array_append_val (intersection, range); + } + return intersection; +} + +static inline gboolean +contributes_to_buffered (GstMediaSourceTrack * track) +{ + switch (gst_media_source_track_get_track_type (track)) { + case GST_MEDIA_SOURCE_TRACK_TYPE_AUDIO: + case GST_MEDIA_SOURCE_TRACK_TYPE_VIDEO: + return TRUE; + default: + return FALSE; + } +} + +/** + * gst_source_buffer_get_buffered: + * @self: #GstSourceBuffer instance + * @error: (out) (optional) (nullable) (transfer full): the resulting error or `NULL` + * + * Returns a sequence of #GstMediaSourceRange values representing which segments + * of @self are buffered in memory. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebuffer-buffered) + * + * Returns: (transfer full) (element-type GstMediaSourceRange): a #GArray of #GstMediaSourceRange values. + * Since: 1.24 + */ +GArray * +gst_source_buffer_get_buffered (GstSourceBuffer * self, GError ** error) +{ + g_return_val_if_fail (GST_IS_SOURCE_BUFFER (self), NULL); + + TRACKS_LOCK (self); + GArray *buffered = get_buffered_unlocked (self); + TRACKS_UNLOCK (self); + return buffered; +} + +static GArray * +get_buffered_unlocked (GstSourceBuffer * self) +{ + GHashTableIter iter; + GArray *buffered = NULL; + g_hash_table_iter_init (&iter, self->track_buffers); + for (gpointer key, value; g_hash_table_iter_next (&iter, &key, &value);) { + GstMediaSourceTrack *track = GST_MEDIA_SOURCE_TRACK (key); + GstMediaSourceTrackBuffer *buffer = GST_MEDIA_SOURCE_TRACK_BUFFER (value); + if (!contributes_to_buffered (track)) { + continue; + } + GArray *current_ranges = gst_media_source_track_buffer_get_ranges (buffer); + if (buffered == NULL) { + buffered = current_ranges; + continue; + } + GArray *intersection = intersect_ranges ( + (GstMediaSourceRange *) buffered->data, + ((GstMediaSourceRange *) buffered->data) + buffered->len, + (GstMediaSourceRange *) current_ranges->data, + ((GstMediaSourceRange *) current_ranges->data) + current_ranges->len); + g_array_unref (buffered); + buffered = intersection; + } + + if (buffered == NULL) { + return g_array_new_ranges (); + } else { + return buffered; + } +} + +/** + * gst_source_buffer_get_content_type: + * @self: #GstSourceBuffer instance + * + * Returns the current content type of @self. + * + * Returns: (transfer full): a string representing the content type + * Since: 1.24 + */ +gchar * +gst_source_buffer_get_content_type (GstSourceBuffer * self) +{ + g_return_val_if_fail (GST_IS_SOURCE_BUFFER (self), NULL); + + GST_OBJECT_LOCK (self); + gchar *content_type = g_strdup (self->content_type); + GST_OBJECT_UNLOCK (self); + + return content_type; +} + +/** + * gst_source_buffer_change_content_type: + * @self: #GstSourceBuffer instance + * @type: (transfer none): the desired content type + * @error: (out) (optional) (nullable) (transfer full): the resulting error or `NULL` + * + * Attempts to change the content type of @self to @type. Any new data appended + * to the Source Buffer must be of the supplied @type afterward. + * + * Returns: `TRUE` on success, `FALSE` otherwise + * Since: 1.24 + */ +gboolean +gst_source_buffer_change_content_type (GstSourceBuffer * self, + const gchar * type, GError ** error) +{ + g_return_val_if_fail (GST_IS_SOURCE_BUFFER (self), FALSE); + + if (type == NULL || g_strcmp0 (type, "") == 0) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_TYPE, + "content type must not be empty"); + return FALSE; + } + + GST_OBJECT_LOCK (self); + + if (is_removed_unlocked (self)) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_INVALID_STATE, + "content type cannot be set on source buffer with no media source"); + goto error; + } + + if (is_updating (self)) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_INVALID_STATE, + "content type cannot be set on source buffer that is updating"); + goto error; + } + + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_NOT_SUPPORTED, + "content type cannot be changed"); + +error: + GST_OBJECT_UNLOCK (self); + return FALSE; +} + +/** + * gst_source_buffer_remove: + * @self: #GstSourceBuffer instance + * @start: The beginning timestamp of data to remove + * @end: The end timestamp of data to remove + * @error: (out) (optional) (nullable) (transfer full): the resulting error or `NULL` + * + * Attempts to remove any parsed data between @start and @end from @self. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebuffer-remove) + * + * Returns: `TRUE` on success, `FALSE` otherwise + * Since: 1.24 + */ +gboolean +gst_source_buffer_remove (GstSourceBuffer * self, GstClockTime start, + GstClockTime end, GError ** error) +{ + g_return_val_if_fail (GST_IS_SOURCE_BUFFER (self), FALSE); + return TRUE; +} + +/** + * gst_source_buffer_get_timestamp_offset: + * @self: #GstSourceBuffer instance + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebuffer-timestampoffset) + * + * Returns: The current timestamp offset as a #GstClockTime + * Since: 1.24 + */ +GstClockTime +gst_source_buffer_get_timestamp_offset (GstSourceBuffer * self) +{ + g_return_val_if_fail (GST_IS_SOURCE_BUFFER (self), FALSE); + + GST_OBJECT_LOCK (self); + GstClockTime timestamp_offset = self->timestamp_offset; + GST_OBJECT_UNLOCK (self); + + return timestamp_offset; +} + +/** + * gst_source_buffer_set_timestamp_offset: + * @self: #GstSourceBuffer instance + * @offset: The new timestamp offset + * @error: (out) (optional) (nullable) (transfer full): the resulting error or `NULL` + * + * Attempt to set the timestamp offset of @self. Any media processed after this + * value is set will have this value added to its start time. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebuffer-timestampoffset) + * + * Returns: `TRUE` on success, `FALSE` otherwise + * Since: 1.24 + */ +gboolean +gst_source_buffer_set_timestamp_offset (GstSourceBuffer * self, GstClockTime + offset, GError ** error) +{ + g_return_val_if_fail (GST_IS_SOURCE_BUFFER (self), FALSE); + + GST_OBJECT_LOCK (self); + + if (is_removed_unlocked (self)) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_INVALID_STATE, + "source buffer is removed"); + goto error; + } + if (is_updating (self)) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_INVALID_STATE, + "source buffer is still updating"); + goto error; + } + if (is_ended_unlocked (self)) { + GstMediaSource *parent = get_media_source_unlocked (self); + gst_media_source_open (parent); + gst_clear_object (&parent); + } + TRACKS_LOCK (self); + GHashTableIter iter; + g_hash_table_iter_init (&iter, self->track_buffers); + for (gpointer value; g_hash_table_iter_next (&iter, NULL, &value);) { + GstMediaSourceTrackBuffer *buffer = value; + gst_media_source_track_buffer_set_group_start (buffer, offset); + } + TRACKS_UNLOCK (self); + + self->timestamp_offset = offset; + + GST_OBJECT_UNLOCK (self); + + g_object_notify_by_pspec (G_OBJECT (self), properties[PROP_TIMESTAMP_OFFSET]); + + return TRUE; + +error: + GST_OBJECT_UNLOCK (self); + return FALSE; +} + +/** + * gst_source_buffer_get_updating: + * @self: #GstSourceBuffer instance + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebuffer-updating) + * + * Returns: Whether @self is currently adding or removing media content. + * Since: 1.24 + */ +gboolean +gst_source_buffer_get_updating (GstSourceBuffer * self) +{ + g_return_val_if_fail (GST_IS_SOURCE_BUFFER (self), FALSE); + return is_updating (self); +} + +static gsize +compute_total_size_unlocked (GstSourceBuffer * self) +{ + GHashTableIter iter; + g_hash_table_iter_init (&iter, self->track_buffers); + gsize total_size = 0; + for (gpointer value; g_hash_table_iter_next (&iter, NULL, &value);) { + GstMediaSourceTrackBuffer *buffer = value; + total_size += gst_media_source_track_buffer_get_storage_size (buffer); + } + return total_size; +} + +static gboolean +will_overflow_unlocked (GstSourceBuffer * self, gsize bytes) +{ + gsize total = compute_total_size_unlocked (self); + return total + bytes > self->size_limit; +} + +static void +evict_coded_frames_unlocked (GstSourceBuffer * self, gsize space_required, + gsize size_limit, GstClockTime position, GstClockTime duration) +{ + if (!will_overflow_unlocked (self, space_required)) { + return; + } + + if (!GST_CLOCK_TIME_IS_VALID (position)) { + GST_ERROR_OBJECT (self, "invalid position, cannot delete anything"); + return; + } + + GstClockTime min_distance_from_position = GST_SECOND * 5; + GstClockTime max_dts = position > min_distance_from_position ? + position - min_distance_from_position : 0; + + GST_DEBUG_OBJECT (self, "position=%" GST_TIMEP_FORMAT + ", attempting removal from 0 to %" GST_TIMEP_FORMAT, &position, &max_dts); + + GHashTableIter iter; + g_hash_table_iter_init (&iter, self->track_buffers); + for (gpointer value; g_hash_table_iter_next (&iter, NULL, &value);) { + GstMediaSourceTrackBuffer *buffer = value; + gst_media_source_track_buffer_remove_range (buffer, 0, max_dts); + } + self->size = compute_total_size_unlocked (self); + + GST_DEBUG_OBJECT (self, "capacity=%" G_GSIZE_FORMAT "/%" G_GSIZE_FORMAT + "(%" G_GSIZE_FORMAT "%%)", self->size, self->size_limit, + self->size * 100 / size_limit); +} + +static void +reset_parser_state_unlocked (GstSourceBuffer * self) +{ + clear_pending_data_unlocked (self); + if (gst_append_pipeline_reset (self->append_pipeline)) { + clear_errored (self); + } else { + set_errored (self); + } +} + +static void +append_error_unlocked (GstSourceBuffer * self) +{ + reset_parser_state_unlocked (self); + clear_updating (self); + + if (is_removed_unlocked (self)) { + return; + } + + schedule_event_unlocked (self, ON_ERROR); + schedule_event_unlocked (self, ON_UPDATE_END); + + GstMediaSource *source = get_media_source_unlocked (self); + gst_media_source_end_of_stream (source, GST_MEDIA_SOURCE_EOS_ERROR_DECODE, + NULL); + gst_object_unref (source); +} + +static void +append_successful_unlocked (GstSourceBuffer * self, gboolean ended) +{ + clear_updating (self); + schedule_event_unlocked (self, ON_UPDATE); + schedule_event_unlocked (self, ON_UPDATE_END); +} + +static gboolean +encountered_bad_bytes_unlocked (GstSourceBuffer * self) +{ + return gst_append_pipeline_get_failed (self->append_pipeline); +} + +static GstBuffer * +await_pending_data_unlocked (GstSourceBuffer * self) +{ + if (self->pending_data == NULL) { + guint64 deadline = g_get_monotonic_time () + G_TIME_SPAN_SECOND; + g_cond_wait_until (&self->pending_data_cond, GST_OBJECT_GET_LOCK (self), + deadline); + } + return take_pending_data_unlocked (self); +} + +static AppendToBufferTask * +append_to_buffer_task_new (GstSourceBuffer * parent) +{ + AppendToBufferTask *task = g_new0 (AppendToBufferTask, 1); + g_rec_mutex_init (&task->lock); + task->parent = parent; + task->task = + gst_task_new ((GstTaskFunction) append_to_buffer_task_func, task, NULL); + task->cancelled = FALSE; + gst_task_set_lock (task->task, &task->lock); + return task; +} + +static void +append_to_buffer_task_free (AppendToBufferTask * task) +{ + append_to_buffer_task_stop (task); + gst_task_join (task->task); + gst_clear_object (&task->task); + g_rec_mutex_clear (&task->lock); + task->parent = NULL; + g_free (task); +} + +static void +append_to_buffer_task_start (AppendToBufferTask * task) +{ + gchar *name = g_strdup_printf ("%s:append", GST_OBJECT_NAME (task->parent)); + g_object_set (task->task, "name", name, NULL); + gst_task_start (task->task); + g_free (name); +} + +static void +append_to_buffer_task_stop (AppendToBufferTask * task) +{ + gst_task_stop (task->task); + g_atomic_int_set (&task->cancelled, TRUE); + g_cond_signal (&task->parent->pending_data_cond); +} + +static void +append_to_buffer_task_func (AppendToBufferTask * task) +{ + GstSourceBuffer *self = task->parent; + if (g_atomic_int_get (&task->cancelled)) { + GST_LOG_OBJECT (task->task, "task is done"); + append_to_buffer_task_stop (task); + return; + } + + GST_OBJECT_LOCK (self); + + GstBuffer *pending_data = await_pending_data_unlocked (self); + + if (is_removed_unlocked (self)) { + append_successful_unlocked (self, TRUE); + goto done; + } + + if (encountered_bad_bytes_unlocked (self)) { + append_error_unlocked (self); + goto done; + } + + if (!GST_IS_BUFFER (pending_data)) { + /* Nacre patch: the wait above times out every second; with nothing + * appended there is nothing to report. Upstream signalled update and + * update-end here, a spurious pair every second while idle. */ + GST_TRACE_OBJECT (self, "no pending data"); + goto done; + } + + /* Nacre patch: the append now waits until its samples reach the track + * buffers, and the new-sample callback takes this object's lock, so drop it + * meanwhile. `updating` stays set, so no other append can start. */ + GstAppendPipeline *pipeline = gst_object_ref (self->append_pipeline); + GST_OBJECT_UNLOCK (self); + GstFlowReturn result = gst_append_pipeline_append (pipeline, pending_data); + gst_object_unref (pipeline); + GST_OBJECT_LOCK (self); + + if (is_removed_unlocked (self)) { + append_successful_unlocked (self, TRUE); + goto done; + } + + if (result != GST_FLOW_OK) { + GST_ERROR_OBJECT (self, "failed to append: %s", gst_flow_get_name (result)); + append_error_unlocked (self); + goto done; + } + + append_successful_unlocked (self, is_ended_unlocked (self)); + +done: + GST_OBJECT_UNLOCK (self); +} + +static gboolean +track_feed_fold (const GValue * item, TrackFeedAccumulator * acc, + TrackFeedTask * feed) +{ + if (g_atomic_int_get (&feed->cancelled)) { + return FALSE; + } + GstSourceBuffer *self = acc->parent; + + GstMediaSourceCodedFrameGroup *group = + gst_value_get_media_source_coded_frame_group (item); + if (group == NULL) { + return FALSE; + } + + for (GList * it = group->samples; it != NULL; it = g_list_next (it)) { + GstSample *sample = GST_SAMPLE (it->data); + if (!g_hash_table_add (acc->processed_samples, gst_sample_ref (sample))) { + continue; + } + if (!gst_media_source_track_push (feed->track, sample)) { + g_hash_table_remove (acc->processed_samples, sample); + GST_LOG_OBJECT (self, "%s: failed to push sample to track", + gst_media_source_track_get_id (feed->track)); + acc->push_failed = TRUE; + return FALSE; + } + } + + return TRUE; +} + +static gint +clip_to_seek_time_dts (const GValue * a, const GValue * b) +{ + GstMediaSourceCodedFrameGroup *group = + gst_value_get_media_source_coded_frame_group (a); + GstClockTime start_dts = g_value_get_uint64 (b); + return group != NULL && start_dts > group->end; +} + +static void +track_feed_task (TrackFeedTask * feed) +{ + GstSourceBuffer *self = g_weak_ref_get (&feed->parent); + if (self == NULL) { + gst_task_stop (feed->task); + return; + } + GstMediaSourceTrack *track = feed->track; + GstMediaSourceTrackBuffer *buffer = feed->buffer; + GstClockTime time = self->seek_time; + const gchar *track_id = gst_media_source_track_get_id (track); + + GST_DEBUG_OBJECT (self, "%s: feed starting@%" GST_TIMEP_FORMAT, track_id, + &time); + + TrackFeedAccumulator acc = { + .parent = self, + .processed_samples = g_hash_table_new_full (g_direct_hash, g_direct_equal, + (GDestroyNotify) gst_sample_unref, NULL), + .push_failed = FALSE, + }; + GValue start_dts_value = G_VALUE_INIT; + g_value_init (&start_dts_value, G_TYPE_UINT64); + g_value_set_uint64 (&start_dts_value, time); + while (TRUE) { + gboolean eos = gst_media_source_track_buffer_is_eos (buffer); + GstIterator *it = gst_media_source_track_buffer_iter_samples (buffer); + it = gst_iterator_filter (it, (GCompareFunc) clip_to_seek_time_dts, + &start_dts_value); + gst_iterator_fold (it, (GstIteratorFoldFunction) track_feed_fold, + (GValue *) & acc, feed); + g_clear_pointer (&it, gst_iterator_free); + + if (acc.push_failed) { + gst_task_stop (feed->task); + break; + } + + if (eos) { + GST_DEBUG_OBJECT (self, "%s: enqueued all %u samples", track_id, + g_hash_table_size (acc.processed_samples)); + gst_media_source_track_push_eos (track); + GST_DEBUG_OBJECT (self, "%s: marked EOS", track_id); + gst_task_stop (feed->task); + break; + } + + if (g_atomic_int_get (&feed->cancelled)) { + GST_DEBUG_OBJECT (self, "feed is cancelled, stopping task"); + gst_task_stop (feed->task); + break; + } + + GST_TRACE_OBJECT (self, "%s: resume after %u samples", + track_id, g_hash_table_size (acc.processed_samples)); + gint64 deadline = g_get_monotonic_time () + G_TIME_SPAN_SECOND; + gst_media_source_track_buffer_await_new_data_until (buffer, deadline); + } + g_clear_pointer (&acc.processed_samples, g_hash_table_unref); + g_value_unset (&start_dts_value); + gst_clear_object (&self); +} + +static void +dispatch_event (SourceBufferEventItem * item, GstSourceBuffer * self) +{ + g_signal_emit (self, signals[item->event], 0); +} + +static void +schedule_event_unlocked (GstSourceBuffer * self, SourceBufferEvent event) +{ + g_return_if_fail (event < N_SIGNALS); + if (is_removed_unlocked (self)) { + return; + } + SourceBufferEventItem item = { + .item = {.destroy = g_free,.visible = TRUE,.size = 1,.object = NULL}, + .event = event, + }; + gst_mse_event_queue_push (self->event_queue, g_memdup2 (&item, + sizeof (SourceBufferEventItem))); +} + +static void +schedule_append_to_buffer_task (GstSourceBuffer * self) +{ + g_cond_signal (&self->pending_data_cond); +} + +/** + * gst_source_buffer_append_buffer: + * @self: #GstSourceBuffer instance + * @buf: (transfer full):The media data to append + * @error: (out) (optional) (nullable) (transfer full): the resulting error or `NULL` + * + * Schedules the bytes inside @buf to be processed by @self. When it is possible + * to accept the supplied data, it will be processed asynchronously and fill in + * the track buffers for playback purposes. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebuffer-appendbuffer) + * + * Returns: `TRUE` on success, `FALSE` otherwise + * Since: 1.24 + */ +gboolean +gst_source_buffer_append_buffer (GstSourceBuffer * self, GstBuffer * buf, + GError ** error) +{ + g_return_val_if_fail (GST_IS_SOURCE_BUFFER (self), FALSE); + g_return_val_if_fail (GST_IS_BUFFER (buf), FALSE); + + GST_OBJECT_LOCK (self); + TRACKS_LOCK (self); + + if (is_removed_unlocked (self) || is_updating (self)) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_INVALID_STATE, + "source buffer is removed or still updating"); + goto error; + } + + if (is_errored (self)) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_INVALID_STATE, + "source buffer has encountered error"); + goto error; + } + + if (is_ended_unlocked (self)) { + open_parent_unlocked (self); + } + + GstMediaSource *source = get_media_source_unlocked (self); + gsize buffer_size = gst_buffer_get_size (buf); + GstClockTime position = gst_media_source_get_position (source); + GstClockTime duration = gst_media_source_get_duration (source); + + gst_object_unref (source); + + evict_coded_frames_unlocked (self, buffer_size, self->size_limit, position, + duration); + + if (will_overflow_unlocked (self, buffer_size)) { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_QUOTA_EXCEEDED, + "buffer is full"); + goto error; + } + + g_return_val_if_fail (self->pending_data == NULL, FALSE); + + set_pending_data_unlocked (self, buf); + set_updating (self); + + schedule_event_unlocked (self, ON_UPDATE_START); + schedule_append_to_buffer_task (self); + + TRACKS_UNLOCK (self); + GST_OBJECT_UNLOCK (self); + return TRUE; + +error: + TRACKS_UNLOCK (self); + GST_OBJECT_UNLOCK (self); + gst_clear_buffer (&buf); + return FALSE; +} + +/** + * gst_source_buffer_abort: + * @self: #GstSourceBuffer instance + * @error: (out) (optional) (nullable) (transfer full): the resulting error or `NULL` + * + * Attempts to end any processing of the currently pending data and reset the + * media parser. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebuffer-abort) + * + * Returns: `TRUE` on success, `FALSE` otherwise + * Since: 1.24 + */ +gboolean +gst_source_buffer_abort (GstSourceBuffer * self, GError ** error) +{ + g_return_val_if_fail (GST_IS_SOURCE_BUFFER (self), FALSE); + if (gst_append_pipeline_eos (self->append_pipeline) == GST_FLOW_OK) { + return TRUE; + } else { + g_set_error (error, + GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_INVALID_STATE, + "failed to abort source buffer"); + return FALSE; + } +} + +gboolean +gst_source_buffer_has_init_segment (GstSourceBuffer * self) +{ + g_return_val_if_fail (GST_IS_SOURCE_BUFFER (self), FALSE); + return gst_append_pipeline_has_init_segment (self->append_pipeline); +} + +static gboolean +is_buffered_fold (const GValue * item, IsBufferedAccumulator * acc, + GstSourceBuffer * self) +{ + GstMediaSourceCodedFrameGroup *group = + gst_value_get_media_source_coded_frame_group (item); + if (group == NULL) { + acc->buffered = FALSE; + return FALSE; + } + GstClockTime start = group->start; + GstClockTime end = group->end; + if (acc->time < start) { + GST_TRACE_OBJECT (self, "position precedes group start, done"); + acc->buffered = FALSE; + return FALSE; + } + if (acc->time >= start && acc->time < end) { + GST_TRACE_OBJECT (self, "position is within group, done"); + acc->buffered = TRUE; + return FALSE; + } + return TRUE; +} + +static gboolean +is_buffered_unlocked (GstSourceBuffer * self, GstClockTime time) +{ + gboolean buffered = TRUE; + GHashTableIter iter; + g_hash_table_iter_init (&iter, self->track_buffers); + for (gpointer key, value; + buffered && g_hash_table_iter_next (&iter, &key, &value);) { + GstMediaSourceTrack *track = key; + if (!gst_media_source_track_get_active (track)) { + continue; + } + GstMediaSourceTrackBuffer *track_buffer = value; + IsBufferedAccumulator acc = { + .time = time, + .buffered = FALSE, + }; + GstIterator *it = gst_media_source_track_buffer_iter_samples (track_buffer); + gst_iterator_fold (it, (GstIteratorFoldFunction) is_buffered_fold, + (GValue *) & acc, self); + g_clear_pointer (&it, gst_iterator_free); + buffered = acc.buffered; + } + return buffered; +} + +gboolean +gst_source_buffer_is_buffered (GstSourceBuffer * self, GstClockTime time) +{ + TRACKS_LOCK (self); + gboolean buffered = is_buffered_unlocked (self, time); + TRACKS_UNLOCK (self); + return buffered; +} + +static gboolean +is_range_buffered_fold (const GValue * item, IsRangeBufferedAccumulator * acc, + GstSourceBuffer * self) +{ + GstMediaSourceCodedFrameGroup *group = + gst_value_get_media_source_coded_frame_group (item); + if (group == NULL) { + return FALSE; + } + GstClockTime buffer_start = group->start; + GstClockTime buffer_end = group->end; + + GstClockTime start = acc->start; + GstClockTime end = acc->end; + + if (!acc->start_buffered) { + if (start < buffer_start) { + GST_TRACE_OBJECT (self, "start position precedes buffer start, done"); + return FALSE; + } + if (start >= buffer_start && start < buffer_end) { + GST_TRACE_OBJECT (self, "start position is within buffer, checking end"); + acc->start_buffered = TRUE; + return TRUE; + } + } else { + if (end < buffer_start) { + GST_TRACE_OBJECT (self, "end position precedes buffer start, done"); + return FALSE; + } + if (end <= buffer_end) { + GST_TRACE_OBJECT (self, "end position is within buffer, done"); + acc->end_buffered = TRUE; + return FALSE; + } + } + + return TRUE; +} + +gboolean +gst_source_buffer_is_range_buffered (GstSourceBuffer * self, GstClockTime start, + GstClockTime end) +{ + GHashTableIter iter; + gboolean buffered = TRUE; + TRACKS_LOCK (self); + g_hash_table_iter_init (&iter, self->track_buffers); + for (gpointer key, value; + buffered && g_hash_table_iter_next (&iter, &key, &value);) { + GstMediaSourceTrack *track = key; + if (!gst_media_source_track_get_active (track)) { + continue; + } + GstMediaSourceTrackBuffer *track_buffer = value; + IsRangeBufferedAccumulator acc = { + .start = start, + .end = end, + .start_buffered = FALSE, + .end_buffered = FALSE, + }; + GstIterator *it = gst_media_source_track_buffer_iter_samples (track_buffer); + gst_iterator_fold (it, (GstIteratorFoldFunction) is_range_buffered_fold, + (GValue *) & acc, self); + g_clear_pointer (&it, gst_iterator_free); + buffered = acc.end_buffered; + } + TRACKS_UNLOCK (self); + return buffered; +} + +GstClockTime +gst_source_buffer_get_duration (GstSourceBuffer * self) +{ + g_return_val_if_fail (GST_IS_SOURCE_BUFFER (self), GST_CLOCK_TIME_NONE); + return gst_append_pipeline_get_duration (self->append_pipeline); +} + +void +gst_source_buffer_teardown (GstSourceBuffer * self) +{ + GST_OBJECT_LOCK (self); + reset_parser_state_unlocked (self); + clear_updating (self); + GST_OBJECT_UNLOCK (self); +} + +GPtrArray * +gst_source_buffer_get_all_tracks (GstSourceBuffer * self) +{ + g_return_val_if_fail (GST_IS_SOURCE_BUFFER (self), NULL); + + GPtrArray *tracks = g_ptr_array_new (); + + GPtrArray *audio_tracks = gst_append_pipeline_get_audio_tracks + (self->append_pipeline); + GPtrArray *text_tracks = gst_append_pipeline_get_text_tracks + (self->append_pipeline); + GPtrArray *video_tracks = gst_append_pipeline_get_video_tracks + (self->append_pipeline); + + if (audio_tracks) { + g_ptr_array_extend (tracks, audio_tracks, NULL, NULL); + } + if (text_tracks) { + g_ptr_array_extend (tracks, text_tracks, NULL, NULL); + } + if (video_tracks) { + g_ptr_array_extend (tracks, video_tracks, NULL, NULL); + } + + return tracks; +} + +static void +seek_track_buffer_unlocked (GstMediaSourceTrack * track, + GstMediaSourceTrackBuffer * buffer, GstSourceBuffer * self) +{ + TrackFeedTask *feed = get_track_feed_unlocked (self, track); + + const gchar *track_id = gst_media_source_track_get_id (track); + GST_DEBUG_OBJECT (self, "%s: seeking", track_id); + reset_track_feed (feed); + GST_DEBUG_OBJECT (self, "%s: restarted track feed", track_id); +} + +void +gst_source_buffer_seek (GstSourceBuffer * self, GstClockTime time) +{ + g_return_if_fail (GST_IS_SOURCE_BUFFER (self)); + g_return_if_fail (GST_CLOCK_TIME_IS_VALID (time)); + + TRACKS_LOCK (self); + self->seek_time = time; + g_hash_table_foreach (self->track_buffers, + (GHFunc) seek_track_buffer_unlocked, self); + TRACKS_UNLOCK (self); +} + +gboolean +gst_source_buffer_get_active (GstSourceBuffer * self) +{ + gboolean active = FALSE; + GHashTableIter iter; + + TRACKS_LOCK (self); + g_hash_table_iter_init (&iter, self->track_buffers); + for (gpointer key; !active && g_hash_table_iter_next (&iter, &key, NULL);) { + GstMediaSourceTrack *track = GST_MEDIA_SOURCE_TRACK (key); + active |= gst_media_source_track_get_active (track); + } + TRACKS_UNLOCK (self); + + return active; +} diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstsourcebuffer.h b/vendor/gst-mse/gst-libs/gst/mse/gstsourcebuffer.h new file mode 100644 index 0000000..1f6b614 --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstsourcebuffer.h @@ -0,0 +1,127 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2013 Google Inc. All rights reserved. + * Copyright (C) 2013 Orange + * Copyright (C) 2013-2020 Apple Inc. All rights reserved. + * Copyright (C) 2014 Sebastian Dröge + * Copyright (C) 2015, 2016, 2017 Igalia, S.L + * Copyright (C) 2015, 2016, 2017 Metrological Group B.V. + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#pragma once + +#include +#include +#include + +G_BEGIN_DECLS + +/** + * GstSourceBufferAppendMode: + * @GST_SOURCE_BUFFER_APPEND_MODE_SEGMENTS: + * @GST_SOURCE_BUFFER_APPEND_MODE_SEQUENCE: + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-appendmode) + * + * Since: 1.24 + */ +typedef enum +{ + GST_SOURCE_BUFFER_APPEND_MODE_SEGMENTS, + GST_SOURCE_BUFFER_APPEND_MODE_SEQUENCE, +} GstSourceBufferAppendMode; + +/** + * GstSourceBufferInterval: + * + * Since: 1.24 + */ +typedef struct +{ + GstClockTime start; + GstClockTime end; +} GstSourceBufferInterval; + +#define GST_TYPE_SOURCE_BUFFER (gst_source_buffer_get_type()) + +GST_MSE_API +G_DECLARE_FINAL_TYPE (GstSourceBuffer, gst_source_buffer, GST, SOURCE_BUFFER, + GstObject); + +GST_MSE_API +GstSourceBufferAppendMode gst_source_buffer_get_append_mode ( + GstSourceBuffer * self); + +GST_MSE_API +gboolean gst_source_buffer_set_append_mode (GstSourceBuffer * self, + GstSourceBufferAppendMode mode, GError ** error); + +GST_MSE_API +gchar *gst_source_buffer_get_content_type (GstSourceBuffer * self) G_GNUC_WARN_UNUSED_RESULT; + +GST_MSE_API +gboolean gst_source_buffer_get_updating (GstSourceBuffer * self); + +GST_MSE_API +GArray * gst_source_buffer_get_buffered (GstSourceBuffer * self, + GError ** error) G_GNUC_WARN_UNUSED_RESULT; + +GST_MSE_API +gboolean gst_source_buffer_set_timestamp_offset (GstSourceBuffer * self, + GstClockTime offset, + GError ** error); + +GST_MSE_API +GstClockTime gst_source_buffer_get_timestamp_offset (GstSourceBuffer * self); + +GST_MSE_API +gboolean gst_source_buffer_set_append_window_start (GstSourceBuffer * self, + GstClockTime start, + GError ** error); + +GST_MSE_API +GstClockTime gst_source_buffer_get_append_window_start (GstSourceBuffer * self); + +GST_MSE_API +gboolean gst_source_buffer_set_append_window_end (GstSourceBuffer * self, + GstClockTime end, + GError ** error); + +GST_MSE_API +GstClockTime gst_source_buffer_get_append_window_end (GstSourceBuffer * self); + +GST_MSE_API +gboolean gst_source_buffer_append_buffer (GstSourceBuffer * self, + GstBuffer * buf, GError ** error); + +GST_MSE_API +gboolean gst_source_buffer_abort (GstSourceBuffer * self, GError ** error); + +GST_MSE_API +gboolean gst_source_buffer_change_content_type (GstSourceBuffer * self, + const gchar * type, + GError ** error); + +GST_MSE_API +gboolean gst_source_buffer_remove (GstSourceBuffer * self, GstClockTime start, + GstClockTime end, GError ** error); + +G_END_DECLS diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstsourcebufferlist-private.h b/vendor/gst-mse/gst-libs/gst/mse/gstsourcebufferlist-private.h new file mode 100644 index 0000000..264fb35 --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstsourcebufferlist-private.h @@ -0,0 +1,64 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#pragma once + +#include +#include "gstsourcebufferlist.h" +#include "gstsourcebuffer.h" + +G_BEGIN_DECLS + +GST_MSE_PRIVATE +GstSourceBufferList *gst_source_buffer_list_new (void); + +GST_MSE_PRIVATE +gboolean gst_source_buffer_list_contains (GstSourceBufferList * self, + GstSourceBuffer * buf); + +GST_MSE_PRIVATE +void gst_source_buffer_list_append (GstSourceBufferList * self, + GstSourceBuffer * buf); + +GST_MSE_PRIVATE +gboolean gst_source_buffer_list_remove (GstSourceBufferList * self, + GstSourceBuffer * buf); + +GST_MSE_PRIVATE +void gst_source_buffer_list_remove_all (GstSourceBufferList * self); + +GST_MSE_PRIVATE +void gst_source_buffer_list_notify_freeze (GstSourceBufferList * self); + +GST_MSE_PRIVATE +void gst_source_buffer_list_notify_cancel (GstSourceBufferList * self); + +GST_MSE_PRIVATE +void gst_source_buffer_list_notify_added (GstSourceBufferList * self); + +GST_MSE_PRIVATE +void gst_source_buffer_list_notify_removed (GstSourceBufferList * self); + +GST_MSE_PRIVATE +void gst_source_buffer_list_notify_thaw (GstSourceBufferList * self); + +G_END_DECLS diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstsourcebufferlist.c b/vendor/gst-mse/gst-libs/gst/mse/gstsourcebufferlist.c new file mode 100644 index 0000000..5d31fc5 --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstsourcebufferlist.c @@ -0,0 +1,486 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +/** + * SECTION:gstsourcebufferlist + * @title: GstSourceBufferList + * @short_description: Source Buffer List + * @include: mse/mse.h + * @symbols: + * - GstSourceBufferList + * + * The Source Buffer List is a list of #GstSourceBuffers that can be + * indexed numerically and monitored for changes. The list itself cannot be + * modified through this interface, though the Source Buffers it holds can be + * modified after retrieval. + * + * It is used by #GstMediaSource to provide direct access to its child + * #GstSourceBuffers through #GstMediaSource:source-buffers as well as + * informing clients which of the Source Buffers are active through + * #GstMediaSource:active-source-buffers. + * + * Since: 1.24 + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "gstsourcebufferlist.h" +#include "gstsourcebufferlist-private.h" + +#include "gstmseeventqueue-private.h" + +typedef struct +{ + gboolean frozen; + gboolean added; + gboolean removed; +} PendingNotifications; + +/** + * GstSourceBufferList: + * + * Since: 1.24 + */ +struct _GstSourceBufferList +{ + GstObject parent_instance; + + GPtrArray *buffers; + + GstMseEventQueue *event_queue; + + PendingNotifications pending_notifications; +}; + +G_DEFINE_TYPE (GstSourceBufferList, gst_source_buffer_list, GST_TYPE_OBJECT); + +enum +{ + PROP_0, + PROP_LENGTH, + N_PROPS, +}; + +typedef enum +{ + ON_SOURCEBUFFER_ADDED, + ON_SOURCEBUFFER_REMOVED, + N_SIGNALS, +} SourceBufferListEvent; + +typedef struct +{ + GstDataQueueItem item; + SourceBufferListEvent event; +} SourceBufferListEventItem; + +static GParamSpec *properties[N_PROPS]; +static guint signals[N_SIGNALS] = { 0 }; + +static guint +get_length_unlocked (GstSourceBufferList * self) +{ + return self->buffers->len; +} + +static gboolean +is_frozen (GstSourceBufferList * self) +{ + return g_atomic_int_get (&self->pending_notifications.frozen); +} + +static void +set_frozen (GstSourceBufferList * self) +{ + g_atomic_int_set (&self->pending_notifications.frozen, TRUE); +} + +static void +clear_frozen (GstSourceBufferList * self) +{ + g_atomic_int_set (&self->pending_notifications.frozen, FALSE); +} + +static void +set_pending_added (GstSourceBufferList * self) +{ + g_atomic_int_set (&self->pending_notifications.added, TRUE); +} + +static void +set_pending_removed (GstSourceBufferList * self) +{ + g_atomic_int_set (&self->pending_notifications.removed, TRUE); +} + +static gboolean +clear_pending_added (GstSourceBufferList * self) +{ + return g_atomic_int_and (&self->pending_notifications.added, FALSE); +} + +static gboolean +clear_pending_removed (GstSourceBufferList * self) +{ + return g_atomic_int_and (&self->pending_notifications.removed, FALSE); +} + +static void +schedule_event (GstSourceBufferList * self, SourceBufferListEvent event) +{ + SourceBufferListEventItem item = { + .item = {.destroy = g_free,.visible = TRUE,.size = 1,.object = NULL}, + .event = event, + }; + + gst_mse_event_queue_push (self->event_queue, g_memdup2 (&item, + sizeof (SourceBufferListEventItem))); +} + +static void +dispatch_event (SourceBufferListEventItem * item, GstSourceBufferList * self) +{ + g_signal_emit (self, signals[item->event], 0); +} + +static void +call_source_buffer_added (GstSourceBufferList * self) +{ + if (is_frozen (self)) { + set_pending_added (self); + } else { + clear_pending_added (self); + schedule_event (self, ON_SOURCEBUFFER_ADDED); + } +} + +static void +call_source_buffer_removed (GstSourceBufferList * self) +{ + if (is_frozen (self)) { + set_pending_removed (self); + } else { + clear_pending_removed (self); + schedule_event (self, ON_SOURCEBUFFER_REMOVED); + } +} + +GstSourceBufferList * +gst_source_buffer_list_new (void) +{ + return gst_object_ref_sink (g_object_new (GST_TYPE_SOURCE_BUFFER_LIST, NULL)); +} + +static void +gst_source_buffer_list_dispose (GObject * object) +{ + GstSourceBufferList *self = (GstSourceBufferList *) object; + gst_clear_object (&self->event_queue); + + G_OBJECT_CLASS (gst_source_buffer_list_parent_class)->dispose (object); +} + +static void +gst_source_buffer_list_finalize (GObject * object) +{ + GstSourceBufferList *self = (GstSourceBufferList *) object; + + g_clear_pointer (&self->buffers, g_ptr_array_unref); + + G_OBJECT_CLASS (gst_source_buffer_list_parent_class)->finalize (object); +} + +static void +gst_source_buffer_list_get_property (GObject * object, guint prop_id, GValue + * value, GParamSpec * pspec) +{ + GstSourceBufferList *self = GST_SOURCE_BUFFER_LIST (object); + + switch (prop_id) { + case PROP_LENGTH: + g_value_set_uint (value, gst_source_buffer_list_get_length (self)); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + } +} + +static void +gst_source_buffer_list_class_init (GstSourceBufferListClass * klass) +{ + GObjectClass *oclass = G_OBJECT_CLASS (klass); + + oclass->dispose = GST_DEBUG_FUNCPTR (gst_source_buffer_list_dispose); + oclass->finalize = GST_DEBUG_FUNCPTR (gst_source_buffer_list_finalize); + oclass->get_property = + GST_DEBUG_FUNCPTR (gst_source_buffer_list_get_property); + + /** + * GstSourceBufferList:length: + * + * The number of #GstSourceBuffers contained by this structure + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebufferlist-length) + * + * Since: 1.24 + */ + properties[PROP_LENGTH] = g_param_spec_ulong ("length", + "Length", + "The number of SourceBuffers contained by this structure", + 0, G_MAXULONG, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS); + + g_object_class_install_properties (oclass, N_PROPS, properties); + + /** + * GstSourceBufferList::on-sourcebuffer-added: + * @self: The #GstSourceBufferList that has just added a + * #GstSourceBuffer + * + * Emitted when a #GstSourceBuffer has been added to this list. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebufferlist-onaddsourcebuffer) + * + * Since: 1.24 + */ + signals[ON_SOURCEBUFFER_ADDED] = g_signal_new ("on-sourcebuffer-added", + G_TYPE_FROM_CLASS (klass), + G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 0); + + /** + * GstSourceBufferList::on-sourcebuffer-removed: + * @self: The #GstSourceBufferList that has just removed a + * #GstSourceBuffer + * + * Emitted when a #GstSourceBuffer has been removed from this list. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebufferlist-onremovesourcebuffer) + * + * Since: 1.24 + */ + signals[ON_SOURCEBUFFER_REMOVED] = g_signal_new ("on-sourcebuffer-removed", + G_TYPE_FROM_CLASS (klass), + G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 0); +} + +static void +gst_source_buffer_list_init (GstSourceBufferList * self) +{ + set_frozen (self); + self->buffers = g_ptr_array_new_with_free_func (gst_object_unref); + self->event_queue = + gst_mse_event_queue_new ((GstMseEventQueueCallback) dispatch_event, self); + clear_pending_added (self); + clear_pending_removed (self); + clear_frozen (self); +} + +/** + * gst_source_buffer_list_index: + * @self: #GstSourceBufferList instance + * @index: index of requested Source Buffer + * + * Retrieves the #GstSourceBuffer at @index from @self. If @index is greater than + * the highest index in the list, it will return `NULL`. + * + * [Specification](https://www.w3.org/TR/media-source-2/#dfn-sourcebufferlist-getter) + * + * Returns: (transfer full) (nullable): The requested #GstSourceBuffer or `NULL` + * Since: 1.24 + */ +GstSourceBuffer * +gst_source_buffer_list_index (GstSourceBufferList * self, guint index) +{ + g_return_val_if_fail (GST_IS_SOURCE_BUFFER_LIST (self), NULL); + + GST_OBJECT_LOCK (self); + guint length = get_length_unlocked (self); + GstSourceBuffer *buf = index >= length ? NULL : gst_object_ref + (g_ptr_array_index (self->buffers, index)); + GST_OBJECT_UNLOCK (self); + + return buf; +} + +/** + * gst_source_buffer_list_get_length: + * @self: #GstSourceBufferList instance + * + * [Specification](https://www.w3.org/TR/media-source-2/#dom-sourcebufferlist-length) + * + * Returns: The number of #GstSourceBuffer objects in the list + * Since: 1.24 + */ +guint +gst_source_buffer_list_get_length (GstSourceBufferList * self) +{ + g_return_val_if_fail (GST_IS_SOURCE_BUFFER_LIST (self), 0); + + GST_OBJECT_LOCK (self); + guint length = get_length_unlocked (self); + GST_OBJECT_UNLOCK (self); + + return length; +} + +gboolean +gst_source_buffer_list_contains (GstSourceBufferList * self, + GstSourceBuffer * buf) +{ + g_return_val_if_fail (GST_IS_SOURCE_BUFFER_LIST (self), FALSE); + g_return_val_if_fail (GST_IS_SOURCE_BUFFER (buf), FALSE); + + GST_OBJECT_LOCK (self); + gboolean found = g_ptr_array_find (self->buffers, buf, NULL); + GST_OBJECT_UNLOCK (self); + + return found; +} + +void +gst_source_buffer_list_append (GstSourceBufferList * self, + GstSourceBuffer * buf) +{ + g_return_if_fail (GST_IS_SOURCE_BUFFER_LIST (self)); + + GST_OBJECT_LOCK (self); + g_ptr_array_add (self->buffers, gst_object_ref (buf)); + GST_OBJECT_UNLOCK (self); + + call_source_buffer_added (self); +} + +gboolean +gst_source_buffer_list_remove (GstSourceBufferList * self, + GstSourceBuffer * buf) +{ + g_return_val_if_fail (GST_IS_SOURCE_BUFFER_LIST (self), FALSE); + gboolean removed = g_ptr_array_remove (self->buffers, buf); + if (removed) { + call_source_buffer_removed (self); + return TRUE; + } else { + return FALSE; + } +} + +void +gst_source_buffer_list_remove_all (GstSourceBufferList * self) +{ + g_return_if_fail (GST_IS_SOURCE_BUFFER_LIST (self)); + if (self->buffers->len < 1) { + return; + } + g_ptr_array_set_size (self->buffers, 0); + call_source_buffer_removed (self); +} + +/** + * gst_source_buffer_list_notify_freeze: + * @self: #GstSourceBufferList instance + * + * Prevents any notifications from being emitted by @self until the next call to + * gst_source_buffer_list_notify_thaw(). + * + */ +void +gst_source_buffer_list_notify_freeze (GstSourceBufferList * self) +{ + g_return_if_fail (GST_IS_SOURCE_BUFFER_LIST (self)); + clear_pending_added (self); + clear_pending_removed (self); + set_frozen (self); +} + +/** + * gst_source_buffer_list_notify_cancel: + * @self: #GstSourceBufferList instance + * + * Cancels any pending notifications that are waiting between calls to + * gst_source_buffer_list_notify_freeze() and + * gst_source_buffer_list_notify_thaw(). + * + */ +void +gst_source_buffer_list_notify_cancel (GstSourceBufferList * self) +{ + g_return_if_fail (GST_IS_SOURCE_BUFFER_LIST (self)); + clear_pending_added (self); + clear_pending_removed (self); +} + +/** + * gst_source_buffer_list_notify_added: + * @self: #GstSourceBufferList instance + * + * Explicitly notifies subscribers to the ::on-sourcebuffer-added signal that an + * item has been added to @self. + * + */ +void +gst_source_buffer_list_notify_added (GstSourceBufferList * self) +{ + g_return_if_fail (GST_IS_SOURCE_BUFFER_LIST (self)); + g_return_if_fail (!is_frozen (self)); + call_source_buffer_added (self); +} + +/** + * gst_source_buffer_list_notify_removed: + * @self: #GstSourceBufferList instance + * + * Explicitly notifies subscribers to the ::on-sourcebuffer-removed signal that + * an item has been removed from @self. + * + */ +void +gst_source_buffer_list_notify_removed (GstSourceBufferList * self) +{ + g_return_if_fail (GST_IS_SOURCE_BUFFER_LIST (self)); + g_return_if_fail (!is_frozen (self)); + call_source_buffer_removed (self); +} + +/** + * gst_source_buffer_list_notify_thaw: + * @self: #GstSourceBufferList instance + * + * Resumes notifications emitted from @self after a call to + * gst_source_buffer_list_notify_freeze(). If any notifications are pending, + * they will be emitted as a result of this call. To prevent pending + * notifications from being published, use + * gst_source_buffer_list_notify_cancel() before calling this method. + * + */ +void +gst_source_buffer_list_notify_thaw (GstSourceBufferList * self) +{ + g_return_if_fail (GST_IS_SOURCE_BUFFER_LIST (self)); + clear_frozen (self); + if (clear_pending_added (self)) { + g_signal_emit (self, signals[ON_SOURCEBUFFER_ADDED], 0); + } + if (clear_pending_removed (self)) { + g_signal_emit (self, signals[ON_SOURCEBUFFER_REMOVED], 0); + } +} diff --git a/vendor/gst-mse/gst-libs/gst/mse/gstsourcebufferlist.h b/vendor/gst-mse/gst-libs/gst/mse/gstsourcebufferlist.h new file mode 100644 index 0000000..050f2ab --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/gstsourcebufferlist.h @@ -0,0 +1,44 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#pragma once + +#include +#include + +#include "gstsourcebuffer.h" + +G_BEGIN_DECLS + +#define GST_TYPE_SOURCE_BUFFER_LIST (gst_source_buffer_list_get_type()) + +GST_MSE_API +G_DECLARE_FINAL_TYPE (GstSourceBufferList, gst_source_buffer_list, GST, + SOURCE_BUFFER_LIST, GstObject); + +GST_MSE_API +GstSourceBuffer *gst_source_buffer_list_index (GstSourceBufferList * self, + guint index) G_GNUC_WARN_UNUSED_RESULT; +GST_MSE_API +guint gst_source_buffer_list_get_length (GstSourceBufferList * self); + +G_END_DECLS diff --git a/vendor/gst-mse/gst-libs/gst/mse/meson.build b/vendor/gst-mse/gst-libs/gst/mse/meson.build new file mode 100644 index 0000000..9404668 --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/meson.build @@ -0,0 +1,163 @@ +if get_option('mse').disabled() + gstmse_private_test_dep = dependency('', required: false) + subdir_done() +endif + +gstmse_headers_private = files( + 'gstappendpipeline-private.h', + 'gstmediasourcesamplemap-private.h', + 'gstmediasourcetrackbuffer-private.h', + 'gstmediasourcetrack-private.h', + 'gstmseeventqueue-private.h', + 'gstmselogging-private.h', + 'gstmsemediatype-private.h', +) + +gstmse_sources_private = files( + 'gstappendpipeline.c', + 'gstmediasourcesamplemap.c', + 'gstmediasourcetrackbuffer.c', + 'gstmediasourcetrack.c', + 'gstmseeventqueue.c', + 'gstmselogging.c', + 'gstmsemediatype.c', +) + +gstmse_headers_public = files( + 'gstmediasource.h', + 'gstsourcebuffer.h', + 'gstsourcebufferlist.h', + 'gstmsesrc.h', + 'mse.h', + 'mse-prelude.h', +) + +gstmse_sources_public = files( + 'gstmediasource.c', + 'gstmsesrc.c', + 'gstsourcebuffer.c', + 'gstsourcebufferlist.c', +) + +doc_sources = [] +foreach s: gstmse_headers_private + gstmse_sources_private + gstmse_headers_public + gstmse_sources_public + doc_sources += s.full_path() +endforeach + +libs_sources += { + 'mse': pathsep.join(doc_sources) +} + +gstmse_header_dir = 'gstreamer-' + api_version + '/gst/mse/' + +gstmse_enums_private = gnome.mkenums_simple('mse-enumtypes-private', + sources : gstmse_headers_private, + body_prefix : '#ifdef HAVE_CONFIG_H\n#include "config.h"\n#endif', + header_prefix : '#include ', + decorator: 'GST_MSE_PRIVATE', + install_header: false, +) + +gstmse_enums = gnome.mkenums_simple('mse-enumtypes', + sources : gstmse_headers_public, + body_prefix : '#ifdef HAVE_CONFIG_H\n#include "config.h"\n#endif', + header_prefix : '#include ', + decorator: 'GST_MSE_API', + install_header: true, + install_dir : join_paths(get_option('includedir'), gstmse_header_dir), +) + +gstmse_deps = [gstbase_dep, gstapp_dep] + +gstmse_enums_private_c = gstmse_enums_private[0] +gstmse_enums_private_h = gstmse_enums_private[1] + +gstmse_enums_c = gstmse_enums[0] +gstmse_enums_h = gstmse_enums[1] + +gstmse_c_args = gst_plugins_bad_args + [ + '-DBUILDING_GST_MSE', + '-DGST_USE_UNSTABLE_API', + '-DG_LOG_DOMAIN="GStreamer-MSE"', +] + +gstmse_sources_all = [ + gstmse_sources_private, + gstmse_sources_public, + gstmse_enums_c, + gstmse_enums_h, + gstmse_enums_private_c, + gstmse_enums_private_h, +] + +gstmse_private_test = library('gstmse-private-test', + gstmse_sources_all, + c_args : [gstmse_c_args, '-DBUILDING_GST_MSE_TEST'], + include_directories : [configinc, libsinc], + dependencies : gstmse_deps, +) + +gstmse_private_test_dep = declare_dependency( + compile_args : [gstmse_c_args, '-DBUILDING_GST_MSE_TEST'], + link_with : [gstmse_private_test], + include_directories : [libsinc], + sources: gstmse_headers_public + [gstmse_enums_h], +) + +gstmse = library('gstmse-' + api_version, + gstmse_sources_all, + c_args : gstmse_c_args, + include_directories : [configinc, libsinc], + version : libversion, + soversion : soversion, + darwin_versions : osxversion, + install : true, + dependencies : gstmse_deps, +) + +pkg_name = 'gstreamer-mse-' + api_version +pkgconfig.generate(gstmse, + libraries : [gst_dep], + variables : pkgconfig_variables, + subdirs : pkgconfig_subdirs, + name : pkg_name, + description : 'GStreamer Support for W3C Media Source Extensions', +) + +library_def = {'lib': gstmse} +gen_sources = [] +if build_gir + gir = { + 'sources' : [ + gstmse_sources_public, + gstmse_headers_public, + gstmse_enums_h, + gstmse_enums_c, + ], + 'namespace' : 'GstMse', + 'nsversion' : api_version, + 'identifier_prefix' : 'Gst', + 'symbol_prefix' : 'gst', + 'export_packages' : pkg_name, + 'includes' : ['Gst-1.0'], + 'install' : true, + 'extra_args' : gir_init_section + ['-DGST_USE_UNSTABLE_API'] + ['--c-include=gst/mse/mse.h'], + 'dependencies' : gstmse_deps, + } + library_def += {'gir': [gir]} + if not static_build + mse_gir = gnome.generate_gir(gstmse, kwargs: gir) + library_def += {'gir_targets': library_def.get('gir_targets', []) + [mse_gir]} + gen_sources += mse_gir + endif +endif +gst_libraries += [[pkg_name, library_def]] + +gstmse_dep = declare_dependency( + link_with : [gstmse], + include_directories : [libsinc], + dependencies : gstmse_deps, + sources: gstmse_headers_public + [gstmse_enums_h], +) +install_headers(gstmse_headers_public, subdir: gstmse_header_dir) +meson.override_dependency(pkg_name, gstmse_dep) diff --git a/vendor/gst-mse/gst-libs/gst/mse/mse-prelude.h b/vendor/gst-mse/gst-libs/gst/mse/mse-prelude.h new file mode 100644 index 0000000..eb807e1 --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/mse-prelude.h @@ -0,0 +1,48 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#pragma once + +#include + +#ifndef GST_MSE_API +# if defined(BUILDING_GST_MSE) && defined(GST_API_EXPORT) +# define GST_MSE_API GST_API_EXPORT +# elif defined(GST_API_IMPORT) +# define GST_MSE_API GST_API_IMPORT +# else +# define GST_MSE_API +# endif +#endif + +#ifndef GST_MSE_PRIVATE +# if defined(BUILDING_GST_MSE_TEST) +# define GST_MSE_PRIVATE GST_MSE_API +# else +# define GST_MSE_PRIVATE G_GNUC_INTERNAL +# endif +#endif + +#ifndef GST_USE_UNSTABLE_API +#warning "The MSE library from gst-plugins-bad is an unstable API and may change in future." +#warning "You can define GST_USE_UNSTABLE_API to avoid this warning." +#endif diff --git a/vendor/gst-mse/gst-libs/gst/mse/mse.h b/vendor/gst-mse/gst-libs/gst/mse/mse.h new file mode 100644 index 0000000..343213e --- /dev/null +++ b/vendor/gst-mse/gst-libs/gst/mse/mse.h @@ -0,0 +1,32 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#pragma once + +#include + +#include "mse-prelude.h" +#include +#include "gstmsesrc.h" +#include "gstmediasource.h" +#include "gstsourcebufferlist.h" +#include "gstsourcebuffer.h" diff --git a/vendor/gst-mse/gst/mse/gstmse.c b/vendor/gst-mse/gst/mse/gstmse.c new file mode 100644 index 0000000..7e8938f --- /dev/null +++ b/vendor/gst-mse/gst/mse/gstmse.c @@ -0,0 +1,49 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +/** + * plugin-mse: + * + * Since: 1.24 + */ + +#include "gstmse.h" + +/** + * SECTION:element-msesrc + * @title: msesrc + * + * Since: 1.24 + */ +GST_ELEMENT_REGISTER_DEFINE (msesrc, "msesrc", GST_RANK_NONE, GST_TYPE_MSE_SRC); + +static gboolean +plugin_init (GstPlugin * plugin) +{ + return GST_ELEMENT_REGISTER (msesrc, plugin); +} + +GST_PLUGIN_DEFINE (GST_VERSION_MAJOR, + GST_VERSION_MINOR, + mse, + "W3C Media Source Extensions Support", + plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN) diff --git a/vendor/gst-mse/gst/mse/gstmse.h b/vendor/gst-mse/gst/mse/gstmse.h new file mode 100644 index 0000000..0500b65 --- /dev/null +++ b/vendor/gst-mse/gst/mse/gstmse.h @@ -0,0 +1,33 @@ +/* GStreamer + * + * SPDX-License-Identifier: LGPL-2.1 + * + * Copyright (C) 2022, 2023 Collabora Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#pragma once + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include + +GST_ELEMENT_REGISTER_DECLARE (msesrc); diff --git a/vendor/gst-mse/gst/mse/meson.build b/vendor/gst-mse/gst/mse/meson.build new file mode 100644 index 0000000..115eaac --- /dev/null +++ b/vendor/gst-mse/gst/mse/meson.build @@ -0,0 +1,29 @@ +mse_sources = ['gstmse.c'] + +mse_headers = [ + 'gstmse.h', +] + +doc_sources = [] +foreach s: mse_sources + mse_headers + doc_sources += meson.current_source_dir() / s +endforeach + +plugin_sources += { + 'mse': pathsep.join(doc_sources) +} + +if get_option('mse').disabled() + subdir_done() +endif + +gstmse_plugin = library('gstmse', + mse_sources, + c_args: gst_plugins_bad_args + ['-DGST_USE_UNSTABLE_API'], + include_directories: [configinc], + dependencies : [gstbase_dep, gstmse_dep], + install : true, + install_dir : plugins_install_dir, +) + +plugins += [gstmse_plugin] diff --git a/vendor/servo-media-gstreamer/registry_scanner.rs b/vendor/servo-media-gstreamer/registry_scanner.rs index b9ac9c7..c4587c6 100644 --- a/vendor/servo-media-gstreamer/registry_scanner.rs +++ b/vendor/servo-media-gstreamer/registry_scanner.rs @@ -76,8 +76,9 @@ impl GStreamerRegistryScanner { let is_opus_supported = has_element_for_media_type(&audio_decoder_factories, "audio/x-opus"); - if is_opus_supported && has_element_for_media_type(&audio_parser_factories, "audio/x-opus") - { + // Nacre patch: a decoder is enough. Demuxers (matroska, qtdemux) hand opusdec framed packets, + // and Arch ships no opusparse (gst-plugins-bad's opus plugin), so requiring one hid Opus. + if is_opus_supported { self.supported_mime_types.insert("audio/opus"); self.supported_codecs.insert("opus"); self.supported_codecs.insert("x-opus");