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