PageRenderTime 78ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/gst-sdk/tutorials/xcode iOS/Tutorial 5/GStreamerBackend.m

https://gitlab.com/JamesGiller/gst-sdk-tutorials
Objective C | 387 lines | 278 code | 62 blank | 47 comment | 48 complexity | 79fcb34af2e4703f2df9ebc7e42ec028 MD5 | raw file
  1. #import "GStreamerBackend.h"
  2. #include <gst/gst.h>
  3. #include <gst/video/video.h>
  4. GST_DEBUG_CATEGORY_STATIC (debug_category);
  5. #define GST_CAT_DEFAULT debug_category
  6. /* Do not allow seeks to be performed closer than this distance. It is visually useless, and will probably
  7. * confuse some demuxers. */
  8. #define SEEK_MIN_DELAY (500 * GST_MSECOND)
  9. @interface GStreamerBackend()
  10. -(void)setUIMessage:(gchar*) message;
  11. -(void)app_function;
  12. -(void)check_initialization_complete;
  13. @end
  14. @implementation GStreamerBackend {
  15. id ui_delegate; /* Class that we use to interact with the user interface */
  16. GstElement *pipeline; /* The running pipeline */
  17. GstElement *video_sink; /* The video sink element which receives XOverlay commands */
  18. GMainContext *context; /* GLib context used to run the main loop */
  19. GMainLoop *main_loop; /* GLib main loop */
  20. gboolean initialized; /* To avoid informing the UI multiple times about the initialization */
  21. UIView *ui_video_view; /* UIView that holds the video */
  22. GstState state; /* Current pipeline state */
  23. GstState target_state; /* Desired pipeline state, to be set once buffering is complete */
  24. gint64 duration; /* Cached clip duration */
  25. gint64 desired_position; /* Position to seek to, once the pipeline is running */
  26. GstClockTime last_seek_time; /* For seeking overflow prevention (throttling) */
  27. gboolean is_live; /* Live streams do not use buffering */
  28. }
  29. /*
  30. * Interface methods
  31. */
  32. -(id) init:(id) uiDelegate videoView:(UIView *)video_view
  33. {
  34. if (self = [super init])
  35. {
  36. self->ui_delegate = uiDelegate;
  37. self->ui_video_view = video_view;
  38. self->duration = GST_CLOCK_TIME_NONE;
  39. GST_DEBUG_CATEGORY_INIT (debug_category, "tutorial-5", 0, "iOS tutorial 5");
  40. gst_debug_set_threshold_for_name("tutorial-5", GST_LEVEL_DEBUG);
  41. /* Start the bus monitoring task */
  42. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  43. [self app_function];
  44. });
  45. }
  46. return self;
  47. }
  48. -(void) deinit
  49. {
  50. if (main_loop) {
  51. g_main_loop_quit(main_loop);
  52. }
  53. }
  54. -(void) play
  55. {
  56. target_state = GST_STATE_PLAYING;
  57. is_live = (gst_element_set_state (pipeline, GST_STATE_PLAYING) == GST_STATE_CHANGE_NO_PREROLL);
  58. }
  59. -(void) pause
  60. {
  61. target_state = GST_STATE_PAUSED;
  62. is_live = (gst_element_set_state (pipeline, GST_STATE_PAUSED) == GST_STATE_CHANGE_NO_PREROLL);
  63. }
  64. -(void) setUri:(NSString*)uri
  65. {
  66. const char *char_uri = [uri UTF8String];
  67. g_object_set(pipeline, "uri", char_uri, NULL);
  68. GST_DEBUG ("URI set to %s", char_uri);
  69. }
  70. -(void) setPosition:(NSInteger)milliseconds
  71. {
  72. gint64 position = (gint64)(milliseconds * GST_MSECOND);
  73. if (state >= GST_STATE_PAUSED) {
  74. execute_seek(position, self);
  75. } else {
  76. GST_DEBUG ("Scheduling seek to %" GST_TIME_FORMAT " for later", GST_TIME_ARGS (position));
  77. self->desired_position = position;
  78. }
  79. }
  80. /*
  81. * Private methods
  82. */
  83. /* Change the message on the UI through the UI delegate */
  84. -(void)setUIMessage:(gchar*) message
  85. {
  86. NSString *string = [NSString stringWithUTF8String:message];
  87. if(ui_delegate && [ui_delegate respondsToSelector:@selector(gstreamerSetUIMessage:)])
  88. {
  89. [ui_delegate gstreamerSetUIMessage:string];
  90. }
  91. }
  92. /* Tell the application what is the current position and clip duration */
  93. -(void) setCurrentUIPosition:(gint)pos duration:(gint)dur
  94. {
  95. if(ui_delegate && [ui_delegate respondsToSelector:@selector(setCurrentPosition:duration:)])
  96. {
  97. [ui_delegate setCurrentPosition:pos duration:dur];
  98. }
  99. }
  100. /* If we have pipeline and it is running, query the current position and clip duration and inform
  101. * the application */
  102. static gboolean refresh_ui (GStreamerBackend *self) {
  103. gint64 position;
  104. /* We do not want to update anything unless we have a working pipeline in the PAUSED or PLAYING state */
  105. if (!self || !self->pipeline || self->state < GST_STATE_PAUSED)
  106. return TRUE;
  107. /* If we didn't know it yet, query the stream duration */
  108. if (!GST_CLOCK_TIME_IS_VALID (self->duration)) {
  109. gst_element_query_duration (self->pipeline, GST_FORMAT_TIME,&self->duration);
  110. }
  111. if (gst_element_query_position (self->pipeline, GST_FORMAT_TIME, &position)) {
  112. /* The UI expects these values in milliseconds, and GStreamer provides nanoseconds */
  113. [self setCurrentUIPosition:position / GST_MSECOND duration:self->duration / GST_MSECOND];
  114. }
  115. return TRUE;
  116. }
  117. /* Forward declaration for the delayed seek callback */
  118. static gboolean delayed_seek_cb (GStreamerBackend *self);
  119. /* Perform seek, if we are not too close to the previous seek. Otherwise, schedule the seek for
  120. * some time in the future. */
  121. static void execute_seek (gint64 position, GStreamerBackend *self) {
  122. gint64 diff;
  123. if (position == GST_CLOCK_TIME_NONE)
  124. return;
  125. diff = gst_util_get_timestamp () - self->last_seek_time;
  126. if (GST_CLOCK_TIME_IS_VALID (self->last_seek_time) && diff < SEEK_MIN_DELAY) {
  127. /* The previous seek was too close, delay this one */
  128. GSource *timeout_source;
  129. if (self->desired_position == GST_CLOCK_TIME_NONE) {
  130. /* There was no previous seek scheduled. Setup a timer for some time in the future */
  131. timeout_source = g_timeout_source_new ((SEEK_MIN_DELAY - diff) / GST_MSECOND);
  132. g_source_set_callback (timeout_source, (GSourceFunc)delayed_seek_cb, (__bridge void *)self, NULL);
  133. g_source_attach (timeout_source, self->context);
  134. g_source_unref (timeout_source);
  135. }
  136. /* Update the desired seek position. If multiple petitions are received before it is time
  137. * to perform a seek, only the last one is remembered. */
  138. self->desired_position = position;
  139. GST_DEBUG ("Throttling seek to %" GST_TIME_FORMAT ", will be in %" GST_TIME_FORMAT,
  140. GST_TIME_ARGS (position), GST_TIME_ARGS (SEEK_MIN_DELAY - diff));
  141. } else {
  142. /* Perform the seek now */
  143. GST_DEBUG ("Seeking to %" GST_TIME_FORMAT, GST_TIME_ARGS (position));
  144. self->last_seek_time = gst_util_get_timestamp ();
  145. gst_element_seek_simple (self->pipeline, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT, position);
  146. self->desired_position = GST_CLOCK_TIME_NONE;
  147. }
  148. }
  149. /* Delayed seek callback. This gets called by the timer setup in the above function. */
  150. static gboolean delayed_seek_cb (GStreamerBackend *self) {
  151. GST_DEBUG ("Doing delayed seek to %" GST_TIME_FORMAT, GST_TIME_ARGS (self->desired_position));
  152. execute_seek (self->desired_position, self);
  153. return FALSE;
  154. }
  155. /* Retrieve errors from the bus and show them on the UI */
  156. static void error_cb (GstBus *bus, GstMessage *msg, GStreamerBackend *self)
  157. {
  158. GError *err;
  159. gchar *debug_info;
  160. gchar *message_string;
  161. gst_message_parse_error (msg, &err, &debug_info);
  162. message_string = g_strdup_printf ("Error received from element %s: %s", GST_OBJECT_NAME (msg->src), err->message);
  163. g_clear_error (&err);
  164. g_free (debug_info);
  165. [self setUIMessage:message_string];
  166. g_free (message_string);
  167. gst_element_set_state (self->pipeline, GST_STATE_NULL);
  168. }
  169. /* Called when the End Of the Stream is reached. Just move to the beginning of the media and pause. */
  170. static void eos_cb (GstBus *bus, GstMessage *msg, GStreamerBackend *self) {
  171. self->target_state = GST_STATE_PAUSED;
  172. self->is_live = (gst_element_set_state (self->pipeline, GST_STATE_PAUSED) == GST_STATE_CHANGE_NO_PREROLL);
  173. execute_seek (0, self);
  174. }
  175. /* Called when the duration of the media changes. Just mark it as unknown, so we re-query it in the next UI refresh. */
  176. static void duration_cb (GstBus *bus, GstMessage *msg, GStreamerBackend *self) {
  177. self->duration = GST_CLOCK_TIME_NONE;
  178. }
  179. /* Called when buffering messages are received. We inform the UI about the current buffering level and
  180. * keep the pipeline paused until 100% buffering is reached. At that point, set the desired state. */
  181. static void buffering_cb (GstBus *bus, GstMessage *msg, GStreamerBackend *self) {
  182. gint percent;
  183. if (self->is_live)
  184. return;
  185. gst_message_parse_buffering (msg, &percent);
  186. if (percent < 100 && self->target_state >= GST_STATE_PAUSED) {
  187. gchar * message_string = g_strdup_printf ("Buffering %d%%", percent);
  188. gst_element_set_state (self->pipeline, GST_STATE_PAUSED);
  189. [self setUIMessage:message_string];
  190. g_free (message_string);
  191. } else if (self->target_state >= GST_STATE_PLAYING) {
  192. gst_element_set_state (self->pipeline, GST_STATE_PLAYING);
  193. } else if (self->target_state >= GST_STATE_PAUSED) {
  194. [self setUIMessage:"Buffering complete"];
  195. }
  196. }
  197. /* Called when the clock is lost */
  198. static void clock_lost_cb (GstBus *bus, GstMessage *msg, GStreamerBackend *self) {
  199. if (self->target_state >= GST_STATE_PLAYING) {
  200. gst_element_set_state (self->pipeline, GST_STATE_PAUSED);
  201. gst_element_set_state (self->pipeline, GST_STATE_PLAYING);
  202. }
  203. }
  204. /* Retrieve the video sink's Caps and tell the application about the media size */
  205. static void check_media_size (GStreamerBackend *self) {
  206. GstElement *video_sink;
  207. GstPad *video_sink_pad;
  208. GstCaps *caps;
  209. GstVideoInfo info;
  210. /* Retrieve the Caps at the entrance of the video sink */
  211. g_object_get (self->pipeline, "video-sink", &video_sink, NULL);
  212. /* Do nothing if there is no video sink (this might be an audio-only clip */
  213. if (!video_sink) return;
  214. video_sink_pad = gst_element_get_static_pad (video_sink, "sink");
  215. caps = gst_pad_get_current_caps (video_sink_pad);
  216. if (gst_video_info_from_caps (&info, caps)) {
  217. info.width = info.width * info.par_n / info.par_d;
  218. GST_DEBUG ("Media size is %dx%d, notifying application", info.width, info.height);
  219. if (self->ui_delegate && [self->ui_delegate respondsToSelector:@selector(mediaSizeChanged:height:)])
  220. {
  221. [self->ui_delegate mediaSizeChanged:info.width height:info.height];
  222. }
  223. }
  224. gst_caps_unref(caps);
  225. gst_object_unref (video_sink_pad);
  226. gst_object_unref(video_sink);
  227. }
  228. /* Notify UI about pipeline state changes */
  229. static void state_changed_cb (GstBus *bus, GstMessage *msg, GStreamerBackend *self)
  230. {
  231. GstState old_state, new_state, pending_state;
  232. gst_message_parse_state_changed (msg, &old_state, &new_state, &pending_state);
  233. /* Only pay attention to messages coming from the pipeline, not its children */
  234. if (GST_MESSAGE_SRC (msg) == GST_OBJECT (self->pipeline)) {
  235. self->state = new_state;
  236. gchar *message = g_strdup_printf("State changed to %s", gst_element_state_get_name(new_state));
  237. [self setUIMessage:message];
  238. g_free (message);
  239. if (old_state == GST_STATE_READY && new_state == GST_STATE_PAUSED)
  240. {
  241. check_media_size(self);
  242. /* If there was a scheduled seek, perform it now that we have moved to the Paused state */
  243. if (GST_CLOCK_TIME_IS_VALID (self->desired_position))
  244. execute_seek (self->desired_position, self);
  245. }
  246. }
  247. }
  248. /* Check if all conditions are met to report GStreamer as initialized.
  249. * These conditions will change depending on the application */
  250. -(void) check_initialization_complete
  251. {
  252. if (!initialized && main_loop) {
  253. GST_DEBUG ("Initialization complete, notifying application.");
  254. if (ui_delegate && [ui_delegate respondsToSelector:@selector(gstreamerInitialized)])
  255. {
  256. [ui_delegate gstreamerInitialized];
  257. }
  258. initialized = TRUE;
  259. }
  260. }
  261. /* Main method for the bus monitoring code */
  262. -(void) app_function
  263. {
  264. GstBus *bus;
  265. GSource *timeout_source;
  266. GSource *bus_source;
  267. GError *error = NULL;
  268. GST_DEBUG ("Creating pipeline");
  269. /* Create our own GLib Main Context and make it the default one */
  270. context = g_main_context_new ();
  271. g_main_context_push_thread_default(context);
  272. /* Build pipeline */
  273. pipeline = gst_parse_launch("playbin", &error);
  274. if (error) {
  275. gchar *message = g_strdup_printf("Unable to build pipeline: %s", error->message);
  276. g_clear_error (&error);
  277. [self setUIMessage:message];
  278. g_free (message);
  279. return;
  280. }
  281. /* Set the pipeline to READY, so it can already accept a window handle */
  282. gst_element_set_state(pipeline, GST_STATE_READY);
  283. video_sink = gst_bin_get_by_interface(GST_BIN(pipeline), GST_TYPE_VIDEO_OVERLAY);
  284. if (!video_sink) {
  285. GST_ERROR ("Could not retrieve video sink");
  286. return;
  287. }
  288. gst_video_overlay_set_window_handle(GST_VIDEO_OVERLAY(video_sink), (guintptr) (id) ui_video_view);
  289. /* Instruct the bus to emit signals for each received message, and connect to the interesting signals */
  290. bus = gst_element_get_bus (pipeline);
  291. bus_source = gst_bus_create_watch (bus);
  292. g_source_set_callback (bus_source, (GSourceFunc) gst_bus_async_signal_func, NULL, NULL);
  293. g_source_attach (bus_source, context);
  294. g_source_unref (bus_source);
  295. g_signal_connect (G_OBJECT (bus), "message::error", (GCallback)error_cb, (__bridge void *)self);
  296. g_signal_connect (G_OBJECT (bus), "message::eos", (GCallback)eos_cb, (__bridge void *)self);
  297. g_signal_connect (G_OBJECT (bus), "message::state-changed", (GCallback)state_changed_cb, (__bridge void *)self);
  298. g_signal_connect (G_OBJECT (bus), "message::duration", (GCallback)duration_cb, (__bridge void *)self);
  299. g_signal_connect (G_OBJECT (bus), "message::buffering", (GCallback)buffering_cb, (__bridge void *)self);
  300. g_signal_connect (G_OBJECT (bus), "message::clock-lost", (GCallback)clock_lost_cb, (__bridge void *)self);
  301. gst_object_unref (bus);
  302. /* Register a function that GLib will call 4 times per second */
  303. timeout_source = g_timeout_source_new (250);
  304. g_source_set_callback (timeout_source, (GSourceFunc)refresh_ui, (__bridge void *)self, NULL);
  305. g_source_attach (timeout_source, context);
  306. g_source_unref (timeout_source);
  307. /* Create a GLib Main Loop and set it to run */
  308. GST_DEBUG ("Entering main loop...");
  309. main_loop = g_main_loop_new (context, FALSE);
  310. [self check_initialization_complete];
  311. g_main_loop_run (main_loop);
  312. GST_DEBUG ("Exited main loop");
  313. g_main_loop_unref (main_loop);
  314. main_loop = NULL;
  315. /* Free resources */
  316. g_main_context_pop_thread_default(context);
  317. g_main_context_unref (context);
  318. gst_element_set_state (pipeline, GST_STATE_NULL);
  319. gst_object_unref (pipeline);
  320. pipeline = NULL;
  321. ui_delegate = NULL;
  322. ui_video_view = NULL;
  323. return;
  324. }
  325. @end