Moving twolame mp2 encoder plugin from -ugly
[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 "gstv4l2object.h"
35 #include "gstv4l2videoenc.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   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   self->probed_sinkcaps = gst_v4l2_object_probe_caps (self->v4l2output,
127       gst_v4l2_object_get_raw_caps ());
128
129   if (gst_caps_is_empty (self->probed_sinkcaps))
130     goto no_raw_format;
131
132   codec_caps = gst_pad_get_pad_template_caps (encoder->srcpad);
133   self->probed_srccaps = gst_v4l2_object_probe_caps (self->v4l2capture,
134       codec_caps);
135   gst_caps_unref (codec_caps);
136
137   if (gst_caps_is_empty (self->probed_srccaps))
138     goto no_encoded_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 output 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 input 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_enc_close (GstVideoEncoder * encoder)
170 {
171   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
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_enc_start (GstVideoEncoder * encoder)
185 {
186   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
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_enc_stop (GstVideoEncoder * encoder)
199 {
200   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
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 (encoder->srcpad);
209
210   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
211   self->output_flow = GST_FLOW_OK;
212   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
213
214   /* Should have been flushed already */
215   g_assert (g_atomic_int_get (&self->active) == FALSE);
216   g_assert (g_atomic_int_get (&self->processing) == FALSE);
217
218   gst_v4l2_object_stop (self->v4l2output);
219   gst_v4l2_object_stop (self->v4l2capture);
220
221   if (self->input_state) {
222     gst_video_codec_state_unref (self->input_state);
223     self->input_state = NULL;
224   }
225
226   GST_DEBUG_OBJECT (self, "Stopped");
227
228   return TRUE;
229 }
230
231 static gboolean
232 gst_v4l2_encoder_cmd (GstV4l2Object * v4l2object, guint cmd, guint flags)
233 {
234   struct v4l2_encoder_cmd ecmd = { 0, };
235
236   GST_DEBUG_OBJECT (v4l2object->element,
237       "sending v4l2 encoder command %u with flags %u", cmd, flags);
238
239   if (!GST_V4L2_IS_OPEN (v4l2object))
240     return FALSE;
241
242   ecmd.cmd = cmd;
243   ecmd.flags = flags;
244   if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_ENCODER_CMD, &ecmd) < 0)
245     goto ecmd_failed;
246
247   return TRUE;
248
249 ecmd_failed:
250   if (errno == ENOTTY) {
251     GST_INFO_OBJECT (v4l2object->element,
252         "Failed to send encoder command %u with flags %u for '%s'. (%s)",
253         cmd, flags, v4l2object->videodev, g_strerror (errno));
254   } else {
255     GST_ERROR_OBJECT (v4l2object->element,
256         "Failed to send encoder command %u with flags %u for '%s'. (%s)",
257         cmd, flags, v4l2object->videodev, g_strerror (errno));
258   }
259   return FALSE;
260 }
261
262 static GstFlowReturn
263 gst_v4l2_video_enc_finish (GstVideoEncoder * encoder)
264 {
265   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
266   GstFlowReturn ret = GST_FLOW_OK;
267
268   if (gst_pad_get_task_state (encoder->srcpad) != GST_TASK_STARTED)
269     goto done;
270
271   GST_DEBUG_OBJECT (self, "Finishing encoding");
272
273   /* drop the stream lock while draining, so remaining buffers can be
274    * pushed from the src pad task thread */
275   GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
276
277   if (gst_v4l2_encoder_cmd (self->v4l2capture, V4L2_ENC_CMD_STOP, 0)) {
278     GstTask *task = encoder->srcpad->task;
279
280     /* Wait for the task to be drained */
281     GST_OBJECT_LOCK (task);
282     while (GST_TASK_STATE (task) == GST_TASK_STARTED)
283       GST_TASK_WAIT (task);
284     GST_OBJECT_UNLOCK (task);
285     ret = GST_FLOW_FLUSHING;
286   }
287
288   /* and ensure the processing thread has stopped in case another error
289    * occured. */
290   gst_v4l2_object_unlock (self->v4l2capture);
291   gst_pad_stop_task (encoder->srcpad);
292   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
293
294   if (ret == GST_FLOW_FLUSHING)
295     ret = self->output_flow;
296
297   GST_DEBUG_OBJECT (encoder, "Done draining buffers");
298
299 done:
300   return ret;
301 }
302
303 static gboolean
304 gst_v4l2_video_enc_set_format (GstVideoEncoder * encoder,
305     GstVideoCodecState * state)
306 {
307   gboolean ret = TRUE;
308   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
309   GstV4l2Error error = GST_V4L2_ERROR_INIT;
310   GstCaps *outcaps;
311   GstVideoCodecState *output;
312
313   GST_DEBUG_OBJECT (self, "Setting format: %" GST_PTR_FORMAT, state->caps);
314
315   if (self->input_state) {
316     if (gst_v4l2_object_caps_equal (self->v4l2output, state->caps)) {
317       GST_DEBUG_OBJECT (self, "Compatible caps");
318       return TRUE;
319     }
320
321     if (gst_v4l2_video_enc_finish (encoder) != GST_FLOW_OK)
322       return FALSE;
323
324     gst_video_codec_state_unref (self->input_state);
325     self->input_state = NULL;
326   }
327
328   outcaps = gst_pad_get_pad_template_caps (encoder->srcpad);
329   outcaps = gst_caps_make_writable (outcaps);
330   output = gst_video_encoder_set_output_state (encoder, outcaps, state);
331   gst_video_codec_state_unref (output);
332
333   if (!gst_video_encoder_negotiate (encoder))
334     return FALSE;
335
336   if (!gst_v4l2_object_set_format (self->v4l2output, state->caps, &error)) {
337     gst_v4l2_error (self, &error);
338     return FALSE;
339   }
340
341   self->input_state = gst_video_codec_state_ref (state);
342
343   GST_DEBUG_OBJECT (self, "output caps: %" GST_PTR_FORMAT, state->caps);
344
345   return ret;
346 }
347
348 static gboolean
349 gst_v4l2_video_enc_flush (GstVideoEncoder * encoder)
350 {
351   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
352
353   GST_DEBUG_OBJECT (self, "Flushing");
354
355   /* Ensure the processing thread has stopped for the reverse playback
356    * iscount case */
357   if (g_atomic_int_get (&self->processing)) {
358     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
359
360     gst_v4l2_object_unlock_stop (self->v4l2output);
361     gst_v4l2_object_unlock_stop (self->v4l2capture);
362     gst_pad_stop_task (encoder->srcpad);
363
364     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
365
366   }
367
368   self->output_flow = GST_FLOW_OK;
369
370   gst_v4l2_object_unlock_stop (self->v4l2output);
371   gst_v4l2_object_unlock_stop (self->v4l2capture);
372
373   return TRUE;
374 }
375
376 struct ProfileLevelCtx
377 {
378   GstV4l2VideoEnc *self;
379   const gchar *profile;
380   const gchar *level;
381 };
382
383 static gboolean
384 get_string_list (GstStructure * s, const gchar * field, GQueue * queue)
385 {
386   const GValue *value;
387
388   value = gst_structure_get_value (s, field);
389
390   if (!value)
391     return FALSE;
392
393   if (GST_VALUE_HOLDS_LIST (value)) {
394     guint i;
395
396     if (gst_value_list_get_size (value) == 0)
397       return FALSE;
398
399     for (i = 0; i < gst_value_list_get_size (value); i++) {
400       const GValue *item = gst_value_list_get_value (value, i);
401
402       if (G_VALUE_HOLDS_STRING (item))
403         g_queue_push_tail (queue, g_value_dup_string (item));
404     }
405   } else if (G_VALUE_HOLDS_STRING (value)) {
406     g_queue_push_tail (queue, g_value_dup_string (value));
407   }
408
409   return TRUE;
410 }
411
412 static gboolean
413 negotiate_profile_and_level (GstCapsFeatures * features, GstStructure * s,
414     gpointer user_data)
415 {
416   struct ProfileLevelCtx *ctx = user_data;
417   GstV4l2VideoEncClass *klass = GST_V4L2_VIDEO_ENC_GET_CLASS (ctx->self);
418   GstV4l2Object *v4l2object = GST_V4L2_VIDEO_ENC (ctx->self)->v4l2output;
419   GQueue profiles = G_QUEUE_INIT;
420   GQueue levels = G_QUEUE_INIT;
421   gboolean failed = FALSE;
422
423   if (klass->profile_cid && get_string_list (s, "profile", &profiles)) {
424     GList *l;
425
426     for (l = profiles.head; l; l = l->next) {
427       struct v4l2_control control = { 0, };
428       gint v4l2_profile;
429       const gchar *profile = l->data;
430
431       GST_TRACE_OBJECT (ctx->self, "Trying profile %s", profile);
432
433       control.id = klass->profile_cid;
434       control.value = v4l2_profile = klass->profile_from_string (profile);
435
436       if (control.value < 0)
437         continue;
438
439       if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_S_CTRL, &control) < 0) {
440         GST_WARNING_OBJECT (ctx->self, "Failed to set %s profile: '%s'",
441             klass->codec_name, g_strerror (errno));
442         break;
443       }
444
445       profile = klass->profile_to_string (control.value);
446
447       if (control.value == v4l2_profile) {
448         ctx->profile = profile;
449         break;
450       }
451
452       if (g_list_find_custom (l, profile, g_str_equal)) {
453         ctx->profile = profile;
454         break;
455       }
456     }
457
458     if (profiles.length && !ctx->profile)
459       failed = TRUE;
460
461     g_queue_foreach (&profiles, (GFunc) g_free, NULL);
462     g_queue_clear (&profiles);
463   }
464
465   if (!failed && klass->level_cid && get_string_list (s, "level", &levels)) {
466     GList *l;
467
468     for (l = levels.head; l; l = l->next) {
469       struct v4l2_control control = { 0, };
470       gint v4l2_level;
471       const gchar *level = l->data;
472
473       GST_TRACE_OBJECT (ctx->self, "Trying level %s", level);
474
475       control.id = klass->level_cid;
476       control.value = v4l2_level = klass->level_from_string (level);
477
478       if (control.value < 0)
479         continue;
480
481       if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_S_CTRL, &control) < 0) {
482         GST_WARNING_OBJECT (ctx->self, "Failed to set %s level: '%s'",
483             klass->codec_name, g_strerror (errno));
484         break;
485       }
486
487       level = klass->level_to_string (control.value);
488
489       if (control.value == v4l2_level) {
490         ctx->level = level;
491         break;
492       }
493
494       if (g_list_find_custom (l, level, g_str_equal)) {
495         ctx->level = level;
496         break;
497       }
498     }
499
500     if (levels.length && !ctx->level)
501       failed = TRUE;
502
503     g_queue_foreach (&levels, (GFunc) g_free, NULL);
504     g_queue_clear (&levels);
505   }
506
507   /* If it failed, we continue */
508   return failed;
509 }
510
511 static gboolean
512 gst_v4l2_video_enc_negotiate (GstVideoEncoder * encoder)
513 {
514   GstV4l2VideoEncClass *klass = GST_V4L2_VIDEO_ENC_GET_CLASS (encoder);
515   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
516   GstV4l2Object *v4l2object = self->v4l2output;
517   GstCaps *allowed_caps;
518   struct ProfileLevelCtx ctx = { self, NULL, NULL };
519   GstVideoCodecState *state;
520   GstStructure *s;
521
522   GST_DEBUG_OBJECT (self, "Negotiating %s profile and level.",
523       klass->codec_name);
524
525   allowed_caps = gst_pad_get_allowed_caps (GST_VIDEO_ENCODER_SRC_PAD (encoder));
526
527   if (allowed_caps) {
528
529     if (gst_caps_is_empty (allowed_caps))
530       goto not_negotiated;
531
532     allowed_caps = gst_caps_make_writable (allowed_caps);
533
534     /* negotiate_profile_and_level() will return TRUE on failure to keep
535      * iterating, if gst_caps_foreach() returns TRUE it means there was no
536      * compatible profile and level in any of the structure */
537     if (gst_caps_foreach (allowed_caps, negotiate_profile_and_level, &ctx)) {
538       goto no_profile_level;
539     }
540   }
541
542   if (klass->profile_cid && !ctx.profile) {
543     struct v4l2_control control = { 0, };
544
545     control.id = klass->profile_cid;
546
547     if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_G_CTRL, &control) < 0)
548       goto g_ctrl_failed;
549
550     ctx.profile = klass->profile_to_string (control.value);
551   }
552
553   if (klass->level_cid && !ctx.level) {
554     struct v4l2_control control = { 0, };
555
556     control.id = klass->level_cid;
557
558     if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_G_CTRL, &control) < 0)
559       goto g_ctrl_failed;
560
561     ctx.level = klass->level_to_string (control.value);
562   }
563
564   GST_DEBUG_OBJECT (self, "Selected %s profile %s at level %s",
565       klass->codec_name, ctx.profile, ctx.level);
566
567   state = gst_video_encoder_get_output_state (encoder);
568   s = gst_caps_get_structure (state->caps, 0);
569
570   if (klass->profile_cid)
571     gst_structure_set (s, "profile", G_TYPE_STRING, ctx.profile, NULL);
572
573   if (klass->level_cid)
574     gst_structure_set (s, "level", G_TYPE_STRING, ctx.level, NULL);
575
576   if (!GST_VIDEO_ENCODER_CLASS (parent_class)->negotiate (encoder))
577     return FALSE;
578
579   if (!gst_buffer_pool_set_active (GST_BUFFER_POOL (self->v4l2capture->pool),
580           TRUE)) {
581     GST_WARNING_OBJECT (self, "Could not activate capture buffer pool.");
582     return FALSE;
583   }
584
585   return TRUE;
586
587 g_ctrl_failed:
588   GST_WARNING_OBJECT (self, "Failed to get %s profile and level: '%s'",
589       klass->codec_name, g_strerror (errno));
590   goto not_negotiated;
591
592 no_profile_level:
593   GST_WARNING_OBJECT (self, "No compatible level and profile in caps: %"
594       GST_PTR_FORMAT, allowed_caps);
595   goto not_negotiated;
596
597 not_negotiated:
598   if (allowed_caps)
599     gst_caps_unref (allowed_caps);
600   return FALSE;
601 }
602
603 static GstVideoCodecFrame *
604 gst_v4l2_video_enc_get_oldest_frame (GstVideoEncoder * encoder)
605 {
606   GstVideoCodecFrame *frame = NULL;
607   GList *frames, *l;
608   gint count = 0;
609
610   frames = gst_video_encoder_get_frames (encoder);
611
612   for (l = frames; l != NULL; l = l->next) {
613     GstVideoCodecFrame *f = l->data;
614
615     if (!frame || frame->pts > f->pts)
616       frame = f;
617
618     count++;
619   }
620
621   if (frame) {
622     GST_LOG_OBJECT (encoder,
623         "Oldest frame is %d %" GST_TIME_FORMAT
624         " and %d frames left",
625         frame->system_frame_number, GST_TIME_ARGS (frame->pts), count - 1);
626     gst_video_codec_frame_ref (frame);
627   }
628
629   g_list_free_full (frames, (GDestroyNotify) gst_video_codec_frame_unref);
630
631   return frame;
632 }
633
634 static void
635 gst_v4l2_video_enc_loop (GstVideoEncoder * encoder)
636 {
637   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
638   GstVideoCodecFrame *frame;
639   GstBuffer *buffer = NULL;
640   GstFlowReturn ret;
641
642   GST_LOG_OBJECT (encoder, "Allocate output buffer");
643
644   buffer = gst_video_encoder_allocate_output_buffer (encoder,
645       self->v4l2capture->info.size);
646
647   if (NULL == buffer) {
648     ret = GST_FLOW_FLUSHING;
649     goto beach;
650   }
651
652
653   /* FIXME Check if buffer isn't the last one here */
654
655   GST_LOG_OBJECT (encoder, "Process output buffer");
656   ret =
657       gst_v4l2_buffer_pool_process (GST_V4L2_BUFFER_POOL
658       (self->v4l2capture->pool), &buffer);
659
660   if (ret != GST_FLOW_OK)
661     goto beach;
662
663   frame = gst_v4l2_video_enc_get_oldest_frame (encoder);
664
665   if (frame) {
666     frame->output_buffer = buffer;
667     buffer = NULL;
668     ret = gst_video_encoder_finish_frame (encoder, frame);
669
670     if (ret != GST_FLOW_OK)
671       goto beach;
672   } else {
673     GST_WARNING_OBJECT (encoder, "Encoder is producing too many buffers");
674     gst_buffer_unref (buffer);
675   }
676
677   return;
678
679 beach:
680   GST_DEBUG_OBJECT (encoder, "Leaving output thread");
681
682   gst_buffer_replace (&buffer, NULL);
683   self->output_flow = ret;
684   g_atomic_int_set (&self->processing, FALSE);
685   gst_v4l2_object_unlock (self->v4l2output);
686   gst_pad_pause_task (encoder->srcpad);
687 }
688
689 static void
690 gst_v4l2_video_enc_loop_stopped (GstV4l2VideoEnc * self)
691 {
692   if (g_atomic_int_get (&self->processing)) {
693     GST_DEBUG_OBJECT (self, "Early stop of encoding thread");
694     self->output_flow = GST_FLOW_FLUSHING;
695     g_atomic_int_set (&self->processing, FALSE);
696   }
697
698   GST_DEBUG_OBJECT (self, "Encoding task destroyed: %s",
699       gst_flow_get_name (self->output_flow));
700
701 }
702
703 static GstFlowReturn
704 gst_v4l2_video_enc_handle_frame (GstVideoEncoder * encoder,
705     GstVideoCodecFrame * frame)
706 {
707   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
708   GstFlowReturn ret = GST_FLOW_OK;
709
710   GST_DEBUG_OBJECT (self, "Handling frame %d", frame->system_frame_number);
711
712   if (G_UNLIKELY (!g_atomic_int_get (&self->active)))
713     goto flushing;
714
715   if (gst_pad_get_task_state (GST_VIDEO_DECODER_SRC_PAD (self)) ==
716       GST_TASK_STOPPED) {
717     GstBufferPool *pool = GST_BUFFER_POOL (self->v4l2output->pool);
718
719     /* It possible that the processing thread stopped due to an error */
720     if (self->output_flow != GST_FLOW_OK &&
721         self->output_flow != GST_FLOW_FLUSHING) {
722       GST_DEBUG_OBJECT (self, "Processing loop stopped with error, leaving");
723       ret = self->output_flow;
724       goto drop;
725     }
726
727     /* Ensure input internal pool is active */
728     if (!gst_buffer_pool_is_active (pool)) {
729       GstStructure *config = gst_buffer_pool_get_config (pool);
730       guint min = MAX (self->v4l2output->min_buffers, GST_V4L2_MIN_BUFFERS);
731
732       gst_buffer_pool_config_set_params (config, self->input_state->caps,
733           self->v4l2output->info.size, min, min);
734
735       /* There is no reason to refuse this config */
736       if (!gst_buffer_pool_set_config (pool, config))
737         goto activate_failed;
738
739       if (!gst_buffer_pool_set_active (pool, TRUE))
740         goto activate_failed;
741     }
742
743     GST_DEBUG_OBJECT (self, "Starting encoding thread");
744
745     /* Start the processing task, when it quits, the task will disable input
746      * processing to unlock input if draining, or prevent potential block */
747     if (!gst_pad_start_task (encoder->srcpad,
748             (GstTaskFunction) gst_v4l2_video_enc_loop, self,
749             (GDestroyNotify) gst_v4l2_video_enc_loop_stopped))
750       goto start_task_failed;
751   }
752
753   if (frame->input_buffer) {
754     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
755     ret =
756         gst_v4l2_buffer_pool_process (GST_V4L2_BUFFER_POOL
757         (self->v4l2output->pool), &frame->input_buffer);
758     GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
759
760     if (ret == GST_FLOW_FLUSHING) {
761       if (gst_pad_get_task_state (GST_VIDEO_DECODER_SRC_PAD (self)) !=
762           GST_TASK_STARTED)
763         ret = self->output_flow;
764       goto drop;
765     } else if (ret != GST_FLOW_OK) {
766       goto process_failed;
767     }
768   }
769
770   gst_video_codec_frame_unref (frame);
771   return ret;
772
773   /* ERRORS */
774 activate_failed:
775   {
776     GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
777         (_("Failed to allocate required memory.")),
778         ("Buffer pool activation failed"));
779     return GST_FLOW_ERROR;
780
781   }
782 flushing:
783   {
784     ret = GST_FLOW_FLUSHING;
785     goto drop;
786   }
787 start_task_failed:
788   {
789     GST_ELEMENT_ERROR (self, RESOURCE, FAILED,
790         (_("Failed to start encoding thread.")), (NULL));
791     g_atomic_int_set (&self->processing, FALSE);
792     ret = GST_FLOW_ERROR;
793     goto drop;
794   }
795 process_failed:
796   {
797     GST_ELEMENT_ERROR (self, RESOURCE, FAILED,
798         (_("Failed to process frame.")),
799         ("Maybe be due to not enough memory or failing driver"));
800     ret = GST_FLOW_ERROR;
801     goto drop;
802   }
803 drop:
804   {
805     gst_video_encoder_finish_frame (encoder, frame);
806     return ret;
807   }
808 }
809
810 static gboolean
811 gst_v4l2_video_enc_decide_allocation (GstVideoEncoder *
812     encoder, GstQuery * query)
813 {
814   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
815   GstVideoCodecState *state = gst_video_encoder_get_output_state (encoder);
816   GstV4l2Error error = GST_V4L2_ERROR_INIT;
817   GstClockTime latency;
818   gboolean ret = FALSE;
819
820   /* We need to set the format here, since this is called right after
821    * GstVideoEncoder have set the width, height and framerate into the state
822    * caps. These are needed by the driver to calculate the buffer size and to
823    * implement bitrate adaptation. */
824   if (!gst_v4l2_object_set_format (self->v4l2capture, state->caps, &error)) {
825     gst_v4l2_error (self, &error);
826     ret = FALSE;
827     goto done;
828   }
829
830   if (gst_v4l2_object_decide_allocation (self->v4l2capture, query)) {
831     GstVideoEncoderClass *enc_class = GST_VIDEO_ENCODER_CLASS (parent_class);
832     ret = enc_class->decide_allocation (encoder, query);
833   }
834
835   /* FIXME This may not be entirely correct, as encoder may keep some
836    * observation withouth delaying the encoding. Linux Media API need some
837    * more work to explicitly expressed the decoder / encoder latency. This
838    * value will then become max latency, and the reported driver latency would
839    * become the min latency. */
840   latency = self->v4l2capture->min_buffers * self->v4l2capture->duration;
841   gst_video_encoder_set_latency (encoder, latency, latency);
842
843 done:
844   gst_video_codec_state_unref (state);
845   return ret;
846 }
847
848 static gboolean
849 gst_v4l2_video_enc_propose_allocation (GstVideoEncoder *
850     encoder, GstQuery * query)
851 {
852   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
853   gboolean ret = FALSE;
854
855   GST_DEBUG_OBJECT (self, "called");
856
857   if (query == NULL)
858     ret = TRUE;
859   else
860     ret = gst_v4l2_object_propose_allocation (self->v4l2output, query);
861
862   if (ret)
863     ret = GST_VIDEO_ENCODER_CLASS (parent_class)->propose_allocation (encoder,
864         query);
865
866   return ret;
867 }
868
869 static gboolean
870 gst_v4l2_video_enc_src_query (GstVideoEncoder * encoder, GstQuery * query)
871 {
872   gboolean ret = TRUE;
873   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
874   switch (GST_QUERY_TYPE (query)) {
875     case GST_QUERY_CAPS:{
876       GstCaps *filter, *result = NULL;
877       GstPad *pad = GST_VIDEO_ENCODER_SRC_PAD (encoder);
878
879       gst_query_parse_caps (query, &filter);
880
881       /* FIXME Try and not probe the entire encoder, but only the implement
882        * subclass format */
883       if (self->probed_srccaps) {
884         GstCaps *tmpl = gst_pad_get_pad_template_caps (pad);
885         result = gst_caps_intersect (tmpl, self->probed_srccaps);
886         gst_caps_unref (tmpl);
887       } else
888         result = gst_pad_get_pad_template_caps (pad);
889
890       if (filter) {
891         GstCaps *tmp = result;
892         result =
893             gst_caps_intersect_full (filter, tmp, GST_CAPS_INTERSECT_FIRST);
894         gst_caps_unref (tmp);
895       }
896
897       GST_DEBUG_OBJECT (self, "Returning src caps %" GST_PTR_FORMAT, result);
898
899       gst_query_set_caps_result (query, result);
900       gst_caps_unref (result);
901       break;
902     }
903
904     default:
905       ret = GST_VIDEO_ENCODER_CLASS (parent_class)->src_query (encoder, query);
906       break;
907   }
908
909   return ret;
910 }
911
912 static gboolean
913 gst_v4l2_video_enc_sink_query (GstVideoEncoder * encoder, GstQuery * query)
914 {
915   gboolean ret = TRUE;
916   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
917
918   switch (GST_QUERY_TYPE (query)) {
919     case GST_QUERY_CAPS:{
920       GstCaps *filter, *result = NULL;
921       GstPad *pad = GST_VIDEO_ENCODER_SINK_PAD (encoder);
922
923       gst_query_parse_caps (query, &filter);
924
925       if (self->probed_sinkcaps)
926         result = gst_caps_ref (self->probed_sinkcaps);
927       else
928         result = gst_pad_get_pad_template_caps (pad);
929
930       if (filter) {
931         GstCaps *tmp = result;
932         result =
933             gst_caps_intersect_full (filter, tmp, GST_CAPS_INTERSECT_FIRST);
934         gst_caps_unref (tmp);
935       }
936
937       GST_DEBUG_OBJECT (self, "Returning sink caps %" GST_PTR_FORMAT, result);
938
939       gst_query_set_caps_result (query, result);
940       gst_caps_unref (result);
941       break;
942     }
943
944     default:
945       ret = GST_VIDEO_ENCODER_CLASS (parent_class)->sink_query (encoder, query);
946       break;
947   }
948
949   return ret;
950 }
951
952 static gboolean
953 gst_v4l2_video_enc_sink_event (GstVideoEncoder * encoder, GstEvent * event)
954 {
955   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
956   gboolean ret;
957
958   switch (GST_EVENT_TYPE (event)) {
959     case GST_EVENT_FLUSH_START:
960       GST_DEBUG_OBJECT (self, "flush start");
961       gst_v4l2_object_unlock (self->v4l2output);
962       gst_v4l2_object_unlock (self->v4l2capture);
963       break;
964     default:
965       break;
966   }
967
968   ret = GST_VIDEO_ENCODER_CLASS (parent_class)->sink_event (encoder, event);
969
970   switch (GST_EVENT_TYPE (event)) {
971     case GST_EVENT_FLUSH_START:
972       gst_pad_stop_task (encoder->srcpad);
973       GST_DEBUG_OBJECT (self, "flush start done");
974     default:
975       break;
976   }
977
978   return ret;
979 }
980
981 static GstStateChangeReturn
982 gst_v4l2_video_enc_change_state (GstElement * element,
983     GstStateChange transition)
984 {
985   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (element);
986
987   if (transition == GST_STATE_CHANGE_PAUSED_TO_READY) {
988     g_atomic_int_set (&self->active, FALSE);
989     gst_v4l2_object_unlock (self->v4l2output);
990     gst_v4l2_object_unlock (self->v4l2capture);
991   }
992
993   return GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
994 }
995
996
997 static void
998 gst_v4l2_video_enc_dispose (GObject * object)
999 {
1000   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (object);
1001
1002   gst_caps_replace (&self->probed_sinkcaps, NULL);
1003   gst_caps_replace (&self->probed_srccaps, NULL);
1004
1005   G_OBJECT_CLASS (parent_class)->dispose (object);
1006 }
1007
1008 static void
1009 gst_v4l2_video_enc_finalize (GObject * object)
1010 {
1011   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (object);
1012
1013   gst_v4l2_object_destroy (self->v4l2capture);
1014   gst_v4l2_object_destroy (self->v4l2output);
1015
1016   G_OBJECT_CLASS (parent_class)->finalize (object);
1017 }
1018
1019
1020 static void
1021 gst_v4l2_video_enc_init (GstV4l2VideoEnc * self)
1022 {
1023   /* V4L2 object are created in subinstance_init */
1024 }
1025
1026 static void
1027 gst_v4l2_video_enc_subinstance_init (GTypeInstance * instance, gpointer g_class)
1028 {
1029   GstV4l2VideoEncClass *klass = GST_V4L2_VIDEO_ENC_CLASS (g_class);
1030   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (instance);
1031
1032   self->v4l2output = gst_v4l2_object_new (GST_ELEMENT (self),
1033       V4L2_BUF_TYPE_VIDEO_OUTPUT, klass->default_device,
1034       gst_v4l2_get_output, gst_v4l2_set_output, NULL);
1035   self->v4l2output->no_initial_format = TRUE;
1036   self->v4l2output->keep_aspect = FALSE;
1037
1038   self->v4l2capture = gst_v4l2_object_new (GST_ELEMENT (self),
1039       V4L2_BUF_TYPE_VIDEO_CAPTURE, klass->default_device,
1040       gst_v4l2_get_input, gst_v4l2_set_input, NULL);
1041   self->v4l2capture->no_initial_format = TRUE;
1042   self->v4l2output->keep_aspect = FALSE;
1043 }
1044
1045 static void
1046 gst_v4l2_video_enc_class_init (GstV4l2VideoEncClass * klass)
1047 {
1048   GstElementClass *element_class;
1049   GObjectClass *gobject_class;
1050   GstVideoEncoderClass *video_encoder_class;
1051
1052   parent_class = g_type_class_peek_parent (klass);
1053
1054   element_class = (GstElementClass *) klass;
1055   gobject_class = (GObjectClass *) klass;
1056   video_encoder_class = (GstVideoEncoderClass *) klass;
1057
1058   GST_DEBUG_CATEGORY_INIT (gst_v4l2_video_enc_debug, "v4l2videoenc", 0,
1059       "V4L2 Video Encoder");
1060
1061   gobject_class->dispose = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_dispose);
1062   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_finalize);
1063   gobject_class->set_property =
1064       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_set_property);
1065   gobject_class->get_property =
1066       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_get_property);
1067
1068   video_encoder_class->open = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_open);
1069   video_encoder_class->close = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_close);
1070   video_encoder_class->start = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_start);
1071   video_encoder_class->stop = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_stop);
1072   video_encoder_class->finish = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_finish);
1073   video_encoder_class->flush = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_flush);
1074   video_encoder_class->set_format =
1075       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_set_format);
1076   video_encoder_class->negotiate =
1077       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_negotiate);
1078   video_encoder_class->decide_allocation =
1079       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_decide_allocation);
1080   video_encoder_class->propose_allocation =
1081       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_propose_allocation);
1082   video_encoder_class->sink_query =
1083       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_sink_query);
1084   video_encoder_class->src_query =
1085       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_src_query);
1086   video_encoder_class->sink_event =
1087       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_sink_event);
1088   video_encoder_class->handle_frame =
1089       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_handle_frame);
1090
1091   element_class->change_state =
1092       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_change_state);
1093
1094   gst_v4l2_object_install_m2m_properties_helper (gobject_class);
1095 }
1096
1097 static void
1098 gst_v4l2_video_enc_subclass_init (gpointer g_class, gpointer data)
1099 {
1100   GstV4l2VideoEncClass *klass = GST_V4L2_VIDEO_ENC_CLASS (g_class);
1101   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
1102   GstV4l2VideoEncCData *cdata = data;
1103
1104   klass->default_device = cdata->device;
1105
1106   /* Note: gst_pad_template_new() take the floating ref from the caps */
1107   gst_element_class_add_pad_template (element_class,
1108       gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
1109           cdata->sink_caps));
1110   gst_element_class_add_pad_template (element_class,
1111       gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
1112           cdata->src_caps));
1113
1114   g_free (cdata);
1115 }
1116
1117 /* Probing functions */
1118 gboolean
1119 gst_v4l2_is_video_enc (GstCaps * sink_caps, GstCaps * src_caps,
1120     GstCaps * codec_caps)
1121 {
1122   gboolean ret = FALSE;
1123   gboolean (*check_caps) (const GstCaps *, const GstCaps *);
1124
1125   if (codec_caps) {
1126     check_caps = gst_caps_can_intersect;
1127   } else {
1128     codec_caps = gst_v4l2_object_get_codec_caps ();
1129     check_caps = gst_caps_is_subset;
1130   }
1131
1132   if (gst_caps_is_subset (sink_caps, gst_v4l2_object_get_raw_caps ())
1133       && check_caps (src_caps, gst_v4l2_object_get_codec_caps ()))
1134     ret = TRUE;
1135
1136   return ret;
1137 }
1138
1139 void
1140 gst_v4l2_video_enc_register (GstPlugin * plugin, GType type,
1141     const char *codec, const gchar * basename, const gchar * device_path,
1142     GstCaps * sink_caps, GstCaps * codec_caps, GstCaps * src_caps)
1143 {
1144   GstCaps *filtered_caps;
1145   GTypeQuery type_query;
1146   GTypeInfo type_info = { 0, };
1147   GType subtype;
1148   gchar *type_name;
1149   GstV4l2VideoEncCData *cdata;
1150
1151   filtered_caps = gst_caps_intersect (src_caps, codec_caps);
1152
1153   cdata = g_new0 (GstV4l2VideoEncCData, 1);
1154   cdata->device = g_strdup (device_path);
1155   cdata->sink_caps = gst_caps_ref (sink_caps);
1156   cdata->src_caps = gst_caps_ref (filtered_caps);
1157
1158   g_type_query (type, &type_query);
1159   memset (&type_info, 0, sizeof (type_info));
1160   type_info.class_size = type_query.class_size;
1161   type_info.instance_size = type_query.instance_size;
1162   type_info.class_init = gst_v4l2_video_enc_subclass_init;
1163   type_info.class_data = cdata;
1164   type_info.instance_init = gst_v4l2_video_enc_subinstance_init;
1165
1166   /* The first encoder to be registered should use a constant name, like
1167    * v4l2h264enc, for any additional encoders, we create unique names. Encoder
1168    * names may change between boots, so this should help gain stable names for
1169    * the most common use cases. */
1170   type_name = g_strdup_printf ("v4l2%senc", codec);
1171
1172   if (g_type_from_name (type_name) != 0) {
1173     g_free (type_name);
1174     type_name = g_strdup_printf ("v4l2%s%senc", basename, codec);
1175   }
1176
1177   subtype = g_type_register_static (type, type_name, &type_info, 0);
1178
1179   if (!gst_element_register (plugin, type_name, GST_RANK_PRIMARY + 1, subtype))
1180     GST_WARNING ("Failed to register plugin '%s'", type_name);
1181
1182   g_free (type_name);
1183 }