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