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