1 #import "GStreamerBackend.h"
4 #include <gst/video/video.h>
6 GST_DEBUG_CATEGORY_STATIC (debug_category);
7 #define GST_CAT_DEFAULT debug_category
9 /* Do not allow seeks to be performed closer than this distance. It is visually useless, and will probably
10 * confuse some demuxers. */
11 #define SEEK_MIN_DELAY (500 * GST_MSECOND)
13 @interface GStreamerBackend()
14 -(void)setUIMessage:(gchar*) message;
16 -(void)check_initialization_complete;
19 @implementation GStreamerBackend {
20 id ui_delegate; /* Class that we use to interact with the user interface */
21 GstElement *pipeline; /* The running pipeline */
22 GstElement *video_sink; /* The video sink element which receives XOverlay commands */
23 GMainContext *context; /* GLib context used to run the main loop */
24 GMainLoop *main_loop; /* GLib main loop */
25 gboolean initialized; /* To avoid informing the UI multiple times about the initialization */
26 UIView *ui_video_view; /* UIView that holds the video */
27 GstState state; /* Current pipeline state */
28 GstState target_state; /* Desired pipeline state, to be set once buffering is complete */
29 gint64 duration; /* Cached clip duration */
30 gint64 desired_position; /* Position to seek to, once the pipeline is running */
31 GstClockTime last_seek_time; /* For seeking overflow prevention (throttling) */
32 gboolean is_live; /* Live streams do not use buffering */
39 -(id) init:(id) uiDelegate videoView:(UIView *)video_view
41 if (self = [super init])
43 self->ui_delegate = uiDelegate;
44 self->ui_video_view = video_view;
45 self->duration = GST_CLOCK_TIME_NONE;
47 GST_DEBUG_CATEGORY_INIT (debug_category, "tutorial-5", 0, "iOS tutorial 5");
48 gst_debug_set_threshold_for_name("tutorial-5", GST_LEVEL_DEBUG);
50 /* Start the bus monitoring task */
51 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
62 g_main_loop_quit(main_loop);
68 target_state = GST_STATE_PLAYING;
69 is_live = (gst_element_set_state (pipeline, GST_STATE_PLAYING) == GST_STATE_CHANGE_NO_PREROLL);
74 target_state = GST_STATE_PAUSED;
75 is_live = (gst_element_set_state (pipeline, GST_STATE_PAUSED) == GST_STATE_CHANGE_NO_PREROLL);
78 -(void) setUri:(NSString*)uri
80 const char *char_uri = [uri UTF8String];
81 g_object_set(pipeline, "uri", char_uri, NULL);
82 GST_DEBUG ("URI set to %s", char_uri);
85 -(void) setPosition:(NSInteger)milliseconds
87 gint64 position = (gint64)(milliseconds * GST_MSECOND);
88 if (state >= GST_STATE_PAUSED) {
89 execute_seek(position, self);
91 GST_DEBUG ("Scheduling seek to %" GST_TIME_FORMAT " for later", GST_TIME_ARGS (position));
92 self->desired_position = position;
100 /* Change the message on the UI through the UI delegate */
101 -(void)setUIMessage:(gchar*) message
103 NSString *string = [NSString stringWithUTF8String:message];
104 if(ui_delegate && [ui_delegate respondsToSelector:@selector(gstreamerSetUIMessage:)])
106 [ui_delegate gstreamerSetUIMessage:string];
110 /* Tell the application what is the current position and clip duration */
111 -(void) setCurrentUIPosition:(gint)pos duration:(gint)dur
113 if(ui_delegate && [ui_delegate respondsToSelector:@selector(setCurrentPosition:duration:)])
115 [ui_delegate setCurrentPosition:pos duration:dur];
119 /* If we have pipeline and it is running, query the current position and clip duration and inform
121 static gboolean refresh_ui (GStreamerBackend *self) {
124 /* We do not want to update anything unless we have a working pipeline in the PAUSED or PLAYING state */
125 if (!self || !self->pipeline || self->state < GST_STATE_PAUSED)
128 /* If we didn't know it yet, query the stream duration */
129 if (!GST_CLOCK_TIME_IS_VALID (self->duration)) {
130 gst_element_query_duration (self->pipeline, GST_FORMAT_TIME,&self->duration);
133 if (gst_element_query_position (self->pipeline, GST_FORMAT_TIME, &position)) {
134 /* The UI expects these values in milliseconds, and GStreamer provides nanoseconds */
135 [self setCurrentUIPosition:position / GST_MSECOND duration:self->duration / GST_MSECOND];
140 /* Forward declaration for the delayed seek callback */
141 static gboolean delayed_seek_cb (GStreamerBackend *self);
143 /* Perform seek, if we are not too close to the previous seek. Otherwise, schedule the seek for
144 * some time in the future. */
145 static void execute_seek (gint64 position, GStreamerBackend *self) {
148 if (position == GST_CLOCK_TIME_NONE)
151 diff = gst_util_get_timestamp () - self->last_seek_time;
153 if (GST_CLOCK_TIME_IS_VALID (self->last_seek_time) && diff < SEEK_MIN_DELAY) {
154 /* The previous seek was too close, delay this one */
155 GSource *timeout_source;
157 if (self->desired_position == GST_CLOCK_TIME_NONE) {
158 /* There was no previous seek scheduled. Setup a timer for some time in the future */
159 timeout_source = g_timeout_source_new ((SEEK_MIN_DELAY - diff) / GST_MSECOND);
160 g_source_set_callback (timeout_source, (GSourceFunc)delayed_seek_cb, (__bridge void *)self, NULL);
161 g_source_attach (timeout_source, self->context);
162 g_source_unref (timeout_source);
164 /* Update the desired seek position. If multiple petitions are received before it is time
165 * to perform a seek, only the last one is remembered. */
166 self->desired_position = position;
167 GST_DEBUG ("Throttling seek to %" GST_TIME_FORMAT ", will be in %" GST_TIME_FORMAT,
168 GST_TIME_ARGS (position), GST_TIME_ARGS (SEEK_MIN_DELAY - diff));
170 /* Perform the seek now */
171 GST_DEBUG ("Seeking to %" GST_TIME_FORMAT, GST_TIME_ARGS (position));
172 self->last_seek_time = gst_util_get_timestamp ();
173 gst_element_seek_simple (self->pipeline, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT, position);
174 self->desired_position = GST_CLOCK_TIME_NONE;
178 /* Delayed seek callback. This gets called by the timer setup in the above function. */
179 static gboolean delayed_seek_cb (GStreamerBackend *self) {
180 GST_DEBUG ("Doing delayed seek to %" GST_TIME_FORMAT, GST_TIME_ARGS (self->desired_position));
181 execute_seek (self->desired_position, self);
185 /* Retrieve errors from the bus and show them on the UI */
186 static void error_cb (GstBus *bus, GstMessage *msg, GStreamerBackend *self)
190 gchar *message_string;
192 gst_message_parse_error (msg, &err, &debug_info);
193 message_string = g_strdup_printf ("Error received from element %s: %s", GST_OBJECT_NAME (msg->src), err->message);
194 g_clear_error (&err);
196 [self setUIMessage:message_string];
197 g_free (message_string);
198 gst_element_set_state (self->pipeline, GST_STATE_NULL);
201 /* Called when the End Of the Stream is reached. Just move to the beginning of the media and pause. */
202 static void eos_cb (GstBus *bus, GstMessage *msg, GStreamerBackend *self) {
203 self->target_state = GST_STATE_PAUSED;
204 self->is_live = (gst_element_set_state (self->pipeline, GST_STATE_PAUSED) == GST_STATE_CHANGE_NO_PREROLL);
205 execute_seek (0, self);
208 /* Called when the duration of the media changes. Just mark it as unknown, so we re-query it in the next UI refresh. */
209 static void duration_cb (GstBus *bus, GstMessage *msg, GStreamerBackend *self) {
210 self->duration = GST_CLOCK_TIME_NONE;
213 /* Called when buffering messages are received. We inform the UI about the current buffering level and
214 * keep the pipeline paused until 100% buffering is reached. At that point, set the desired state. */
215 static void buffering_cb (GstBus *bus, GstMessage *msg, GStreamerBackend *self) {
221 gst_message_parse_buffering (msg, &percent);
222 if (percent < 100 && self->target_state >= GST_STATE_PAUSED) {
223 gchar * message_string = g_strdup_printf ("Buffering %d%%", percent);
224 gst_element_set_state (self->pipeline, GST_STATE_PAUSED);
225 [self setUIMessage:message_string];
226 g_free (message_string);
227 } else if (self->target_state >= GST_STATE_PLAYING) {
228 gst_element_set_state (self->pipeline, GST_STATE_PLAYING);
229 } else if (self->target_state >= GST_STATE_PAUSED) {
230 [self setUIMessage:"Buffering complete"];
234 /* Called when the clock is lost */
235 static void clock_lost_cb (GstBus *bus, GstMessage *msg, GStreamerBackend *self) {
236 if (self->target_state >= GST_STATE_PLAYING) {
237 gst_element_set_state (self->pipeline, GST_STATE_PAUSED);
238 gst_element_set_state (self->pipeline, GST_STATE_PLAYING);
242 /* Retrieve the video sink's Caps and tell the application about the media size */
243 static void check_media_size (GStreamerBackend *self) {
244 GstElement *video_sink;
245 GstPad *video_sink_pad;
249 /* Retrieve the Caps at the entrance of the video sink */
250 g_object_get (self->pipeline, "video-sink", &video_sink, NULL);
252 /* Do nothing if there is no video sink (this might be an audio-only clip */
253 if (!video_sink) return;
255 video_sink_pad = gst_element_get_static_pad (video_sink, "sink");
256 caps = gst_pad_get_current_caps (video_sink_pad);
258 if (gst_video_info_from_caps (&info, caps)) {
259 info.width = info.width * info.par_n / info.par_d;
260 GST_DEBUG ("Media size is %dx%d, notifying application", info.width, info.height);
262 if (self->ui_delegate && [self->ui_delegate respondsToSelector:@selector(mediaSizeChanged:height:)])
264 [self->ui_delegate mediaSizeChanged:info.width height:info.height];
268 gst_caps_unref(caps);
269 gst_object_unref (video_sink_pad);
270 gst_object_unref(video_sink);
273 /* Notify UI about pipeline state changes */
274 static void state_changed_cb (GstBus *bus, GstMessage *msg, GStreamerBackend *self)
276 GstState old_state, new_state, pending_state;
277 gst_message_parse_state_changed (msg, &old_state, &new_state, &pending_state);
278 /* Only pay attention to messages coming from the pipeline, not its children */
279 if (GST_MESSAGE_SRC (msg) == GST_OBJECT (self->pipeline)) {
280 self->state = new_state;
281 gchar *message = g_strdup_printf("State changed to %s", gst_element_state_get_name(new_state));
282 [self setUIMessage:message];
285 if (old_state == GST_STATE_READY && new_state == GST_STATE_PAUSED)
287 check_media_size(self);
289 /* If there was a scheduled seek, perform it now that we have moved to the Paused state */
290 if (GST_CLOCK_TIME_IS_VALID (self->desired_position))
291 execute_seek (self->desired_position, self);
296 /* Check if all conditions are met to report GStreamer as initialized.
297 * These conditions will change depending on the application */
298 -(void) check_initialization_complete
300 if (!initialized && main_loop) {
301 GST_DEBUG ("Initialization complete, notifying application.");
302 if (ui_delegate && [ui_delegate respondsToSelector:@selector(gstreamerInitialized)])
304 [ui_delegate gstreamerInitialized];
310 /* Main method for the bus monitoring code */
314 GSource *timeout_source;
316 GError *error = NULL;
318 GST_DEBUG ("Creating pipeline");
320 /* Create our own GLib Main Context and make it the default one */
321 context = g_main_context_new ();
322 g_main_context_push_thread_default(context);
325 pipeline = gst_parse_launch("playbin", &error);
327 gchar *message = g_strdup_printf("Unable to build pipeline: %s", error->message);
328 g_clear_error (&error);
329 [self setUIMessage:message];
334 /* Set the pipeline to READY, so it can already accept a window handle */
335 gst_element_set_state(pipeline, GST_STATE_READY);
337 video_sink = gst_bin_get_by_interface(GST_BIN(pipeline), GST_TYPE_VIDEO_OVERLAY);
339 GST_ERROR ("Could not retrieve video sink");
342 gst_video_overlay_set_window_handle(GST_VIDEO_OVERLAY(video_sink), (guintptr) (id) ui_video_view);
344 /* Instruct the bus to emit signals for each received message, and connect to the interesting signals */
345 bus = gst_element_get_bus (pipeline);
346 bus_source = gst_bus_create_watch (bus);
347 g_source_set_callback (bus_source, (GSourceFunc) gst_bus_async_signal_func, NULL, NULL);
348 g_source_attach (bus_source, context);
349 g_source_unref (bus_source);
350 g_signal_connect (G_OBJECT (bus), "message::error", (GCallback)error_cb, (__bridge void *)self);
351 g_signal_connect (G_OBJECT (bus), "message::eos", (GCallback)eos_cb, (__bridge void *)self);
352 g_signal_connect (G_OBJECT (bus), "message::state-changed", (GCallback)state_changed_cb, (__bridge void *)self);
353 g_signal_connect (G_OBJECT (bus), "message::duration", (GCallback)duration_cb, (__bridge void *)self);
354 g_signal_connect (G_OBJECT (bus), "message::buffering", (GCallback)buffering_cb, (__bridge void *)self);
355 g_signal_connect (G_OBJECT (bus), "message::clock-lost", (GCallback)clock_lost_cb, (__bridge void *)self);
356 gst_object_unref (bus);
358 /* Register a function that GLib will call 4 times per second */
359 timeout_source = g_timeout_source_new (250);
360 g_source_set_callback (timeout_source, (GSourceFunc)refresh_ui, (__bridge void *)self, NULL);
361 g_source_attach (timeout_source, context);
362 g_source_unref (timeout_source);
364 /* Create a GLib Main Loop and set it to run */
365 GST_DEBUG ("Entering main loop...");
366 main_loop = g_main_loop_new (context, FALSE);
367 [self check_initialization_complete];
368 g_main_loop_run (main_loop);
369 GST_DEBUG ("Exited main loop");
370 g_main_loop_unref (main_loop);
374 g_main_context_pop_thread_default(context);
375 g_main_context_unref (context);
376 gst_element_set_state (pipeline, GST_STATE_NULL);
377 gst_object_unref (pipeline);
381 ui_video_view = NULL;