Split out documentation into subfolders.
[platform/upstream/gstreamer.git] / examples / tutorials / xcode iOS / Tutorial 5 / GStreamerBackend.m
1 #import "GStreamerBackend.h"
2
3 #include <gst/gst.h>
4 #include <gst/video/video.h>
5
6 GST_DEBUG_CATEGORY_STATIC (debug_category);
7 #define GST_CAT_DEFAULT debug_category
8
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)
12
13 @interface GStreamerBackend()
14 -(void)setUIMessage:(gchar*) message;
15 -(void)app_function;
16 -(void)check_initialization_complete;
17 @end
18
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 */
33 }
34
35 /*
36  * Interface methods
37  */
38
39 -(id) init:(id) uiDelegate videoView:(UIView *)video_view
40 {
41     if (self = [super init])
42     {
43         self->ui_delegate = uiDelegate;
44         self->ui_video_view = video_view;
45         self->duration = GST_CLOCK_TIME_NONE;
46
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);
49
50         /* Start the bus monitoring task */
51         dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
52             [self app_function];
53         });
54     }
55
56     return self;
57 }
58
59 -(void) deinit
60 {
61     if (main_loop) {
62         g_main_loop_quit(main_loop);
63     }
64 }
65
66 -(void) play
67 {
68     target_state = GST_STATE_PLAYING;
69     is_live = (gst_element_set_state (pipeline, GST_STATE_PLAYING) == GST_STATE_CHANGE_NO_PREROLL);
70 }
71
72 -(void) pause
73 {
74     target_state = GST_STATE_PAUSED;
75     is_live = (gst_element_set_state (pipeline, GST_STATE_PAUSED) == GST_STATE_CHANGE_NO_PREROLL);
76 }
77
78 -(void) setUri:(NSString*)uri
79 {
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);
83 }
84
85 -(void) setPosition:(NSInteger)milliseconds
86 {
87     gint64 position = (gint64)(milliseconds * GST_MSECOND);
88     if (state >= GST_STATE_PAUSED) {
89         execute_seek(position, self);
90     } else {
91         GST_DEBUG ("Scheduling seek to %" GST_TIME_FORMAT " for later", GST_TIME_ARGS (position));
92         self->desired_position = position;
93     }
94 }
95
96 /*
97  * Private methods
98  */
99
100 /* Change the message on the UI through the UI delegate */
101 -(void)setUIMessage:(gchar*) message
102 {
103     NSString *string = [NSString stringWithUTF8String:message];
104     if(ui_delegate && [ui_delegate respondsToSelector:@selector(gstreamerSetUIMessage:)])
105     {
106         [ui_delegate gstreamerSetUIMessage:string];
107     }
108 }
109
110 /* Tell the application what is the current position and clip duration */
111 -(void) setCurrentUIPosition:(gint)pos duration:(gint)dur
112 {
113     if(ui_delegate && [ui_delegate respondsToSelector:@selector(setCurrentPosition:duration:)])
114     {
115         [ui_delegate setCurrentPosition:pos duration:dur];
116     }
117 }
118
119 /* If we have pipeline and it is running, query the current position and clip duration and inform
120  * the application */
121 static gboolean refresh_ui (GStreamerBackend *self) {
122     gint64 position;
123
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)
126         return TRUE;
127
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);
131     }
132
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];
136     }
137     return TRUE;
138 }
139
140 /* Forward declaration for the delayed seek callback */
141 static gboolean delayed_seek_cb (GStreamerBackend *self);
142
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) {
146     gint64 diff;
147
148     if (position == GST_CLOCK_TIME_NONE)
149         return;
150
151     diff = gst_util_get_timestamp () - self->last_seek_time;
152
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;
156
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);
163         }
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));
169     } else {
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;
175     }
176 }
177
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);
182     return FALSE;
183 }
184
185 /* Retrieve errors from the bus and show them on the UI */
186 static void error_cb (GstBus *bus, GstMessage *msg, GStreamerBackend *self)
187 {
188     GError *err;
189     gchar *debug_info;
190     gchar *message_string;
191
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);
195     g_free (debug_info);
196     [self setUIMessage:message_string];
197     g_free (message_string);
198     gst_element_set_state (self->pipeline, GST_STATE_NULL);
199 }
200
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);
206 }
207
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;
211 }
212
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) {
216     gint percent;
217
218     if (self->is_live)
219         return;
220
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"];
231     }
232 }
233
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);
239     }
240 }
241
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;
246     GstCaps *caps;
247     GstVideoInfo info;
248
249     /* Retrieve the Caps at the entrance of the video sink */
250     g_object_get (self->pipeline, "video-sink", &video_sink, NULL);
251
252     /* Do nothing if there is no video sink (this might be an audio-only clip */
253     if (!video_sink) return;
254
255     video_sink_pad = gst_element_get_static_pad (video_sink, "sink");
256     caps = gst_pad_get_current_caps (video_sink_pad);
257
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);
261
262         if (self->ui_delegate && [self->ui_delegate respondsToSelector:@selector(mediaSizeChanged:height:)])
263         {
264             [self->ui_delegate mediaSizeChanged:info.width height:info.height];
265         }
266     }
267
268     gst_caps_unref(caps);
269     gst_object_unref (video_sink_pad);
270     gst_object_unref(video_sink);
271 }
272
273 /* Notify UI about pipeline state changes */
274 static void state_changed_cb (GstBus *bus, GstMessage *msg, GStreamerBackend *self)
275 {
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];
283         g_free (message);
284
285         if (old_state == GST_STATE_READY && new_state == GST_STATE_PAUSED)
286         {
287             check_media_size(self);
288
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);
292         }
293     }
294 }
295
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
299 {
300     if (!initialized && main_loop) {
301         GST_DEBUG ("Initialization complete, notifying application.");
302         if (ui_delegate && [ui_delegate respondsToSelector:@selector(gstreamerInitialized)])
303         {
304             [ui_delegate gstreamerInitialized];
305         }
306         initialized = TRUE;
307     }
308 }
309
310 /* Main method for the bus monitoring code */
311 -(void) app_function
312 {
313     GstBus *bus;
314     GSource *timeout_source;
315     GSource *bus_source;
316     GError *error = NULL;
317
318     GST_DEBUG ("Creating pipeline");
319
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);
323
324     /* Build pipeline */
325     pipeline = gst_parse_launch("playbin", &error);
326     if (error) {
327         gchar *message = g_strdup_printf("Unable to build pipeline: %s", error->message);
328         g_clear_error (&error);
329         [self setUIMessage:message];
330         g_free (message);
331         return;
332     }
333
334     /* Set the pipeline to READY, so it can already accept a window handle */
335     gst_element_set_state(pipeline, GST_STATE_READY);
336
337     video_sink = gst_bin_get_by_interface(GST_BIN(pipeline), GST_TYPE_VIDEO_OVERLAY);
338     if (!video_sink) {
339         GST_ERROR ("Could not retrieve video sink");
340         return;
341     }
342     gst_video_overlay_set_window_handle(GST_VIDEO_OVERLAY(video_sink), (guintptr) (id) ui_video_view);
343
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);
357
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);
363
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);
371     main_loop = NULL;
372
373     /* Free resources */
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);
378     pipeline = NULL;
379
380     ui_delegate = NULL;
381     ui_video_view = NULL;
382
383     return;
384 }
385
386 @end