v4l2videodec: Correctly free caps to avoid memory leak
[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     goto use_acquired_caps;
470
471   /* Fixate pixel format */
472   caps = gst_caps_fixate (caps);
473
474   GST_DEBUG_OBJECT (self, "Chosen decoded caps: %" GST_PTR_FORMAT, caps);
475
476   /* Try to set negotiated format, on success replace acquired format */
477   if (gst_v4l2_object_set_format (self->v4l2capture, caps, &error))
478     gst_video_info_from_caps (&info, caps);
479   else
480     gst_v4l2_clear_error (&error);
481
482 use_acquired_caps:
483   gst_caps_unref (acquired_caps);
484   gst_caps_unref (caps);
485
486   /* catch possible bogus driver that don't enumerate the format it actually
487    * returned from G_FMT */
488   if (!self->v4l2capture->fmtdesc)
489     goto not_negotiated;
490
491   output_state = gst_video_decoder_set_output_state (decoder,
492       info.finfo->format, info.width, info.height, self->input_state);
493
494   /* Copy the rest of the information, there might be more in the future */
495   output_state->info.interlace_mode = info.interlace_mode;
496   output_state->info.colorimetry = info.colorimetry;
497   gst_video_codec_state_unref (output_state);
498
499   ret = GST_VIDEO_DECODER_CLASS (parent_class)->negotiate (decoder);
500   if (!ret)
501     goto not_negotiated;
502
503   /* The pool may be created through gst_video_decoder_negotiate(), so must
504    * be kept after */
505   cpool = gst_v4l2_object_get_buffer_pool (self->v4l2capture);
506   gst_v4l2_buffer_pool_enable_resolution_change (GST_V4L2_BUFFER_POOL (cpool));
507
508   /* Ensure our internal pool is activated */
509   active = gst_buffer_pool_set_active (cpool, TRUE);
510   if (cpool)
511     gst_object_unref (cpool);
512   if (!active)
513     goto activate_failed;
514
515   return TRUE;
516
517 not_negotiated:
518   GST_ERROR_OBJECT (self, "not negotiated");
519   gst_v4l2_error (self, &error);
520   gst_v4l2_object_stop (self->v4l2capture);
521   return FALSE;
522 activate_failed:
523   GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
524       (_("Failed to allocate required memory.")),
525       ("Buffer pool activation failed"));
526   gst_v4l2_object_stop (self->v4l2capture);
527   return FALSE;
528 }
529
530 static gboolean
531 gst_v4l2_decoder_cmd (GstV4l2Object * v4l2object, guint cmd, guint flags)
532 {
533   struct v4l2_decoder_cmd dcmd = { 0, };
534
535   GST_DEBUG_OBJECT (v4l2object->element,
536       "sending v4l2 decoder command %u with flags %u", cmd, flags);
537
538   if (!GST_V4L2_IS_OPEN (v4l2object))
539     return FALSE;
540
541   dcmd.cmd = cmd;
542   dcmd.flags = flags;
543   if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_DECODER_CMD, &dcmd) < 0)
544     goto dcmd_failed;
545
546   return TRUE;
547
548 dcmd_failed:
549   if (errno == ENOTTY) {
550     GST_INFO_OBJECT (v4l2object->element,
551         "Failed to send decoder command %u with flags %u for '%s'. (%s)",
552         cmd, flags, v4l2object->videodev, g_strerror (errno));
553   } else {
554     GST_ERROR_OBJECT (v4l2object->element,
555         "Failed to send decoder command %u with flags %u for '%s'. (%s)",
556         cmd, flags, v4l2object->videodev, g_strerror (errno));
557   }
558   return FALSE;
559 }
560
561 static GstFlowReturn
562 gst_v4l2_video_dec_finish (GstVideoDecoder * decoder)
563 {
564   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
565   GstFlowReturn ret = GST_FLOW_OK;
566   GstBuffer *buffer;
567   GList *pending_frames = NULL;
568
569   if (gst_pad_get_task_state (decoder->srcpad) != GST_TASK_STARTED)
570     goto done;
571
572   GST_DEBUG_OBJECT (self, "Finishing decoding");
573
574   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
575
576   /* If we are in the middle of a source change, cancel it */
577   self->draining = FALSE;
578
579   if (gst_v4l2_decoder_cmd (self->v4l2output, V4L2_DEC_CMD_STOP, 0)) {
580     GstTask *task;
581
582     GST_OBJECT_LOCK (decoder->srcpad);
583     task = GST_PAD_TASK (decoder->srcpad);
584     if (task)
585       gst_object_ref (task);
586     GST_OBJECT_UNLOCK (decoder->srcpad);
587
588     if (task) {
589       /* If the decoder stop command succeeded, just wait until processing is
590        * finished */
591       GST_DEBUG_OBJECT (self, "Waiting for decoder stop");
592       GST_OBJECT_LOCK (task);
593       while (GST_TASK_STATE (task) == GST_TASK_STARTED)
594         GST_TASK_WAIT (task);
595       GST_OBJECT_UNLOCK (task);
596
597       ret = GST_FLOW_FLUSHING;
598       gst_object_unref (task);
599     }
600   } else {
601     GstBufferPool *opool = gst_v4l2_object_get_buffer_pool (self->v4l2output);
602     /* otherwise keep queuing empty buffers until the processing thread has
603      * stopped, _pool_process() will return FLUSHING when that happened */
604     while (ret == GST_FLOW_OK) {
605       buffer = gst_buffer_new ();
606       ret =
607           gst_v4l2_buffer_pool_process (GST_V4L2_BUFFER_POOL (opool), &buffer,
608           NULL);
609       gst_buffer_unref (buffer);
610     }
611     if (opool)
612       gst_object_unref (opool);
613   }
614
615   /* and ensure the processing thread has stopped in case another error
616    * occurred. */
617   gst_v4l2_object_unlock (self->v4l2capture);
618   gst_pad_stop_task (decoder->srcpad);
619   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
620
621   if (ret == GST_FLOW_FLUSHING)
622     ret = self->output_flow;
623
624   GST_DEBUG_OBJECT (decoder, "Done draining buffers");
625
626   /* Draining of the capture buffer has completed.
627    * If any pending frames remain at this point there is a decoder error.
628    * This has been observed as a driver bug, where eos is sent too early.
629    * These frames will never be rendered, so drop them now with a warning */
630
631   pending_frames = gst_video_decoder_get_frames (decoder);
632   if (pending_frames) {
633     int counter = 0;
634     guint32 first, last;
635     for (GList * g = pending_frames; g; g = g->next) {
636       GstVideoCodecFrame *frame = g->data;
637       g->data = NULL;
638       last = frame->system_frame_number;
639       if (!counter)
640         first = last;
641       counter++;
642       gst_video_decoder_drop_frame (decoder, frame);
643     }
644     if (self->output_flow == GST_FLOW_OK) {
645       g_warning ("%s: %i frames %u-%u left undrained after CMD_STOP, "
646           "eos sent too early: bug in decoder -- please file a bug",
647           GST_ELEMENT_NAME (decoder), counter, first, last);
648     }
649     if (pending_frames)
650       g_list_free (pending_frames);
651   }
652
653 done:
654   return ret;
655 }
656
657 static GstFlowReturn
658 gst_v4l2_video_dec_drain (GstVideoDecoder * decoder)
659 {
660   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
661
662   GST_DEBUG_OBJECT (self, "Draining...");
663   gst_v4l2_video_dec_finish (decoder);
664   gst_v4l2_video_dec_flush (decoder);
665
666   return GST_FLOW_OK;
667 }
668
669 static gboolean
670 check_system_frame_number_too_old (guint32 current, guint32 old)
671 {
672   guint32 absdiff = current > old ? current - old : old - current;
673
674   /* More than 100 frames in the past, or current wrapped around */
675   if (absdiff > 100) {
676     /* Wraparound and difference is actually smaller than 100 */
677     if (absdiff > G_MAXUINT32 - 100)
678       return FALSE;
679     return TRUE;
680   }
681
682   return FALSE;
683 }
684
685 /* Only used initially to wait for a SRC_CH event
686  * called with decoder stream lock */
687 static GstFlowReturn
688 gst_v4l2_video_dec_wait_for_src_ch (GstV4l2VideoDec * self)
689 {
690   GstFlowReturn flowret;
691
692   if (!self->wait_for_source_change)
693     return GST_FLOW_OK;
694
695   GST_DEBUG_OBJECT (self, "Waiting for source change event");
696
697   GST_VIDEO_DECODER_STREAM_UNLOCK (GST_VIDEO_DECODER (self));
698   flowret = gst_v4l2_object_poll (self->v4l2capture, GST_CLOCK_TIME_NONE);
699   GST_VIDEO_DECODER_STREAM_LOCK (GST_VIDEO_DECODER (self));
700
701   /* Fix the flow return value, as the poll is watching for buffer, but we are
702    * looking for the source change event */
703   if (flowret == GST_V4L2_FLOW_RESOLUTION_CHANGE) {
704     self->wait_for_source_change = FALSE;
705     flowret = GST_FLOW_OK;
706   } else if (flowret == GST_FLOW_OK) {
707     /* A buffer would be unexpected, in this case just terminate */
708     flowret = GST_V4L2_FLOW_LAST_BUFFER;
709   }
710
711   return flowret;
712 }
713
714 static void
715 gst_v4l2_video_dec_loop (GstVideoDecoder * decoder)
716 {
717   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
718   GstBufferPool *pool;
719   GstVideoCodecFrame *frame;
720   GstBuffer *buffer = NULL;
721   GstFlowReturn ret;
722
723   GST_LOG_OBJECT (self, "Looping.");
724
725   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
726   if (G_UNLIKELY (!GST_V4L2_IS_ACTIVE (self->v4l2capture))) {
727     ret = gst_v4l2_video_dec_wait_for_src_ch (self);
728     if (ret != GST_FLOW_OK) {
729       GST_INFO_OBJECT (decoder, "Polling for source change was interrupted");
730       GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
731       goto beach;
732     }
733
734     GST_DEBUG_OBJECT (decoder, "Setup the capture queue");
735     if (G_UNLIKELY (!GST_V4L2_IS_ACTIVE (self->v4l2capture))) {
736       if (!gst_video_decoder_negotiate (decoder)) {
737         /* FIXME not super nice ? */
738         if (GST_PAD_IS_FLUSHING (decoder->sinkpad)
739             || GST_PAD_IS_FLUSHING (decoder->srcpad)) {
740           ret = GST_FLOW_FLUSHING;
741         } else {
742           ret = GST_FLOW_NOT_NEGOTIATED;
743           GST_ERROR_OBJECT (decoder, "Failed to setup capture queue");
744         }
745         GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
746         goto beach;
747       }
748     }
749
750     /* just a safety, as introducing mistakes in negotiation seems rather
751      * easy.*/
752     g_return_if_fail (GST_V4L2_IS_ACTIVE (self->v4l2capture));
753   }
754   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
755
756   GST_LOG_OBJECT (decoder, "Acquire output buffer");
757
758   self->output_flow = GST_FLOW_OK;
759
760   do {
761     /* We cannot use the base class allotate helper since it taking the internal
762      * stream lock. we know that the acquire may need to poll until more frames
763      * comes in and holding this lock would prevent that.
764      */
765     pool = gst_video_decoder_get_buffer_pool (decoder);
766
767     /* Pool may be NULL if we started going to READY state */
768     if (pool == NULL) {
769       ret = GST_FLOW_FLUSHING;
770       goto beach;
771     }
772
773     ret = gst_buffer_pool_acquire_buffer (pool, &buffer, NULL);
774     g_object_unref (pool);
775
776     if (ret != GST_FLOW_OK)
777       goto beach;
778
779     GST_LOG_OBJECT (decoder, "Process output buffer");
780     {
781       GstV4l2BufferPool *cpool =
782           GST_V4L2_BUFFER_POOL (gst_v4l2_object_get_buffer_pool
783           (self->v4l2capture));
784       ret = gst_v4l2_buffer_pool_process (cpool, &buffer, NULL);
785       if (cpool)
786         gst_object_unref (cpool);
787     }
788   } while (ret == GST_V4L2_FLOW_CORRUPTED_BUFFER);
789
790   if (ret != GST_FLOW_OK)
791     goto beach;
792
793   if (GST_BUFFER_TIMESTAMP (buffer) % GST_SECOND != 0)
794     GST_ERROR_OBJECT (decoder,
795         "Driver bug detected - check driver with v4l2-compliance from http://git.linuxtv.org/v4l-utils.git");
796   GST_LOG_OBJECT (decoder, "Got buffer for frame number %u",
797       (guint32) (GST_BUFFER_TIMESTAMP (buffer) / GST_SECOND));
798
799   frame =
800       gst_video_decoder_get_frame (decoder,
801       GST_BUFFER_TIMESTAMP (buffer) / GST_SECOND);
802   if (frame) {
803     GstVideoCodecFrame *oldest_frame;
804     gboolean warned = FALSE;
805
806     /* Garbage collect old frames in case of codec bugs */
807     while ((oldest_frame = gst_video_decoder_get_oldest_frame (decoder)) &&
808         check_system_frame_number_too_old (frame->system_frame_number,
809             oldest_frame->system_frame_number)) {
810       if (oldest_frame->system_frame_number > 0) {
811         gst_video_decoder_drop_frame (decoder, oldest_frame);
812         oldest_frame = NULL;
813
814         if (!warned) {
815           g_warning ("%s: Too old frames, bug in decoder -- please file a bug",
816               GST_ELEMENT_NAME (decoder));
817           warned = TRUE;
818         }
819       } else {
820         /* special treatment when oldest_frame->system_frame_number = 0:
821          * if a consecutive sequence 0, 1, 2,..., n < frame->system_frame_number
822          * is pending, drop them all at this time. (This has been seen to occur
823          * as a driver bug when the initial frame triggered a Caps re-negotiation,
824          * and the driver dropped these frames) */
825         guint32 counter = 0;
826         while (oldest_frame) {
827           gst_video_decoder_drop_frame (decoder, oldest_frame);
828           counter++;
829           oldest_frame = gst_video_decoder_get_oldest_frame (decoder);
830           if (oldest_frame &&
831               (oldest_frame->system_frame_number > counter ||
832                   oldest_frame->system_frame_number >=
833                   frame->system_frame_number)) {
834             gst_video_codec_frame_unref (oldest_frame);
835             oldest_frame = NULL;
836           }
837         }
838         g_warning
839             ("%s: %i initial frames were not dequeued: bug in decoder -- please file a bug",
840             GST_ELEMENT_NAME (decoder), counter);
841       }
842     }
843     if (oldest_frame)
844       gst_video_codec_frame_unref (oldest_frame);
845
846     frame->duration = self->v4l2capture->duration;
847     frame->output_buffer = buffer;
848     buffer = NULL;
849     ret = gst_video_decoder_finish_frame (decoder, frame);
850
851     if (ret != GST_FLOW_OK)
852       goto beach;
853   } else {
854     GST_WARNING_OBJECT (decoder, "Decoder is producing too many buffers");
855     gst_buffer_unref (buffer);
856   }
857
858   return;
859
860 beach:
861   if (ret == GST_V4L2_FLOW_RESOLUTION_CHANGE) {
862     GST_VIDEO_DECODER_STREAM_LOCK (decoder);
863     self->draining = TRUE;
864     GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
865     GST_INFO_OBJECT (decoder, "Received resolution change");
866     return;
867   }
868
869   if (ret == GST_V4L2_FLOW_LAST_BUFFER) {
870     GST_VIDEO_DECODER_STREAM_LOCK (decoder);
871     if (self->draining) {
872       self->draining = FALSE;
873       gst_v4l2_object_stop (self->v4l2capture);
874       GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
875       return;
876     }
877
878     GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
879   }
880
881   GST_DEBUG_OBJECT (decoder, "Leaving output thread: %s",
882       gst_flow_get_name (ret));
883
884   gst_buffer_replace (&buffer, NULL);
885   self->output_flow = ret;
886   gst_v4l2_object_unlock (self->v4l2output);
887   gst_pad_pause_task (decoder->srcpad);
888 }
889
890 static GstFlowReturn
891 gst_v4l2_video_dec_handle_frame (GstVideoDecoder * decoder,
892     GstVideoCodecFrame * frame)
893 {
894   GstV4l2Error error = GST_V4L2_ERROR_INIT;
895   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
896   GstBufferPool *pool = NULL;
897   GstFlowReturn ret = GST_FLOW_OK;
898   gboolean processed = FALSE;
899   GstBuffer *tmp;
900   GstTaskState task_state;
901
902   GST_DEBUG_OBJECT (self, "Handling frame %d", frame->system_frame_number);
903
904   if (G_UNLIKELY (!g_atomic_int_get (&self->active)))
905     goto flushing;
906
907   if (G_UNLIKELY (!GST_V4L2_IS_ACTIVE (self->v4l2output))) {
908     if (!self->input_state)
909       goto not_negotiated;
910     if (!gst_v4l2_object_set_format (self->v4l2output, self->input_state->caps,
911             &error))
912       goto not_negotiated;
913   }
914
915   pool = gst_v4l2_object_get_buffer_pool (self->v4l2output);
916   if (G_UNLIKELY (!gst_buffer_pool_is_active (pool))) {
917     GstBuffer *codec_data;
918     GstStructure *config = gst_buffer_pool_get_config (pool);
919     guint min = MAX (self->v4l2output->min_buffers,
920         GST_V4L2_MIN_BUFFERS (self->v4l2output));
921     guint max = VIDEO_MAX_FRAME;
922     guint32 dummy_frame_number = 0;
923
924     GST_DEBUG_OBJECT (self, "Sending header");
925     codec_data = self->input_state->codec_data;
926
927     /* We are running in byte-stream mode, so we don't know the headers, but
928      * we need to send something, otherwise the decoder will refuse to
929      * initialize.
930      */
931     if (codec_data) {
932       gst_buffer_ref (codec_data);
933     } else {
934       codec_data = gst_buffer_ref (frame->input_buffer);
935       processed = TRUE;
936     }
937
938     /* Ensure input internal pool is active */
939
940     gst_buffer_pool_config_set_params (config, self->input_state->caps,
941         self->v4l2output->info.size, min, max);
942
943     /* There is no reason to refuse this config */
944     if (!gst_buffer_pool_set_config (pool, config)) {
945       config = gst_buffer_pool_get_config (pool);
946
947       if (!gst_buffer_pool_config_validate_params (config,
948               self->input_state->caps, self->v4l2output->info.size, min, max)) {
949         gst_structure_free (config);
950         goto activate_failed;
951       }
952
953       if (!gst_buffer_pool_set_config (pool, config))
954         goto activate_failed;
955     }
956
957     /* Ensure to unlock capture, as it may be flushing due to previous
958      * unlock/stop calls */
959     gst_v4l2_object_unlock_stop (self->v4l2output);
960     gst_v4l2_object_unlock_stop (self->v4l2capture);
961
962     if (!gst_buffer_pool_set_active (pool, TRUE))
963       goto activate_failed;
964
965     GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
966     GST_LOG_OBJECT (decoder, "Passing buffer with system frame number %u",
967         processed ? frame->system_frame_number : 0);
968     ret =
969         gst_v4l2_buffer_pool_process (GST_V4L2_BUFFER_POOL (pool), &codec_data,
970         processed ? &frame->system_frame_number : &dummy_frame_number);
971     GST_VIDEO_DECODER_STREAM_LOCK (decoder);
972
973     gst_buffer_unref (codec_data);
974
975     /* Only wait for source change if the formats supports it */
976     if (!GST_V4L2_IS_ACTIVE (self->v4l2capture) &&
977         self->v4l2output->fmtdesc->flags & V4L2_FMT_FLAG_DYN_RESOLUTION) {
978       gst_v4l2_object_unlock_stop (self->v4l2capture);
979       self->wait_for_source_change = TRUE;
980     }
981   }
982
983   task_state = gst_pad_get_task_state (GST_VIDEO_DECODER_SRC_PAD (self));
984   if (task_state == GST_TASK_STOPPED || task_state == GST_TASK_PAUSED) {
985     /* It's possible that the processing thread stopped due to an error */
986     if (self->output_flow != GST_FLOW_OK &&
987         self->output_flow != GST_FLOW_FLUSHING) {
988       GST_DEBUG_OBJECT (self, "Processing loop stopped with error, leaving");
989       ret = self->output_flow;
990       goto drop;
991     }
992
993     GST_DEBUG_OBJECT (self, "Starting decoding thread");
994
995     /* Start the processing task, when it quits, the task will disable input
996      * processing to unlock input if draining, or prevent potential block */
997     self->output_flow = GST_FLOW_FLUSHING;
998     self->draining = FALSE;
999     if (!gst_pad_start_task (decoder->srcpad,
1000             (GstTaskFunction) gst_v4l2_video_dec_loop, self, NULL))
1001       goto start_task_failed;
1002   }
1003
1004   if (!processed) {
1005     GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1006     GST_LOG_OBJECT (decoder, "Passing buffer with system frame number %u",
1007         frame->system_frame_number);
1008     ret =
1009         gst_v4l2_buffer_pool_process (GST_V4L2_BUFFER_POOL (pool),
1010         &frame->input_buffer, &frame->system_frame_number);
1011     GST_VIDEO_DECODER_STREAM_LOCK (decoder);
1012
1013     if (ret == GST_FLOW_FLUSHING) {
1014       if (gst_pad_get_task_state (GST_VIDEO_DECODER_SRC_PAD (self)) !=
1015           GST_TASK_STARTED)
1016         ret = self->output_flow;
1017       goto drop;
1018     } else if (ret != GST_FLOW_OK) {
1019       goto process_failed;
1020     }
1021   }
1022
1023   /* No need to keep input around */
1024   tmp = frame->input_buffer;
1025   frame->input_buffer = gst_buffer_new ();
1026   gst_buffer_copy_into (frame->input_buffer, tmp,
1027       GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_TIMESTAMPS |
1028       GST_BUFFER_COPY_META, 0, 0);
1029   gst_buffer_unref (tmp);
1030
1031   gst_video_codec_frame_unref (frame);
1032   if (pool)
1033     gst_object_unref (pool);
1034   return ret;
1035
1036   /* ERRORS */
1037 not_negotiated:
1038   {
1039     GST_ERROR_OBJECT (self, "not negotiated");
1040     ret = GST_FLOW_NOT_NEGOTIATED;
1041     gst_v4l2_error (self, &error);
1042     goto drop;
1043   }
1044 activate_failed:
1045   {
1046     GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
1047         (_("Failed to allocate required memory.")),
1048         ("Buffer pool activation failed"));
1049     ret = GST_FLOW_ERROR;
1050     goto drop;
1051   }
1052 flushing:
1053   {
1054     ret = GST_FLOW_FLUSHING;
1055     goto drop;
1056   }
1057
1058 start_task_failed:
1059   {
1060     GST_ELEMENT_ERROR (self, RESOURCE, FAILED,
1061         (_("Failed to start decoding thread.")), (NULL));
1062     ret = GST_FLOW_ERROR;
1063     goto drop;
1064   }
1065 process_failed:
1066   {
1067     GST_ELEMENT_ERROR (self, RESOURCE, FAILED,
1068         (_("Failed to process frame.")),
1069         ("Maybe be due to not enough memory or failing driver"));
1070     ret = GST_FLOW_ERROR;
1071     goto drop;
1072   }
1073 drop:
1074   {
1075     if (pool)
1076       gst_object_unref (pool);
1077     gst_video_decoder_drop_frame (decoder, frame);
1078     return ret;
1079   }
1080 }
1081
1082 static gboolean
1083 gst_v4l2_video_dec_decide_allocation (GstVideoDecoder * decoder,
1084     GstQuery * query)
1085 {
1086   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
1087   GstClockTime latency;
1088   gboolean ret = FALSE;
1089
1090   if (gst_v4l2_object_decide_allocation (self->v4l2capture, query))
1091     ret = GST_VIDEO_DECODER_CLASS (parent_class)->decide_allocation (decoder,
1092         query);
1093
1094   if (GST_CLOCK_TIME_IS_VALID (self->v4l2capture->duration)) {
1095     latency = self->v4l2capture->min_buffers * self->v4l2capture->duration;
1096     GST_DEBUG_OBJECT (self, "Setting latency: %" GST_TIME_FORMAT " (%"
1097         G_GUINT32_FORMAT " * %" G_GUINT64_FORMAT, GST_TIME_ARGS (latency),
1098         self->v4l2capture->min_buffers, self->v4l2capture->duration);
1099     gst_video_decoder_set_latency (decoder, latency, latency);
1100   } else {
1101     GST_WARNING_OBJECT (self, "Duration invalid, not setting latency");
1102   }
1103
1104   return ret;
1105 }
1106
1107 static gboolean
1108 gst_v4l2_video_dec_src_query (GstVideoDecoder * decoder, GstQuery * query)
1109 {
1110   gboolean ret = TRUE;
1111   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
1112
1113   switch (GST_QUERY_TYPE (query)) {
1114     case GST_QUERY_CAPS:{
1115       GstCaps *filter, *result = NULL;
1116       GstPad *pad = GST_VIDEO_DECODER_SRC_PAD (decoder);
1117
1118       gst_query_parse_caps (query, &filter);
1119
1120       if (self->probed_srccaps)
1121         result = gst_caps_ref (self->probed_srccaps);
1122       else
1123         result = gst_pad_get_pad_template_caps (pad);
1124
1125       if (filter) {
1126         GstCaps *tmp = result;
1127         result =
1128             gst_caps_intersect_full (filter, tmp, GST_CAPS_INTERSECT_FIRST);
1129         gst_caps_unref (tmp);
1130       }
1131
1132       GST_DEBUG_OBJECT (self, "Returning src caps %" GST_PTR_FORMAT, result);
1133
1134       gst_query_set_caps_result (query, result);
1135       gst_caps_unref (result);
1136       break;
1137     }
1138
1139     default:
1140       ret = GST_VIDEO_DECODER_CLASS (parent_class)->src_query (decoder, query);
1141       break;
1142   }
1143
1144   return ret;
1145 }
1146
1147 static GstCaps *
1148 gst_v4l2_video_dec_sink_getcaps (GstVideoDecoder * decoder, GstCaps * filter)
1149 {
1150   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
1151   GstCaps *result;
1152
1153   result = gst_video_decoder_proxy_getcaps (decoder, self->probed_sinkcaps,
1154       filter);
1155
1156   GST_DEBUG_OBJECT (self, "Returning sink caps %" GST_PTR_FORMAT, result);
1157
1158   return result;
1159 }
1160
1161 static gboolean
1162 gst_v4l2_video_dec_sink_event (GstVideoDecoder * decoder, GstEvent * event)
1163 {
1164   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
1165   gboolean ret;
1166   GstEventType type = GST_EVENT_TYPE (event);
1167
1168   switch (type) {
1169     case GST_EVENT_FLUSH_START:
1170       GST_DEBUG_OBJECT (self, "flush start");
1171       gst_v4l2_object_unlock (self->v4l2output);
1172       gst_v4l2_object_unlock (self->v4l2capture);
1173       break;
1174     default:
1175       break;
1176   }
1177
1178   ret = GST_VIDEO_DECODER_CLASS (parent_class)->sink_event (decoder, event);
1179
1180   switch (type) {
1181     case GST_EVENT_FLUSH_START:
1182       /* The processing thread should stop now, wait for it */
1183       gst_pad_stop_task (decoder->srcpad);
1184       GST_DEBUG_OBJECT (self, "flush start done");
1185       break;
1186     default:
1187       break;
1188   }
1189
1190   return ret;
1191 }
1192
1193 static GstStateChangeReturn
1194 gst_v4l2_video_dec_change_state (GstElement * element,
1195     GstStateChange transition)
1196 {
1197   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (element);
1198   GstVideoDecoder *decoder = GST_VIDEO_DECODER (element);
1199
1200   if (transition == GST_STATE_CHANGE_PAUSED_TO_READY) {
1201     g_atomic_int_set (&self->active, FALSE);
1202     gst_v4l2_object_unlock (self->v4l2output);
1203     gst_v4l2_object_unlock (self->v4l2capture);
1204     gst_pad_stop_task (decoder->srcpad);
1205   }
1206
1207   return GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1208 }
1209
1210 static void
1211 gst_v4l2_video_dec_dispose (GObject * object)
1212 {
1213   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (object);
1214
1215   gst_caps_replace (&self->probed_sinkcaps, NULL);
1216   gst_caps_replace (&self->probed_srccaps, NULL);
1217
1218   G_OBJECT_CLASS (parent_class)->dispose (object);
1219 }
1220
1221 static void
1222 gst_v4l2_video_dec_finalize (GObject * object)
1223 {
1224   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (object);
1225
1226   gst_v4l2_object_destroy (self->v4l2capture);
1227   gst_v4l2_object_destroy (self->v4l2output);
1228
1229   G_OBJECT_CLASS (parent_class)->finalize (object);
1230 }
1231
1232 static void
1233 gst_v4l2_video_dec_init (GstV4l2VideoDec * self)
1234 {
1235   /* V4L2 object are created in subinstance_init */
1236 }
1237
1238 static void
1239 gst_v4l2_video_dec_subinstance_init (GTypeInstance * instance, gpointer g_class)
1240 {
1241   GstV4l2VideoDecClass *klass = GST_V4L2_VIDEO_DEC_CLASS (g_class);
1242   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (instance);
1243   GstVideoDecoder *decoder = GST_VIDEO_DECODER (instance);
1244
1245   gst_video_decoder_set_packetized (decoder, TRUE);
1246
1247   self->v4l2output = gst_v4l2_object_new (GST_ELEMENT (self),
1248       GST_OBJECT (GST_VIDEO_DECODER_SINK_PAD (self)),
1249       V4L2_BUF_TYPE_VIDEO_OUTPUT, klass->default_device,
1250       gst_v4l2_get_output, gst_v4l2_set_output, NULL);
1251   self->v4l2output->no_initial_format = TRUE;
1252   self->v4l2output->keep_aspect = FALSE;
1253
1254   self->v4l2capture = gst_v4l2_object_new (GST_ELEMENT (self),
1255       GST_OBJECT (GST_VIDEO_DECODER_SRC_PAD (self)),
1256       V4L2_BUF_TYPE_VIDEO_CAPTURE, klass->default_device,
1257       gst_v4l2_get_input, gst_v4l2_set_input, NULL);
1258 }
1259
1260 static void
1261 gst_v4l2_video_dec_class_init (GstV4l2VideoDecClass * klass)
1262 {
1263   GstElementClass *element_class;
1264   GObjectClass *gobject_class;
1265   GstVideoDecoderClass *video_decoder_class;
1266
1267   parent_class = g_type_class_peek_parent (klass);
1268
1269   element_class = (GstElementClass *) klass;
1270   gobject_class = (GObjectClass *) klass;
1271   video_decoder_class = (GstVideoDecoderClass *) klass;
1272
1273   GST_DEBUG_CATEGORY_INIT (gst_v4l2_video_dec_debug, "v4l2videodec", 0,
1274       "V4L2 Video Decoder");
1275
1276   gobject_class->dispose = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_dispose);
1277   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_finalize);
1278   gobject_class->set_property =
1279       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_set_property);
1280   gobject_class->get_property =
1281       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_get_property);
1282
1283   video_decoder_class->open = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_open);
1284   video_decoder_class->close = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_close);
1285   video_decoder_class->start = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_start);
1286   video_decoder_class->stop = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_stop);
1287   video_decoder_class->finish = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_finish);
1288   video_decoder_class->flush = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_flush);
1289   video_decoder_class->drain = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_drain);
1290   video_decoder_class->set_format =
1291       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_set_format);
1292   video_decoder_class->negotiate =
1293       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_negotiate);
1294   video_decoder_class->decide_allocation =
1295       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_decide_allocation);
1296   /* FIXME propose_allocation or not ? */
1297   video_decoder_class->handle_frame =
1298       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_handle_frame);
1299   video_decoder_class->getcaps =
1300       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_sink_getcaps);
1301   video_decoder_class->src_query =
1302       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_src_query);
1303   video_decoder_class->sink_event =
1304       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_sink_event);
1305
1306   element_class->change_state =
1307       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_change_state);
1308
1309   gst_v4l2_object_install_m2m_properties_helper (gobject_class);
1310 }
1311
1312 static void
1313 gst_v4l2_video_dec_subclass_init (gpointer g_class, gpointer data)
1314 {
1315   GstV4l2VideoDecClass *klass = GST_V4L2_VIDEO_DEC_CLASS (g_class);
1316   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
1317   GstV4l2VideoDecCData *cdata = data;
1318
1319   klass->default_device = cdata->device;
1320
1321   gst_element_class_add_pad_template (element_class,
1322       gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
1323           cdata->sink_caps));
1324   gst_element_class_add_pad_template (element_class,
1325       gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
1326           cdata->src_caps));
1327
1328   gst_element_class_set_metadata (element_class, cdata->longname,
1329       "Codec/Decoder/Video/Hardware", cdata->description,
1330       "Nicolas Dufresne <nicolas.dufresne@collabora.com>");
1331
1332   gst_caps_unref (cdata->sink_caps);
1333   gst_caps_unref (cdata->src_caps);
1334   g_free (cdata);
1335 }
1336
1337 /* Probing functions */
1338 gboolean
1339 gst_v4l2_is_video_dec (GstCaps * sink_caps, GstCaps * src_caps)
1340 {
1341   gboolean ret = FALSE;
1342
1343   if (gst_caps_is_subset (sink_caps, gst_v4l2_object_get_codec_caps ())
1344       && gst_caps_is_subset (src_caps, gst_v4l2_object_get_raw_caps ()))
1345     ret = TRUE;
1346
1347   return ret;
1348 }
1349
1350 static gchar *
1351 gst_v4l2_video_dec_set_metadata (GstStructure * s, GstV4l2VideoDecCData * cdata,
1352     const gchar * basename)
1353 {
1354   gchar *codec_name = NULL;
1355   gchar *type_name = NULL;
1356
1357 #define SET_META(codec) \
1358 G_STMT_START { \
1359   cdata->longname = "V4L2 " codec " Decoder"; \
1360   cdata->description = "Decodes " codec " streams via V4L2 API"; \
1361   codec_name = g_ascii_strdown (codec, -1); \
1362 } G_STMT_END
1363
1364   if (gst_structure_has_name (s, "image/jpeg")) {
1365     SET_META ("JPEG");
1366   } else if (gst_structure_has_name (s, "video/mpeg")) {
1367     gint mpegversion = 0;
1368     gst_structure_get_int (s, "mpegversion", &mpegversion);
1369
1370     if (mpegversion == 4) {
1371       SET_META ("MPEG4");
1372       cdata->codec = gst_v4l2_mpeg4_get_codec ();
1373     } else {
1374       /* MPEG 2 decoders supports MPEG 1 format */
1375       SET_META ("MPEG2");
1376       cdata->codec = gst_v4l2_mpeg2_get_codec ();
1377     }
1378   } else if (gst_structure_has_name (s, "video/x-h263")) {
1379     SET_META ("H263");
1380   } else if (gst_structure_has_name (s, "video/x-fwht")) {
1381     SET_META ("FWHT");
1382   } else if (gst_structure_has_name (s, "video/x-h264")) {
1383     SET_META ("H264");
1384     cdata->codec = gst_v4l2_h264_get_codec ();
1385   } else if (gst_structure_has_name (s, "video/x-h265")) {
1386     SET_META ("H265");
1387     cdata->codec = gst_v4l2_h265_get_codec ();
1388   } else if (gst_structure_has_name (s, "video/x-wmv")) {
1389     SET_META ("VC1");
1390   } else if (gst_structure_has_name (s, "video/x-vp8")) {
1391     SET_META ("VP8");
1392     cdata->codec = gst_v4l2_vp8_get_codec ();
1393   } else if (gst_structure_has_name (s, "video/x-vp9")) {
1394     SET_META ("VP9");
1395     cdata->codec = gst_v4l2_vp9_get_codec ();
1396   } else if (gst_structure_has_name (s, "video/x-bayer")) {
1397     SET_META ("BAYER");
1398   } else if (gst_structure_has_name (s, "video/x-sonix")) {
1399     SET_META ("SONIX");
1400   } else if (gst_structure_has_name (s, "video/x-pwc1")) {
1401     SET_META ("PWC1");
1402   } else if (gst_structure_has_name (s, "video/x-pwc2")) {
1403     SET_META ("PWC2");
1404   } else {
1405     /* This code should be kept on sync with the exposed CODEC type of format
1406      * from gstv4l2object.c. This warning will only occur in case we forget
1407      * to also add a format here. */
1408     gchar *s_str = gst_structure_to_string (s);
1409     g_warning ("Missing fixed name mapping for caps '%s', this is a GStreamer "
1410         "bug, please report at https://bugs.gnome.org", s_str);
1411     g_free (s_str);
1412   }
1413
1414   if (codec_name) {
1415     type_name = g_strdup_printf ("v4l2%sdec", codec_name);
1416     if (g_type_from_name (type_name) != 0) {
1417       g_free (type_name);
1418       type_name = g_strdup_printf ("v4l2%s%sdec", basename, codec_name);
1419     }
1420
1421     g_free (codec_name);
1422   }
1423
1424   return type_name;
1425 #undef SET_META
1426 }
1427
1428 void
1429 gst_v4l2_video_dec_register (GstPlugin * plugin, const gchar * basename,
1430     const gchar * device_path, gint video_fd, GstCaps * sink_caps,
1431     GstCaps * src_caps)
1432 {
1433   gint i;
1434
1435   for (i = 0; i < gst_caps_get_size (sink_caps); i++) {
1436     GstV4l2VideoDecCData *cdata;
1437     GstStructure *s;
1438     GTypeQuery type_query;
1439     GTypeInfo type_info = { 0, };
1440     GType type, subtype;
1441     gchar *type_name;
1442
1443     s = gst_caps_get_structure (sink_caps, i);
1444
1445     cdata = g_new0 (GstV4l2VideoDecCData, 1);
1446     cdata->device = g_strdup (device_path);
1447     cdata->sink_caps = gst_caps_new_empty ();
1448     gst_caps_append_structure (cdata->sink_caps, gst_structure_copy (s));
1449     cdata->src_caps = gst_caps_ref (src_caps);
1450     type_name = gst_v4l2_video_dec_set_metadata (s, cdata, basename);
1451
1452     /* Skip over if we hit an unmapped type */
1453     if (!type_name) {
1454       g_free (cdata);
1455       continue;
1456     }
1457
1458     if (cdata->codec != NULL && cdata->codec != gst_v4l2_vp8_get_codec ()
1459         && cdata->codec != gst_v4l2_vp9_get_codec ()) {
1460       GValue value = G_VALUE_INIT;
1461
1462       if (gst_v4l2_codec_probe_levels (cdata->codec, video_fd, &value)) {
1463         gst_caps_set_value (cdata->sink_caps, "level", &value);
1464         g_value_unset (&value);
1465       }
1466
1467       if (gst_v4l2_codec_probe_profiles (cdata->codec, video_fd, &value)) {
1468         gst_caps_set_value (cdata->sink_caps, "profile", &value);
1469         g_value_unset (&value);
1470       }
1471     }
1472
1473     type = gst_v4l2_video_dec_get_type ();
1474     g_type_query (type, &type_query);
1475     memset (&type_info, 0, sizeof (type_info));
1476     type_info.class_size = type_query.class_size;
1477     type_info.instance_size = type_query.instance_size;
1478     type_info.class_init = gst_v4l2_video_dec_subclass_init;
1479     type_info.class_data = cdata;
1480     type_info.instance_init = gst_v4l2_video_dec_subinstance_init;
1481
1482     subtype = g_type_register_static (type, type_name, &type_info, 0);
1483     if (!gst_element_register (plugin, type_name, GST_RANK_PRIMARY + 1,
1484             subtype))
1485       GST_WARNING ("Failed to register plugin '%s'", type_name);
1486
1487     g_free (type_name);
1488   }
1489 }