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