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