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