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