v4l2videodec: Implement stable element names
[platform/upstream/gst-plugins-good.git] / sys / v4l2 / gstv4l2videodec.c
1 /*
2  * Copyright (C) 2014 Collabora Ltd.
3  *     Author: Nicolas Dufresne <nicolas.dufresne@collabora.com>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  *
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include "config.h"
24 #endif
25
26 #include <sys/stat.h>
27 #include <fcntl.h>
28 #include <errno.h>
29 #include <unistd.h>
30 #include <string.h>
31
32 #include "gstv4l2videodec.h"
33 #include "v4l2_calls.h"
34
35 #include <string.h>
36 #include <gst/gst-i18n-plugin.h>
37
38 GST_DEBUG_CATEGORY_STATIC (gst_v4l2_video_dec_debug);
39 #define GST_CAT_DEFAULT gst_v4l2_video_dec_debug
40
41 typedef struct
42 {
43   gchar *device;
44   GstCaps *sink_caps;
45   GstCaps *src_caps;
46   const gchar *longname;
47   const gchar *description;
48 } GstV4l2VideoDecCData;
49
50 enum
51 {
52   PROP_0,
53   V4L2_STD_OBJECT_PROPS
54 };
55
56 #define gst_v4l2_video_dec_parent_class parent_class
57 G_DEFINE_ABSTRACT_TYPE (GstV4l2VideoDec, gst_v4l2_video_dec,
58     GST_TYPE_VIDEO_DECODER);
59
60 static void
61 gst_v4l2_video_dec_set_property (GObject * object,
62     guint prop_id, const GValue * value, GParamSpec * pspec)
63 {
64   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (object);
65
66   switch (prop_id) {
67     case PROP_OUTPUT_IO_MODE:
68       gst_v4l2_object_set_property_helper (self->v4l2output, prop_id, value,
69           pspec);
70       break;
71     case PROP_CAPTURE_IO_MODE:
72       gst_v4l2_object_set_property_helper (self->v4l2capture, prop_id, value,
73           pspec);
74       break;
75
76       /* By default, only set on output */
77     default:
78       if (!gst_v4l2_object_set_property_helper (self->v4l2output,
79               prop_id, value, pspec)) {
80         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
81       }
82       break;
83   }
84 }
85
86 static void
87 gst_v4l2_video_dec_get_property (GObject * object,
88     guint prop_id, GValue * value, GParamSpec * pspec)
89 {
90   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (object);
91
92   switch (prop_id) {
93     case PROP_OUTPUT_IO_MODE:
94       gst_v4l2_object_get_property_helper (self->v4l2output, prop_id, value,
95           pspec);
96       break;
97     case PROP_CAPTURE_IO_MODE:
98       gst_v4l2_object_get_property_helper (self->v4l2capture, prop_id, value,
99           pspec);
100       break;
101
102       /* By default read from output */
103     default:
104       if (!gst_v4l2_object_get_property_helper (self->v4l2output,
105               prop_id, value, pspec)) {
106         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
107       }
108       break;
109   }
110 }
111
112 static gboolean
113 gst_v4l2_video_dec_open (GstVideoDecoder * decoder)
114 {
115   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
116
117   GST_DEBUG_OBJECT (self, "Opening");
118
119   if (!gst_v4l2_object_open (self->v4l2output))
120     goto failure;
121
122   if (!gst_v4l2_object_open_shared (self->v4l2capture, self->v4l2output))
123     goto failure;
124
125   self->probed_sinkcaps = gst_v4l2_object_get_caps (self->v4l2output,
126       gst_v4l2_object_get_codec_caps ());
127
128   if (gst_caps_is_empty (self->probed_sinkcaps))
129     goto no_encoded_format;
130
131   self->probed_srccaps = gst_v4l2_object_get_caps (self->v4l2capture,
132       gst_v4l2_object_get_raw_caps ());
133
134   if (gst_caps_is_empty (self->probed_srccaps))
135     goto no_raw_format;
136
137   return TRUE;
138
139 no_encoded_format:
140   GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
141       (_("Encoder on device %s has no supported input format"),
142           self->v4l2output->videodev), (NULL));
143   goto failure;
144
145
146 no_raw_format:
147   GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
148       (_("Encoder on device %s has no supported output format"),
149           self->v4l2output->videodev), (NULL));
150   goto failure;
151
152 failure:
153   if (GST_V4L2_IS_OPEN (self->v4l2output))
154     gst_v4l2_object_close (self->v4l2output);
155
156   if (GST_V4L2_IS_OPEN (self->v4l2capture))
157     gst_v4l2_object_close (self->v4l2capture);
158
159   gst_caps_replace (&self->probed_srccaps, NULL);
160   gst_caps_replace (&self->probed_sinkcaps, NULL);
161
162   return FALSE;
163 }
164
165 static gboolean
166 gst_v4l2_video_dec_close (GstVideoDecoder * decoder)
167 {
168   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
169
170   GST_DEBUG_OBJECT (self, "Closing");
171
172   gst_v4l2_object_close (self->v4l2output);
173   gst_v4l2_object_close (self->v4l2capture);
174   gst_caps_replace (&self->probed_srccaps, NULL);
175   gst_caps_replace (&self->probed_sinkcaps, NULL);
176
177   return TRUE;
178 }
179
180 static gboolean
181 gst_v4l2_video_dec_start (GstVideoDecoder * decoder)
182 {
183   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
184
185   GST_DEBUG_OBJECT (self, "Starting");
186
187   gst_v4l2_object_unlock (self->v4l2output);
188   g_atomic_int_set (&self->active, TRUE);
189   self->output_flow = GST_FLOW_OK;
190
191   return TRUE;
192 }
193
194 static gboolean
195 gst_v4l2_video_dec_stop (GstVideoDecoder * decoder)
196 {
197   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
198
199   GST_DEBUG_OBJECT (self, "Stopping");
200
201   gst_v4l2_object_unlock (self->v4l2output);
202   gst_v4l2_object_unlock (self->v4l2capture);
203
204   /* Wait for capture thread to stop */
205   gst_pad_stop_task (decoder->srcpad);
206
207   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
208   self->output_flow = GST_FLOW_OK;
209   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
210
211   /* Should have been flushed already */
212   g_assert (g_atomic_int_get (&self->active) == FALSE);
213
214   gst_v4l2_object_stop (self->v4l2output);
215   gst_v4l2_object_stop (self->v4l2capture);
216
217   if (self->input_state) {
218     gst_video_codec_state_unref (self->input_state);
219     self->input_state = NULL;
220   }
221
222   GST_DEBUG_OBJECT (self, "Stopped");
223
224   return TRUE;
225 }
226
227 static gboolean
228 gst_v4l2_video_dec_set_format (GstVideoDecoder * decoder,
229     GstVideoCodecState * state)
230 {
231   GstV4l2Error error = GST_V4L2_ERROR_INIT;
232   gboolean ret = TRUE;
233   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
234
235   GST_DEBUG_OBJECT (self, "Setting format: %" GST_PTR_FORMAT, state->caps);
236
237   if (self->input_state) {
238     if (gst_v4l2_object_caps_equal (self->v4l2output, state->caps)) {
239       GST_DEBUG_OBJECT (self, "Compatible caps");
240       goto done;
241     }
242     gst_video_codec_state_unref (self->input_state);
243     self->input_state = NULL;
244
245     /* FIXME we probably need to do more work if pools are active */
246   }
247
248   ret = gst_v4l2_object_set_format (self->v4l2output, state->caps, &error);
249
250   if (ret)
251     self->input_state = gst_video_codec_state_ref (state);
252   else
253     gst_v4l2_error (self, &error);
254
255 done:
256   return ret;
257 }
258
259 static gboolean
260 gst_v4l2_video_dec_flush (GstVideoDecoder * decoder)
261 {
262   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
263
264   GST_DEBUG_OBJECT (self, "Flushed");
265
266   /* Ensure the processing thread has stopped for the reverse playback
267    * discount case */
268   if (gst_pad_get_task_state (decoder->srcpad) == GST_TASK_STARTED) {
269     GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
270
271     gst_v4l2_object_unlock (self->v4l2output);
272     gst_v4l2_object_unlock (self->v4l2capture);
273     gst_pad_stop_task (decoder->srcpad);
274     GST_VIDEO_DECODER_STREAM_LOCK (decoder);
275   }
276
277   self->output_flow = GST_FLOW_OK;
278
279   gst_v4l2_object_unlock_stop (self->v4l2output);
280   gst_v4l2_object_unlock_stop (self->v4l2capture);
281
282   return TRUE;
283 }
284
285 static gboolean
286 gst_v4l2_video_dec_negotiate (GstVideoDecoder * decoder)
287 {
288   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
289
290   /* We don't allow renegotiation without carefull disabling the pool */
291   if (self->v4l2capture->pool &&
292       gst_buffer_pool_is_active (GST_BUFFER_POOL (self->v4l2capture->pool)))
293     return TRUE;
294
295   return GST_VIDEO_DECODER_CLASS (parent_class)->negotiate (decoder);
296 }
297
298 static gboolean
299 gst_v4l2_decoder_cmd (GstV4l2Object * v4l2object, guint cmd, guint flags)
300 {
301   struct v4l2_decoder_cmd dcmd = { 0, };
302
303   GST_DEBUG_OBJECT (v4l2object->element,
304       "sending v4l2 decoder command %u with flags %u", cmd, flags);
305
306   if (!GST_V4L2_IS_OPEN (v4l2object))
307     return FALSE;
308
309   dcmd.cmd = cmd;
310   dcmd.flags = flags;
311   if (v4l2_ioctl (v4l2object->video_fd, VIDIOC_DECODER_CMD, &dcmd) < 0)
312     goto dcmd_failed;
313
314   return TRUE;
315
316 dcmd_failed:
317   if (errno == ENOTTY) {
318     GST_INFO_OBJECT (v4l2object->element,
319         "Failed to send decoder command %u with flags %u for '%s'. (%s)",
320         cmd, flags, v4l2object->videodev, g_strerror (errno));
321   } else {
322     GST_ERROR_OBJECT (v4l2object->element,
323         "Failed to send decoder command %u with flags %u for '%s'. (%s)",
324         cmd, flags, v4l2object->videodev, g_strerror (errno));
325   }
326   return FALSE;
327 }
328
329 static GstFlowReturn
330 gst_v4l2_video_dec_finish (GstVideoDecoder * decoder)
331 {
332   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
333   GstFlowReturn ret = GST_FLOW_OK;
334   GstBuffer *buffer;
335
336   if (gst_pad_get_task_state (decoder->srcpad) != GST_TASK_STARTED)
337     goto done;
338
339   GST_DEBUG_OBJECT (self, "Finishing decoding");
340
341   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
342
343   if (gst_v4l2_decoder_cmd (self->v4l2output, V4L2_DEC_CMD_STOP, 0)) {
344     GstTask *task = decoder->srcpad->task;
345
346     /* If the decoder stop command succeeded, just wait until processing is
347      * finished */
348     GST_OBJECT_LOCK (task);
349     while (GST_TASK_STATE (task) == GST_TASK_STARTED)
350       GST_TASK_WAIT (task);
351     GST_OBJECT_UNLOCK (task);
352     ret = GST_FLOW_FLUSHING;
353   } else {
354     /* otherwise keep queuing empty buffers until the processing thread has
355      * stopped, _pool_process() will return FLUSHING when that happened */
356     while (ret == GST_FLOW_OK) {
357       buffer = gst_buffer_new ();
358       ret =
359           gst_v4l2_buffer_pool_process (GST_V4L2_BUFFER_POOL (self->
360               v4l2output->pool), &buffer);
361       gst_buffer_unref (buffer);
362     }
363   }
364
365   /* and ensure the processing thread has stopped in case another error
366    * occured. */
367   gst_v4l2_object_unlock (self->v4l2capture);
368   gst_pad_stop_task (decoder->srcpad);
369   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
370
371   if (ret == GST_FLOW_FLUSHING)
372     ret = self->output_flow;
373
374   GST_DEBUG_OBJECT (decoder, "Done draining buffers");
375
376 done:
377   return ret;
378 }
379
380 static GstVideoCodecFrame *
381 gst_v4l2_video_dec_get_oldest_frame (GstVideoDecoder * decoder)
382 {
383   GstVideoCodecFrame *frame = NULL;
384   GList *frames, *l;
385   gint count = 0;
386
387   frames = gst_video_decoder_get_frames (decoder);
388
389   for (l = frames; l != NULL; l = l->next) {
390     GstVideoCodecFrame *f = l->data;
391
392     if (!frame || frame->pts > f->pts)
393       frame = f;
394
395     count++;
396   }
397
398   if (frame) {
399     GST_LOG_OBJECT (decoder,
400         "Oldest frame is %d %" GST_TIME_FORMAT " and %d frames left",
401         frame->system_frame_number, GST_TIME_ARGS (frame->pts), count - 1);
402     gst_video_codec_frame_ref (frame);
403   }
404
405   g_list_free_full (frames, (GDestroyNotify) gst_video_codec_frame_unref);
406
407   return frame;
408 }
409
410 static void
411 gst_v4l2_video_dec_loop (GstVideoDecoder * decoder)
412 {
413   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
414   GstV4l2BufferPool *v4l2_pool = GST_V4L2_BUFFER_POOL (self->v4l2capture->pool);
415   GstBufferPool *pool;
416   GstVideoCodecFrame *frame;
417   GstBuffer *buffer = NULL;
418   GstFlowReturn ret;
419
420   GST_LOG_OBJECT (decoder, "Allocate output buffer");
421
422   self->output_flow = GST_FLOW_OK;
423   do {
424     /* We cannot use the base class allotate helper since it taking the internal
425      * stream lock. we know that the acquire may need to poll until more frames
426      * comes in and holding this lock would prevent that.
427      */
428     pool = gst_video_decoder_get_buffer_pool (decoder);
429
430     /* Pool may be NULL if we started going to READY state */
431     if (pool == NULL) {
432       ret = GST_FLOW_FLUSHING;
433       goto beach;
434     }
435
436     ret = gst_buffer_pool_acquire_buffer (pool, &buffer, NULL);
437     g_object_unref (pool);
438
439     if (ret != GST_FLOW_OK)
440       goto beach;
441
442     GST_LOG_OBJECT (decoder, "Process output buffer");
443     ret = gst_v4l2_buffer_pool_process (v4l2_pool, &buffer);
444
445   } while (ret == GST_V4L2_FLOW_CORRUPTED_BUFFER);
446
447   if (ret != GST_FLOW_OK)
448     goto beach;
449
450   frame = gst_v4l2_video_dec_get_oldest_frame (decoder);
451
452   if (frame) {
453     frame->output_buffer = buffer;
454     buffer = NULL;
455     ret = gst_video_decoder_finish_frame (decoder, frame);
456
457     if (ret != GST_FLOW_OK)
458       goto beach;
459   } else {
460     GST_WARNING_OBJECT (decoder, "Decoder is producing too many buffers");
461     gst_buffer_unref (buffer);
462   }
463
464   return;
465
466 beach:
467   GST_DEBUG_OBJECT (decoder, "Leaving output thread: %s",
468       gst_flow_get_name (ret));
469
470   gst_buffer_replace (&buffer, NULL);
471   self->output_flow = ret;
472   gst_v4l2_object_unlock (self->v4l2output);
473   gst_pad_pause_task (decoder->srcpad);
474 }
475
476 static gboolean
477 gst_v4l2_video_remove_padding (GstCapsFeatures * features,
478     GstStructure * structure, gpointer user_data)
479 {
480   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (user_data);
481   GstVideoAlignment *align = &self->v4l2capture->align;
482   GstVideoInfo *info = &self->v4l2capture->info;
483   int width, height;
484
485   if (!gst_structure_get_int (structure, "width", &width))
486     return TRUE;
487
488   if (!gst_structure_get_int (structure, "height", &height))
489     return TRUE;
490
491   if (align->padding_left != 0 || align->padding_top != 0 ||
492       width != info->width + align->padding_right ||
493       height != info->height + align->padding_bottom)
494     return TRUE;
495
496   gst_structure_set (structure,
497       "width", G_TYPE_INT, width - align->padding_right,
498       "height", G_TYPE_INT, height - align->padding_bottom, NULL);
499
500   return TRUE;
501 }
502
503 static GstFlowReturn
504 gst_v4l2_video_dec_handle_frame (GstVideoDecoder * decoder,
505     GstVideoCodecFrame * frame)
506 {
507   GstV4l2Error error = GST_V4L2_ERROR_INIT;
508   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
509   GstFlowReturn ret = GST_FLOW_OK;
510   gboolean processed = FALSE;
511   GstBuffer *tmp;
512
513   GST_DEBUG_OBJECT (self, "Handling frame %d", frame->system_frame_number);
514
515   if (G_UNLIKELY (!g_atomic_int_get (&self->active)))
516     goto flushing;
517
518   if (G_UNLIKELY (!GST_V4L2_IS_ACTIVE (self->v4l2output))) {
519     if (!self->input_state)
520       goto not_negotiated;
521     if (!gst_v4l2_object_set_format (self->v4l2output, self->input_state->caps,
522             &error))
523       goto not_negotiated;
524   }
525
526   if (G_UNLIKELY (!GST_V4L2_IS_ACTIVE (self->v4l2capture))) {
527     GstBufferPool *pool = GST_BUFFER_POOL (self->v4l2output->pool);
528     GstVideoInfo info;
529     GstVideoCodecState *output_state;
530     GstBuffer *codec_data;
531     GstCaps *acquired_caps, *available_caps, *caps, *filter;
532     GstStructure *st;
533
534     GST_DEBUG_OBJECT (self, "Sending header");
535
536     codec_data = self->input_state->codec_data;
537
538     /* We are running in byte-stream mode, so we don't know the headers, but
539      * we need to send something, otherwise the decoder will refuse to
540      * intialize.
541      */
542     if (codec_data) {
543       gst_buffer_ref (codec_data);
544     } else {
545       codec_data = gst_buffer_ref (frame->input_buffer);
546       processed = TRUE;
547     }
548
549     /* Ensure input internal pool is active */
550     if (!gst_buffer_pool_is_active (pool)) {
551       GstStructure *config = gst_buffer_pool_get_config (pool);
552       gst_buffer_pool_config_set_params (config, self->input_state->caps,
553           self->v4l2output->info.size, 2, 2);
554
555       /* There is no reason to refuse this config */
556       if (!gst_buffer_pool_set_config (pool, config))
557         goto activate_failed;
558
559       if (!gst_buffer_pool_set_active (pool, TRUE))
560         goto activate_failed;
561     }
562
563     GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
564     ret =
565         gst_v4l2_buffer_pool_process (GST_V4L2_BUFFER_POOL (self->
566             v4l2output->pool), &codec_data);
567     GST_VIDEO_DECODER_STREAM_LOCK (decoder);
568
569     gst_buffer_unref (codec_data);
570
571     /* For decoders G_FMT returns coded size, G_SELECTION returns visible size
572      * in the compose rectangle. gst_v4l2_object_acquire_format() checks both
573      * and returns the visible size as with/height and the coded size as
574      * padding. */
575     if (!gst_v4l2_object_acquire_format (self->v4l2capture, &info))
576       goto not_negotiated;
577
578     /* Create caps from the acquired format, remove the format field */
579     acquired_caps = gst_video_info_to_caps (&info);
580     st = gst_caps_get_structure (acquired_caps, 0);
581     gst_structure_remove_field (st, "format");
582
583     /* Probe currently available pixel formats */
584     available_caps = gst_v4l2_object_probe_caps (self->v4l2capture, NULL);
585     available_caps = gst_caps_make_writable (available_caps);
586
587     /* Replace coded size with visible size, we want to negotiate visible size
588      * with downstream, not coded size. */
589     gst_caps_map_in_place (available_caps, gst_v4l2_video_remove_padding, self);
590
591     filter = gst_caps_intersect_full (available_caps, acquired_caps,
592         GST_CAPS_INTERSECT_FIRST);
593     gst_caps_unref (acquired_caps);
594     gst_caps_unref (available_caps);
595     caps = gst_pad_peer_query_caps (decoder->srcpad, filter);
596     gst_caps_unref (filter);
597
598     GST_DEBUG_OBJECT (self, "Possible decoded caps: %" GST_PTR_FORMAT, caps);
599     if (gst_caps_is_empty (caps)) {
600       gst_caps_unref (caps);
601       goto not_negotiated;
602     }
603
604     /* Fixate pixel format */
605     caps = gst_caps_fixate (caps);
606
607     GST_DEBUG_OBJECT (self, "Chosen decoded caps: %" GST_PTR_FORMAT, caps);
608
609     /* Try to set negotiated format, on success replace acquired format */
610     if (gst_v4l2_object_set_format (self->v4l2capture, caps, &error))
611       gst_video_info_from_caps (&info, caps);
612     else
613       gst_v4l2_clear_error (&error);
614     gst_caps_unref (caps);
615
616     output_state = gst_video_decoder_set_output_state (decoder,
617         info.finfo->format, info.width, info.height, self->input_state);
618
619     /* Copy the rest of the information, there might be more in the future */
620     output_state->info.interlace_mode = info.interlace_mode;
621     gst_video_codec_state_unref (output_state);
622
623     if (!gst_video_decoder_negotiate (decoder)) {
624       if (GST_PAD_IS_FLUSHING (decoder->srcpad))
625         goto flushing;
626       else
627         goto not_negotiated;
628     }
629
630     /* Ensure our internal pool is activated */
631     if (!gst_buffer_pool_set_active (GST_BUFFER_POOL (self->v4l2capture->pool),
632             TRUE))
633       goto activate_failed;
634   }
635
636   if (gst_pad_get_task_state (GST_VIDEO_DECODER_SRC_PAD (self)) ==
637       GST_TASK_STOPPED) {
638     /* It's possible that the processing thread stopped due to an error */
639     if (self->output_flow != GST_FLOW_OK &&
640         self->output_flow != GST_FLOW_FLUSHING) {
641       GST_DEBUG_OBJECT (self, "Processing loop stopped with error, leaving");
642       ret = self->output_flow;
643       goto drop;
644     }
645
646     GST_DEBUG_OBJECT (self, "Starting decoding thread");
647
648     /* Start the processing task, when it quits, the task will disable input
649      * processing to unlock input if draining, or prevent potential block */
650     self->output_flow = GST_FLOW_FLUSHING;
651     if (!gst_pad_start_task (decoder->srcpad,
652             (GstTaskFunction) gst_v4l2_video_dec_loop, self, NULL))
653       goto start_task_failed;
654   }
655
656   if (!processed) {
657     GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
658     ret =
659         gst_v4l2_buffer_pool_process (GST_V4L2_BUFFER_POOL (self->v4l2output->
660             pool), &frame->input_buffer);
661     GST_VIDEO_DECODER_STREAM_LOCK (decoder);
662
663     if (ret == GST_FLOW_FLUSHING) {
664       if (gst_pad_get_task_state (GST_VIDEO_DECODER_SRC_PAD (self)) !=
665           GST_TASK_STARTED)
666         ret = self->output_flow;
667       goto drop;
668     } else if (ret != GST_FLOW_OK) {
669       goto process_failed;
670     }
671   }
672
673   /* No need to keep input arround */
674   tmp = frame->input_buffer;
675   frame->input_buffer = gst_buffer_new ();
676   gst_buffer_copy_into (frame->input_buffer, tmp,
677       GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_TIMESTAMPS |
678       GST_BUFFER_COPY_META, 0, 0);
679   gst_buffer_unref (tmp);
680
681   gst_video_codec_frame_unref (frame);
682   return ret;
683
684   /* ERRORS */
685 not_negotiated:
686   {
687     GST_ERROR_OBJECT (self, "not negotiated");
688     ret = GST_FLOW_NOT_NEGOTIATED;
689     gst_v4l2_error (self, &error);
690     goto drop;
691   }
692 activate_failed:
693   {
694     GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
695         (_("Failed to allocate required memory.")),
696         ("Buffer pool activation failed"));
697     ret = GST_FLOW_ERROR;
698     goto drop;
699   }
700 flushing:
701   {
702     ret = GST_FLOW_FLUSHING;
703     goto drop;
704   }
705
706 start_task_failed:
707   {
708     GST_ELEMENT_ERROR (self, RESOURCE, FAILED,
709         (_("Failed to start decoding thread.")), (NULL));
710     ret = GST_FLOW_ERROR;
711     goto drop;
712   }
713 process_failed:
714   {
715     GST_ELEMENT_ERROR (self, RESOURCE, FAILED,
716         (_("Failed to process frame.")),
717         ("Maybe be due to not enough memory or failing driver"));
718     ret = GST_FLOW_ERROR;
719     goto drop;
720   }
721 drop:
722   {
723     gst_video_decoder_drop_frame (decoder, frame);
724     return ret;
725   }
726 }
727
728 static gboolean
729 gst_v4l2_video_dec_decide_allocation (GstVideoDecoder * decoder,
730     GstQuery * query)
731 {
732   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
733   GstClockTime latency;
734   gboolean ret = FALSE;
735
736   if (gst_v4l2_object_decide_allocation (self->v4l2capture, query))
737     ret = GST_VIDEO_DECODER_CLASS (parent_class)->decide_allocation (decoder,
738         query);
739
740   if (GST_CLOCK_TIME_IS_VALID (self->v4l2capture->duration)) {
741     latency = self->v4l2capture->min_buffers * self->v4l2capture->duration;
742     GST_DEBUG_OBJECT (self, "Setting latency: %" GST_TIME_FORMAT " (%"
743         G_GUINT32_FORMAT " * %" G_GUINT64_FORMAT, GST_TIME_ARGS (latency),
744         self->v4l2capture->min_buffers, self->v4l2capture->duration);
745     gst_video_decoder_set_latency (decoder, latency, latency);
746   } else {
747     GST_WARNING_OBJECT (self, "Duration invalid, not setting latency");
748   }
749
750   return ret;
751 }
752
753 static gboolean
754 gst_v4l2_video_dec_src_query (GstVideoDecoder * decoder, GstQuery * query)
755 {
756   gboolean ret = TRUE;
757   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
758
759   switch (GST_QUERY_TYPE (query)) {
760     case GST_QUERY_CAPS:{
761       GstCaps *filter, *result = NULL;
762       GstPad *pad = GST_VIDEO_DECODER_SRC_PAD (decoder);
763
764       gst_query_parse_caps (query, &filter);
765
766       if (self->probed_srccaps)
767         result = gst_caps_ref (self->probed_srccaps);
768       else
769         result = gst_pad_get_pad_template_caps (pad);
770
771       if (filter) {
772         GstCaps *tmp = result;
773         result =
774             gst_caps_intersect_full (filter, tmp, GST_CAPS_INTERSECT_FIRST);
775         gst_caps_unref (tmp);
776       }
777
778       GST_DEBUG_OBJECT (self, "Returning src caps %" GST_PTR_FORMAT, result);
779
780       gst_query_set_caps_result (query, result);
781       gst_caps_unref (result);
782       break;
783     }
784
785     default:
786       ret = GST_VIDEO_DECODER_CLASS (parent_class)->src_query (decoder, query);
787       break;
788   }
789
790   return ret;
791 }
792
793 static GstCaps *
794 gst_v4l2_video_dec_sink_getcaps (GstVideoDecoder * decoder, GstCaps * filter)
795 {
796   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
797   GstCaps *result;
798
799   result = gst_video_decoder_proxy_getcaps (decoder, self->probed_sinkcaps,
800       filter);
801
802   GST_DEBUG_OBJECT (self, "Returning sink caps %" GST_PTR_FORMAT, result);
803
804   return result;
805 }
806
807 static gboolean
808 gst_v4l2_video_dec_sink_event (GstVideoDecoder * decoder, GstEvent * event)
809 {
810   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
811   gboolean ret;
812
813   switch (GST_EVENT_TYPE (event)) {
814     case GST_EVENT_FLUSH_START:
815       GST_DEBUG_OBJECT (self, "flush start");
816       gst_v4l2_object_unlock (self->v4l2output);
817       gst_v4l2_object_unlock (self->v4l2capture);
818       break;
819     default:
820       break;
821   }
822
823   ret = GST_VIDEO_DECODER_CLASS (parent_class)->sink_event (decoder, event);
824
825   switch (GST_EVENT_TYPE (event)) {
826     case GST_EVENT_FLUSH_START:
827       /* The processing thread should stop now, wait for it */
828       gst_pad_stop_task (decoder->srcpad);
829       GST_DEBUG_OBJECT (self, "flush start done");
830       break;
831     default:
832       break;
833   }
834
835   return ret;
836 }
837
838 static GstStateChangeReturn
839 gst_v4l2_video_dec_change_state (GstElement * element,
840     GstStateChange transition)
841 {
842   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (element);
843   GstVideoDecoder *decoder = GST_VIDEO_DECODER (element);
844
845   if (transition == GST_STATE_CHANGE_PAUSED_TO_READY) {
846     g_atomic_int_set (&self->active, FALSE);
847     gst_v4l2_object_unlock (self->v4l2output);
848     gst_v4l2_object_unlock (self->v4l2capture);
849     gst_pad_stop_task (decoder->srcpad);
850   }
851
852   return GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
853 }
854
855 static void
856 gst_v4l2_video_dec_dispose (GObject * object)
857 {
858   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (object);
859
860   gst_caps_replace (&self->probed_sinkcaps, NULL);
861   gst_caps_replace (&self->probed_srccaps, NULL);
862
863   G_OBJECT_CLASS (parent_class)->dispose (object);
864 }
865
866 static void
867 gst_v4l2_video_dec_finalize (GObject * object)
868 {
869   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (object);
870
871   gst_v4l2_object_destroy (self->v4l2capture);
872   gst_v4l2_object_destroy (self->v4l2output);
873
874   G_OBJECT_CLASS (parent_class)->finalize (object);
875 }
876
877 static void
878 gst_v4l2_video_dec_init (GstV4l2VideoDec * self)
879 {
880   /* V4L2 object are created in subinstance_init */
881 }
882
883 static void
884 gst_v4l2_video_dec_subinstance_init (GTypeInstance * instance, gpointer g_class)
885 {
886   GstV4l2VideoDecClass *klass = GST_V4L2_VIDEO_DEC_CLASS (g_class);
887   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (instance);
888   GstVideoDecoder *decoder = GST_VIDEO_DECODER (instance);
889
890   gst_video_decoder_set_packetized (decoder, TRUE);
891
892   self->v4l2output = gst_v4l2_object_new (GST_ELEMENT (self),
893       V4L2_BUF_TYPE_VIDEO_OUTPUT, klass->default_device,
894       gst_v4l2_get_output, gst_v4l2_set_output, NULL);
895   self->v4l2output->no_initial_format = TRUE;
896   self->v4l2output->keep_aspect = FALSE;
897
898   self->v4l2capture = gst_v4l2_object_new (GST_ELEMENT (self),
899       V4L2_BUF_TYPE_VIDEO_CAPTURE, klass->default_device,
900       gst_v4l2_get_input, gst_v4l2_set_input, NULL);
901   self->v4l2capture->no_initial_format = TRUE;
902   self->v4l2output->keep_aspect = FALSE;
903 }
904
905 static void
906 gst_v4l2_video_dec_class_init (GstV4l2VideoDecClass * klass)
907 {
908   GstElementClass *element_class;
909   GObjectClass *gobject_class;
910   GstVideoDecoderClass *video_decoder_class;
911
912   parent_class = g_type_class_peek_parent (klass);
913
914   element_class = (GstElementClass *) klass;
915   gobject_class = (GObjectClass *) klass;
916   video_decoder_class = (GstVideoDecoderClass *) klass;
917
918   GST_DEBUG_CATEGORY_INIT (gst_v4l2_video_dec_debug, "v4l2videodec", 0,
919       "V4L2 Video Decoder");
920
921   gobject_class->dispose = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_dispose);
922   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_finalize);
923   gobject_class->set_property =
924       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_set_property);
925   gobject_class->get_property =
926       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_get_property);
927
928   video_decoder_class->open = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_open);
929   video_decoder_class->close = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_close);
930   video_decoder_class->start = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_start);
931   video_decoder_class->stop = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_stop);
932   video_decoder_class->finish = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_finish);
933   video_decoder_class->flush = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_flush);
934   video_decoder_class->set_format =
935       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_set_format);
936   video_decoder_class->negotiate =
937       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_negotiate);
938   video_decoder_class->decide_allocation =
939       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_decide_allocation);
940   /* FIXME propose_allocation or not ? */
941   video_decoder_class->handle_frame =
942       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_handle_frame);
943   video_decoder_class->getcaps =
944       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_sink_getcaps);
945   video_decoder_class->src_query =
946       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_src_query);
947   video_decoder_class->sink_event =
948       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_sink_event);
949
950   element_class->change_state =
951       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_change_state);
952
953   gst_v4l2_object_install_m2m_properties_helper (gobject_class);
954 }
955
956 static void
957 gst_v4l2_video_dec_subclass_init (gpointer g_class, gpointer data)
958 {
959   GstV4l2VideoDecClass *klass = GST_V4L2_VIDEO_DEC_CLASS (g_class);
960   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
961   GstV4l2VideoDecCData *cdata = data;
962
963   klass->default_device = cdata->device;
964
965   /* Note: gst_pad_template_new() take the floating ref from the caps */
966   gst_element_class_add_pad_template (element_class,
967       gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
968           cdata->sink_caps));
969   gst_element_class_add_pad_template (element_class,
970       gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
971           cdata->src_caps));
972
973   gst_element_class_set_static_metadata (element_class, cdata->longname,
974       "Codec/Decoder/Video", cdata->description,
975       "Nicolas Dufresne <nicolas.dufresne@collabora.com>");
976
977   g_free (cdata);
978 }
979
980 /* Probing functions */
981 gboolean
982 gst_v4l2_is_video_dec (GstCaps * sink_caps, GstCaps * src_caps)
983 {
984   gboolean ret = FALSE;
985
986   if (gst_caps_is_subset (sink_caps, gst_v4l2_object_get_codec_caps ())
987       && gst_caps_is_subset (src_caps, gst_v4l2_object_get_raw_caps ()))
988     ret = TRUE;
989
990   return ret;
991 }
992
993 static gchar *
994 gst_v4l2_video_dec_set_metadata (GstStructure * s, GstV4l2VideoDecCData * cdata,
995     const gchar * basename)
996 {
997   gchar *codec_name = NULL;
998   gchar *type_name = NULL;
999
1000 #define SET_META(codec) \
1001 G_STMT_START { \
1002   cdata->longname = "V4L2 " codec " Decoder"; \
1003   cdata->description = "Decodes " codec " streams via V4L2 API"; \
1004   codec_name = g_ascii_strdown (codec, -1); \
1005 } G_STMT_END
1006
1007   if (gst_structure_has_name (s, "image/jpeg")) {
1008     SET_META ("JPEG");
1009   } else if (gst_structure_has_name (s, "video/mpeg")) {
1010     gint mpegversion = 0;
1011     gst_structure_get_int (s, "mpegversion", &mpegversion);
1012
1013     if (mpegversion == 2) {
1014       SET_META ("MPEG2");
1015     } else {
1016       SET_META ("MPEG4");
1017     }
1018   } else if (gst_structure_has_name (s, "video/x-h263")) {
1019     SET_META ("H263");
1020   } else if (gst_structure_has_name (s, "video/x-h264")) {
1021     SET_META ("H264");
1022   } else if (gst_structure_has_name (s, "video/x-wmv")) {
1023     SET_META ("VC1");
1024   } else if (gst_structure_has_name (s, "video/x-vp8")) {
1025     SET_META ("VP8");
1026   } else if (gst_structure_has_name (s, "video/x-bayer")) {
1027     SET_META ("BAYER");
1028   } else if (gst_structure_has_name (s, "video/x-sonix")) {
1029     SET_META ("SONIX");
1030   } else if (gst_structure_has_name (s, "video/x-pwc1")) {
1031     SET_META ("PWC1");
1032   } else if (gst_structure_has_name (s, "video/x-pwc2")) {
1033     SET_META ("PWC2");
1034   } else {
1035     /* This code should be kept on sync with the exposed CODEC type of format
1036      * from gstv4l2object.c. This warning will only occure in case we forget
1037      * to also add a format here. */
1038     gchar *s_str = gst_structure_to_string (s);
1039     g_warning ("Missing fixed name mapping for caps '%s', this is a GStreamer "
1040         "bug, please report at https://bugs.gnome.org", s_str);
1041     g_free (s_str);
1042   }
1043
1044   if (codec_name) {
1045     type_name = g_strdup_printf ("v4l2%sdec", codec_name);
1046     if (g_type_from_name (type_name) != 0) {
1047       g_free (type_name);
1048       type_name = g_strdup_printf ("v4l2%s%sdec", basename, codec_name);
1049     }
1050   }
1051
1052   return type_name;
1053 #undef SET_META
1054 }
1055
1056 gboolean
1057 gst_v4l2_video_dec_register (GstPlugin * plugin, const gchar * basename,
1058     const gchar * device_path, GstCaps * sink_caps, GstCaps * src_caps)
1059 {
1060   gint i;
1061
1062   for (i = 0; i < gst_caps_get_size (sink_caps); i++) {
1063     GstV4l2VideoDecCData *cdata;
1064     GstStructure *s;
1065     GTypeQuery type_query;
1066     GTypeInfo type_info = { 0, };
1067     GType type, subtype;
1068     gchar *type_name;
1069
1070     s = gst_caps_get_structure (sink_caps, i);
1071
1072     cdata = g_new0 (GstV4l2VideoDecCData, 1);
1073     cdata->device = g_strdup (device_path);
1074     cdata->sink_caps = gst_caps_new_empty ();
1075     gst_caps_append_structure (cdata->sink_caps, gst_structure_copy (s));
1076     cdata->src_caps = gst_caps_ref (src_caps);
1077     type_name = gst_v4l2_video_dec_set_metadata (s, cdata, basename);
1078
1079     /* Skip over if we hit an unmapped type */
1080     if (!type_name) {
1081       g_free (cdata);
1082       continue;
1083     }
1084
1085     type = gst_v4l2_video_dec_get_type ();
1086     g_type_query (type, &type_query);
1087     memset (&type_info, 0, sizeof (type_info));
1088     type_info.class_size = type_query.class_size;
1089     type_info.instance_size = type_query.instance_size;
1090     type_info.class_init = gst_v4l2_video_dec_subclass_init;
1091     type_info.class_data = cdata;
1092     type_info.instance_init = gst_v4l2_video_dec_subinstance_init;
1093
1094     subtype = g_type_register_static (type, type_name, &type_info, 0);
1095     gst_element_register (plugin, type_name, GST_RANK_PRIMARY + 1, subtype);
1096
1097     g_free (type_name);
1098   }
1099
1100   return TRUE;
1101 }