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