5d9d1e1e890daa0eb9d861234277488522ea5ffa
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-good / 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 "gstv4l2object.h"
33 #include "gstv4l2videodec.h"
34
35 #include "gstv4l2h264codec.h"
36 #include "gstv4l2h265codec.h"
37 #include "gstv4l2mpeg2codec.h"
38 #include "gstv4l2mpeg4codec.h"
39 #include "gstv4l2vp8codec.h"
40 #include "gstv4l2vp9codec.h"
41
42 #include <string.h>
43 #include <glib/gi18n-lib.h>
44
45 GST_DEBUG_CATEGORY_STATIC (gst_v4l2_video_dec_debug);
46 #define GST_CAT_DEFAULT gst_v4l2_video_dec_debug
47
48 typedef struct
49 {
50   gchar *device;
51   GstCaps *sink_caps;
52   GstCaps *src_caps;
53   const gchar *longname;
54   const gchar *description;
55   const GstV4l2Codec *codec;
56 } GstV4l2VideoDecCData;
57
58 enum
59 {
60   PROP_0,
61   V4L2_STD_OBJECT_PROPS
62 };
63
64 #define gst_v4l2_video_dec_parent_class parent_class
65 G_DEFINE_ABSTRACT_TYPE (GstV4l2VideoDec, gst_v4l2_video_dec,
66     GST_TYPE_VIDEO_DECODER);
67
68 static GstFlowReturn gst_v4l2_video_dec_finish (GstVideoDecoder * decoder);
69
70 static void
71 gst_v4l2_video_dec_set_property (GObject * object,
72     guint prop_id, const GValue * value, GParamSpec * pspec)
73 {
74   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (object);
75
76   switch (prop_id) {
77     case PROP_CAPTURE_IO_MODE:
78       if (!gst_v4l2_object_set_property_helper (self->v4l2capture,
79               prop_id, value, pspec)) {
80         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
81       }
82       break;
83
84       /* By default, only set on output */
85     default:
86       if (!gst_v4l2_object_set_property_helper (self->v4l2output,
87               prop_id, value, pspec)) {
88         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
89       }
90       break;
91   }
92 }
93
94 static void
95 gst_v4l2_video_dec_get_property (GObject * object,
96     guint prop_id, GValue * value, GParamSpec * pspec)
97 {
98   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (object);
99
100   switch (prop_id) {
101     case PROP_CAPTURE_IO_MODE:
102       if (!gst_v4l2_object_get_property_helper (self->v4l2capture,
103               prop_id, value, pspec)) {
104         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
105       }
106       break;
107
108       /* By default read from output */
109     default:
110       if (!gst_v4l2_object_get_property_helper (self->v4l2output,
111               prop_id, value, pspec)) {
112         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
113       }
114       break;
115   }
116 }
117
118 static gboolean
119 gst_v4l2_video_dec_open (GstVideoDecoder * decoder)
120 {
121   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
122   GstV4l2Error error = GST_V4L2_ERROR_INIT;
123   GstCaps *codec_caps;
124
125   GST_DEBUG_OBJECT (self, "Opening");
126
127   if (!gst_v4l2_object_open (self->v4l2output, &error))
128     goto failure;
129
130   if (!gst_v4l2_object_open_shared (self->v4l2capture, self->v4l2output))
131     goto failure;
132
133   codec_caps = gst_pad_get_pad_template_caps (decoder->sinkpad);
134   self->probed_sinkcaps = gst_v4l2_object_probe_caps (self->v4l2output,
135       codec_caps);
136   gst_caps_unref (codec_caps);
137
138   if (gst_caps_is_empty (self->probed_sinkcaps))
139     goto no_encoded_format;
140
141   return TRUE;
142
143 no_encoded_format:
144   GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
145       (_("Decoder on device %s has no supported input format"),
146           self->v4l2output->videodev), (NULL));
147   goto failure;
148
149 failure:
150   if (GST_V4L2_IS_OPEN (self->v4l2output))
151     gst_v4l2_object_close (self->v4l2output);
152
153   if (GST_V4L2_IS_OPEN (self->v4l2capture))
154     gst_v4l2_object_close (self->v4l2capture);
155
156   gst_caps_replace (&self->probed_srccaps, NULL);
157   gst_caps_replace (&self->probed_sinkcaps, NULL);
158
159   gst_v4l2_error (self, &error);
160
161   return FALSE;
162 }
163
164 static gboolean
165 gst_v4l2_video_dec_close (GstVideoDecoder * decoder)
166 {
167   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
168
169   GST_DEBUG_OBJECT (self, "Closing");
170
171   gst_v4l2_object_close (self->v4l2output);
172   gst_v4l2_object_close (self->v4l2capture);
173   gst_caps_replace (&self->probed_srccaps, NULL);
174   gst_caps_replace (&self->probed_sinkcaps, NULL);
175
176   return TRUE;
177 }
178
179 static gboolean
180 gst_v4l2_video_dec_start (GstVideoDecoder * decoder)
181 {
182   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
183
184   GST_DEBUG_OBJECT (self, "Starting");
185
186   gst_v4l2_object_unlock (self->v4l2output);
187   g_atomic_int_set (&self->active, TRUE);
188   g_atomic_int_set (&self->capture_configuration_change, FALSE);
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 compatible_caps (GstV4l2VideoDec * self, GstCaps * new_caps)
229 {
230   GstCaps *current_caps, *caps1, *caps2;
231   GstStructure *s;
232   gboolean ret;
233
234   current_caps = gst_v4l2_object_get_current_caps (self->v4l2output);
235   if (!current_caps)
236     return FALSE;
237
238   caps1 = gst_caps_copy (current_caps);
239   s = gst_caps_get_structure (caps1, 0);
240   gst_structure_remove_field (s, "framerate");
241
242   caps2 = gst_caps_copy (new_caps);
243   s = gst_caps_get_structure (caps2, 0);
244   gst_structure_remove_field (s, "framerate");
245
246   ret = gst_caps_is_equal (caps1, caps2);
247
248   gst_caps_unref (caps1);
249   gst_caps_unref (caps2);
250   gst_caps_unref (current_caps);
251
252   return ret;
253 }
254
255 static gboolean
256 gst_v4l2_video_dec_set_format (GstVideoDecoder * decoder,
257     GstVideoCodecState * state)
258 {
259   GstV4l2Error error = GST_V4L2_ERROR_INIT;
260   gboolean ret = TRUE;
261   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
262
263   GST_DEBUG_OBJECT (self, "Setting format: %" GST_PTR_FORMAT, state->caps);
264
265   if (self->input_state) {
266     if (compatible_caps (self, state->caps)) {
267       GST_DEBUG_OBJECT (self, "Compatible caps");
268       goto done;
269     }
270     gst_video_codec_state_unref (self->input_state);
271     self->input_state = NULL;
272
273     gst_v4l2_video_dec_finish (decoder);
274     gst_v4l2_object_stop (self->v4l2output);
275
276     /* The renegotiation flow don't blend with the base class flow. To properly
277      * stop the capture pool, if the buffers can't be orphaned, we need to
278      * reclaim our buffers, which will happend through the allocation query.
279      * The allocation query is triggered by gst_video_decoder_negotiate() which
280      * requires the output caps to be set, but we can't know this information
281      * as we rely on the decoder, which requires the capture queue to be
282      * stopped.
283      *
284      * To workaround this issue, we simply run an allocation query with the
285      * old negotiated caps in order to drain/reclaim our buffers. That breaks
286      * the complexity and should not have much impact in performance since the
287      * following allocation query will happen on a drained pipeline and won't
288      * block. */
289     if (!gst_v4l2_buffer_pool_orphan (self->v4l2capture)) {
290       GstCaps *caps = gst_pad_get_current_caps (decoder->srcpad);
291       if (caps) {
292         GstQuery *query = gst_query_new_allocation (caps, FALSE);
293         gst_pad_peer_query (decoder->srcpad, query);
294         gst_query_unref (query);
295         gst_caps_unref (caps);
296       }
297     }
298
299     gst_v4l2_object_stop (self->v4l2capture);
300     self->output_flow = GST_FLOW_OK;
301   }
302
303   ret = gst_v4l2_object_set_format (self->v4l2output, state->caps, &error);
304
305   gst_caps_replace (&self->probed_srccaps, NULL);
306   self->probed_srccaps = gst_v4l2_object_probe_caps (self->v4l2capture,
307       gst_v4l2_object_get_raw_caps ());
308
309   if (gst_caps_is_empty (self->probed_srccaps))
310     goto no_raw_format;
311
312   if (ret)
313     self->input_state = gst_video_codec_state_ref (state);
314   else
315     gst_v4l2_error (self, &error);
316
317 done:
318   return ret;
319
320 no_raw_format:
321   GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
322       (_("Decoder on device %s has no supported output format"),
323           self->v4l2output->videodev), (NULL));
324   return GST_FLOW_ERROR;
325 }
326
327 static gboolean
328 gst_v4l2_video_dec_flush (GstVideoDecoder * decoder)
329 {
330   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
331
332   GST_DEBUG_OBJECT (self, "Flushed");
333
334   /* Ensure the processing thread has stopped for the reverse playback
335    * discount case */
336   if (gst_pad_get_task_state (decoder->srcpad) == GST_TASK_STARTED) {
337     GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
338
339     gst_v4l2_object_unlock (self->v4l2output);
340     gst_v4l2_object_unlock (self->v4l2capture);
341     gst_pad_stop_task (decoder->srcpad);
342     GST_VIDEO_DECODER_STREAM_LOCK (decoder);
343   }
344
345   if (G_UNLIKELY (!g_atomic_int_get (&self->active)))
346     return TRUE;
347
348   self->output_flow = GST_FLOW_OK;
349
350   gst_v4l2_object_unlock_stop (self->v4l2output);
351   gst_v4l2_object_unlock_stop (self->v4l2capture);
352
353   gst_v4l2_buffer_pool_flush (self->v4l2output);
354
355   /* gst_v4l2_buffer_pool_flush() calls streamon the capture pool and must be
356    * called after gst_v4l2_object_unlock_stop() stopped flushing the buffer
357    * pool. */
358   gst_v4l2_buffer_pool_flush (self->v4l2capture);
359
360   return TRUE;
361 }
362
363 static gboolean
364 gst_v4l2_video_dec_negotiate (GstVideoDecoder * decoder)
365 {
366   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
367
368   /* We don't allow renegotiation without careful disabling the pool */
369   {
370     GstBufferPool *cpool = gst_v4l2_object_get_buffer_pool (self->v4l2capture);
371     if (cpool) {
372       gboolean is_active = gst_buffer_pool_is_active (cpool);
373       gst_object_unref (cpool);
374       if (is_active)
375         return TRUE;
376     }
377   }
378
379   return GST_VIDEO_DECODER_CLASS (parent_class)->negotiate (decoder);
380 }
381
382 static gboolean
383 gst_v4l2_decoder_cmd (GstV4l2Object * v4l2object, guint cmd, guint flags)
384 {
385   struct v4l2_decoder_cmd dcmd = { 0, };
386
387   GST_DEBUG_OBJECT (v4l2object->element,
388       "sending v4l2 decoder command %u with flags %u", cmd, flags);
389
390   if (!GST_V4L2_IS_OPEN (v4l2object))
391     return FALSE;
392
393   dcmd.cmd = cmd;
394   dcmd.flags = flags;
395   if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_DECODER_CMD, &dcmd) < 0)
396     goto dcmd_failed;
397
398   return TRUE;
399
400 dcmd_failed:
401   if (errno == ENOTTY) {
402     GST_INFO_OBJECT (v4l2object->element,
403         "Failed to send decoder command %u with flags %u for '%s'. (%s)",
404         cmd, flags, v4l2object->videodev, g_strerror (errno));
405   } else {
406     GST_ERROR_OBJECT (v4l2object->element,
407         "Failed to send decoder command %u with flags %u for '%s'. (%s)",
408         cmd, flags, v4l2object->videodev, g_strerror (errno));
409   }
410   return FALSE;
411 }
412
413 static GstFlowReturn
414 gst_v4l2_video_dec_finish (GstVideoDecoder * decoder)
415 {
416   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
417   GstFlowReturn ret = GST_FLOW_OK;
418   GstBuffer *buffer;
419   GList *pending_frames = NULL;
420
421   if (gst_pad_get_task_state (decoder->srcpad) != GST_TASK_STARTED)
422     goto done;
423
424   GST_DEBUG_OBJECT (self, "Finishing decoding");
425
426   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
427
428   if (gst_v4l2_decoder_cmd (self->v4l2output, V4L2_DEC_CMD_STOP, 0)) {
429     GstTask *task;
430
431     GST_OBJECT_LOCK (decoder->srcpad);
432     task = GST_PAD_TASK (decoder->srcpad);
433     if (task)
434       gst_object_ref (task);
435     GST_OBJECT_UNLOCK (decoder->srcpad);
436
437     if (task) {
438       /* If the decoder stop command succeeded, just wait until processing is
439        * finished */
440       GST_DEBUG_OBJECT (self, "Waiting for decoder stop");
441       GST_OBJECT_LOCK (task);
442       while (GST_TASK_STATE (task) == GST_TASK_STARTED)
443         GST_TASK_WAIT (task);
444       GST_OBJECT_UNLOCK (task);
445
446       ret = GST_FLOW_FLUSHING;
447       gst_object_unref (task);
448     }
449   } else {
450     GstBufferPool *opool = gst_v4l2_object_get_buffer_pool (self->v4l2output);
451     /* otherwise keep queuing empty buffers until the processing thread has
452      * stopped, _pool_process() will return FLUSHING when that happened */
453     while (ret == GST_FLOW_OK) {
454       buffer = gst_buffer_new ();
455       ret =
456           gst_v4l2_buffer_pool_process (GST_V4L2_BUFFER_POOL (opool), &buffer,
457           NULL);
458       gst_buffer_unref (buffer);
459     }
460     if (opool)
461       gst_object_unref (opool);
462   }
463
464   /* and ensure the processing thread has stopped in case another error
465    * occurred. */
466   gst_v4l2_object_unlock (self->v4l2capture);
467   gst_pad_stop_task (decoder->srcpad);
468   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
469
470   if (ret == GST_FLOW_FLUSHING)
471     ret = self->output_flow;
472
473   GST_DEBUG_OBJECT (decoder, "Done draining buffers");
474
475   /* Draining of the capture buffer has completed. 
476    * If any pending frames remain at this point there is a decoder error.
477    * This has been observed as a driver bug, where eos is sent too early.   
478    * These frames will never be rendered, so drop them now with a warning */
479
480   pending_frames = gst_video_decoder_get_frames (decoder);
481   if (pending_frames) {
482     int counter = 0;
483     guint32 first, last;
484     for (GList * g = pending_frames; g; g = g->next) {
485       GstVideoCodecFrame *frame = g->data;
486       g->data = NULL;
487       last = frame->system_frame_number;
488       if (!counter)
489         first = last;
490       counter++;
491       gst_video_decoder_drop_frame (decoder, frame);
492     }
493     g_warning
494         ("%s: %i frames %u-%u left undrained after CMD_STOP, eos sent too early: bug in decoder -- please file a bug",
495         GST_ELEMENT_NAME (decoder), counter, first, last);
496     if (pending_frames)
497       g_list_free (pending_frames);
498   }
499
500 done:
501   return ret;
502 }
503
504 static GstFlowReturn
505 gst_v4l2_video_dec_drain (GstVideoDecoder * decoder)
506 {
507   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
508
509   GST_DEBUG_OBJECT (self, "Draining...");
510   gst_v4l2_video_dec_finish (decoder);
511   gst_v4l2_video_dec_flush (decoder);
512
513   return GST_FLOW_OK;
514 }
515
516 static gboolean
517 check_system_frame_number_too_old (guint32 current, guint32 old)
518 {
519   guint32 absdiff = current > old ? current - old : old - current;
520
521   /* More than 100 frames in the past, or current wrapped around */
522   if (absdiff > 100) {
523     /* Wraparound and difference is actually smaller than 100 */
524     if (absdiff > G_MAXUINT32 - 100)
525       return FALSE;
526     return TRUE;
527   }
528
529   return FALSE;
530 }
531
532 static gboolean
533 gst_v4l2_video_remove_padding (GstCapsFeatures * features,
534     GstStructure * structure, gpointer user_data)
535 {
536   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (user_data);
537   GstVideoAlignment *align = &self->v4l2capture->align;
538   GstVideoInfo *info = &self->v4l2capture->info;
539   int width, height;
540
541   if (!gst_structure_get_int (structure, "width", &width))
542     return TRUE;
543
544   if (!gst_structure_get_int (structure, "height", &height))
545     return TRUE;
546
547   if (align->padding_left != 0 || align->padding_top != 0 ||
548       height != info->height + align->padding_bottom)
549     return TRUE;
550
551   if (height == info->height + align->padding_bottom) {
552     /* Some drivers may round up width to the padded with */
553     if (width == info->width + align->padding_right)
554       gst_structure_set (structure,
555           "width", G_TYPE_INT, width - align->padding_right,
556           "height", G_TYPE_INT, height - align->padding_bottom, NULL);
557     /* Some drivers may keep visible width and only round up bytesperline */
558     else if (width == info->width)
559       gst_structure_set (structure,
560           "height", G_TYPE_INT, height - align->padding_bottom, NULL);
561   }
562
563   return TRUE;
564 }
565
566 static GstFlowReturn
567 gst_v4l2_video_dec_setup_capture (GstVideoDecoder * decoder)
568 {
569   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
570   GstV4l2Error error = GST_V4L2_ERROR_INIT;
571   GstVideoInfo info;
572   GstVideoCodecState *output_state;
573   GstCaps *acquired_caps, *available_caps, *caps, *filter;
574   GstStructure *st;
575   GstBufferPool *cpool;
576   gboolean active;
577
578   if (G_UNLIKELY (!GST_V4L2_IS_ACTIVE (self->v4l2capture))) {
579     /* init capture fps according to output */
580     self->v4l2capture->info.fps_d = self->v4l2output->info.fps_d;
581     self->v4l2capture->info.fps_n = self->v4l2output->info.fps_n;
582
583     /* For decoders G_FMT returns coded size, G_SELECTION returns visible size
584      * in the compose rectangle. gst_v4l2_object_acquire_format() checks both
585      * and returns the visible size as with/height and the coded size as
586      * padding. */
587     if (!gst_v4l2_object_acquire_format (self->v4l2capture, &info))
588       goto not_negotiated;
589
590     /* gst_v4l2_object_acquire_format() does not set fps, copy from sink */
591     info.fps_n = self->v4l2output->info.fps_n;
592     info.fps_d = self->v4l2output->info.fps_d;
593
594     gst_v4l2_object_clear_format_list (self->v4l2capture);
595     gst_caps_replace (&self->probed_srccaps, NULL);
596     self->probed_srccaps = gst_v4l2_object_probe_caps (self->v4l2capture,
597         gst_v4l2_object_get_raw_caps ());
598     /* Create caps from the acquired format, remove the format field */
599     acquired_caps = gst_video_info_to_caps (&info);
600     GST_DEBUG_OBJECT (self, "Acquired caps: %" GST_PTR_FORMAT, acquired_caps);
601     st = gst_caps_get_structure (acquired_caps, 0);
602     gst_structure_remove_fields (st, "format", "colorimetry", "chroma-site",
603         NULL);
604
605     /* Probe currently available pixel formats */
606     available_caps = gst_caps_copy (self->probed_srccaps);
607     GST_DEBUG_OBJECT (self, "Available caps: %" GST_PTR_FORMAT, available_caps);
608
609     /* Replace coded size with visible size, we want to negotiate visible size
610      * with downstream, not coded size. */
611     gst_caps_map_in_place (available_caps, gst_v4l2_video_remove_padding, self);
612
613     filter = gst_caps_intersect_full (available_caps, acquired_caps,
614         GST_CAPS_INTERSECT_FIRST);
615     GST_DEBUG_OBJECT (self, "Filtered caps: %" GST_PTR_FORMAT, filter);
616     gst_caps_unref (acquired_caps);
617     gst_caps_unref (available_caps);
618     caps = gst_pad_peer_query_caps (decoder->srcpad, filter);
619     gst_caps_unref (filter);
620
621     GST_DEBUG_OBJECT (self, "Possible decoded caps: %" GST_PTR_FORMAT, caps);
622     if (gst_caps_is_empty (caps)) {
623       gst_caps_unref (caps);
624       goto not_negotiated;
625     }
626
627     /* Fixate pixel format */
628     caps = gst_caps_fixate (caps);
629
630     GST_DEBUG_OBJECT (self, "Chosen decoded caps: %" GST_PTR_FORMAT, caps);
631
632     /* Try to set negotiated format, on success replace acquired format */
633     if (gst_v4l2_object_set_format (self->v4l2capture, caps, &error))
634       gst_video_info_from_caps (&info, caps);
635     else
636       gst_v4l2_clear_error (&error);
637     gst_caps_unref (caps);
638
639     output_state = gst_video_decoder_set_output_state (decoder,
640         info.finfo->format, info.width, info.height, self->input_state);
641
642     /* Copy the rest of the information, there might be more in the future */
643     output_state->info.interlace_mode = info.interlace_mode;
644     output_state->info.colorimetry = info.colorimetry;
645     gst_video_codec_state_unref (output_state);
646
647     cpool = gst_v4l2_object_get_buffer_pool (self->v4l2capture);
648     gst_v4l2_buffer_pool_enable_resolution_change (GST_V4L2_BUFFER_POOL
649         (cpool));
650
651     if (!gst_video_decoder_negotiate (decoder)) {
652       if (cpool)
653         gst_object_unref (cpool);
654       if (GST_PAD_IS_FLUSHING (decoder->srcpad))
655         goto flushing;
656       else
657         goto not_negotiated;
658     }
659
660     /* Ensure our internal pool is activated */
661     active = gst_buffer_pool_set_active (cpool, TRUE);
662     if (cpool)
663       gst_object_unref (cpool);
664     if (!active)
665       goto activate_failed;
666   }
667
668   return GST_FLOW_OK;
669
670 not_negotiated:
671   GST_ERROR_OBJECT (self, "not negotiated");
672   gst_v4l2_error (self, &error);
673   return GST_FLOW_NOT_NEGOTIATED;
674 activate_failed:
675   GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
676       (_("Failed to allocate required memory.")),
677       ("Buffer pool activation failed"));
678   return GST_FLOW_ERROR;
679 flushing:
680   return GST_FLOW_FLUSHING;
681 }
682
683 static void
684 gst_v4l2_video_dec_loop (GstVideoDecoder * decoder)
685 {
686   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
687   GstBufferPool *pool;
688   GstVideoCodecFrame *frame;
689   GstBuffer *buffer = NULL;
690   GstFlowReturn ret;
691
692   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
693   if (g_atomic_int_get (&self->capture_configuration_change)) {
694     gst_v4l2_object_stop (self->v4l2capture);
695     ret = gst_v4l2_video_dec_setup_capture (decoder);
696     if (ret != GST_FLOW_OK) {
697       GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
698
699       /* if caps negotiation failed, avoid trying it repeatly */
700       if (ret == GST_FLOW_NOT_NEGOTIATED) {
701         GST_ERROR_OBJECT (decoder,
702             "capture configuration change fail, return negotiation fail");
703         goto beach;
704       } else {
705         return;
706       }
707     }
708     g_atomic_int_set (&self->capture_configuration_change, FALSE);
709   }
710   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
711
712   if (G_UNLIKELY (!GST_V4L2_IS_ACTIVE (self->v4l2capture)))
713     return;
714
715   GST_LOG_OBJECT (decoder, "Allocate output buffer");
716
717   self->output_flow = GST_FLOW_OK;
718
719   do {
720     /* We cannot use the base class allotate helper since it taking the internal
721      * stream lock. we know that the acquire may need to poll until more frames
722      * comes in and holding this lock would prevent that.
723      */
724     pool = gst_video_decoder_get_buffer_pool (decoder);
725
726     /* Pool may be NULL if we started going to READY state */
727     if (pool == NULL) {
728       ret = GST_FLOW_FLUSHING;
729       goto beach;
730     }
731
732     ret = gst_buffer_pool_acquire_buffer (pool, &buffer, NULL);
733     g_object_unref (pool);
734
735     if (ret == GST_V4L2_FLOW_RESOLUTION_CHANGE) {
736       GST_INFO_OBJECT (decoder, "Received resolution change");
737       g_atomic_int_set (&self->capture_configuration_change, TRUE);
738       return;
739     }
740
741     if (ret != GST_FLOW_OK)
742       goto beach;
743
744     GST_LOG_OBJECT (decoder, "Process output buffer");
745     {
746       GstV4l2BufferPool *cpool =
747           GST_V4L2_BUFFER_POOL (gst_v4l2_object_get_buffer_pool
748           (self->v4l2capture));
749       ret = gst_v4l2_buffer_pool_process (cpool, &buffer, NULL);
750       if (cpool)
751         gst_object_unref (cpool);
752     }
753
754     if (ret == GST_V4L2_FLOW_RESOLUTION_CHANGE) {
755       GST_INFO_OBJECT (decoder, "Received resolution change");
756       g_atomic_int_set (&self->capture_configuration_change, TRUE);
757       return;
758     }
759   } while (ret == GST_V4L2_FLOW_CORRUPTED_BUFFER);
760
761   if (ret != GST_FLOW_OK)
762     goto beach;
763
764   if (GST_BUFFER_TIMESTAMP (buffer) % GST_SECOND != 0)
765     GST_ERROR_OBJECT (decoder,
766         "Driver bug detected - check driver with v4l2-compliance from http://git.linuxtv.org/v4l-utils.git");
767   GST_LOG_OBJECT (decoder, "Got buffer for frame number %u",
768       (guint32) (GST_BUFFER_TIMESTAMP (buffer) / GST_SECOND));
769
770   frame =
771       gst_video_decoder_get_frame (decoder,
772       GST_BUFFER_TIMESTAMP (buffer) / GST_SECOND);
773   if (frame) {
774     GstVideoCodecFrame *oldest_frame;
775     gboolean warned = FALSE;
776
777     /* Garbage collect old frames in case of codec bugs */
778     while ((oldest_frame = gst_video_decoder_get_oldest_frame (decoder)) &&
779         check_system_frame_number_too_old (frame->system_frame_number,
780             oldest_frame->system_frame_number)) {
781       if (oldest_frame->system_frame_number > 0) {
782         gst_video_decoder_drop_frame (decoder, oldest_frame);
783         oldest_frame = NULL;
784
785         if (!warned) {
786           g_warning ("%s: Too old frames, bug in decoder -- please file a bug",
787               GST_ELEMENT_NAME (decoder));
788           warned = TRUE;
789         }
790       } else {
791         /* special treatment when oldest_frame->system_frame_number = 0:
792          * if a consecutive sequence 0, 1, 2,..., n < frame->system_frame_number
793          * is pending, drop them all at this time. (This has been seen to occur
794          * as a driver bug when the initial frame triggered a Caps re-negotiation,
795          * and the driver dropped these frames) */
796         guint32 counter = 0;
797         while (oldest_frame) {
798           gst_video_decoder_drop_frame (decoder, oldest_frame);
799           counter++;
800           oldest_frame = gst_video_decoder_get_oldest_frame (decoder);
801           if (oldest_frame &&
802               (oldest_frame->system_frame_number > counter ||
803                   oldest_frame->system_frame_number >=
804                   frame->system_frame_number)) {
805             gst_video_codec_frame_unref (oldest_frame);
806             oldest_frame = NULL;
807           }
808         }
809         g_warning
810             ("%s: %i initial frames were not dequeued: bug in decoder -- please file a bug",
811             GST_ELEMENT_NAME (decoder), counter);
812       }
813     }
814     if (oldest_frame)
815       gst_video_codec_frame_unref (oldest_frame);
816
817     frame->duration = self->v4l2capture->duration;
818     frame->output_buffer = buffer;
819     buffer = NULL;
820     ret = gst_video_decoder_finish_frame (decoder, frame);
821
822     if (ret != GST_FLOW_OK)
823       goto beach;
824   } else {
825     GST_WARNING_OBJECT (decoder, "Decoder is producing too many buffers");
826     gst_buffer_unref (buffer);
827   }
828
829   return;
830
831 beach:
832   GST_DEBUG_OBJECT (decoder, "Leaving output thread: %s",
833       gst_flow_get_name (ret));
834
835   gst_buffer_replace (&buffer, NULL);
836   self->output_flow = ret;
837   gst_v4l2_object_unlock (self->v4l2output);
838   gst_pad_pause_task (decoder->srcpad);
839 }
840
841 static GstFlowReturn
842 gst_v4l2_video_dec_handle_frame (GstVideoDecoder * decoder,
843     GstVideoCodecFrame * frame)
844 {
845   GstV4l2Error error = GST_V4L2_ERROR_INIT;
846   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
847   GstBufferPool *pool = gst_v4l2_object_get_buffer_pool (self->v4l2output);
848   GstFlowReturn ret = GST_FLOW_OK;
849   gboolean processed = FALSE;
850   GstBuffer *tmp;
851   GstTaskState task_state;
852
853   GST_DEBUG_OBJECT (self, "Handling frame %d", frame->system_frame_number);
854
855   if (G_UNLIKELY (!g_atomic_int_get (&self->active)))
856     goto flushing;
857
858   if (G_UNLIKELY (!GST_V4L2_IS_ACTIVE (self->v4l2output))) {
859     if (!self->input_state)
860       goto not_negotiated;
861     if (!gst_v4l2_object_set_format (self->v4l2output, self->input_state->caps,
862             &error))
863       goto not_negotiated;
864   }
865
866   if (!g_atomic_int_get (&self->capture_configuration_change)) {
867     ret = gst_v4l2_video_dec_setup_capture (decoder);
868     if (ret != GST_FLOW_OK) {
869       GST_ERROR_OBJECT (decoder, "setup capture fail\n");
870       goto not_negotiated;
871     }
872   }
873
874   if (G_UNLIKELY (!gst_buffer_pool_is_active (pool))) {
875     GstBuffer *codec_data;
876     GstStructure *config = gst_buffer_pool_get_config (pool);
877     guint min = MAX (self->v4l2output->min_buffers,
878         GST_V4L2_MIN_BUFFERS (self->v4l2output));
879     guint max = VIDEO_MAX_FRAME;
880     guint32 dummy_frame_number = 0;
881
882     GST_DEBUG_OBJECT (self, "Sending header");
883     codec_data = self->input_state->codec_data;
884
885     /* We are running in byte-stream mode, so we don't know the headers, but
886      * we need to send something, otherwise the decoder will refuse to
887      * initialize.
888      */
889     if (codec_data) {
890       gst_buffer_ref (codec_data);
891     } else {
892       codec_data = gst_buffer_ref (frame->input_buffer);
893       processed = TRUE;
894     }
895
896     /* Ensure input internal pool is active */
897
898     gst_buffer_pool_config_set_params (config, self->input_state->caps,
899         self->v4l2output->info.size, min, max);
900
901     /* There is no reason to refuse this config */
902     if (!gst_buffer_pool_set_config (pool, config)) {
903       config = gst_buffer_pool_get_config (pool);
904
905       if (!gst_buffer_pool_config_validate_params (config,
906               self->input_state->caps, self->v4l2output->info.size, min, max)) {
907         gst_structure_free (config);
908         goto activate_failed;
909       }
910
911       if (!gst_buffer_pool_set_config (pool, config))
912         goto activate_failed;
913     }
914
915     if (!gst_buffer_pool_set_active (pool, TRUE))
916       goto activate_failed;
917
918     GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
919     GST_LOG_OBJECT (decoder, "Passing buffer with system frame number %u",
920         processed ? frame->system_frame_number : 0);
921     ret =
922         gst_v4l2_buffer_pool_process (GST_V4L2_BUFFER_POOL (pool), &codec_data,
923         processed ? &frame->system_frame_number : &dummy_frame_number);
924     GST_VIDEO_DECODER_STREAM_LOCK (decoder);
925
926     gst_buffer_unref (codec_data);
927   }
928
929   task_state = gst_pad_get_task_state (GST_VIDEO_DECODER_SRC_PAD (self));
930   if (task_state == GST_TASK_STOPPED || task_state == GST_TASK_PAUSED) {
931     /* It's possible that the processing thread stopped due to an error */
932     if (self->output_flow != GST_FLOW_OK &&
933         self->output_flow != GST_FLOW_FLUSHING) {
934       GST_DEBUG_OBJECT (self, "Processing loop stopped with error, leaving");
935       ret = self->output_flow;
936       goto drop;
937     }
938
939     GST_DEBUG_OBJECT (self, "Starting decoding thread");
940
941     /* Start the processing task, when it quits, the task will disable input
942      * processing to unlock input if draining, or prevent potential block */
943     self->output_flow = GST_FLOW_FLUSHING;
944     if (!gst_pad_start_task (decoder->srcpad,
945             (GstTaskFunction) gst_v4l2_video_dec_loop, self, NULL))
946       goto start_task_failed;
947   }
948
949   if (!processed) {
950     GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
951     GST_LOG_OBJECT (decoder, "Passing buffer with system frame number %u",
952         frame->system_frame_number);
953     ret =
954         gst_v4l2_buffer_pool_process (GST_V4L2_BUFFER_POOL (pool),
955         &frame->input_buffer, &frame->system_frame_number);
956     GST_VIDEO_DECODER_STREAM_LOCK (decoder);
957
958     if (ret == GST_FLOW_FLUSHING) {
959       if (gst_pad_get_task_state (GST_VIDEO_DECODER_SRC_PAD (self)) !=
960           GST_TASK_STARTED)
961         ret = self->output_flow;
962       goto drop;
963     } else if (ret != GST_FLOW_OK) {
964       goto process_failed;
965     }
966   }
967
968   /* No need to keep input around */
969   tmp = frame->input_buffer;
970   frame->input_buffer = gst_buffer_new ();
971   gst_buffer_copy_into (frame->input_buffer, tmp,
972       GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_TIMESTAMPS |
973       GST_BUFFER_COPY_META, 0, 0);
974   gst_buffer_unref (tmp);
975
976   gst_video_codec_frame_unref (frame);
977   if (pool)
978     gst_object_unref (pool);
979   return ret;
980
981   /* ERRORS */
982 not_negotiated:
983   {
984     GST_ERROR_OBJECT (self, "not negotiated");
985     ret = GST_FLOW_NOT_NEGOTIATED;
986     gst_v4l2_error (self, &error);
987     goto drop;
988   }
989 activate_failed:
990   {
991     GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
992         (_("Failed to allocate required memory.")),
993         ("Buffer pool activation failed"));
994     ret = GST_FLOW_ERROR;
995     goto drop;
996   }
997 flushing:
998   {
999     ret = GST_FLOW_FLUSHING;
1000     goto drop;
1001   }
1002
1003 start_task_failed:
1004   {
1005     GST_ELEMENT_ERROR (self, RESOURCE, FAILED,
1006         (_("Failed to start decoding thread.")), (NULL));
1007     ret = GST_FLOW_ERROR;
1008     goto drop;
1009   }
1010 process_failed:
1011   {
1012     GST_ELEMENT_ERROR (self, RESOURCE, FAILED,
1013         (_("Failed to process frame.")),
1014         ("Maybe be due to not enough memory or failing driver"));
1015     ret = GST_FLOW_ERROR;
1016     goto drop;
1017   }
1018 drop:
1019   {
1020     if (pool)
1021       gst_object_unref (pool);
1022     gst_video_decoder_drop_frame (decoder, frame);
1023     return ret;
1024   }
1025 }
1026
1027 static gboolean
1028 gst_v4l2_video_dec_decide_allocation (GstVideoDecoder * decoder,
1029     GstQuery * query)
1030 {
1031   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
1032   GstClockTime latency;
1033   gboolean ret = FALSE;
1034
1035   if (gst_v4l2_object_decide_allocation (self->v4l2capture, query))
1036     ret = GST_VIDEO_DECODER_CLASS (parent_class)->decide_allocation (decoder,
1037         query);
1038
1039   if (GST_CLOCK_TIME_IS_VALID (self->v4l2capture->duration)) {
1040     latency = self->v4l2capture->min_buffers * self->v4l2capture->duration;
1041     GST_DEBUG_OBJECT (self, "Setting latency: %" GST_TIME_FORMAT " (%"
1042         G_GUINT32_FORMAT " * %" G_GUINT64_FORMAT, GST_TIME_ARGS (latency),
1043         self->v4l2capture->min_buffers, self->v4l2capture->duration);
1044     gst_video_decoder_set_latency (decoder, latency, latency);
1045   } else {
1046     GST_WARNING_OBJECT (self, "Duration invalid, not setting latency");
1047   }
1048
1049   return ret;
1050 }
1051
1052 static gboolean
1053 gst_v4l2_video_dec_src_query (GstVideoDecoder * decoder, GstQuery * query)
1054 {
1055   gboolean ret = TRUE;
1056   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
1057
1058   switch (GST_QUERY_TYPE (query)) {
1059     case GST_QUERY_CAPS:{
1060       GstCaps *filter, *result = NULL;
1061       GstPad *pad = GST_VIDEO_DECODER_SRC_PAD (decoder);
1062
1063       gst_query_parse_caps (query, &filter);
1064
1065       if (self->probed_srccaps)
1066         result = gst_caps_ref (self->probed_srccaps);
1067       else
1068         result = gst_pad_get_pad_template_caps (pad);
1069
1070       if (filter) {
1071         GstCaps *tmp = result;
1072         result =
1073             gst_caps_intersect_full (filter, tmp, GST_CAPS_INTERSECT_FIRST);
1074         gst_caps_unref (tmp);
1075       }
1076
1077       GST_DEBUG_OBJECT (self, "Returning src caps %" GST_PTR_FORMAT, result);
1078
1079       gst_query_set_caps_result (query, result);
1080       gst_caps_unref (result);
1081       break;
1082     }
1083
1084     default:
1085       ret = GST_VIDEO_DECODER_CLASS (parent_class)->src_query (decoder, query);
1086       break;
1087   }
1088
1089   return ret;
1090 }
1091
1092 static GstCaps *
1093 gst_v4l2_video_dec_sink_getcaps (GstVideoDecoder * decoder, GstCaps * filter)
1094 {
1095   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
1096   GstCaps *result;
1097
1098   result = gst_video_decoder_proxy_getcaps (decoder, self->probed_sinkcaps,
1099       filter);
1100
1101   GST_DEBUG_OBJECT (self, "Returning sink caps %" GST_PTR_FORMAT, result);
1102
1103   return result;
1104 }
1105
1106 static gboolean
1107 gst_v4l2_video_dec_sink_event (GstVideoDecoder * decoder, GstEvent * event)
1108 {
1109   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
1110   gboolean ret;
1111   GstEventType type = GST_EVENT_TYPE (event);
1112
1113   switch (type) {
1114     case GST_EVENT_FLUSH_START:
1115       GST_DEBUG_OBJECT (self, "flush start");
1116       gst_v4l2_object_unlock (self->v4l2output);
1117       gst_v4l2_object_unlock (self->v4l2capture);
1118       break;
1119     default:
1120       break;
1121   }
1122
1123   ret = GST_VIDEO_DECODER_CLASS (parent_class)->sink_event (decoder, event);
1124
1125   switch (type) {
1126     case GST_EVENT_FLUSH_START:
1127       /* The processing thread should stop now, wait for it */
1128       gst_pad_stop_task (decoder->srcpad);
1129       GST_DEBUG_OBJECT (self, "flush start done");
1130       break;
1131     default:
1132       break;
1133   }
1134
1135   return ret;
1136 }
1137
1138 static GstStateChangeReturn
1139 gst_v4l2_video_dec_change_state (GstElement * element,
1140     GstStateChange transition)
1141 {
1142   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (element);
1143   GstVideoDecoder *decoder = GST_VIDEO_DECODER (element);
1144
1145   if (transition == GST_STATE_CHANGE_PAUSED_TO_READY) {
1146     g_atomic_int_set (&self->active, FALSE);
1147     gst_v4l2_object_unlock (self->v4l2output);
1148     gst_v4l2_object_unlock (self->v4l2capture);
1149     gst_pad_stop_task (decoder->srcpad);
1150   }
1151
1152   return GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1153 }
1154
1155 static void
1156 gst_v4l2_video_dec_dispose (GObject * object)
1157 {
1158   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (object);
1159
1160   gst_caps_replace (&self->probed_sinkcaps, NULL);
1161   gst_caps_replace (&self->probed_srccaps, NULL);
1162
1163   G_OBJECT_CLASS (parent_class)->dispose (object);
1164 }
1165
1166 static void
1167 gst_v4l2_video_dec_finalize (GObject * object)
1168 {
1169   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (object);
1170
1171   gst_v4l2_object_destroy (self->v4l2capture);
1172   gst_v4l2_object_destroy (self->v4l2output);
1173
1174   G_OBJECT_CLASS (parent_class)->finalize (object);
1175 }
1176
1177 static void
1178 gst_v4l2_video_dec_init (GstV4l2VideoDec * self)
1179 {
1180   /* V4L2 object are created in subinstance_init */
1181 }
1182
1183 static void
1184 gst_v4l2_video_dec_subinstance_init (GTypeInstance * instance, gpointer g_class)
1185 {
1186   GstV4l2VideoDecClass *klass = GST_V4L2_VIDEO_DEC_CLASS (g_class);
1187   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (instance);
1188   GstVideoDecoder *decoder = GST_VIDEO_DECODER (instance);
1189
1190   gst_video_decoder_set_packetized (decoder, TRUE);
1191
1192   self->v4l2output = gst_v4l2_object_new (GST_ELEMENT (self),
1193       GST_OBJECT (GST_VIDEO_DECODER_SINK_PAD (self)),
1194       V4L2_BUF_TYPE_VIDEO_OUTPUT, klass->default_device,
1195       gst_v4l2_get_output, gst_v4l2_set_output, NULL);
1196   self->v4l2output->no_initial_format = TRUE;
1197   self->v4l2output->keep_aspect = FALSE;
1198
1199   self->v4l2capture = gst_v4l2_object_new (GST_ELEMENT (self),
1200       GST_OBJECT (GST_VIDEO_DECODER_SRC_PAD (self)),
1201       V4L2_BUF_TYPE_VIDEO_CAPTURE, klass->default_device,
1202       gst_v4l2_get_input, gst_v4l2_set_input, NULL);
1203 }
1204
1205 static void
1206 gst_v4l2_video_dec_class_init (GstV4l2VideoDecClass * klass)
1207 {
1208   GstElementClass *element_class;
1209   GObjectClass *gobject_class;
1210   GstVideoDecoderClass *video_decoder_class;
1211
1212   parent_class = g_type_class_peek_parent (klass);
1213
1214   element_class = (GstElementClass *) klass;
1215   gobject_class = (GObjectClass *) klass;
1216   video_decoder_class = (GstVideoDecoderClass *) klass;
1217
1218   GST_DEBUG_CATEGORY_INIT (gst_v4l2_video_dec_debug, "v4l2videodec", 0,
1219       "V4L2 Video Decoder");
1220
1221   gobject_class->dispose = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_dispose);
1222   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_finalize);
1223   gobject_class->set_property =
1224       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_set_property);
1225   gobject_class->get_property =
1226       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_get_property);
1227
1228   video_decoder_class->open = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_open);
1229   video_decoder_class->close = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_close);
1230   video_decoder_class->start = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_start);
1231   video_decoder_class->stop = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_stop);
1232   video_decoder_class->finish = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_finish);
1233   video_decoder_class->flush = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_flush);
1234   video_decoder_class->drain = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_drain);
1235   video_decoder_class->set_format =
1236       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_set_format);
1237   video_decoder_class->negotiate =
1238       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_negotiate);
1239   video_decoder_class->decide_allocation =
1240       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_decide_allocation);
1241   /* FIXME propose_allocation or not ? */
1242   video_decoder_class->handle_frame =
1243       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_handle_frame);
1244   video_decoder_class->getcaps =
1245       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_sink_getcaps);
1246   video_decoder_class->src_query =
1247       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_src_query);
1248   video_decoder_class->sink_event =
1249       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_sink_event);
1250
1251   element_class->change_state =
1252       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_change_state);
1253
1254   gst_v4l2_object_install_m2m_properties_helper (gobject_class);
1255 }
1256
1257 static void
1258 gst_v4l2_video_dec_subclass_init (gpointer g_class, gpointer data)
1259 {
1260   GstV4l2VideoDecClass *klass = GST_V4L2_VIDEO_DEC_CLASS (g_class);
1261   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
1262   GstV4l2VideoDecCData *cdata = data;
1263
1264   klass->default_device = cdata->device;
1265
1266   gst_element_class_add_pad_template (element_class,
1267       gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
1268           cdata->sink_caps));
1269   gst_element_class_add_pad_template (element_class,
1270       gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
1271           cdata->src_caps));
1272
1273   gst_element_class_set_metadata (element_class, cdata->longname,
1274       "Codec/Decoder/Video/Hardware", cdata->description,
1275       "Nicolas Dufresne <nicolas.dufresne@collabora.com>");
1276
1277   gst_caps_unref (cdata->sink_caps);
1278   gst_caps_unref (cdata->src_caps);
1279   g_free (cdata);
1280 }
1281
1282 /* Probing functions */
1283 gboolean
1284 gst_v4l2_is_video_dec (GstCaps * sink_caps, GstCaps * src_caps)
1285 {
1286   gboolean ret = FALSE;
1287
1288   if (gst_caps_is_subset (sink_caps, gst_v4l2_object_get_codec_caps ())
1289       && gst_caps_is_subset (src_caps, gst_v4l2_object_get_raw_caps ()))
1290     ret = TRUE;
1291
1292   return ret;
1293 }
1294
1295 static gchar *
1296 gst_v4l2_video_dec_set_metadata (GstStructure * s, GstV4l2VideoDecCData * cdata,
1297     const gchar * basename)
1298 {
1299   gchar *codec_name = NULL;
1300   gchar *type_name = NULL;
1301
1302 #define SET_META(codec) \
1303 G_STMT_START { \
1304   cdata->longname = "V4L2 " codec " Decoder"; \
1305   cdata->description = "Decodes " codec " streams via V4L2 API"; \
1306   codec_name = g_ascii_strdown (codec, -1); \
1307 } G_STMT_END
1308
1309   if (gst_structure_has_name (s, "image/jpeg")) {
1310     SET_META ("JPEG");
1311   } else if (gst_structure_has_name (s, "video/mpeg")) {
1312     gint mpegversion = 0;
1313     gst_structure_get_int (s, "mpegversion", &mpegversion);
1314
1315     if (mpegversion == 2) {
1316       SET_META ("MPEG2");
1317       cdata->codec = gst_v4l2_mpeg2_get_codec ();
1318     } else {
1319       SET_META ("MPEG4");
1320       cdata->codec = gst_v4l2_mpeg4_get_codec ();
1321     }
1322   } else if (gst_structure_has_name (s, "video/x-h263")) {
1323     SET_META ("H263");
1324   } else if (gst_structure_has_name (s, "video/x-fwht")) {
1325     SET_META ("FWHT");
1326   } else if (gst_structure_has_name (s, "video/x-h264")) {
1327     SET_META ("H264");
1328     cdata->codec = gst_v4l2_h264_get_codec ();
1329   } else if (gst_structure_has_name (s, "video/x-h265")) {
1330     SET_META ("H265");
1331     cdata->codec = gst_v4l2_h265_get_codec ();
1332   } else if (gst_structure_has_name (s, "video/x-wmv")) {
1333     SET_META ("VC1");
1334   } else if (gst_structure_has_name (s, "video/x-vp8")) {
1335     SET_META ("VP8");
1336     cdata->codec = gst_v4l2_vp8_get_codec ();
1337   } else if (gst_structure_has_name (s, "video/x-vp9")) {
1338     SET_META ("VP9");
1339     cdata->codec = gst_v4l2_vp9_get_codec ();
1340   } else if (gst_structure_has_name (s, "video/x-bayer")) {
1341     SET_META ("BAYER");
1342   } else if (gst_structure_has_name (s, "video/x-sonix")) {
1343     SET_META ("SONIX");
1344   } else if (gst_structure_has_name (s, "video/x-pwc1")) {
1345     SET_META ("PWC1");
1346   } else if (gst_structure_has_name (s, "video/x-pwc2")) {
1347     SET_META ("PWC2");
1348   } else {
1349     /* This code should be kept on sync with the exposed CODEC type of format
1350      * from gstv4l2object.c. This warning will only occur in case we forget
1351      * to also add a format here. */
1352     gchar *s_str = gst_structure_to_string (s);
1353     g_warning ("Missing fixed name mapping for caps '%s', this is a GStreamer "
1354         "bug, please report at https://bugs.gnome.org", s_str);
1355     g_free (s_str);
1356   }
1357
1358   if (codec_name) {
1359     type_name = g_strdup_printf ("v4l2%sdec", codec_name);
1360     if (g_type_from_name (type_name) != 0) {
1361       g_free (type_name);
1362       type_name = g_strdup_printf ("v4l2%s%sdec", basename, codec_name);
1363     }
1364
1365     g_free (codec_name);
1366   }
1367
1368   return type_name;
1369 #undef SET_META
1370 }
1371
1372 void
1373 gst_v4l2_video_dec_register (GstPlugin * plugin, const gchar * basename,
1374     const gchar * device_path, gint video_fd, GstCaps * sink_caps,
1375     GstCaps * src_caps)
1376 {
1377   gint i;
1378
1379   for (i = 0; i < gst_caps_get_size (sink_caps); i++) {
1380     GstV4l2VideoDecCData *cdata;
1381     GstStructure *s;
1382     GTypeQuery type_query;
1383     GTypeInfo type_info = { 0, };
1384     GType type, subtype;
1385     gchar *type_name;
1386
1387     s = gst_caps_get_structure (sink_caps, i);
1388
1389     cdata = g_new0 (GstV4l2VideoDecCData, 1);
1390     cdata->device = g_strdup (device_path);
1391     cdata->sink_caps = gst_caps_new_empty ();
1392     gst_caps_append_structure (cdata->sink_caps, gst_structure_copy (s));
1393     cdata->src_caps = gst_caps_ref (src_caps);
1394     type_name = gst_v4l2_video_dec_set_metadata (s, cdata, basename);
1395
1396     /* Skip over if we hit an unmapped type */
1397     if (!type_name) {
1398       g_free (cdata);
1399       continue;
1400     }
1401
1402     if (cdata->codec != NULL && cdata->codec != gst_v4l2_vp8_get_codec ()
1403         && cdata->codec != gst_v4l2_vp9_get_codec ()) {
1404       GValue value = G_VALUE_INIT;
1405
1406       if (gst_v4l2_codec_probe_levels (cdata->codec, video_fd, &value)) {
1407         gst_caps_set_value (cdata->sink_caps, "level", &value);
1408         g_value_unset (&value);
1409       }
1410
1411       if (gst_v4l2_codec_probe_profiles (cdata->codec, video_fd, &value)) {
1412         gst_caps_set_value (cdata->sink_caps, "profile", &value);
1413         g_value_unset (&value);
1414       }
1415     }
1416
1417     type = gst_v4l2_video_dec_get_type ();
1418     g_type_query (type, &type_query);
1419     memset (&type_info, 0, sizeof (type_info));
1420     type_info.class_size = type_query.class_size;
1421     type_info.instance_size = type_query.instance_size;
1422     type_info.class_init = gst_v4l2_video_dec_subclass_init;
1423     type_info.class_data = cdata;
1424     type_info.instance_init = gst_v4l2_video_dec_subinstance_init;
1425
1426     subtype = g_type_register_static (type, type_name, &type_info, 0);
1427     if (!gst_element_register (plugin, type_name, GST_RANK_PRIMARY + 1,
1428             subtype))
1429       GST_WARNING ("Failed to register plugin '%s'", type_name);
1430
1431     g_free (type_name);
1432   }
1433 }