v4l2videoenc: Set default latency if the frame duration is invalid
[platform/upstream/gstreamer.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   const GstV4l2Codec *codec;
49 } GstV4l2VideoEncCData;
50
51 enum
52 {
53   PROP_0,
54   V4L2_STD_OBJECT_PROPS,
55 };
56
57 #define gst_v4l2_video_enc_parent_class parent_class
58 G_DEFINE_ABSTRACT_TYPE (GstV4l2VideoEnc, gst_v4l2_video_enc,
59     GST_TYPE_VIDEO_ENCODER);
60
61 static void
62 gst_v4l2_video_enc_set_property (GObject * object,
63     guint prop_id, const GValue * value, GParamSpec * pspec)
64 {
65   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (object);
66
67   switch (prop_id) {
68     case PROP_CAPTURE_IO_MODE:
69       if (!gst_v4l2_object_set_property_helper (self->v4l2capture,
70               prop_id, value, pspec)) {
71         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
72       }
73       break;
74
75       /* By default, only set on output */
76     default:
77       if (!gst_v4l2_object_set_property_helper (self->v4l2output,
78               prop_id, value, pspec)) {
79         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
80       }
81       break;
82   }
83 }
84
85 static void
86 gst_v4l2_video_enc_get_property (GObject * object,
87     guint prop_id, GValue * value, GParamSpec * pspec)
88 {
89   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (object);
90
91   switch (prop_id) {
92     case PROP_CAPTURE_IO_MODE:
93       if (!gst_v4l2_object_get_property_helper (self->v4l2capture,
94               prop_id, value, pspec)) {
95         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
96       }
97       break;
98
99       /* By default read from output */
100     default:
101       if (!gst_v4l2_object_get_property_helper (self->v4l2output,
102               prop_id, value, pspec)) {
103         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
104       }
105       break;
106   }
107 }
108
109 static gboolean
110 gst_v4l2_video_enc_open (GstVideoEncoder * encoder)
111 {
112   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
113   GstV4l2Error error = GST_V4L2_ERROR_INIT;
114   GstCaps *codec_caps;
115
116   GST_DEBUG_OBJECT (self, "Opening");
117
118   if (!gst_v4l2_object_open (self->v4l2output, &error))
119     goto failure;
120
121   if (!gst_v4l2_object_open_shared (self->v4l2capture, self->v4l2output))
122     goto failure;
123
124   self->probed_sinkcaps = gst_v4l2_object_probe_caps (self->v4l2output,
125       gst_v4l2_object_get_raw_caps ());
126
127   if (gst_caps_is_empty (self->probed_sinkcaps))
128     goto no_raw_format;
129
130   codec_caps = gst_pad_get_pad_template_caps (encoder->srcpad);
131   self->probed_srccaps = gst_v4l2_object_probe_caps (self->v4l2capture,
132       codec_caps);
133   gst_caps_unref (codec_caps);
134
135   if (gst_caps_is_empty (self->probed_srccaps))
136     goto no_encoded_format;
137
138   return TRUE;
139
140 no_encoded_format:
141   GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
142       (_("Encoder on device %s has no supported output format"),
143           self->v4l2output->videodev), (NULL));
144   goto failure;
145
146
147 no_raw_format:
148   GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
149       (_("Encoder on device %s has no supported input 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   gst_v4l2_error (self, &error);
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_DEBUG_OBJECT (self, "Waiting for encoder stop");
282     GST_OBJECT_LOCK (task);
283     while (GST_TASK_STATE (task) == GST_TASK_STARTED)
284       GST_TASK_WAIT (task);
285     GST_OBJECT_UNLOCK (task);
286     ret = GST_FLOW_FLUSHING;
287   }
288
289   /* and ensure the processing thread has stopped in case another error
290    * occurred. */
291   gst_v4l2_object_unlock (self->v4l2capture);
292   gst_pad_stop_task (encoder->srcpad);
293   GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
294
295   if (ret == GST_FLOW_FLUSHING)
296     ret = self->output_flow;
297
298   GST_DEBUG_OBJECT (encoder, "Done draining buffers");
299
300 done:
301   return ret;
302 }
303
304 static gboolean
305 gst_v4l2_video_enc_set_format (GstVideoEncoder * encoder,
306     GstVideoCodecState * state)
307 {
308   gboolean ret = TRUE;
309   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
310   GstV4l2Error error = GST_V4L2_ERROR_INIT;
311   GstCaps *outcaps;
312   GstVideoCodecState *output;
313
314   GST_DEBUG_OBJECT (self, "Setting format: %" GST_PTR_FORMAT, state->caps);
315
316   if (self->input_state) {
317     if (gst_v4l2_object_caps_equal (self->v4l2output, state->caps)) {
318       GST_DEBUG_OBJECT (self, "Compatible caps");
319       return TRUE;
320     }
321
322     if (gst_v4l2_video_enc_finish (encoder) != GST_FLOW_OK)
323       return FALSE;
324
325     gst_v4l2_object_stop (self->v4l2output);
326     gst_v4l2_object_stop (self->v4l2capture);
327
328     gst_video_codec_state_unref (self->input_state);
329     self->input_state = NULL;
330   }
331
332   outcaps = gst_pad_get_pad_template_caps (encoder->srcpad);
333   outcaps = gst_caps_make_writable (outcaps);
334   output = gst_video_encoder_set_output_state (encoder, outcaps, state);
335   gst_video_codec_state_unref (output);
336
337   if (!gst_video_encoder_negotiate (encoder))
338     return FALSE;
339
340   if (!gst_v4l2_object_set_format (self->v4l2output, state->caps, &error)) {
341     gst_v4l2_error (self, &error);
342     return FALSE;
343   }
344
345   self->input_state = gst_video_codec_state_ref (state);
346
347   GST_DEBUG_OBJECT (self, "output caps: %" GST_PTR_FORMAT, state->caps);
348
349   return ret;
350 }
351
352 static gboolean
353 gst_v4l2_video_enc_flush (GstVideoEncoder * encoder)
354 {
355   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
356
357   GST_DEBUG_OBJECT (self, "Flushing");
358
359   /* Ensure the processing thread has stopped for the reverse playback
360    * iscount case */
361   if (g_atomic_int_get (&self->processing)) {
362     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
363
364     gst_v4l2_object_unlock_stop (self->v4l2output);
365     gst_v4l2_object_unlock_stop (self->v4l2capture);
366     gst_pad_stop_task (encoder->srcpad);
367
368     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
369
370   }
371
372   self->output_flow = GST_FLOW_OK;
373
374   gst_v4l2_object_unlock_stop (self->v4l2output);
375   gst_v4l2_object_unlock_stop (self->v4l2capture);
376
377   return TRUE;
378 }
379
380 struct ProfileLevelCtx
381 {
382   GstV4l2VideoEnc *self;
383   const gchar *profile;
384   const gchar *level;
385 };
386
387 static gboolean
388 get_string_list (GstStructure * s, const gchar * field, GQueue * queue)
389 {
390   const GValue *value;
391
392   value = gst_structure_get_value (s, field);
393
394   if (!value)
395     return FALSE;
396
397   if (GST_VALUE_HOLDS_LIST (value)) {
398     guint i;
399
400     if (gst_value_list_get_size (value) == 0)
401       return FALSE;
402
403     for (i = 0; i < gst_value_list_get_size (value); i++) {
404       const GValue *item = gst_value_list_get_value (value, i);
405
406       if (G_VALUE_HOLDS_STRING (item))
407         g_queue_push_tail (queue, g_value_dup_string (item));
408     }
409   } else if (G_VALUE_HOLDS_STRING (value)) {
410     g_queue_push_tail (queue, g_value_dup_string (value));
411   }
412
413   return TRUE;
414 }
415
416 static gboolean
417 negotiate_profile_and_level (GstCapsFeatures * features, GstStructure * s,
418     gpointer user_data)
419 {
420   struct ProfileLevelCtx *ctx = user_data;
421   GstV4l2VideoEncClass *klass = GST_V4L2_VIDEO_ENC_GET_CLASS (ctx->self);
422   GstV4l2Object *v4l2object = GST_V4L2_VIDEO_ENC (ctx->self)->v4l2output;
423   GQueue profiles = G_QUEUE_INIT;
424   GQueue levels = G_QUEUE_INIT;
425   gboolean failed = FALSE;
426   const GstV4l2Codec *codec = klass->codec;
427
428   if (codec->profile_cid && get_string_list (s, "profile", &profiles)) {
429     GList *l;
430
431     for (l = profiles.head; l; l = l->next) {
432       struct v4l2_control control = { 0, };
433       gint v4l2_profile;
434       const gchar *profile = l->data;
435
436       GST_TRACE_OBJECT (ctx->self, "Trying profile %s", profile);
437
438       control.id = codec->profile_cid;
439
440       control.value = v4l2_profile = codec->profile_from_string (profile);
441
442       if (control.value < 0)
443         continue;
444
445       if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_S_CTRL, &control) < 0) {
446         GST_WARNING_OBJECT (ctx->self, "Failed to set %s profile: '%s'",
447             klass->codec_name, g_strerror (errno));
448         break;
449       }
450
451       profile = codec->profile_to_string (control.value);
452
453       if (control.value == v4l2_profile) {
454         ctx->profile = profile;
455         break;
456       }
457
458       if (g_list_find_custom (l, profile, g_str_equal)) {
459         ctx->profile = profile;
460         break;
461       }
462     }
463
464     if (profiles.length && !ctx->profile)
465       failed = TRUE;
466
467     g_queue_foreach (&profiles, (GFunc) g_free, NULL);
468     g_queue_clear (&profiles);
469   }
470
471   if (!failed && codec->level_cid && get_string_list (s, "level", &levels)) {
472     GList *l;
473
474     for (l = levels.head; l; l = l->next) {
475       struct v4l2_control control = { 0, };
476       gint v4l2_level;
477       const gchar *level = l->data;
478
479       GST_TRACE_OBJECT (ctx->self, "Trying level %s", level);
480
481       control.id = codec->level_cid;
482       control.value = v4l2_level = codec->level_from_string (level);
483
484       if (control.value < 0)
485         continue;
486
487       if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_S_CTRL, &control) < 0) {
488         GST_WARNING_OBJECT (ctx->self, "Failed to set %s level: '%s'",
489             klass->codec_name, g_strerror (errno));
490         break;
491       }
492
493       level = codec->level_to_string (control.value);
494
495       if (control.value == v4l2_level) {
496         ctx->level = level;
497         break;
498       }
499
500       if (g_list_find_custom (l, level, g_str_equal)) {
501         ctx->level = level;
502         break;
503       }
504     }
505
506     if (levels.length && !ctx->level)
507       failed = TRUE;
508
509     g_queue_foreach (&levels, (GFunc) g_free, NULL);
510     g_queue_clear (&levels);
511   }
512
513   /* If it failed, we continue */
514   return failed;
515 }
516
517 static gboolean
518 gst_v4l2_video_enc_negotiate (GstVideoEncoder * encoder)
519 {
520   GstV4l2VideoEncClass *klass = GST_V4L2_VIDEO_ENC_GET_CLASS (encoder);
521   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
522   GstV4l2Object *v4l2object = self->v4l2output;
523   GstCaps *allowed_caps;
524   struct ProfileLevelCtx ctx = { self, NULL, NULL };
525   GstVideoCodecState *state;
526   GstStructure *s;
527   const GstV4l2Codec *codec = klass->codec;
528
529   GST_DEBUG_OBJECT (self, "Negotiating %s profile and level.",
530       klass->codec_name);
531
532   /* Only renegotiate on upstream changes */
533   if (self->input_state)
534     return TRUE;
535
536   if (!codec)
537     goto done;
538
539   allowed_caps = gst_pad_get_allowed_caps (GST_VIDEO_ENCODER_SRC_PAD (encoder));
540
541   if (allowed_caps) {
542
543     if (gst_caps_is_empty (allowed_caps))
544       goto not_negotiated;
545
546     allowed_caps = gst_caps_make_writable (allowed_caps);
547
548     /* negotiate_profile_and_level() will return TRUE on failure to keep
549      * iterating, if gst_caps_foreach() returns TRUE it means there was no
550      * compatible profile and level in any of the structure */
551     if (gst_caps_foreach (allowed_caps, negotiate_profile_and_level, &ctx)) {
552       goto no_profile_level;
553     }
554
555     gst_caps_unref (allowed_caps);
556     allowed_caps = NULL;
557   }
558
559   if (codec->profile_cid && !ctx.profile) {
560     struct v4l2_control control = { 0, };
561
562     control.id = codec->profile_cid;
563
564     if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_G_CTRL, &control) < 0)
565       goto g_ctrl_failed;
566
567     ctx.profile = codec->profile_to_string (control.value);
568   }
569
570   if (codec->level_cid && !ctx.level) {
571     struct v4l2_control control = { 0, };
572
573     control.id = codec->level_cid;
574
575     if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_G_CTRL, &control) < 0)
576       goto g_ctrl_failed;
577
578     ctx.level = codec->level_to_string (control.value);
579   }
580
581   GST_DEBUG_OBJECT (self, "Selected %s profile %s at level %s",
582       klass->codec_name, ctx.profile, ctx.level);
583
584   state = gst_video_encoder_get_output_state (encoder);
585   s = gst_caps_get_structure (state->caps, 0);
586
587   if (codec->profile_cid)
588     gst_structure_set (s, "profile", G_TYPE_STRING, ctx.profile, NULL);
589
590   if (codec->level_cid)
591     gst_structure_set (s, "level", G_TYPE_STRING, ctx.level, NULL);
592
593 done:
594   if (!GST_VIDEO_ENCODER_CLASS (parent_class)->negotiate (encoder))
595     return FALSE;
596
597   return TRUE;
598
599 g_ctrl_failed:
600   GST_WARNING_OBJECT (self, "Failed to get %s profile and level: '%s'",
601       klass->codec_name, g_strerror (errno));
602   goto not_negotiated;
603
604 no_profile_level:
605   GST_WARNING_OBJECT (self, "No compatible level and profile in caps: %"
606       GST_PTR_FORMAT, allowed_caps);
607   goto not_negotiated;
608
609 not_negotiated:
610   if (allowed_caps)
611     gst_caps_unref (allowed_caps);
612   return FALSE;
613 }
614
615 static gboolean
616 check_system_frame_number_too_old (guint32 current, guint32 old)
617 {
618   guint32 absdiff = current > old ? current - old : old - current;
619
620   /* More than 100 frames in the past, or current wrapped around */
621   if (absdiff > 100) {
622     /* Wraparound and difference is actually smaller than 100 */
623     if (absdiff > G_MAXUINT32 - 100)
624       return FALSE;
625     return TRUE;
626   }
627
628   return FALSE;
629 }
630
631 static void
632 gst_v4l2_video_enc_loop (GstVideoEncoder * encoder)
633 {
634   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
635   GstVideoCodecFrame *frame;
636   GstBuffer *buffer = NULL;
637   GstFlowReturn ret;
638
639   GST_LOG_OBJECT (encoder, "Allocate output buffer");
640
641   buffer = gst_video_encoder_allocate_output_buffer (encoder,
642       self->v4l2capture->info.size);
643
644   if (NULL == buffer) {
645     ret = GST_FLOW_FLUSHING;
646     goto beach;
647   }
648
649   /* FIXME Check if buffer isn't the last one here */
650
651   GST_LOG_OBJECT (encoder, "Process output buffer");
652   ret =
653       gst_v4l2_buffer_pool_process (GST_V4L2_BUFFER_POOL
654       (self->v4l2capture->pool), &buffer, NULL);
655
656   if (ret != GST_FLOW_OK)
657     goto beach;
658
659   if (GST_BUFFER_TIMESTAMP (buffer) % GST_SECOND != 0)
660     GST_ERROR_OBJECT (encoder,
661         "Driver bug detected - check driver with v4l2-compliance from http://git.linuxtv.org/v4l-utils.git");
662   GST_LOG_OBJECT (encoder, "Got buffer for frame number %u",
663       (guint32) (GST_BUFFER_PTS (buffer) / GST_SECOND));
664   frame =
665       gst_video_encoder_get_frame (encoder,
666       GST_BUFFER_TIMESTAMP (buffer) / GST_SECOND);
667
668   if (frame) {
669     GstVideoCodecFrame *oldest_frame;
670     gboolean warned = FALSE;
671
672     /* Garbage collect old frames in case of codec bugs */
673     while ((oldest_frame = gst_video_encoder_get_oldest_frame (encoder)) &&
674         check_system_frame_number_too_old (frame->system_frame_number,
675             oldest_frame->system_frame_number)) {
676       gst_video_encoder_finish_frame (encoder, oldest_frame);
677       oldest_frame = NULL;
678
679       if (!warned) {
680         g_warning ("%s: Too old frames, bug in encoder -- please file a bug",
681             GST_ELEMENT_NAME (encoder));
682         warned = TRUE;
683       }
684     }
685     if (oldest_frame)
686       gst_video_codec_frame_unref (oldest_frame);
687
688     /* At this point, the delta unit buffer flag is already correctly set by
689      * gst_v4l2_buffer_pool_process. Since gst_video_encoder_finish_frame
690      * will overwrite it from GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame),
691      * set that here.
692      */
693     if (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT))
694       GST_VIDEO_CODEC_FRAME_UNSET_SYNC_POINT (frame);
695     else
696       GST_VIDEO_CODEC_FRAME_SET_SYNC_POINT (frame);
697     frame->output_buffer = buffer;
698     buffer = NULL;
699     ret = gst_video_encoder_finish_frame (encoder, frame);
700
701     if (ret != GST_FLOW_OK)
702       goto beach;
703   } else {
704     GST_WARNING_OBJECT (encoder, "Encoder is producing too many buffers");
705     gst_buffer_unref (buffer);
706   }
707
708   return;
709
710 beach:
711   GST_DEBUG_OBJECT (encoder, "Leaving output thread");
712
713   gst_buffer_replace (&buffer, NULL);
714   self->output_flow = ret;
715   g_atomic_int_set (&self->processing, FALSE);
716   gst_v4l2_object_unlock (self->v4l2output);
717   gst_pad_pause_task (encoder->srcpad);
718 }
719
720 static void
721 gst_v4l2_video_enc_loop_stopped (GstV4l2VideoEnc * self)
722 {
723   if (g_atomic_int_get (&self->processing)) {
724     GST_DEBUG_OBJECT (self, "Early stop of encoding thread");
725     self->output_flow = GST_FLOW_FLUSHING;
726     g_atomic_int_set (&self->processing, FALSE);
727   }
728
729   GST_DEBUG_OBJECT (self, "Encoding task destroyed: %s",
730       gst_flow_get_name (self->output_flow));
731
732 }
733
734 static GstFlowReturn
735 gst_v4l2_video_enc_handle_frame (GstVideoEncoder * encoder,
736     GstVideoCodecFrame * frame)
737 {
738   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
739   GstFlowReturn ret = GST_FLOW_OK;
740   GstTaskState task_state;
741
742   GST_DEBUG_OBJECT (self, "Handling frame %d", frame->system_frame_number);
743
744   if (G_UNLIKELY (!g_atomic_int_get (&self->active)))
745     goto flushing;
746
747   task_state = gst_pad_get_task_state (GST_VIDEO_ENCODER_SRC_PAD (self));
748   if (task_state == GST_TASK_STOPPED || task_state == GST_TASK_PAUSED) {
749     GstBufferPool *pool = GST_BUFFER_POOL (self->v4l2output->pool);
750
751     /* It is possible that the processing thread stopped due to an error or
752      * when the last buffer has been met during the draining process. */
753     if (self->output_flow != GST_FLOW_OK &&
754         self->output_flow != GST_FLOW_FLUSHING &&
755         self->output_flow != GST_V4L2_FLOW_LAST_BUFFER) {
756       GST_DEBUG_OBJECT (self, "Processing loop stopped with error: %s, leaving",
757           gst_flow_get_name (self->output_flow));
758       ret = self->output_flow;
759       goto drop;
760     }
761
762     /* Ensure input internal pool is active */
763     if (!gst_buffer_pool_is_active (pool)) {
764       GstStructure *config = gst_buffer_pool_get_config (pool);
765       guint min = MAX (self->v4l2output->min_buffers,
766           GST_V4L2_MIN_BUFFERS (self->v4l2output));
767
768       gst_buffer_pool_config_set_params (config, self->input_state->caps,
769           self->v4l2output->info.size, min, min);
770
771       /* There is no reason to refuse this config */
772       if (!gst_buffer_pool_set_config (pool, config))
773         goto activate_failed;
774
775       if (!gst_buffer_pool_set_active (pool, TRUE))
776         goto activate_failed;
777     }
778
779     if (!gst_buffer_pool_set_active
780         (GST_BUFFER_POOL (self->v4l2capture->pool), TRUE)) {
781       GST_WARNING_OBJECT (self, "Could not activate capture buffer pool.");
782       goto activate_failed;
783     }
784
785     GST_DEBUG_OBJECT (self, "Starting encoding thread");
786
787     /* Start the processing task, when it quits, the task will disable input
788      * processing to unlock input if draining, or prevent potential block */
789     if (!gst_pad_start_task (encoder->srcpad,
790             (GstTaskFunction) gst_v4l2_video_enc_loop, self,
791             (GDestroyNotify) gst_v4l2_video_enc_loop_stopped))
792       goto start_task_failed;
793   }
794
795   if (frame->input_buffer) {
796     GST_VIDEO_ENCODER_STREAM_UNLOCK (encoder);
797     GST_LOG_OBJECT (encoder, "Passing buffer with frame number %u",
798         frame->system_frame_number);
799     ret =
800         gst_v4l2_buffer_pool_process (GST_V4L2_BUFFER_POOL (self->
801             v4l2output->pool), &frame->input_buffer,
802         &frame->system_frame_number);
803     GST_VIDEO_ENCODER_STREAM_LOCK (encoder);
804
805     if (ret == GST_FLOW_FLUSHING) {
806       if (gst_pad_get_task_state (encoder->srcpad) != GST_TASK_STARTED)
807         ret = self->output_flow;
808       goto drop;
809     } else if (ret != GST_FLOW_OK) {
810       goto process_failed;
811     }
812   }
813
814   gst_video_codec_frame_unref (frame);
815   return ret;
816
817   /* ERRORS */
818 activate_failed:
819   {
820     GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
821         (_("Failed to allocate required memory.")),
822         ("Buffer pool activation failed"));
823     return GST_FLOW_ERROR;
824
825   }
826 flushing:
827   {
828     ret = GST_FLOW_FLUSHING;
829     goto drop;
830   }
831 start_task_failed:
832   {
833     GST_ELEMENT_ERROR (self, RESOURCE, FAILED,
834         (_("Failed to start encoding thread.")), (NULL));
835     g_atomic_int_set (&self->processing, FALSE);
836     ret = GST_FLOW_ERROR;
837     goto drop;
838   }
839 process_failed:
840   {
841     GST_ELEMENT_ERROR (self, RESOURCE, FAILED,
842         (_("Failed to process frame.")),
843         ("Maybe be due to not enough memory or failing driver"));
844     ret = GST_FLOW_ERROR;
845     goto drop;
846   }
847 drop:
848   {
849     gst_video_encoder_finish_frame (encoder, frame);
850     return ret;
851   }
852 }
853
854 static gboolean
855 gst_v4l2_video_enc_decide_allocation (GstVideoEncoder *
856     encoder, GstQuery * query)
857 {
858   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
859   GstVideoCodecState *state = gst_video_encoder_get_output_state (encoder);
860   GstCaps *caps;
861   GstV4l2Error error = GST_V4L2_ERROR_INIT;
862   GstClockTime latency;
863   gboolean ret = FALSE;
864
865   /* We need to set the format here, since this is called right after
866    * GstVideoEncoder have set the width, height and framerate into the state
867    * caps. These are needed by the driver to calculate the buffer size and to
868    * implement bitrate adaptation. */
869   caps = gst_caps_copy (state->caps);
870   gst_structure_remove_field (gst_caps_get_structure (caps, 0), "colorimetry");
871   if (!gst_v4l2_object_set_format (self->v4l2capture, caps, &error)) {
872     gst_v4l2_error (self, &error);
873     gst_caps_unref (caps);
874     ret = FALSE;
875     goto done;
876   }
877   gst_caps_unref (caps);
878
879   if (gst_v4l2_object_decide_allocation (self->v4l2capture, query)) {
880     GstVideoEncoderClass *enc_class = GST_VIDEO_ENCODER_CLASS (parent_class);
881     ret = enc_class->decide_allocation (encoder, query);
882   }
883
884   /* FIXME This may not be entirely correct, as encoder may keep some
885    * observation without delaying the encoding. Linux Media API need some
886    * more work to explicitly expressed the decoder / encoder latency. This
887    * value will then become max latency, and the reported driver latency would
888    * become the min latency. */
889   if (!GST_CLOCK_TIME_IS_VALID (self->v4l2capture->duration))
890     self->v4l2capture->duration = gst_util_uint64_scale_int (GST_SECOND, 1, 25);
891   latency = self->v4l2capture->min_buffers * self->v4l2capture->duration;
892   gst_video_encoder_set_latency (encoder, latency, latency);
893   GST_DEBUG_OBJECT (self, "Setting latency: %" GST_TIME_FORMAT,
894       GST_TIME_ARGS (latency));
895
896 done:
897   gst_video_codec_state_unref (state);
898   return ret;
899 }
900
901 static gboolean
902 gst_v4l2_video_enc_propose_allocation (GstVideoEncoder *
903     encoder, GstQuery * query)
904 {
905   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
906   gboolean ret = FALSE;
907
908   GST_DEBUG_OBJECT (self, "called");
909
910   if (query == NULL)
911     ret = TRUE;
912   else
913     ret = gst_v4l2_object_propose_allocation (self->v4l2output, query);
914
915   if (ret)
916     ret = GST_VIDEO_ENCODER_CLASS (parent_class)->propose_allocation (encoder,
917         query);
918
919   return ret;
920 }
921
922 static gboolean
923 gst_v4l2_video_enc_src_query (GstVideoEncoder * encoder, GstQuery * query)
924 {
925   gboolean ret = TRUE;
926   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
927   switch (GST_QUERY_TYPE (query)) {
928     case GST_QUERY_CAPS:{
929       GstCaps *filter, *result = NULL;
930       GstPad *pad = GST_VIDEO_ENCODER_SRC_PAD (encoder);
931
932       gst_query_parse_caps (query, &filter);
933
934       /* FIXME Try and not probe the entire encoder, but only the implement
935        * subclass format */
936       if (self->probed_srccaps) {
937         GstCaps *tmpl = gst_pad_get_pad_template_caps (pad);
938         result = gst_caps_intersect (tmpl, self->probed_srccaps);
939         gst_caps_unref (tmpl);
940       } else
941         result = gst_pad_get_pad_template_caps (pad);
942
943       if (filter) {
944         GstCaps *tmp = result;
945         result =
946             gst_caps_intersect_full (filter, tmp, GST_CAPS_INTERSECT_FIRST);
947         gst_caps_unref (tmp);
948       }
949
950       GST_DEBUG_OBJECT (self, "Returning src caps %" GST_PTR_FORMAT, result);
951
952       gst_query_set_caps_result (query, result);
953       gst_caps_unref (result);
954       break;
955     }
956
957     default:
958       ret = GST_VIDEO_ENCODER_CLASS (parent_class)->src_query (encoder, query);
959       break;
960   }
961
962   return ret;
963 }
964
965 static gboolean
966 gst_v4l2_video_enc_sink_query (GstVideoEncoder * encoder, GstQuery * query)
967 {
968   gboolean ret = TRUE;
969   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
970
971   switch (GST_QUERY_TYPE (query)) {
972     case GST_QUERY_CAPS:{
973       GstCaps *filter, *result = NULL;
974       GstPad *pad = GST_VIDEO_ENCODER_SINK_PAD (encoder);
975
976       gst_query_parse_caps (query, &filter);
977
978       if (self->probed_sinkcaps)
979         result = gst_caps_ref (self->probed_sinkcaps);
980       else
981         result = gst_pad_get_pad_template_caps (pad);
982
983       if (filter) {
984         GstCaps *tmp = result;
985         result =
986             gst_caps_intersect_full (filter, tmp, GST_CAPS_INTERSECT_FIRST);
987         gst_caps_unref (tmp);
988       }
989
990       GST_DEBUG_OBJECT (self, "Returning sink caps %" GST_PTR_FORMAT, result);
991
992       gst_query_set_caps_result (query, result);
993       gst_caps_unref (result);
994       break;
995     }
996
997     default:
998       ret = GST_VIDEO_ENCODER_CLASS (parent_class)->sink_query (encoder, query);
999       break;
1000   }
1001
1002   return ret;
1003 }
1004
1005 static gboolean
1006 gst_v4l2_video_enc_sink_event (GstVideoEncoder * encoder, GstEvent * event)
1007 {
1008   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (encoder);
1009   gboolean ret;
1010   GstEventType type = GST_EVENT_TYPE (event);
1011
1012   switch (type) {
1013     case GST_EVENT_FLUSH_START:
1014       GST_DEBUG_OBJECT (self, "flush start");
1015       gst_v4l2_object_unlock (self->v4l2output);
1016       gst_v4l2_object_unlock (self->v4l2capture);
1017       break;
1018     default:
1019       break;
1020   }
1021
1022   ret = GST_VIDEO_ENCODER_CLASS (parent_class)->sink_event (encoder, event);
1023
1024   switch (type) {
1025     case GST_EVENT_FLUSH_START:
1026       gst_pad_stop_task (encoder->srcpad);
1027       GST_DEBUG_OBJECT (self, "flush start done");
1028     default:
1029       break;
1030   }
1031
1032   return ret;
1033 }
1034
1035 static GstStateChangeReturn
1036 gst_v4l2_video_enc_change_state (GstElement * element,
1037     GstStateChange transition)
1038 {
1039   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (element);
1040
1041   if (transition == GST_STATE_CHANGE_PAUSED_TO_READY) {
1042     g_atomic_int_set (&self->active, FALSE);
1043     gst_v4l2_object_unlock (self->v4l2output);
1044     gst_v4l2_object_unlock (self->v4l2capture);
1045   }
1046
1047   return GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1048 }
1049
1050
1051 static void
1052 gst_v4l2_video_enc_dispose (GObject * object)
1053 {
1054   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (object);
1055
1056   gst_caps_replace (&self->probed_sinkcaps, NULL);
1057   gst_caps_replace (&self->probed_srccaps, NULL);
1058
1059   G_OBJECT_CLASS (parent_class)->dispose (object);
1060 }
1061
1062 static void
1063 gst_v4l2_video_enc_finalize (GObject * object)
1064 {
1065   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (object);
1066
1067   gst_v4l2_object_destroy (self->v4l2capture);
1068   gst_v4l2_object_destroy (self->v4l2output);
1069
1070   G_OBJECT_CLASS (parent_class)->finalize (object);
1071 }
1072
1073
1074 static void
1075 gst_v4l2_video_enc_init (GstV4l2VideoEnc * self)
1076 {
1077   /* V4L2 object are created in subinstance_init */
1078 }
1079
1080 static void
1081 gst_v4l2_video_enc_subinstance_init (GTypeInstance * instance, gpointer g_class)
1082 {
1083   GstV4l2VideoEncClass *klass = GST_V4L2_VIDEO_ENC_CLASS (g_class);
1084   GstV4l2VideoEnc *self = GST_V4L2_VIDEO_ENC (instance);
1085
1086   self->v4l2output = gst_v4l2_object_new (GST_ELEMENT (self),
1087       GST_OBJECT (GST_VIDEO_ENCODER_SINK_PAD (self)),
1088       V4L2_BUF_TYPE_VIDEO_OUTPUT, klass->default_device,
1089       gst_v4l2_get_output, gst_v4l2_set_output, NULL);
1090   self->v4l2output->no_initial_format = TRUE;
1091   self->v4l2output->keep_aspect = FALSE;
1092
1093   self->v4l2capture = gst_v4l2_object_new (GST_ELEMENT (self),
1094       GST_OBJECT (GST_VIDEO_ENCODER_SRC_PAD (self)),
1095       V4L2_BUF_TYPE_VIDEO_CAPTURE, klass->default_device,
1096       gst_v4l2_get_input, gst_v4l2_set_input, NULL);
1097 }
1098
1099 static void
1100 gst_v4l2_video_enc_class_init (GstV4l2VideoEncClass * klass)
1101 {
1102   GstElementClass *element_class;
1103   GObjectClass *gobject_class;
1104   GstVideoEncoderClass *video_encoder_class;
1105
1106   parent_class = g_type_class_peek_parent (klass);
1107
1108   element_class = (GstElementClass *) klass;
1109   gobject_class = (GObjectClass *) klass;
1110   video_encoder_class = (GstVideoEncoderClass *) klass;
1111
1112   GST_DEBUG_CATEGORY_INIT (gst_v4l2_video_enc_debug, "v4l2videoenc", 0,
1113       "V4L2 Video Encoder");
1114
1115   gobject_class->dispose = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_dispose);
1116   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_finalize);
1117   gobject_class->set_property =
1118       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_set_property);
1119   gobject_class->get_property =
1120       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_get_property);
1121
1122   video_encoder_class->open = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_open);
1123   video_encoder_class->close = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_close);
1124   video_encoder_class->start = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_start);
1125   video_encoder_class->stop = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_stop);
1126   video_encoder_class->finish = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_finish);
1127   video_encoder_class->flush = GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_flush);
1128   video_encoder_class->set_format =
1129       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_set_format);
1130   video_encoder_class->negotiate =
1131       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_negotiate);
1132   video_encoder_class->decide_allocation =
1133       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_decide_allocation);
1134   video_encoder_class->propose_allocation =
1135       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_propose_allocation);
1136   video_encoder_class->sink_query =
1137       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_sink_query);
1138   video_encoder_class->src_query =
1139       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_src_query);
1140   video_encoder_class->sink_event =
1141       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_sink_event);
1142   video_encoder_class->handle_frame =
1143       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_handle_frame);
1144
1145   element_class->change_state =
1146       GST_DEBUG_FUNCPTR (gst_v4l2_video_enc_change_state);
1147
1148   gst_v4l2_object_install_m2m_properties_helper (gobject_class);
1149 }
1150
1151 static void
1152 gst_v4l2_video_enc_subclass_init (gpointer g_class, gpointer data)
1153 {
1154   GstV4l2VideoEncClass *klass = GST_V4L2_VIDEO_ENC_CLASS (g_class);
1155   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
1156   GstV4l2VideoEncCData *cdata = data;
1157
1158   klass->default_device = cdata->device;
1159   klass->codec = cdata->codec;
1160
1161   gst_element_class_add_pad_template (element_class,
1162       gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
1163           cdata->sink_caps));
1164   gst_element_class_add_pad_template (element_class,
1165       gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
1166           cdata->src_caps));
1167
1168   gst_caps_unref (cdata->sink_caps);
1169   gst_caps_unref (cdata->src_caps);
1170   g_free (cdata);
1171 }
1172
1173 /* Probing functions */
1174 gboolean
1175 gst_v4l2_is_video_enc (GstCaps * sink_caps, GstCaps * src_caps,
1176     GstCaps * codec_caps)
1177 {
1178   gboolean ret = FALSE;
1179   gboolean (*check_caps) (const GstCaps *, const GstCaps *);
1180
1181   if (codec_caps) {
1182     check_caps = gst_caps_can_intersect;
1183   } else {
1184     codec_caps = gst_v4l2_object_get_codec_caps ();
1185     check_caps = gst_caps_is_subset;
1186   }
1187
1188   if (gst_caps_is_subset (sink_caps, gst_v4l2_object_get_raw_caps ())
1189       && check_caps (src_caps, codec_caps))
1190     ret = TRUE;
1191
1192   return ret;
1193 }
1194
1195 void
1196 gst_v4l2_video_enc_register (GstPlugin * plugin, GType type,
1197     const char *codec_name, const gchar * basename, const gchar * device_path,
1198     const GstV4l2Codec * codec, gint video_fd, GstCaps * sink_caps,
1199     GstCaps * codec_caps, GstCaps * src_caps)
1200 {
1201   GstCaps *filtered_caps;
1202   GTypeQuery type_query;
1203   GTypeInfo type_info = { 0, };
1204   GType subtype;
1205   gchar *type_name;
1206   GstV4l2VideoEncCData *cdata;
1207   GValue value = G_VALUE_INIT;
1208
1209   filtered_caps = gst_caps_intersect (src_caps, codec_caps);
1210
1211   if (codec != NULL && video_fd != -1) {
1212     if (gst_v4l2_codec_probe_levels (codec, video_fd, &value)) {
1213       gst_caps_set_value (filtered_caps, "level", &value);
1214       g_value_unset (&value);
1215     }
1216
1217     if (gst_v4l2_codec_probe_profiles (codec, video_fd, &value)) {
1218       gst_caps_set_value (filtered_caps, "profile", &value);
1219       g_value_unset (&value);
1220     }
1221   }
1222
1223   cdata = g_new0 (GstV4l2VideoEncCData, 1);
1224   cdata->device = g_strdup (device_path);
1225   cdata->sink_caps = gst_caps_ref (sink_caps);
1226   cdata->src_caps = gst_caps_ref (filtered_caps);
1227   cdata->codec = codec;
1228
1229   g_type_query (type, &type_query);
1230   memset (&type_info, 0, sizeof (type_info));
1231   type_info.class_size = type_query.class_size;
1232   type_info.instance_size = type_query.instance_size;
1233   type_info.class_init = gst_v4l2_video_enc_subclass_init;
1234   type_info.class_data = cdata;
1235   type_info.instance_init = gst_v4l2_video_enc_subinstance_init;
1236
1237   /* The first encoder to be registered should use a constant name, like
1238    * v4l2h264enc, for any additional encoders, we create unique names. Encoder
1239    * names may change between boots, so this should help gain stable names for
1240    * the most common use cases. */
1241   type_name = g_strdup_printf ("v4l2%senc", codec_name);
1242
1243   if (g_type_from_name (type_name) != 0) {
1244     g_free (type_name);
1245     type_name = g_strdup_printf ("v4l2%s%senc", basename, codec_name);
1246   }
1247
1248   subtype = g_type_register_static (type, type_name, &type_info, 0);
1249
1250   if (!gst_element_register (plugin, type_name, GST_RANK_PRIMARY + 1, subtype))
1251     GST_WARNING ("Failed to register plugin '%s'", type_name);
1252
1253   g_free (type_name);
1254 }