v4l2videoenc: Don't leak VideoCodecState
[platform/upstream/gst-plugins-good.git] / sys / v4l2 / gstv4l2videoenc.c
1 /*
2  * Copyright (C) 2014-2017 SUMOMO Computer Association
3  *     Authors Ayaka <ayaka@soulik.info>
4  * Copyright (C) 2017 Collabora Ltd.
5  *     Author: Nicolas Dufresne <nicolas.dufresne@collabora.com>
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  *
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #include "config.h"
26 #endif
27
28 #include <sys/stat.h>
29 #include <fcntl.h>
30 #include <errno.h>
31 #include <unistd.h>
32 #include <string.h>
33
34 #include "gstv4l2videoenc.h"
35 #include "v4l2_calls.h"
36
37 #include <string.h>
38 #include <gst/gst-i18n-plugin.h>
39
40 GST_DEBUG_CATEGORY_STATIC (gst_v4l2_video_enc_debug);
41 #define GST_CAT_DEFAULT gst_v4l2_video_enc_debug
42
43 typedef struct
44 {
45   gchar *device;
46   GstCaps *sink_caps;
47   GstCaps *src_caps;
48 } GstV4l2VideoEncCData;
49
50 enum
51 {
52   PROP_0,
53   V4L2_STD_OBJECT_PROPS,
54 };
55
56 #define gst_v4l2_video_enc_parent_class parent_class
57 G_DEFINE_ABSTRACT_TYPE (GstV4l2VideoEnc, gst_v4l2_video_enc,
58     GST_TYPE_VIDEO_ENCODER);
59
60 static void
61 gst_v4l2_video_enc_set_property (GObject * object,
62     guint prop_id, const GValue * value, GParamSpec * pspec)
63 {
64   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (object);
65
66   switch (prop_id) {
67     case PROP_OUTPUT_IO_MODE:
68       gst_v4l2_object_set_property_helper (self->v4l2output,
69           prop_id, value, pspec);
70       break;
71     case PROP_CAPTURE_IO_MODE:
72       gst_v4l2_object_set_property_helper (self->v4l2capture,
73           prop_id, value, 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_enc_get_property (GObject * object,
88     guint prop_id, GValue * value, GParamSpec * pspec)
89 {
90   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (object);
91
92   switch (prop_id) {
93     case PROP_OUTPUT_IO_MODE:
94       gst_v4l2_object_get_property_helper (self->v4l2output,
95           prop_id, value, pspec);
96       break;
97     case PROP_CAPTURE_IO_MODE:
98       gst_v4l2_object_get_property_helper (self->v4l2output,
99           PROP_IO_MODE, value, 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_enc_open (GstVideoEncoder * encoder)
114 {
115   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
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_raw_caps ());
127
128   if (gst_caps_is_empty (self->probed_sinkcaps))
129     goto no_raw_format;
130
131   self->probed_srccaps = gst_v4l2_object_get_caps (self->v4l2capture,
132       gst_v4l2_object_get_codec_caps ());
133
134   if (gst_caps_is_empty (self->probed_srccaps))
135     goto no_encoded_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 output 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 input 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_enc_close (GstVideoEncoder * encoder)
167 {
168   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
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_enc_start (GstVideoEncoder * encoder)
182 {
183   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
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_enc_stop (GstVideoEncoder * encoder)
196 {
197   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
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 (encoder->srcpad);
206
207   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
208   self->output_flow = GST_FLOW_OK;
209   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
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_encoder_cmd (GstV4l2Object * v4l2object, guint cmd, guint flags)
230 {
231   struct v4l2_encoder_cmd ecmd = { 0, };
232
233   GST_DEBUG_OBJECT (v4l2object->element,
234       "sending v4l2 encoder command %u with flags %u", cmd, flags);
235
236   if (!GST_V4L2_IS_OPEN (v4l2object))
237     return FALSE;
238
239   ecmd.cmd = cmd;
240   ecmd.flags = flags;
241   if (v4l2_ioctl (v4l2object->video_fd, VIDIOC_ENCODER_CMD, &ecmd) < 0)
242     goto ecmd_failed;
243
244   return TRUE;
245
246 ecmd_failed:
247   if (errno == ENOTTY) {
248     GST_INFO_OBJECT (v4l2object->element,
249         "Failed to send encoder command %u with flags %u for '%s'. (%s)",
250         cmd, flags, v4l2object->videodev, g_strerror (errno));
251   } else {
252     GST_ERROR_OBJECT (v4l2object->element,
253         "Failed to send encoder command %u with flags %u for '%s'. (%s)",
254         cmd, flags, v4l2object->videodev, g_strerror (errno));
255   }
256   return FALSE;
257 }
258
259 static GstFlowReturn
260 gst_v4l2_video_enc_finish (GstVideoEncoder * encoder)
261 {
262   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
263   GstFlowReturn ret = GST_FLOW_OK;
264
265   if (gst_pad_get_task_state (encoder->srcpad) != GST_TASK_STARTED)
266     goto done;
267
268   GST_DEBUG_OBJECT (self, "Finishing encoding");
269
270   /* drop the stream lock while draining, so remaining buffers can be
271    * pushed from the src pad task thread */
272   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
273
274   if (gst_v4l2_encoder_cmd (self->v4l2capture, V4L2_ENC_CMD_STOP, 0)) {
275     GstTask *task = encoder->srcpad->task;
276
277     /* Wait for the task to be drained */
278     GST_OBJECT_LOCK (task);
279     while (GST_TASK_STATE (task) == GST_TASK_STARTED)
280       GST_TASK_WAIT (task);
281     GST_OBJECT_UNLOCK (task);
282     ret = GST_FLOW_FLUSHING;
283   }
284
285   /* and ensure the processing thread has stopped in case another error
286    * occured. */
287   gst_v4l2_object_unlock (self->v4l2capture);
288   gst_pad_stop_task (encoder->srcpad);
289   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
290
291   if (ret == GST_FLOW_FLUSHING)
292     ret = self->output_flow;
293
294   GST_DEBUG_OBJECT (encoder, "Done draining buffers");
295
296 done:
297   return ret;
298 }
299
300 static gboolean
301 gst_v4l2_video_enc_set_format (GstVideoEncoder * encoder,
302     GstVideoCodecState * state)
303 {
304   gboolean ret = TRUE;
305   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
306   GstV4l2Error error = GST_V4L2_ERROR_INIT;
307   GstCaps *outcaps;
308   GstVideoCodecState *output;
309
310   GST_DEBUG_OBJECT (self, "Setting format: %" GST_PTR_FORMAT, state->caps);
311
312   if (self->input_state) {
313     if (gst_v4l2_object_caps_equal (self->v4l2output, state->caps)) {
314       GST_DEBUG_OBJECT (self, "Compatible caps");
315       return TRUE;
316     }
317
318     if (gst_v4l2_video_enc_finish (encoder) != GST_FLOW_OK)
319       return FALSE;
320
321     gst_video_codec_state_unref (self->input_state);
322     self->input_state = NULL;
323   }
324
325   outcaps = gst_pad_get_pad_template_caps (encoder->srcpad);
326   outcaps = gst_caps_make_writable (outcaps);
327   output = gst_video_encoder_set_output_state (encoder, outcaps, state);
328   gst_video_codec_state_unref (output);
329
330   if (!gst_video_encoder_negotiate (encoder))
331     return FALSE;
332
333   if (!gst_v4l2_object_set_format (self->v4l2output, state->caps, &error)) {
334     gst_v4l2_error (self, &error);
335     return FALSE;
336   }
337
338   self->input_state = gst_video_codec_state_ref (state);
339
340   GST_DEBUG_OBJECT (self, "output caps: %" GST_PTR_FORMAT, state->caps);
341
342   return ret;
343 }
344
345 static gboolean
346 gst_v4l2_video_enc_flush (GstVideoEncoder * encoder)
347 {
348   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
349
350   GST_DEBUG_OBJECT (self, "Flushing");
351
352   /* Ensure the processing thread has stopped for the reverse playback
353    * iscount case */
354   if (g_atomic_int_get (&self->processing)) {
355     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
356
357     gst_v4l2_object_unlock_stop (self->v4l2output);
358     gst_v4l2_object_unlock_stop (self->v4l2capture);
359     gst_pad_stop_task (encoder->srcpad);
360
361     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
362
363   }
364
365   self->output_flow = GST_FLOW_OK;
366
367   gst_v4l2_object_unlock_stop (self->v4l2output);
368   gst_v4l2_object_unlock_stop (self->v4l2capture);
369
370   return TRUE;
371 }
372
373 static gboolean
374 gst_v4l2_video_enc_negotiate (GstVideoEncoder * encoder)
375 {
376   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
377   gboolean ret;
378
379   ret = GST_VIDEO_ENCODER_CLASS (parent_class)->negotiate (encoder);
380
381   if (!gst_buffer_pool_set_active (GST_BUFFER_POOL (self->v4l2capture->pool),
382           TRUE)) {
383     GST_WARNING_OBJECT (self, "Could not activate capture buffer pool.");
384     ret = FALSE;
385   }
386
387   return ret;
388 }
389
390 static GstVideoCodecFrame *
391 gst_v4l2_video_enc_get_oldest_frame (GstVideoEncoder * encoder)
392 {
393   GstVideoCodecFrame *frame = NULL;
394   GList *frames, *l;
395   gint count = 0;
396
397   frames = gst_video_encoder_get_frames (encoder);
398
399   for (l = frames; l != NULL; l = l->next) {
400     GstVideoCodecFrame *f = l->data;
401
402     if (!frame || frame->pts > f->pts)
403       frame = f;
404
405     count++;
406   }
407
408   if (frame) {
409     GST_LOG_OBJECT (encoder,
410         "Oldest frame is %d %" GST_TIME_FORMAT
411         " and %d frames left",
412         frame->system_frame_number, GST_TIME_ARGS (frame->pts), count - 1);
413     gst_video_codec_frame_ref (frame);
414   }
415
416   g_list_free_full (frames, (GDestroyNotify) gst_video_codec_frame_unref);
417
418   return frame;
419 }
420
421 static void
422 gst_v4l2_video_enc_loop (GstVideoEncoder * encoder)
423 {
424   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
425   GstVideoCodecFrame *frame;
426   GstBuffer *buffer = NULL;
427   GstFlowReturn ret;
428
429   GST_LOG_OBJECT (encoder, "Allocate output buffer");
430
431   buffer = gst_video_encoder_allocate_output_buffer (encoder,
432       self->v4l2capture->info.size);
433
434   if (NULL == buffer) {
435     ret = GST_FLOW_FLUSHING;
436     goto beach;
437   }
438
439
440   /* FIXME Check if buffer isn't the last one here */
441
442   GST_LOG_OBJECT (encoder, "Process output buffer");
443   ret =
444       gst_v4l2_buffer_pool_process (GST_V4L2_BUFFER_POOL
445       (self->v4l2capture->pool), &buffer);
446
447   if (ret != GST_FLOW_OK)
448     goto beach;
449
450   frame = gst_v4l2_video_enc_get_oldest_frame (encoder);
451
452   if (frame) {
453     frame->output_buffer = buffer;
454     buffer = NULL;
455     ret = gst_video_encoder_finish_frame (encoder, frame);
456
457     if (ret != GST_FLOW_OK)
458       goto beach;
459   } else {
460     GST_WARNING_OBJECT (encoder, "Encoder is producing too many buffers");
461     gst_buffer_unref (buffer);
462   }
463
464   return;
465
466 beach:
467   GST_DEBUG_OBJECT (encoder, "Leaving output thread");
468
469   gst_buffer_replace (&buffer, NULL);
470   self->output_flow = ret;
471   g_atomic_int_set (&self->processing, FALSE);
472   gst_v4l2_object_unlock (self->v4l2output);
473   gst_pad_pause_task (encoder->srcpad);
474 }
475
476 static void
477 gst_v4l2_video_enc_loop_stopped (GstV4l2VideoEnc * self)
478 {
479   if (g_atomic_int_get (&self->processing)) {
480     GST_DEBUG_OBJECT (self, "Early stop of encoding thread");
481     self->output_flow = GST_FLOW_FLUSHING;
482     g_atomic_int_set (&self->processing, FALSE);
483   }
484
485   GST_DEBUG_OBJECT (self, "Encoding task destroyed: %s",
486       gst_flow_get_name (self->output_flow));
487
488 }
489
490 static GstFlowReturn
491 gst_v4l2_video_enc_handle_frame (GstVideoEncoder * encoder,
492     GstVideoCodecFrame * frame)
493 {
494   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
495   GstFlowReturn ret = GST_FLOW_OK;
496
497   GST_DEBUG_OBJECT (self, "Handling frame %d", frame->system_frame_number);
498
499   if (G_UNLIKELY (!g_atomic_int_get (&self->active)))
500     goto flushing;
501
502   if (gst_pad_get_task_state (GST_VIDEO_DECODER_SRC_PAD (self)) ==
503       GST_TASK_STOPPED) {
504     GstBufferPool *pool = GST_BUFFER_POOL (self->v4l2output->pool);
505
506     /* It possible that the processing thread stopped due to an error */
507     if (self->output_flow != GST_FLOW_OK &&
508         self->output_flow != GST_FLOW_FLUSHING) {
509       GST_DEBUG_OBJECT (self, "Processing loop stopped with error, leaving");
510       ret = self->output_flow;
511       goto drop;
512     }
513
514     /* Ensure input internal pool is active */
515     if (!gst_buffer_pool_is_active (pool)) {
516       GstStructure *config = gst_buffer_pool_get_config (pool);
517       gst_buffer_pool_config_set_params (config, self->input_state->caps,
518           self->v4l2output->info.size, self->v4l2output->min_buffers,
519           self->v4l2output->min_buffers);
520
521       /* There is no reason to refuse this config */
522       if (!gst_buffer_pool_set_config (pool, config))
523         goto activate_failed;
524
525       if (!gst_buffer_pool_set_active (pool, TRUE))
526         goto activate_failed;
527     }
528
529     GST_DEBUG_OBJECT (self, "Starting encoding thread");
530
531     /* Start the processing task, when it quits, the task will disable input
532      * processing to unlock input if draining, or prevent potential block */
533     if (!gst_pad_start_task (encoder->srcpad,
534             (GstTaskFunction) gst_v4l2_video_enc_loop, self,
535             (GDestroyNotify) gst_v4l2_video_enc_loop_stopped))
536       goto start_task_failed;
537   }
538
539   if (frame->input_buffer) {
540     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
541     ret =
542         gst_v4l2_buffer_pool_process (GST_V4L2_BUFFER_POOL
543         (self->v4l2output->pool), &frame->input_buffer);
544     GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
545
546     if (ret == GST_FLOW_FLUSHING) {
547       if (gst_pad_get_task_state (GST_VIDEO_DECODER_SRC_PAD (self)) !=
548           GST_TASK_STARTED)
549         ret = self->output_flow;
550       goto drop;
551     } else if (ret != GST_FLOW_OK) {
552       goto process_failed;
553     }
554   }
555
556   gst_video_codec_frame_unref (frame);
557   return ret;
558
559   /* ERRORS */
560 activate_failed:
561   {
562     GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
563         (_("Failed to allocate required memory.")),
564         ("Buffer pool activation failed"));
565     return GST_FLOW_ERROR;
566
567   }
568 flushing:
569   {
570     ret = GST_FLOW_FLUSHING;
571     goto drop;
572   }
573 start_task_failed:
574   {
575     GST_ELEMENT_ERROR (self, RESOURCE, FAILED,
576         (_("Failed to start encoding thread.")), (NULL));
577     g_atomic_int_set (&self->processing, FALSE);
578     ret = GST_FLOW_ERROR;
579     goto drop;
580   }
581 process_failed:
582   {
583     GST_ELEMENT_ERROR (self, RESOURCE, FAILED,
584         (_("Failed to process frame.")),
585         ("Maybe be due to not enough memory or failing driver"));
586     ret = GST_FLOW_ERROR;
587     goto drop;
588   }
589 drop:
590   {
591     gst_video_encoder_finish_frame (encoder, frame);
592     return ret;
593   }
594 }
595
596 static gboolean
597 gst_v4l2_video_enc_decide_allocation (GstVideoEncoder *
598     encoder, GstQuery * query)
599 {
600   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
601   GstVideoCodecState *state = gst_video_encoder_get_output_state (encoder);
602   GstV4l2Error error = GST_V4L2_ERROR_INIT;
603   GstClockTime latency;
604   gboolean ret = FALSE;
605
606   /* We need to set the format here, since this is called right after
607    * GstVideoEncoder have set the width, height and framerate into the state
608    * caps. These are needed by the driver to calculate the buffer size and to
609    * implement bitrate adaptation. */
610   if (!gst_v4l2_object_set_format (self->v4l2capture, state->caps, &error)) {
611     gst_v4l2_error (self, &error);
612     ret = FALSE;
613     goto done;
614   }
615
616   if (gst_v4l2_object_decide_allocation (self->v4l2capture, query)) {
617     GstVideoEncoderClass *enc_class = GST_VIDEO_ENCODER_CLASS (parent_class);
618     ret = enc_class->decide_allocation (encoder, query);
619   }
620
621   /* FIXME This may not be entirely correct, as encoder may keep some
622    * observation withouth delaying the encoding. Linux Media API need some
623    * more work to explicitly expressed the decoder / encoder latency. This
624    * value will then become max latency, and the reported driver latency would
625    * become the min latency. */
626   latency = self->v4l2capture->min_buffers * self->v4l2capture->duration;
627   gst_video_encoder_set_latency (encoder, latency, latency);
628
629 done:
630   gst_video_codec_state_unref (state);
631   return ret;
632 }
633
634 static gboolean
635 gst_v4l2_video_enc_propose_allocation (GstVideoEncoder *
636     encoder, GstQuery * query)
637 {
638   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
639   gboolean ret = FALSE;
640
641   GST_DEBUG_OBJECT (self, "called");
642
643   if (query == NULL)
644     ret = TRUE;
645   else
646     ret = gst_v4l2_object_propose_allocation (self->v4l2output, query);
647
648   if (ret)
649     ret = GST_VIDEO_ENCODER_CLASS (parent_class)->propose_allocation (encoder,
650         query);
651
652   return ret;
653 }
654
655 static gboolean
656 gst_v4l2_video_enc_src_query (GstVideoEncoder * encoder, GstQuery * query)
657 {
658   gboolean ret = TRUE;
659   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
660   switch (GST_QUERY_TYPE (query)) {
661     case GST_QUERY_CAPS:{
662       GstCaps *filter, *result = NULL;
663       GstPad *pad = GST_VIDEO_ENCODER_SRC_PAD (encoder);
664
665       gst_query_parse_caps (query, &filter);
666
667       /* FIXME Try and not probe the entire encoder, but only the implement
668        * subclass format */
669       if (self->probed_srccaps) {
670         GstCaps *tmpl = gst_pad_get_pad_template_caps (pad);
671         result = gst_caps_intersect (tmpl, self->probed_srccaps);
672         gst_caps_unref (tmpl);
673       } else
674         result = gst_pad_get_pad_template_caps (pad);
675
676       if (filter) {
677         GstCaps *tmp = result;
678         result =
679             gst_caps_intersect_full (filter, tmp, GST_CAPS_INTERSECT_FIRST);
680         gst_caps_unref (tmp);
681       }
682
683       GST_DEBUG_OBJECT (self, "Returning src caps %" GST_PTR_FORMAT, result);
684
685       gst_query_set_caps_result (query, result);
686       gst_caps_unref (result);
687       break;
688     }
689
690     default:
691       ret = GST_VIDEO_ENCODER_CLASS (parent_class)->src_query (encoder, query);
692       break;
693   }
694
695   return ret;
696 }
697
698 static gboolean
699 gst_v4l2_video_enc_sink_query (GstVideoEncoder * encoder, GstQuery * query)
700 {
701   gboolean ret = TRUE;
702   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
703
704   switch (GST_QUERY_TYPE (query)) {
705     case GST_QUERY_CAPS:{
706       GstCaps *filter, *result = NULL;
707       GstPad *pad = GST_VIDEO_ENCODER_SINK_PAD (encoder);
708
709       gst_query_parse_caps (query, &filter);
710
711       if (self->probed_sinkcaps)
712         result = gst_caps_ref (self->probed_sinkcaps);
713       else
714         result = gst_pad_get_pad_template_caps (pad);
715
716       if (filter) {
717         GstCaps *tmp = result;
718         result =
719             gst_caps_intersect_full (filter, tmp, GST_CAPS_INTERSECT_FIRST);
720         gst_caps_unref (tmp);
721       }
722
723       GST_DEBUG_OBJECT (self, "Returning sink caps %" GST_PTR_FORMAT, result);
724
725       gst_query_set_caps_result (query, result);
726       gst_caps_unref (result);
727       break;
728     }
729
730     default:
731       ret = GST_VIDEO_ENCODER_CLASS (parent_class)->sink_query (encoder, query);
732       break;
733   }
734
735   return ret;
736 }
737
738 static gboolean
739 gst_v4l2_video_enc_sink_event (GstVideoEncoder * encoder, GstEvent * event)
740 {
741   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
742   gboolean ret;
743
744   switch (GST_EVENT_TYPE (event)) {
745     case GST_EVENT_FLUSH_START:
746       GST_DEBUG_OBJECT (self, "flush start");
747       gst_v4l2_object_unlock (self->v4l2output);
748       gst_v4l2_object_unlock (self->v4l2capture);
749       break;
750     default:
751       break;
752   }
753
754   ret = GST_VIDEO_ENCODER_CLASS (parent_class)->sink_event (encoder, event);
755
756   switch (GST_EVENT_TYPE (event)) {
757     case GST_EVENT_FLUSH_START:
758       gst_pad_stop_task (encoder->srcpad);
759       GST_DEBUG_OBJECT (self, "flush start done");
760     default:
761       break;
762   }
763
764   return ret;
765 }
766
767 static GstStateChangeReturn
768 gst_v4l2_video_enc_change_state (GstElement * element,
769     GstStateChange transition)
770 {
771   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (element);
772
773   if (transition == GST_STATE_CHANGE_PAUSED_TO_READY) {
774     g_atomic_int_set (&self->active, FALSE);
775     gst_v4l2_object_unlock (self->v4l2output);
776     gst_v4l2_object_unlock (self->v4l2capture);
777   }
778
779   return GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
780 }
781
782 static void
783 gst_v4l2_video_enc_dispose (GObject * object)
784 {
785   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (object);
786
787   gst_caps_replace (&self->probed_sinkcaps, NULL);
788   gst_caps_replace (&self->probed_srccaps, NULL);
789
790   G_OBJECT_CLASS (parent_class)->dispose (object);
791 }
792
793 static void
794 gst_v4l2_video_enc_finalize (GObject * object)
795 {
796   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (object);
797
798   gst_v4l2_object_destroy (self->v4l2capture);
799   gst_v4l2_object_destroy (self->v4l2output);
800
801   G_OBJECT_CLASS (parent_class)->finalize (object);
802 }
803
804 static void
805 gst_v4l2_video_enc_init (GstV4l2VideoEnc * self)
806 {
807   /* V4L2 object are created in subinstance_init */
808 }
809
810 static void
811 gst_v4l2_video_enc_subinstance_init (GTypeInstance * instance, gpointer g_class)
812 {
813   GstV4l2VideoEncClass *klass = GST_V4L2_VIDEO_ENC_CLASS (g_class);
814   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (instance);
815
816   self->v4l2output = gst_v4l2_object_new (GST_ELEMENT (self),
817       V4L2_BUF_TYPE_VIDEO_OUTPUT, klass->default_device,
818       gst_v4l2_get_output, gst_v4l2_set_output, NULL);
819   self->v4l2output->no_initial_format = TRUE;
820   self->v4l2output->keep_aspect = FALSE;
821
822   self->v4l2capture = gst_v4l2_object_new (GST_ELEMENT (self),
823       V4L2_BUF_TYPE_VIDEO_CAPTURE, klass->default_device,
824       gst_v4l2_get_input, gst_v4l2_set_input, NULL);
825   self->v4l2capture->no_initial_format = TRUE;
826   self->v4l2output->keep_aspect = FALSE;
827 }
828
829 static void
830 gst_v4l2_video_enc_class_init (GstV4l2VideoEncClass * klass)
831 {
832   GstElementClass *element_class;
833   GObjectClass *gobject_class;
834   GstVideoEncoderClass *video_encoder_class;
835
836   parent_class = g_type_class_peek_parent (klass);
837
838   element_class = (GstElementClass *) klass;
839   gobject_class = (GObjectClass *) klass;
840   video_encoder_class = (GstVideoEncoderClass *) klass;
841
842   GST_DEBUG_CATEGORY_INIT (gst_v4l2_video_enc_debug, "v4l2videoenc", 0,
843       "V4L2 Video Encoder");
844
845   gobject_class->dispose = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_dispose);
846   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_finalize);
847   gobject_class->set_property =
848       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_set_property);
849   gobject_class->get_property =
850       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_get_property);
851
852   video_encoder_class->open = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_open);
853   video_encoder_class->close = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_close);
854   video_encoder_class->start = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_start);
855   video_encoder_class->stop = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_stop);
856   video_encoder_class->finish = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_finish);
857   video_encoder_class->flush = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_flush);
858   video_encoder_class->set_format =
859       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_set_format);
860   video_encoder_class->negotiate =
861       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_negotiate);
862   video_encoder_class->decide_allocation =
863       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_decide_allocation);
864   video_encoder_class->propose_allocation =
865       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_propose_allocation);
866   video_encoder_class->sink_query =
867       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_sink_query);
868   video_encoder_class->src_query =
869       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_src_query);
870   video_encoder_class->sink_event =
871       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_sink_event);
872   video_encoder_class->handle_frame =
873       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_handle_frame);
874
875   element_class->change_state =
876       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_change_state);
877
878   gst_v4l2_object_install_m2m_properties_helper (gobject_class);
879 }
880
881 static void
882 gst_v4l2_video_enc_subclass_init (gpointer g_class, gpointer data)
883 {
884   GstV4l2VideoEncClass *klass = GST_V4L2_VIDEO_ENC_CLASS (g_class);
885   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
886   GstV4l2VideoEncCData *cdata = data;
887
888   klass->default_device = cdata->device;
889
890   /* Note: gst_pad_template_new() take the floating ref from the caps */
891   gst_element_class_add_pad_template (element_class,
892       gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
893           cdata->sink_caps));
894   gst_element_class_add_pad_template (element_class,
895       gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
896           cdata->src_caps));
897
898   g_free (cdata);
899 }
900
901 /* Probing functions */
902 gboolean
903 gst_v4l2_video_enc_register (GstPlugin * plugin, GType type,
904     const char *codec, const gchar * basename, const gchar * device_path,
905     GstCaps * sink_caps, GstCaps * codec_caps, GstCaps * src_caps)
906 {
907   GstCaps *filtered_caps;
908   GTypeQuery type_query;
909   GTypeInfo type_info = { 0, };
910   GType subtype;
911   gchar *type_name;
912   GstV4l2VideoEncCData *cdata;
913
914   filtered_caps = gst_caps_intersect (src_caps, codec_caps);
915
916   cdata = g_new0 (GstV4l2VideoEncCData, 1);
917   cdata->device = g_strdup (device_path);
918   cdata->sink_caps = gst_caps_ref (sink_caps);
919   cdata->src_caps = gst_caps_ref (filtered_caps);
920
921   g_type_query (type, &type_query);
922   memset (&type_info, 0, sizeof (type_info));
923   type_info.class_size = type_query.class_size;
924   type_info.instance_size = type_query.instance_size;
925   type_info.class_init = gst_v4l2_video_enc_subclass_init;
926   type_info.class_data = cdata;
927   type_info.instance_init = gst_v4l2_video_enc_subinstance_init;
928
929   /* The first encoder to be registered should use a constant name, like
930    * v4l2h264enc, for any additional encoders, we create unique names. Encoder
931    * names may change between boots, so this should help gain stable names for
932    * the most common use cases. */
933   type_name = g_strdup_printf ("v4l2%senc", codec);
934
935   if (g_type_from_name (type_name) != 0) {
936     g_free (type_name);
937     type_name = g_strdup_printf ("v4l2%s%senc", basename, codec);
938   }
939
940   subtype = g_type_register_static (type, type_name, &type_info, 0);
941   gst_element_register (plugin, type_name, GST_RANK_PRIMARY + 1, subtype);
942
943   g_free (type_name);
944
945   return TRUE;
946 }