Merge remote-tracking branch 'origin/master' into 0.11
[platform/upstream/gstreamer.git] / gst-libs / gst / video / convertframe.c
1 /* Small helper element for format conversion
2  * Copyright (C) 2005 Tim-Philipp Müller <tim centricular net>
3  * Copyright (C) 2010 Brandon Lewis <brandon.lewis@collabora.co.uk>
4  * Copyright (C) 2010 Edward Hervey <edward.hervey@collabora.co.uk>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 #include <string.h>
23 #include "video.h"
24
25 #include "gst/glib-compat-private.h"
26
27 static gboolean
28 caps_are_raw (const GstCaps * caps)
29 {
30   guint i, len;
31
32   len = gst_caps_get_size (caps);
33
34   for (i = 0; i < len; i++) {
35     GstStructure *st = gst_caps_get_structure (caps, i);
36     if (gst_structure_has_name (st, "video/x-raw"))
37       return TRUE;
38   }
39
40   return FALSE;
41 }
42
43 static gboolean
44 create_element (const gchar * factory_name, GstElement ** element,
45     GError ** err)
46 {
47   *element = gst_element_factory_make (factory_name, NULL);
48   if (*element)
49     return TRUE;
50
51   if (err && *err == NULL) {
52     *err = g_error_new (GST_CORE_ERROR, GST_CORE_ERROR_MISSING_PLUGIN,
53         "cannot create element '%s' - please check your GStreamer installation",
54         factory_name);
55   }
56
57   return FALSE;
58 }
59
60 static GstElement *
61 get_encoder (const GstCaps * caps, GError ** err)
62 {
63   GList *encoders = NULL;
64   GList *filtered = NULL;
65   GstElementFactory *factory = NULL;
66   GstElement *encoder = NULL;
67
68   encoders =
69       gst_element_factory_list_get_elements (GST_ELEMENT_FACTORY_TYPE_ENCODER |
70       GST_ELEMENT_FACTORY_TYPE_MEDIA_IMAGE, GST_RANK_NONE);
71
72   if (encoders == NULL) {
73     *err = g_error_new (GST_CORE_ERROR, GST_CORE_ERROR_MISSING_PLUGIN,
74         "Cannot find any image encoder");
75     goto fail;
76   }
77
78   GST_INFO ("got factory list %p", encoders);
79   gst_plugin_feature_list_debug (encoders);
80
81   filtered =
82       gst_element_factory_list_filter (encoders, caps, GST_PAD_SRC, FALSE);
83   GST_INFO ("got filtered list %p", filtered);
84
85   if (filtered == NULL) {
86     gchar *tmp = gst_caps_to_string (caps);
87     *err = g_error_new (GST_CORE_ERROR, GST_CORE_ERROR_MISSING_PLUGIN,
88         "Cannot find any image encoder for caps %s", tmp);
89     g_free (tmp);
90     goto fail;
91   }
92
93   gst_plugin_feature_list_debug (filtered);
94
95   factory = (GstElementFactory *) filtered->data;
96
97   GST_INFO ("got factory %p", factory);
98   encoder = gst_element_factory_create (factory, NULL);
99
100   GST_INFO ("created encoder element %p, %s", encoder,
101       gst_element_get_name (encoder));
102
103 fail:
104   if (encoders)
105     gst_plugin_feature_list_free (encoders);
106   if (filtered)
107     gst_plugin_feature_list_free (filtered);
108
109   return encoder;
110 }
111
112 static GstElement *
113 build_convert_frame_pipeline (GstElement ** src_element,
114     GstElement ** sink_element, const GstCaps * from_caps,
115     const GstCaps * to_caps, GError ** err)
116 {
117   GstElement *src = NULL, *csp = NULL, *vscale = NULL;
118   GstElement *sink = NULL, *encoder = NULL, *pipeline;
119   GError *error = NULL;
120
121   /* videoscale is here to correct for the pixel-aspect-ratio for us */
122   GST_DEBUG ("creating elements");
123   if (!create_element ("appsrc", &src, &error) ||
124       !create_element ("videoconvert", &csp, &error) ||
125       !create_element ("videoscale", &vscale, &error) ||
126       !create_element ("appsink", &sink, &error))
127     goto no_elements;
128
129   pipeline = gst_pipeline_new ("videoconvert-pipeline");
130   if (pipeline == NULL)
131     goto no_pipeline;
132
133   /* Add black borders if necessary to keep the DAR */
134   g_object_set (vscale, "add-borders", TRUE, NULL);
135
136   GST_DEBUG ("adding elements");
137   gst_bin_add_many (GST_BIN (pipeline), src, csp, vscale, sink, NULL);
138
139   /* set caps */
140   g_object_set (src, "caps", from_caps, NULL);
141   g_object_set (sink, "caps", to_caps, NULL);
142
143   /* FIXME: linking is still way too expensive, profile this properly */
144   GST_DEBUG ("linking src->csp");
145   if (!gst_element_link_pads (src, "src", csp, "sink"))
146     goto link_failed;
147
148   GST_DEBUG ("linking csp->vscale");
149   if (!gst_element_link_pads_full (csp, "src", vscale, "sink",
150           GST_PAD_LINK_CHECK_NOTHING))
151     goto link_failed;
152
153   if (caps_are_raw (to_caps)) {
154     GST_DEBUG ("linking vscale->sink");
155
156     if (!gst_element_link_pads_full (vscale, "src", sink, "sink",
157             GST_PAD_LINK_CHECK_NOTHING))
158       goto link_failed;
159   } else {
160     encoder = get_encoder (to_caps, &error);
161     if (!encoder)
162       goto no_encoder;
163     gst_bin_add (GST_BIN (pipeline), encoder);
164
165     GST_DEBUG ("linking vscale->encoder");
166     if (!gst_element_link (vscale, encoder))
167       goto link_failed;
168
169     GST_DEBUG ("linking encoder->sink");
170     if (!gst_element_link_pads (encoder, "src", sink, "sink"))
171       goto link_failed;
172   }
173
174   g_object_set (src, "emit-signals", TRUE, NULL);
175   g_object_set (sink, "emit-signals", TRUE, NULL);
176
177   *src_element = src;
178   *sink_element = sink;
179
180   return pipeline;
181   /* ERRORS */
182 no_encoder:
183   {
184     gst_object_unref (pipeline);
185
186     GST_ERROR ("could not find an encoder for provided caps");
187     if (err)
188       *err = error;
189     else
190       g_error_free (error);
191
192     return NULL;
193   }
194 no_elements:
195   {
196     if (src)
197       gst_object_unref (src);
198     if (csp)
199       gst_object_unref (csp);
200     if (vscale)
201       gst_object_unref (vscale);
202     if (sink)
203       gst_object_unref (sink);
204     GST_ERROR ("Could not convert video frame: %s", error->message);
205     if (err)
206       *err = error;
207     else
208       g_error_free (error);
209     return NULL;
210   }
211 no_pipeline:
212   {
213     gst_object_unref (src);
214     gst_object_unref (csp);
215     gst_object_unref (vscale);
216     gst_object_unref (sink);
217
218     GST_ERROR ("Could not convert video frame: no pipeline (unknown error)");
219     if (err)
220       *err = g_error_new (GST_CORE_ERROR, GST_CORE_ERROR_FAILED,
221           "Could not convert video frame: no pipeline (unknown error)");
222     return NULL;
223   }
224 link_failed:
225   {
226     gst_object_unref (pipeline);
227
228     GST_ERROR ("Could not convert video frame: failed to link elements");
229     if (err)
230       *err = g_error_new (GST_CORE_ERROR, GST_CORE_ERROR_NEGOTIATION,
231           "Could not convert video frame: failed to link elements");
232     return NULL;
233   }
234 }
235
236 /**
237  * gst_video_convert_sample:
238  * @sample: a #GstSample
239  * @to_caps: the #GstCaps to convert to
240  * @timeout: the maximum amount of time allowed for the processing.
241  * @error: pointer to a #GError. Can be %NULL.
242  *
243  * Converts a raw video buffer into the specified output caps.
244  *
245  * The output caps can be any raw video formats or any image formats (jpeg, png, ...).
246  *
247  * The width, height and pixel-aspect-ratio can also be specified in the output caps.
248  *
249  * Returns: The converted #GstSample, or %NULL if an error happened (in which case @err
250  * will point to the #GError).
251  *
252  * Since: 0.10.31
253  *
254  */
255 GstSample *
256 gst_video_convert_sample (GstSample * sample, const GstCaps * to_caps,
257     GstClockTime timeout, GError ** error)
258 {
259   GstMessage *msg;
260   GstBuffer *buf;
261   GstSample *result = NULL;
262   GError *err = NULL;
263   GstBus *bus;
264   GstCaps *from_caps, *to_caps_copy = NULL;
265   GstFlowReturn ret;
266   GstElement *pipeline, *src, *sink;
267   guint i, n;
268
269   g_return_val_if_fail (sample != NULL, NULL);
270   g_return_val_if_fail (to_caps != NULL, NULL);
271
272   buf = gst_sample_get_buffer (sample);
273   g_return_val_if_fail (buf != NULL, NULL);
274
275   from_caps = gst_sample_get_caps (sample);
276   g_return_val_if_fail (from_caps != NULL, NULL);
277
278
279   to_caps_copy = gst_caps_new_empty ();
280   n = gst_caps_get_size (to_caps);
281   for (i = 0; i < n; i++) {
282     GstStructure *s = gst_caps_get_structure (to_caps, i);
283
284     s = gst_structure_copy (s);
285     gst_structure_remove_field (s, "framerate");
286     gst_caps_append_structure (to_caps_copy, s);
287   }
288
289   pipeline =
290       build_convert_frame_pipeline (&src, &sink, from_caps, to_caps_copy, &err);
291   if (!pipeline)
292     goto no_pipeline;
293
294   /* now set the pipeline to the paused state, after we push the buffer into
295    * appsrc, this should preroll the converted buffer in appsink */
296   GST_DEBUG ("running conversion pipeline to caps %" GST_PTR_FORMAT,
297       to_caps_copy);
298   gst_element_set_state (pipeline, GST_STATE_PAUSED);
299
300   /* feed buffer in appsrc */
301   GST_DEBUG ("feeding buffer %p, size %" G_GSIZE_FORMAT ", caps %"
302       GST_PTR_FORMAT, buf, gst_buffer_get_size (buf), from_caps);
303   g_signal_emit_by_name (src, "push-buffer", buf, &ret);
304
305   /* now see what happens. We either got an error somewhere or the pipeline
306    * prerolled */
307   bus = gst_element_get_bus (pipeline);
308   msg = gst_bus_timed_pop_filtered (bus,
309       timeout, GST_MESSAGE_ERROR | GST_MESSAGE_ASYNC_DONE);
310
311   if (msg) {
312     switch (GST_MESSAGE_TYPE (msg)) {
313       case GST_MESSAGE_ASYNC_DONE:
314       {
315         /* we're prerolled, get the frame from appsink */
316         g_signal_emit_by_name (sink, "pull-preroll", &result);
317
318         if (result) {
319           GST_DEBUG ("conversion successful: result = %p", result);
320         } else {
321           GST_ERROR ("prerolled but no result frame?!");
322         }
323         break;
324       }
325       case GST_MESSAGE_ERROR:{
326         gchar *dbg = NULL;
327
328         gst_message_parse_error (msg, &err, &dbg);
329         if (err) {
330           GST_ERROR ("Could not convert video frame: %s", err->message);
331           GST_DEBUG ("%s [debug: %s]", err->message, GST_STR_NULL (dbg));
332           if (error)
333             *error = err;
334           else
335             g_error_free (err);
336         }
337         g_free (dbg);
338         break;
339       }
340       default:{
341         g_return_val_if_reached (NULL);
342       }
343     }
344     gst_message_unref (msg);
345   } else {
346     GST_ERROR ("Could not convert video frame: timeout during conversion");
347     if (error)
348       *error = g_error_new (GST_CORE_ERROR, GST_CORE_ERROR_FAILED,
349           "Could not convert video frame: timeout during conversion");
350   }
351
352   gst_element_set_state (pipeline, GST_STATE_NULL);
353   gst_object_unref (bus);
354   gst_object_unref (pipeline);
355   gst_caps_unref (to_caps_copy);
356
357   return result;
358
359   /* ERRORS */
360 no_pipeline:
361   {
362     gst_caps_unref (to_caps_copy);
363
364     if (error)
365       *error = err;
366     else
367       g_error_free (err);
368
369     return NULL;
370   }
371 }
372
373 typedef struct
374 {
375   GMutex *mutex;
376   GstElement *pipeline;
377   GstVideoConvertSampleCallback callback;
378   gpointer user_data;
379   GDestroyNotify destroy_notify;
380   GMainContext *context;
381   GstSample *sample;
382   //GstBuffer *buffer;
383   gulong timeout_id;
384   gboolean finished;
385 } GstVideoConvertSampleContext;
386
387 typedef struct
388 {
389   GstVideoConvertSampleCallback callback;
390   GstSample *sample;
391   //GstBuffer *buffer;
392   GError *error;
393   gpointer user_data;
394   GDestroyNotify destroy_notify;
395
396   GstVideoConvertSampleContext *context;
397 } GstVideoConvertSampleCallbackContext;
398
399 static void
400 gst_video_convert_frame_context_free (GstVideoConvertSampleContext * ctx)
401 {
402   /* Wait until all users of the mutex are done */
403   g_mutex_lock (ctx->mutex);
404   g_mutex_unlock (ctx->mutex);
405   g_mutex_free (ctx->mutex);
406   if (ctx->timeout_id)
407     g_source_remove (ctx->timeout_id);
408   //if (ctx->buffer)
409   //  gst_buffer_unref (ctx->buffer);
410   if (ctx->sample)
411     gst_sample_unref (ctx->sample);
412   g_main_context_unref (ctx->context);
413
414   gst_element_set_state (ctx->pipeline, GST_STATE_NULL);
415   gst_object_unref (ctx->pipeline);
416
417   g_slice_free (GstVideoConvertSampleContext, ctx);
418 }
419
420 static void
421     gst_video_convert_frame_callback_context_free
422     (GstVideoConvertSampleCallbackContext * ctx)
423 {
424   if (ctx->context)
425     gst_video_convert_frame_context_free (ctx->context);
426   g_slice_free (GstVideoConvertSampleCallbackContext, ctx);
427 }
428
429 static gboolean
430 convert_frame_dispatch_callback (GstVideoConvertSampleCallbackContext * ctx)
431 {
432   ctx->callback (ctx->sample, ctx->error, ctx->user_data);
433
434   if (ctx->destroy_notify)
435     ctx->destroy_notify (ctx->user_data);
436
437   return FALSE;
438 }
439
440 static void
441 convert_frame_finish (GstVideoConvertSampleContext * context,
442     GstSample * sample, GError * error)
443 {
444   GSource *source;
445   GstVideoConvertSampleCallbackContext *ctx;
446
447   if (context->timeout_id)
448     g_source_remove (context->timeout_id);
449   context->timeout_id = 0;
450
451   ctx = g_slice_new (GstVideoConvertSampleCallbackContext);
452   ctx->callback = context->callback;
453   ctx->user_data = context->user_data;
454   ctx->destroy_notify = context->destroy_notify;
455   ctx->sample = sample;
456   //ctx->buffer = buffer;
457   ctx->error = error;
458   ctx->context = context;
459
460   source = g_timeout_source_new (0);
461   g_source_set_callback (source,
462       (GSourceFunc) convert_frame_dispatch_callback, ctx,
463       (GDestroyNotify) gst_video_convert_frame_callback_context_free);
464   g_source_attach (source, context->context);
465   g_source_unref (source);
466
467   context->finished = TRUE;
468 }
469
470 static gboolean
471 convert_frame_timeout_callback (GstVideoConvertSampleContext * context)
472 {
473   GError *error;
474
475   g_mutex_lock (context->mutex);
476
477   if (context->finished)
478     goto done;
479
480   GST_ERROR ("Could not convert video frame: timeout");
481
482   error = g_error_new (GST_CORE_ERROR, GST_CORE_ERROR_FAILED,
483       "Could not convert video frame: timeout");
484
485   convert_frame_finish (context, NULL, error);
486
487 done:
488   g_mutex_unlock (context->mutex);
489   return FALSE;
490 }
491
492 static gboolean
493 convert_frame_bus_callback (GstBus * bus, GstMessage * message,
494     GstVideoConvertSampleContext * context)
495 {
496   g_mutex_lock (context->mutex);
497
498   if (context->finished)
499     goto done;
500
501   switch (GST_MESSAGE_TYPE (message)) {
502     case GST_MESSAGE_ERROR:{
503       GError *error;
504       gchar *dbg = NULL;
505
506       gst_message_parse_error (message, &error, &dbg);
507
508       GST_ERROR ("Could not convert video frame: %s", error->message);
509       GST_DEBUG ("%s [debug: %s]", error->message, GST_STR_NULL (dbg));
510
511       convert_frame_finish (context, NULL, error);
512
513       g_free (dbg);
514       break;
515     }
516     default:
517       break;
518   }
519
520 done:
521   g_mutex_unlock (context->mutex);
522
523   return FALSE;
524 }
525
526 static void
527 convert_frame_need_data_callback (GstElement * src, guint size,
528     GstVideoConvertSampleContext * context)
529 {
530   GstFlowReturn ret = GST_FLOW_ERROR;
531   GError *error;
532   GstBuffer *buffer;
533
534   g_mutex_lock (context->mutex);
535
536   if (context->finished)
537     goto done;
538
539   buffer = gst_sample_get_buffer (context->sample);
540   g_signal_emit_by_name (src, "push-buffer", buffer, &ret);
541   gst_sample_unref (context->sample);
542   context->sample = NULL;
543
544   if (ret != GST_FLOW_OK) {
545     GST_ERROR ("Could not push video frame: %s", gst_flow_get_name (ret));
546
547     error = g_error_new (GST_CORE_ERROR, GST_CORE_ERROR_FAILED,
548         "Could not push video frame: %s", gst_flow_get_name (ret));
549
550     convert_frame_finish (context, NULL, error);
551   }
552
553   g_signal_handlers_disconnect_by_func (src, convert_frame_need_data_callback,
554       context);
555
556 done:
557   g_mutex_unlock (context->mutex);
558 }
559
560 static void
561 convert_frame_new_preroll_callback (GstElement * sink,
562     GstVideoConvertSampleContext * context)
563 {
564   GstSample *sample = NULL;
565   GError *error = NULL;
566
567   g_mutex_lock (context->mutex);
568
569   if (context->finished)
570     goto done;
571
572   g_signal_emit_by_name (sink, "pull-preroll", &sample);
573
574   if (!sample) {
575     error = g_error_new (GST_CORE_ERROR, GST_CORE_ERROR_FAILED,
576         "Could not get converted video sample");
577   }
578   convert_frame_finish (context, sample, error);
579
580   g_signal_handlers_disconnect_by_func (sink, convert_frame_need_data_callback,
581       context);
582
583 done:
584   g_mutex_unlock (context->mutex);
585 }
586
587 /**
588  * gst_video_convert_sample_async:
589  * @sample: a #GstSample
590  * @to_caps: the #GstCaps to convert to
591  * @timeout: the maximum amount of time allowed for the processing.
592  * @callback: %GstVideoConvertSampleCallback that will be called after conversion.
593  * @user_data: extra data that will be passed to the @callback
594  * @destroy_notify: %GDestroyNotify to be called after @user_data is not needed anymore
595  *
596  * Converts a raw video buffer into the specified output caps.
597  *
598  * The output caps can be any raw video formats or any image formats (jpeg, png, ...).
599  *
600  * The width, height and pixel-aspect-ratio can also be specified in the output caps.
601  *
602  * @callback will be called after conversion, when an error occured or if conversion didn't
603  * finish after @timeout. @callback will always be called from the thread default
604  * %GMainContext, see g_main_context_get_thread_default(). If GLib before 2.22 is used,
605  * this will always be the global default main context.
606  *
607  * @destroy_notify will be called after the callback was called and @user_data is not needed
608  * anymore.
609  *
610  * Since: 0.10.31
611  *
612  */
613 void
614 gst_video_convert_sample_async (GstSample * sample,
615     const GstCaps * to_caps, GstClockTime timeout,
616     GstVideoConvertSampleCallback callback, gpointer user_data,
617     GDestroyNotify destroy_notify)
618 {
619   GMainContext *context = NULL;
620   GError *error = NULL;
621   GstBus *bus;
622   GstBuffer *buf;
623   GstCaps *from_caps, *to_caps_copy = NULL;
624   GstElement *pipeline, *src, *sink;
625   guint i, n;
626   GSource *source;
627   GstVideoConvertSampleContext *ctx;
628
629   g_return_if_fail (sample != NULL);
630   buf = gst_sample_get_buffer (sample);
631   g_return_if_fail (buf != NULL);
632
633   g_return_if_fail (to_caps != NULL);
634
635   from_caps = gst_sample_get_caps (sample);
636   g_return_if_fail (from_caps != NULL);
637   g_return_if_fail (callback != NULL);
638
639   context = g_main_context_get_thread_default ();
640
641   if (!context)
642     context = g_main_context_default ();
643
644   to_caps_copy = gst_caps_new_empty ();
645   n = gst_caps_get_size (to_caps);
646   for (i = 0; i < n; i++) {
647     GstStructure *s = gst_caps_get_structure (to_caps, i);
648
649     s = gst_structure_copy (s);
650     gst_structure_remove_field (s, "framerate");
651     gst_caps_append_structure (to_caps_copy, s);
652   }
653
654   pipeline =
655       build_convert_frame_pipeline (&src, &sink, from_caps, to_caps_copy,
656       &error);
657   if (!pipeline)
658     goto no_pipeline;
659
660   bus = gst_element_get_bus (pipeline);
661
662   ctx = g_slice_new0 (GstVideoConvertSampleContext);
663   ctx->mutex = g_mutex_new ();
664   //ctx->buffer = gst_buffer_ref (buf);
665   ctx->sample = gst_sample_ref (sample);
666   ctx->callback = callback;
667   ctx->user_data = user_data;
668   ctx->destroy_notify = destroy_notify;
669   ctx->context = g_main_context_ref (context);
670   ctx->finished = FALSE;
671   ctx->pipeline = pipeline;
672
673   if (timeout != GST_CLOCK_TIME_NONE) {
674     source = g_timeout_source_new (timeout / GST_MSECOND);
675     g_source_set_callback (source,
676         (GSourceFunc) convert_frame_timeout_callback, ctx, NULL);
677     ctx->timeout_id = g_source_attach (source, context);
678     g_source_unref (source);
679   }
680
681   g_signal_connect (src, "need-data",
682       G_CALLBACK (convert_frame_need_data_callback), ctx);
683   g_signal_connect (sink, "new-preroll",
684       G_CALLBACK (convert_frame_new_preroll_callback), ctx);
685
686   source = gst_bus_create_watch (bus);
687   g_source_set_callback (source, (GSourceFunc) convert_frame_bus_callback,
688       ctx, NULL);
689   g_source_attach (source, context);
690   g_source_unref (source);
691
692   gst_element_set_state (pipeline, GST_STATE_PLAYING);
693
694   gst_object_unref (bus);
695   gst_caps_unref (to_caps_copy);
696
697   return;
698   /* ERRORS */
699 no_pipeline:
700   {
701     GstVideoConvertSampleCallbackContext *ctx;
702     GSource *source;
703
704     gst_caps_unref (to_caps_copy);
705
706     ctx = g_slice_new0 (GstVideoConvertSampleCallbackContext);
707     ctx->callback = callback;
708     ctx->user_data = user_data;
709     ctx->destroy_notify = destroy_notify;
710     ctx->sample = NULL;
711     ctx->error = error;
712
713     source = g_timeout_source_new (0);
714     g_source_set_callback (source,
715         (GSourceFunc) convert_frame_dispatch_callback, ctx,
716         (GDestroyNotify) gst_video_convert_frame_callback_context_free);
717     g_source_attach (source, context);
718     g_source_unref (source);
719   }
720 }