v4l2videodec: use decoder stop command instead of queueing empty buffers
[platform/upstream/gst-plugins-good.git] / sys / v4l2 / gstv4l2videodec.c
1 /*
2  * Copyright (C) 2014 Collabora Ltd.
3  *     Author: Nicolas Dufresne <nicolas.dufresne@collabora.co.uk>
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 "gstv4l2videodec.h"
33 #include "v4l2_calls.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 static gboolean gst_v4l2_video_dec_flush (GstVideoDecoder * decoder);
42
43 typedef struct
44 {
45   gchar *device;
46   GstCaps *sink_caps;
47   GstCaps *src_caps;
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 void
61 gst_v4l2_video_dec_set_property (GObject * object,
62     guint prop_id, const GValue * value, GParamSpec * pspec)
63 {
64   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (object);
65
66   switch (prop_id) {
67     case PROP_OUTPUT_IO_MODE:
68       gst_v4l2_object_set_property_helper (self->v4l2output, prop_id, value,
69           pspec);
70       break;
71     case PROP_CAPTURE_IO_MODE:
72       gst_v4l2_object_set_property_helper (self->v4l2capture, prop_id, value,
73           pspec);
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_OUTPUT_IO_MODE:
94       gst_v4l2_object_get_property_helper (self->v4l2output, prop_id, value,
95           pspec);
96       break;
97     case PROP_CAPTURE_IO_MODE:
98       gst_v4l2_object_get_property_helper (self->v4l2capture, prop_id, value,
99           pspec);
100       break;
101
102       /* By default read from output */
103     default:
104       if (!gst_v4l2_object_get_property_helper (self->v4l2output,
105               prop_id, value, pspec)) {
106         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
107       }
108       break;
109   }
110 }
111
112 static gboolean
113 gst_v4l2_video_dec_open (GstVideoDecoder * decoder)
114 {
115   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
116
117   GST_DEBUG_OBJECT (self, "Opening");
118
119   if (!gst_v4l2_object_open (self->v4l2output))
120     goto failure;
121
122   if (!gst_v4l2_object_open_shared (self->v4l2capture, self->v4l2output))
123     goto failure;
124
125   self->probed_sinkcaps = gst_v4l2_object_get_caps (self->v4l2output,
126       gst_v4l2_object_get_codec_caps ());
127
128   if (gst_caps_is_empty (self->probed_sinkcaps))
129     goto no_encoded_format;
130
131   self->probed_srccaps = gst_v4l2_object_get_caps (self->v4l2capture,
132       gst_v4l2_object_get_raw_caps ());
133
134   if (gst_caps_is_empty (self->probed_srccaps))
135     goto no_raw_format;
136
137   return TRUE;
138
139 no_encoded_format:
140   GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
141       (_("Encoder on device %s has no supported input format"),
142           self->v4l2output->videodev), (NULL));
143   goto failure;
144
145
146 no_raw_format:
147   GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
148       (_("Encoder on device %s has no supported output format"),
149           self->v4l2output->videodev), (NULL));
150   goto failure;
151
152 failure:
153   if (GST_V4L2_IS_OPEN (self->v4l2output))
154     gst_v4l2_object_close (self->v4l2output);
155
156   if (GST_V4L2_IS_OPEN (self->v4l2capture))
157     gst_v4l2_object_close (self->v4l2capture);
158
159   gst_caps_replace (&self->probed_srccaps, NULL);
160   gst_caps_replace (&self->probed_sinkcaps, NULL);
161
162   return FALSE;
163 }
164
165 static gboolean
166 gst_v4l2_video_dec_close (GstVideoDecoder * decoder)
167 {
168   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
169
170   GST_DEBUG_OBJECT (self, "Closing");
171
172   gst_v4l2_object_close (self->v4l2output);
173   gst_v4l2_object_close (self->v4l2capture);
174   gst_caps_replace (&self->probed_srccaps, NULL);
175   gst_caps_replace (&self->probed_sinkcaps, NULL);
176
177   return TRUE;
178 }
179
180 static gboolean
181 gst_v4l2_video_dec_start (GstVideoDecoder * decoder)
182 {
183   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
184
185   GST_DEBUG_OBJECT (self, "Starting");
186
187   gst_v4l2_object_unlock (self->v4l2output);
188   g_atomic_int_set (&self->active, TRUE);
189   self->output_flow = GST_FLOW_OK;
190
191   return TRUE;
192 }
193
194 static gboolean
195 gst_v4l2_video_dec_stop (GstVideoDecoder * decoder)
196 {
197   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
198
199   GST_DEBUG_OBJECT (self, "Stopping");
200
201   gst_v4l2_object_unlock (self->v4l2output);
202   gst_v4l2_object_unlock (self->v4l2capture);
203
204   /* Wait for capture thread to stop */
205   gst_pad_stop_task (decoder->srcpad);
206
207   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
208   self->output_flow = GST_FLOW_OK;
209   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
210
211   /* Should have been flushed already */
212   g_assert (g_atomic_int_get (&self->active) == FALSE);
213   g_assert (g_atomic_int_get (&self->processing) == FALSE);
214
215   gst_v4l2_object_stop (self->v4l2output);
216   gst_v4l2_object_stop (self->v4l2capture);
217
218   if (self->input_state) {
219     gst_video_codec_state_unref (self->input_state);
220     self->input_state = NULL;
221   }
222
223   GST_DEBUG_OBJECT (self, "Stopped");
224
225   return TRUE;
226 }
227
228 static gboolean
229 gst_v4l2_video_dec_set_format (GstVideoDecoder * decoder,
230     GstVideoCodecState * state)
231 {
232   gboolean ret = TRUE;
233   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
234
235   GST_DEBUG_OBJECT (self, "Setting format: %" GST_PTR_FORMAT, state->caps);
236
237   if (self->input_state) {
238     if (gst_v4l2_object_caps_equal (self->v4l2output, state->caps)) {
239       GST_DEBUG_OBJECT (self, "Compatible caps");
240       goto done;
241     }
242     gst_video_codec_state_unref (self->input_state);
243     self->input_state = NULL;
244
245     /* FIXME we probably need to do more work if pools are active */
246   }
247
248   ret = gst_v4l2_object_set_format (self->v4l2output, state->caps);
249
250   if (ret)
251     self->input_state = gst_video_codec_state_ref (state);
252
253 done:
254   return ret;
255 }
256
257 static gboolean
258 gst_v4l2_video_dec_flush (GstVideoDecoder * decoder)
259 {
260   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
261
262   GST_DEBUG_OBJECT (self, "Flushed");
263
264   /* Ensure the processing thread has stopped for the reverse playback
265    * discount case */
266   if (g_atomic_int_get (&self->processing)) {
267     GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
268
269     gst_v4l2_object_unlock (self->v4l2output);
270     gst_v4l2_object_unlock (self->v4l2capture);
271     gst_pad_stop_task (decoder->srcpad);
272     GST_VIDEO_DECODER_STREAM_LOCK (decoder);
273   }
274
275   self->output_flow = GST_FLOW_OK;
276
277   gst_v4l2_object_unlock_stop (self->v4l2output);
278   gst_v4l2_object_unlock_stop (self->v4l2capture);
279
280   return TRUE;
281 }
282
283 static gboolean
284 gst_v4l2_video_dec_negotiate (GstVideoDecoder * decoder)
285 {
286   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
287
288   /* We don't allow renegotiation without carefull disabling the pool */
289   if (self->v4l2capture->pool &&
290       gst_buffer_pool_is_active (GST_BUFFER_POOL (self->v4l2capture->pool)))
291     return TRUE;
292
293   return GST_VIDEO_DECODER_CLASS (parent_class)->negotiate (decoder);
294 }
295
296 static gboolean
297 gst_v4l2_decoder_cmd (GstV4l2Object * v4l2object, guint cmd, guint flags)
298 {
299   struct v4l2_decoder_cmd dcmd = { 0, };
300
301   GST_DEBUG_OBJECT (v4l2object->element,
302       "sending v4l2 decoder command %u with flags %u", cmd, flags);
303
304   if (!GST_V4L2_IS_OPEN (v4l2object))
305     return FALSE;
306
307   dcmd.cmd = cmd;
308   dcmd.flags = flags;
309   if (v4l2_ioctl (v4l2object->video_fd, VIDIOC_DECODER_CMD, &dcmd) < 0)
310     goto dcmd_failed;
311
312   return TRUE;
313
314 dcmd_failed:
315   if (errno == ENOTTY) {
316     GST_INFO_OBJECT (v4l2object->element,
317         "Failed to send decoder command %u with flags %u for '%s'. (%s)",
318         cmd, flags, v4l2object->videodev, g_strerror (errno));
319   } else {
320     GST_ERROR_OBJECT (v4l2object->element,
321         "Failed to send decoder command %u with flags %u for '%s'. (%s)",
322         cmd, flags, v4l2object->videodev, g_strerror (errno));
323   }
324   return FALSE;
325 }
326
327 static GstFlowReturn
328 gst_v4l2_video_dec_finish (GstVideoDecoder * decoder)
329 {
330   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
331   GstFlowReturn ret = GST_FLOW_OK;
332   GstBuffer *buffer;
333
334   if (!g_atomic_int_get (&self->processing))
335     goto done;
336
337   GST_DEBUG_OBJECT (self, "Finishing decoding");
338
339   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
340
341   if (gst_v4l2_decoder_cmd (self->v4l2output, V4L2_DEC_CMD_STOP, 0)) {
342     GstTask *task = decoder->srcpad->task;
343
344     /* If the decoder stop command succeeded, just wait until processing is
345      * finished */
346     GST_OBJECT_LOCK (task);
347     while (GST_TASK_STATE (task) == GST_TASK_STARTED)
348       GST_TASK_WAIT (task);
349     GST_OBJECT_UNLOCK (task);
350     ret = GST_FLOW_FLUSHING;
351   } else {
352     /* otherwise keep queuing empty buffers until the processing thread has
353      * stopped, _pool_process() will return FLUSHING when that happened */
354     while (ret == GST_FLOW_OK) {
355       buffer = gst_buffer_new ();
356       ret =
357           gst_v4l2_buffer_pool_process (GST_V4L2_BUFFER_POOL (self->
358               v4l2output->pool), &buffer);
359       gst_buffer_unref (buffer);
360     }
361   }
362
363   /* and ensure the processing thread has stopped in case another error
364    * occured. */
365   gst_v4l2_object_unlock (self->v4l2capture);
366   gst_pad_stop_task (decoder->srcpad);
367   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
368
369   if (ret == GST_FLOW_FLUSHING)
370     ret = self->output_flow;
371
372   GST_DEBUG_OBJECT (decoder, "Done draining buffers");
373
374 done:
375   return ret;
376 }
377
378 static GstVideoCodecFrame *
379 gst_v4l2_video_dec_get_oldest_frame (GstVideoDecoder * decoder)
380 {
381   GstVideoCodecFrame *frame = NULL;
382   GList *frames, *l;
383   gint count = 0;
384
385   frames = gst_video_decoder_get_frames (decoder);
386
387   for (l = frames; l != NULL; l = l->next) {
388     GstVideoCodecFrame *f = l->data;
389
390     if (!frame || frame->pts > f->pts)
391       frame = f;
392
393     count++;
394   }
395
396   if (frame) {
397     GST_LOG_OBJECT (decoder,
398         "Oldest frame is %d %" GST_TIME_FORMAT " and %d frames left",
399         frame->system_frame_number, GST_TIME_ARGS (frame->pts), count - 1);
400     gst_video_codec_frame_ref (frame);
401   }
402
403   g_list_free_full (frames, (GDestroyNotify) gst_video_codec_frame_unref);
404
405   return frame;
406 }
407
408 static void
409 gst_v4l2_video_dec_loop (GstVideoDecoder * decoder)
410 {
411   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
412   GstV4l2BufferPool *v4l2_pool = GST_V4L2_BUFFER_POOL (self->v4l2capture->pool);
413   GstBufferPool *pool;
414   GstVideoCodecFrame *frame;
415   GstBuffer *buffer = NULL;
416   GstFlowReturn ret;
417
418   GST_LOG_OBJECT (decoder, "Allocate output buffer");
419
420   do {
421     /* We cannot use the base class allotate helper since it taking the internal
422      * stream lock. we know that the acquire may need to poll until more frames
423      * comes in and holding this lock would prevent that.
424      */
425     pool = gst_video_decoder_get_buffer_pool (decoder);
426
427     /* Pool may be NULL if we started going to READY state */
428     if (pool == NULL) {
429       ret = GST_FLOW_FLUSHING;
430       goto beach;
431     }
432
433     ret = gst_buffer_pool_acquire_buffer (pool, &buffer, NULL);
434     g_object_unref (pool);
435
436     if (ret != GST_FLOW_OK)
437       goto beach;
438
439     GST_LOG_OBJECT (decoder, "Process output buffer");
440     ret = gst_v4l2_buffer_pool_process (v4l2_pool, &buffer);
441
442   } while (ret == GST_V4L2_FLOW_CORRUPTED_BUFFER);
443
444   if (ret != GST_FLOW_OK)
445     goto beach;
446
447   frame = gst_v4l2_video_dec_get_oldest_frame (decoder);
448
449   if (frame) {
450     frame->output_buffer = buffer;
451     buffer = NULL;
452     ret = gst_video_decoder_finish_frame (decoder, frame);
453
454     if (ret != GST_FLOW_OK)
455       goto beach;
456   } else {
457     GST_WARNING_OBJECT (decoder, "Decoder is producing too many buffers");
458     gst_buffer_unref (buffer);
459   }
460
461   return;
462
463 beach:
464   GST_DEBUG_OBJECT (decoder, "Leaving output thread: %s",
465       gst_flow_get_name (ret));
466
467   gst_buffer_replace (&buffer, NULL);
468   self->output_flow = ret;
469   g_atomic_int_set (&self->processing, FALSE);
470   gst_v4l2_object_unlock (self->v4l2output);
471   gst_pad_pause_task (decoder->srcpad);
472 }
473
474 static void
475 gst_v4l2_video_dec_loop_stopped (GstV4l2VideoDec * self)
476 {
477   /* When flushing, decoding thread may never run */
478   if (g_atomic_int_get (&self->processing)) {
479     GST_DEBUG_OBJECT (self, "Early stop of decoding thread");
480     self->output_flow = GST_FLOW_FLUSHING;
481     g_atomic_int_set (&self->processing, FALSE);
482   }
483
484   GST_DEBUG_OBJECT (self, "Decoding task destroyed: %s",
485       gst_flow_get_name (self->output_flow));
486 }
487
488 static gboolean
489 gst_v4l2_video_remove_padding(GstCapsFeatures * features,
490     GstStructure * structure, gpointer user_data)
491 {
492   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (user_data);
493   GstVideoAlignment *align = &self->v4l2capture->align;
494   GstVideoInfo *info = &self->v4l2capture->info;
495   int width, height;
496
497   if (!gst_structure_get_int(structure, "width", &width))
498     return TRUE;
499
500   if (!gst_structure_get_int(structure, "height", &height))
501     return TRUE;
502
503   if (align->padding_left != 0 || align->padding_top != 0 ||
504       width != info->width + align->padding_right ||
505       height != info->height + align->padding_bottom)
506     return TRUE;
507
508   gst_structure_set(structure,
509       "width", G_TYPE_INT, width - align->padding_right,
510       "height", G_TYPE_INT, height - align->padding_bottom, NULL);
511
512   return TRUE;
513 }
514
515 static GstFlowReturn
516 gst_v4l2_video_dec_handle_frame (GstVideoDecoder * decoder,
517     GstVideoCodecFrame * frame)
518 {
519   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
520   GstFlowReturn ret = GST_FLOW_OK;
521
522   GST_DEBUG_OBJECT (self, "Handling frame %d", frame->system_frame_number);
523
524   if (G_UNLIKELY (!g_atomic_int_get (&self->active)))
525     goto flushing;
526
527   if (G_UNLIKELY (!GST_V4L2_IS_ACTIVE (self->v4l2output))) {
528     if (!self->input_state)
529       goto not_negotiated;
530     if (!gst_v4l2_object_set_format (self->v4l2output, self->input_state->caps))
531       goto not_negotiated;
532   }
533
534   if (G_UNLIKELY (!GST_V4L2_IS_ACTIVE (self->v4l2capture))) {
535     GstBufferPool *pool = GST_BUFFER_POOL (self->v4l2output->pool);
536     GstVideoInfo info;
537     GstVideoCodecState *output_state;
538     GstBuffer *codec_data;
539     GstCaps *acquired_caps, *available_caps, *caps, *filter;
540     GstStructure *st;
541
542     GST_DEBUG_OBJECT (self, "Sending header");
543
544     codec_data = self->input_state->codec_data;
545
546     /* We are running in byte-stream mode, so we don't know the headers, but
547      * we need to send something, otherwise the decoder will refuse to
548      * intialize.
549      */
550     if (codec_data) {
551       gst_buffer_ref (codec_data);
552     } else {
553       codec_data = frame->input_buffer;
554       frame->input_buffer = NULL;
555     }
556
557     /* Ensure input internal pool is active */
558     if (!gst_buffer_pool_is_active (pool)) {
559       GstStructure *config = gst_buffer_pool_get_config (pool);
560       gst_buffer_pool_config_set_params (config, self->input_state->caps,
561           self->v4l2output->info.size, 2, 2);
562
563       /* There is no reason to refuse this config */
564       if (!gst_buffer_pool_set_config (pool, config))
565         goto activate_failed;
566
567       if (!gst_buffer_pool_set_active (pool, TRUE))
568         goto activate_failed;
569     }
570
571     GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
572     ret =
573         gst_v4l2_buffer_pool_process (GST_V4L2_BUFFER_POOL (self->
574             v4l2output->pool), &codec_data);
575     GST_VIDEO_DECODER_STREAM_LOCK (decoder);
576
577     gst_buffer_unref (codec_data);
578
579     /* For decoders G_FMT returns coded size, G_SELECTION returns visible size
580      * in the compose rectangle. gst_v4l2_object_acquire_format() checks both
581      * and returns the visible size as with/height and the coded size as
582      * padding. */
583     if (!gst_v4l2_object_acquire_format (self->v4l2capture, &info))
584       goto not_negotiated;
585
586     /* Create caps from the acquired format, remove the format field */
587     acquired_caps = gst_video_info_to_caps (&info);
588     st = gst_caps_get_structure (acquired_caps, 0);
589     gst_structure_remove_field (st, "format");
590
591     /* Probe currently available pixel formats */
592     available_caps = gst_v4l2_object_probe_caps (self->v4l2capture, NULL);
593     available_caps = gst_caps_make_writable (available_caps);
594
595     /* Replace coded size with visible size, we want to negotiate visible size
596      * with downstream, not coded size. */
597     gst_caps_map_in_place (available_caps, gst_v4l2_video_remove_padding, self);
598
599     filter = gst_caps_intersect_full (available_caps, acquired_caps,
600         GST_CAPS_INTERSECT_FIRST);
601     gst_caps_unref (acquired_caps);
602     gst_caps_unref (available_caps);
603     caps = gst_pad_peer_query_caps (decoder->srcpad, filter);
604     gst_caps_unref (filter);
605
606     GST_DEBUG_OBJECT (self, "Possible decoded caps: %" GST_PTR_FORMAT, caps);
607     if (gst_caps_is_empty (caps)) {
608       gst_caps_unref (caps);
609       goto not_negotiated;
610     }
611
612     /* Fixate pixel format */
613     caps = gst_caps_fixate (caps);
614
615     GST_DEBUG_OBJECT (self, "Chosen decoded caps: %" GST_PTR_FORMAT, caps);
616
617     /* Try to set negotiated format, on success replace acquired format */
618     if (gst_v4l2_object_set_format (self->v4l2capture, caps))
619       gst_video_info_from_caps (&info, caps);
620     gst_caps_unref (caps);
621
622     output_state = gst_video_decoder_set_output_state (decoder,
623         info.finfo->format, info.width, info.height, self->input_state);
624
625     /* Copy the rest of the information, there might be more in the future */
626     output_state->info.interlace_mode = info.interlace_mode;
627     gst_video_codec_state_unref (output_state);
628
629     if (!gst_video_decoder_negotiate (decoder)) {
630       if (GST_PAD_IS_FLUSHING (decoder->srcpad))
631         goto flushing;
632       else
633         goto not_negotiated;
634     }
635
636     /* Ensure our internal pool is activated */
637     if (!gst_buffer_pool_set_active (GST_BUFFER_POOL (self->v4l2capture->pool),
638             TRUE))
639       goto activate_failed;
640   }
641
642   if (g_atomic_int_get (&self->processing) == FALSE) {
643     /* It's possible that the processing thread stopped due to an error */
644     if (self->output_flow != GST_FLOW_OK &&
645         self->output_flow != GST_FLOW_FLUSHING) {
646       GST_DEBUG_OBJECT (self, "Processing loop stopped with error, leaving");
647       ret = self->output_flow;
648       goto drop;
649     }
650
651     GST_DEBUG_OBJECT (self, "Starting decoding thread");
652
653     /* Start the processing task, when it quits, the task will disable input
654      * processing to unlock input if draining, or prevent potential block */
655     g_atomic_int_set (&self->processing, TRUE);
656     if (!gst_pad_start_task (decoder->srcpad,
657             (GstTaskFunction) gst_v4l2_video_dec_loop, self,
658             (GDestroyNotify) gst_v4l2_video_dec_loop_stopped))
659       goto start_task_failed;
660   }
661
662   if (frame->input_buffer) {
663     GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
664     ret =
665         gst_v4l2_buffer_pool_process (GST_V4L2_BUFFER_POOL (self->v4l2output->
666             pool), &frame->input_buffer);
667     GST_VIDEO_DECODER_STREAM_LOCK (decoder);
668
669     if (ret == GST_FLOW_FLUSHING) {
670       if (g_atomic_int_get (&self->processing) == FALSE)
671         ret = self->output_flow;
672       goto drop;
673     } else if (ret != GST_FLOW_OK) {
674       goto process_failed;
675     }
676
677     /* No need to keep input arround */
678     gst_buffer_replace (&frame->input_buffer, NULL);
679   }
680
681   gst_video_codec_frame_unref (frame);
682   return ret;
683
684   /* ERRORS */
685 not_negotiated:
686   {
687     GST_ERROR_OBJECT (self, "not negotiated");
688     ret = GST_FLOW_NOT_NEGOTIATED;
689     goto drop;
690   }
691 activate_failed:
692   {
693     GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
694         (_("Failed to allocate required memory.")),
695         ("Buffer pool activation failed"));
696     ret = GST_FLOW_ERROR;
697     goto drop;
698   }
699 flushing:
700   {
701     ret = GST_FLOW_FLUSHING;
702     goto drop;
703   }
704
705 start_task_failed:
706   {
707     GST_ELEMENT_ERROR (self, RESOURCE, FAILED,
708         (_("Failed to start decoding thread.")), (NULL));
709     g_atomic_int_set (&self->processing, FALSE);
710     ret = GST_FLOW_ERROR;
711     goto drop;
712   }
713 process_failed:
714   {
715     GST_ELEMENT_ERROR (self, RESOURCE, FAILED,
716         (_("Failed to process frame.")),
717         ("Maybe be due to not enough memory or failing driver"));
718     ret = GST_FLOW_ERROR;
719     goto drop;
720   }
721 drop:
722   {
723     gst_video_decoder_drop_frame (decoder, frame);
724     return ret;
725   }
726 }
727
728 static gboolean
729 gst_v4l2_video_dec_decide_allocation (GstVideoDecoder * decoder,
730     GstQuery * query)
731 {
732   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
733   GstClockTime latency;
734   gboolean ret = FALSE;
735
736   if (gst_v4l2_object_decide_allocation (self->v4l2capture, query))
737     ret = GST_VIDEO_DECODER_CLASS (parent_class)->decide_allocation (decoder,
738         query);
739
740   latency = self->v4l2capture->min_buffers * self->v4l2capture->duration;
741   gst_video_decoder_set_latency (decoder, latency, latency);
742
743   return ret;
744 }
745
746 static gboolean
747 gst_v4l2_video_dec_src_query (GstVideoDecoder * decoder, GstQuery * query)
748 {
749   gboolean ret = TRUE;
750   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
751
752   switch (GST_QUERY_TYPE (query)) {
753     case GST_QUERY_CAPS:{
754       GstCaps *filter, *result = NULL;
755       GstPad *pad = GST_VIDEO_DECODER_SRC_PAD (decoder);
756
757       gst_query_parse_caps (query, &filter);
758
759       if (self->probed_srccaps)
760         result = gst_caps_ref (self->probed_srccaps);
761       else
762         result = gst_pad_get_pad_template_caps (pad);
763
764       if (filter) {
765         GstCaps *tmp = result;
766         result =
767             gst_caps_intersect_full (filter, tmp, GST_CAPS_INTERSECT_FIRST);
768         gst_caps_unref (tmp);
769       }
770
771       GST_DEBUG_OBJECT (self, "Returning src caps %" GST_PTR_FORMAT, result);
772
773       gst_query_set_caps_result (query, result);
774       gst_caps_unref (result);
775       break;
776     }
777
778     default:
779       ret = GST_VIDEO_DECODER_CLASS (parent_class)->src_query (decoder, query);
780       break;
781   }
782
783   return ret;
784 }
785
786 static GstCaps *
787 gst_v4l2_video_dec_sink_getcaps (GstVideoDecoder * decoder, GstCaps * filter)
788 {
789   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
790   GstCaps *result;
791
792   result = gst_video_decoder_proxy_getcaps (decoder, self->probed_sinkcaps,
793       filter);
794
795   GST_DEBUG_OBJECT (self, "Returning sink caps %" GST_PTR_FORMAT, result);
796
797   return result;
798 }
799
800 static gboolean
801 gst_v4l2_video_dec_sink_event (GstVideoDecoder * decoder, GstEvent * event)
802 {
803   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (decoder);
804   gboolean ret;
805
806   switch (GST_EVENT_TYPE (event)) {
807     case GST_EVENT_FLUSH_START:
808       GST_DEBUG_OBJECT (self, "flush start");
809       gst_v4l2_object_unlock (self->v4l2output);
810       gst_v4l2_object_unlock (self->v4l2capture);
811       break;
812     default:
813       break;
814   }
815
816   ret = GST_VIDEO_DECODER_CLASS (parent_class)->sink_event (decoder, event);
817
818   switch (GST_EVENT_TYPE (event)) {
819     case GST_EVENT_FLUSH_START:
820       /* The processing thread should stop now, wait for it */
821       gst_pad_stop_task (decoder->srcpad);
822       GST_DEBUG_OBJECT (self, "flush start done");
823       break;
824     default:
825       break;
826   }
827
828   return ret;
829 }
830
831 static GstStateChangeReturn
832 gst_v4l2_video_dec_change_state (GstElement * element,
833     GstStateChange transition)
834 {
835   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (element);
836   GstVideoDecoder *decoder = GST_VIDEO_DECODER (element);
837
838   if (transition == GST_STATE_CHANGE_PAUSED_TO_READY) {
839     g_atomic_int_set (&self->active, FALSE);
840     gst_v4l2_object_unlock (self->v4l2output);
841     gst_v4l2_object_unlock (self->v4l2capture);
842     gst_pad_stop_task (decoder->srcpad);
843   }
844
845   return GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
846 }
847
848 static void
849 gst_v4l2_video_dec_dispose (GObject * object)
850 {
851   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (object);
852
853   gst_caps_replace (&self->probed_sinkcaps, NULL);
854   gst_caps_replace (&self->probed_srccaps, NULL);
855
856   G_OBJECT_CLASS (parent_class)->dispose (object);
857 }
858
859 static void
860 gst_v4l2_video_dec_finalize (GObject * object)
861 {
862   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (object);
863
864   gst_v4l2_object_destroy (self->v4l2capture);
865   gst_v4l2_object_destroy (self->v4l2output);
866
867   G_OBJECT_CLASS (parent_class)->finalize (object);
868 }
869
870 static void
871 gst_v4l2_video_dec_init (GstV4l2VideoDec * self)
872 {
873   /* V4L2 object are created in subinstance_init */
874 }
875
876 static void
877 gst_v4l2_video_dec_subinstance_init (GTypeInstance * instance, gpointer g_class)
878 {
879   GstV4l2VideoDecClass *klass = GST_V4L2_VIDEO_DEC_CLASS (g_class);
880   GstV4l2VideoDec *self = GST_V4L2_VIDEO_DEC (instance);
881   GstVideoDecoder *decoder = GST_VIDEO_DECODER (instance);
882
883   gst_video_decoder_set_packetized (decoder, TRUE);
884
885   self->v4l2output = gst_v4l2_object_new (GST_ELEMENT (self),
886       V4L2_BUF_TYPE_VIDEO_OUTPUT, klass->default_device,
887       gst_v4l2_get_output, gst_v4l2_set_output, NULL);
888   self->v4l2output->no_initial_format = TRUE;
889   self->v4l2output->keep_aspect = FALSE;
890
891   self->v4l2capture = gst_v4l2_object_new (GST_ELEMENT (self),
892       V4L2_BUF_TYPE_VIDEO_CAPTURE, klass->default_device,
893       gst_v4l2_get_input, gst_v4l2_set_input, NULL);
894   self->v4l2capture->no_initial_format = TRUE;
895   self->v4l2output->keep_aspect = FALSE;
896 }
897
898 static void
899 gst_v4l2_video_dec_class_init (GstV4l2VideoDecClass * klass)
900 {
901   GstElementClass *element_class;
902   GObjectClass *gobject_class;
903   GstVideoDecoderClass *video_decoder_class;
904
905   parent_class = g_type_class_peek_parent (klass);
906
907   element_class = (GstElementClass *) klass;
908   gobject_class = (GObjectClass *) klass;
909   video_decoder_class = (GstVideoDecoderClass *) klass;
910
911   GST_DEBUG_CATEGORY_INIT (gst_v4l2_video_dec_debug, "v4l2videodec", 0,
912       "V4L2 Video Decoder");
913
914   gst_element_class_set_static_metadata (element_class,
915       "V4L2 Video Decoder",
916       "Codec/Decoder/Video",
917       "Decode video streams via V4L2 API",
918       "Nicolas Dufresne <nicolas.dufresne@collabora.co.uk>");
919
920   gobject_class->dispose = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_dispose);
921   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_finalize);
922   gobject_class->set_property =
923       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_set_property);
924   gobject_class->get_property =
925       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_get_property);
926
927   video_decoder_class->open = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_open);
928   video_decoder_class->close = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_close);
929   video_decoder_class->start = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_start);
930   video_decoder_class->stop = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_stop);
931   video_decoder_class->finish = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_finish);
932   video_decoder_class->flush = GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_flush);
933   video_decoder_class->set_format =
934       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_set_format);
935   video_decoder_class->negotiate =
936       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_negotiate);
937   video_decoder_class->decide_allocation =
938       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_decide_allocation);
939   /* FIXME propose_allocation or not ? */
940   video_decoder_class->handle_frame =
941       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_handle_frame);
942   video_decoder_class->getcaps =
943       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_sink_getcaps);
944   video_decoder_class->src_query =
945       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_src_query);
946   video_decoder_class->sink_event =
947       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_sink_event);
948
949   element_class->change_state =
950       GST_DEBUG_FUNCPTR (gst_v4l2_video_dec_change_state);
951
952   gst_v4l2_object_install_m2m_properties_helper (gobject_class);
953 }
954
955 static void
956 gst_v4l2_video_dec_subclass_init (gpointer g_class, gpointer data)
957 {
958   GstV4l2VideoDecClass *klass = GST_V4L2_VIDEO_DEC_CLASS (g_class);
959   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
960   GstV4l2VideoDecCData *cdata = data;
961
962   klass->default_device = cdata->device;
963
964   /* Note: gst_pad_template_new() take the floating ref from the caps */
965   gst_element_class_add_pad_template (element_class,
966       gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
967           cdata->sink_caps));
968   gst_element_class_add_pad_template (element_class,
969       gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
970           cdata->src_caps));
971
972   g_free (cdata);
973 }
974
975 /* Probing functions */
976 gboolean
977 gst_v4l2_is_video_dec (GstCaps * sink_caps, GstCaps * src_caps)
978 {
979   gboolean ret = FALSE;
980
981   if (gst_caps_is_subset (sink_caps, gst_v4l2_object_get_codec_caps ())
982       && gst_caps_is_subset (src_caps, gst_v4l2_object_get_raw_caps ()))
983     ret = TRUE;
984
985   return ret;
986 }
987
988 gboolean
989 gst_v4l2_video_dec_register (GstPlugin * plugin, const gchar * basename,
990     const gchar * device_path, GstCaps * sink_caps, GstCaps * src_caps)
991 {
992   GTypeQuery type_query;
993   GTypeInfo type_info = { 0, };
994   GType type, subtype;
995   gchar *type_name;
996   GstV4l2VideoDecCData *cdata;
997
998   cdata = g_new0 (GstV4l2VideoDecCData, 1);
999   cdata->device = g_strdup (device_path);
1000   cdata->sink_caps = gst_caps_ref (sink_caps);
1001   cdata->src_caps = gst_caps_ref (src_caps);
1002
1003   type = gst_v4l2_video_dec_get_type ();
1004   g_type_query (type, &type_query);
1005   memset (&type_info, 0, sizeof (type_info));
1006   type_info.class_size = type_query.class_size;
1007   type_info.instance_size = type_query.instance_size;
1008   type_info.class_init = gst_v4l2_video_dec_subclass_init;
1009   type_info.class_data = cdata;
1010   type_info.instance_init = gst_v4l2_video_dec_subinstance_init;
1011
1012   type_name = g_strdup_printf ("v4l2%sdec", basename);
1013   subtype = g_type_register_static (type, type_name, &type_info, 0);
1014
1015   gst_element_register (plugin, type_name, GST_RANK_PRIMARY + 1, subtype);
1016
1017   g_free (type_name);
1018
1019   return TRUE;
1020 }