v4l2codecs: Wait for buffers to come back
[platform/upstream/gstreamer.git] / sys / v4l2codecs / gstv4l2codech264dec.c
1 /* GStreamer
2  * Copyright (C) 2020 Nicolas Dufresne <nicolas.dufresne@collabora.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
23
24 #include "gstv4l2codecallocator.h"
25 #include "gstv4l2codech264dec.h"
26 #include "gstv4l2codecpool.h"
27 #include "linux/h264-ctrls.h"
28
29 GST_DEBUG_CATEGORY_STATIC (v4l2_h264dec_debug);
30 #define GST_CAT_DEFAULT v4l2_h264dec_debug
31
32 enum
33 {
34   PROP_0,
35   PROP_LAST = PROP_0
36 };
37
38 static GstStaticPadTemplate sink_template =
39 GST_STATIC_PAD_TEMPLATE (GST_VIDEO_DECODER_SINK_NAME,
40     GST_PAD_SINK, GST_PAD_ALWAYS,
41     GST_STATIC_CAPS ("video/x-h264, "
42         "stream-format=(string) byte-stream, alignment=(string) au")
43     );
44
45 static GstStaticPadTemplate src_template =
46 GST_STATIC_PAD_TEMPLATE (GST_VIDEO_DECODER_SRC_NAME,
47     GST_PAD_SRC, GST_PAD_ALWAYS,
48     GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE ("{ NV12, YUY2 }")));
49
50 struct _GstV4l2CodecH264Dec
51 {
52   GstH264Decoder parent;
53   GstV4l2Decoder *decoder;
54   GstVideoCodecState *output_state;
55   GstVideoInfo vinfo;
56   gint display_width;
57   gint display_height;
58   gint coded_width;
59   gint coded_height;
60   guint bitdepth;
61   guint chroma_format_idc;
62
63   GstV4l2CodecAllocator *sink_allocator;
64   GstV4l2CodecAllocator *src_allocator;
65   GstV4l2CodecPool *src_pool;
66   gint min_pool_size;
67   gboolean has_videometa;
68   gboolean need_negotiation;
69   gboolean copy_frames;
70
71   struct v4l2_ctrl_h264_sps sps;
72   struct v4l2_ctrl_h264_pps pps;
73   struct v4l2_ctrl_h264_scaling_matrix scaling_matrix;
74   struct v4l2_ctrl_h264_decode_params decode_params;
75   GArray *slice_params;
76
77   GstMemory *bitstream;
78   GstMapInfo bitstream_map;
79 };
80
81 G_DEFINE_ABSTRACT_TYPE_WITH_CODE (GstV4l2CodecH264Dec,
82     gst_v4l2_codec_h264_dec, GST_TYPE_H264_DECODER,
83     GST_DEBUG_CATEGORY_INIT (v4l2_h264dec_debug, "v4l2codecs-h264dec", 0,
84         "V4L2 stateless h264 decoder"));
85 #define parent_class gst_v4l2_codec_h264_dec_parent_class
86
87 static gboolean
88 gst_v4l2_codec_h264_dec_open (GstVideoDecoder * decoder)
89 {
90   GstV4l2CodecH264Dec *self = GST_V4L2_CODEC_H264_DEC (decoder);
91
92   if (!gst_v4l2_decoder_open (self->decoder)) {
93     GST_ELEMENT_ERROR (self, RESOURCE, OPEN_READ_WRITE,
94         ("Failed to open H264 decoder"),
95         ("gst_v4l2_decoder_open() failed: %s", g_strerror (errno)));
96     return FALSE;
97   }
98
99   return TRUE;
100 }
101
102 static gboolean
103 gst_v4l2_codec_h264_dec_close (GstVideoDecoder * decoder)
104 {
105   GstV4l2CodecH264Dec *self = GST_V4L2_CODEC_H264_DEC (decoder);
106   gst_v4l2_decoder_close (self->decoder);
107   return TRUE;
108 }
109
110 static void
111 gst_v4l2_codec_h264_dec_reset_allocation (GstV4l2CodecH264Dec * self)
112 {
113   if (self->sink_allocator) {
114     gst_v4l2_codec_allocator_detach (self->sink_allocator);
115     g_clear_object (&self->sink_allocator);
116   }
117
118   if (self->src_allocator) {
119     gst_v4l2_codec_allocator_detach (self->src_allocator);
120     g_clear_object (&self->src_allocator);
121     g_clear_object (&self->src_pool);
122   }
123 }
124
125 static gboolean
126 gst_v4l2_codec_h264_dec_stop (GstVideoDecoder * decoder)
127 {
128   GstV4l2CodecH264Dec *self = GST_V4L2_CODEC_H264_DEC (decoder);
129
130   gst_v4l2_decoder_streamoff (self->decoder, GST_PAD_SINK);
131   gst_v4l2_decoder_streamoff (self->decoder, GST_PAD_SRC);
132
133   gst_v4l2_codec_h264_dec_reset_allocation (self);
134
135   if (self->output_state)
136     gst_video_codec_state_unref (self->output_state);
137   self->output_state = NULL;
138
139   return GST_VIDEO_DECODER_CLASS (parent_class)->stop (decoder);
140 }
141
142 static gboolean
143 gst_v4l2_codec_h264_dec_negotiate (GstVideoDecoder * decoder)
144 {
145   GstV4l2CodecH264Dec *self = GST_V4L2_CODEC_H264_DEC (decoder);
146   GstH264Decoder *h264dec = GST_H264_DECODER (decoder);
147   /* *INDENT-OFF* */
148   struct v4l2_ext_control control[] = {
149     {
150       .id = V4L2_CID_MPEG_VIDEO_H264_SPS,
151       .ptr = &self->sps,
152       .size = sizeof (self->sps),
153     },
154   };
155   /* *INDENT-ON* */
156   GstCaps *filter, *caps;
157
158   /* Ignore downstream renegotiation request. */
159   if (!self->need_negotiation)
160     return TRUE;
161   self->need_negotiation = FALSE;
162
163   GST_DEBUG_OBJECT (self, "Negotiate");
164
165   gst_v4l2_codec_h264_dec_reset_allocation (self);
166
167   gst_v4l2_decoder_streamoff (self->decoder, GST_PAD_SINK);
168   gst_v4l2_decoder_streamoff (self->decoder, GST_PAD_SRC);
169
170   if (!gst_v4l2_decoder_set_sink_fmt (self->decoder, V4L2_PIX_FMT_H264_SLICE,
171           self->coded_width, self->coded_height)) {
172     GST_ELEMENT_ERROR (self, CORE, NEGOTIATION,
173         ("Failed to configure H264 decoder"),
174         ("gst_v4l2_decoder_set_sink_fmt() failed: %s", g_strerror (errno)));
175     gst_v4l2_decoder_close (self->decoder);
176     return FALSE;
177   }
178
179   if (!gst_v4l2_decoder_set_controls (self->decoder, NULL, control,
180           G_N_ELEMENTS (control))) {
181     GST_ELEMENT_ERROR (decoder, RESOURCE, WRITE,
182         ("Driver does not support the selected stream."), (NULL));
183     return FALSE;
184   }
185
186   filter = gst_v4l2_decoder_enum_src_formats (self->decoder);
187   GST_DEBUG_OBJECT (self, "Supported output formats: %" GST_PTR_FORMAT, filter);
188
189   caps = gst_pad_peer_query_caps (decoder->srcpad, filter);
190   gst_caps_unref (filter);
191   GST_DEBUG_OBJECT (self, "Peer supported formats: %" GST_PTR_FORMAT, caps);
192
193   if (!gst_v4l2_decoder_select_src_format (self->decoder, caps, &self->vinfo)) {
194     GST_ELEMENT_ERROR (self, CORE, NEGOTIATION,
195         ("Unsupported bitdepth/chroma format"),
196         ("No support for %ux%u %ubit chroma IDC %i", self->coded_width,
197             self->coded_height, self->bitdepth, self->chroma_format_idc));
198     gst_caps_unref (caps);
199     return FALSE;
200   }
201   gst_caps_unref (caps);
202
203   if (self->output_state)
204     gst_video_codec_state_unref (self->output_state);
205
206   self->output_state =
207       gst_video_decoder_set_output_state (GST_VIDEO_DECODER (self),
208       self->vinfo.finfo->format, self->display_width,
209       self->display_height, h264dec->input_state);
210
211   self->output_state->caps = gst_video_info_to_caps (&self->output_state->info);
212
213   if (GST_VIDEO_DECODER_CLASS (parent_class)->negotiate (decoder)) {
214     if (!gst_v4l2_decoder_streamon (self->decoder, GST_PAD_SINK)) {
215       GST_ELEMENT_ERROR (self, RESOURCE, FAILED,
216           ("Could not enable the decoder driver."),
217           ("VIDIOC_STREAMON(SINK) failed: %s", g_strerror (errno)));
218       return FALSE;
219     }
220
221     if (!gst_v4l2_decoder_streamon (self->decoder, GST_PAD_SRC)) {
222       GST_ELEMENT_ERROR (self, RESOURCE, FAILED,
223           ("Could not enable the decoder driver."),
224           ("VIDIOC_STREAMON(SRC) failed: %s", g_strerror (errno)));
225       return FALSE;
226     }
227
228     return TRUE;
229   }
230
231   return FALSE;
232 }
233
234 static gboolean
235 gst_v4l2_codec_h264_dec_decide_allocation (GstVideoDecoder * decoder,
236     GstQuery * query)
237 {
238   GstV4l2CodecH264Dec *self = GST_V4L2_CODEC_H264_DEC (decoder);
239   guint min = 0;
240
241   self->has_videometa = gst_query_find_allocation_meta (query,
242       GST_VIDEO_META_API_TYPE, NULL);
243
244   g_clear_object (&self->src_pool);
245   g_clear_object (&self->src_allocator);
246
247   if (gst_query_get_n_allocation_pools (query) > 0)
248     gst_query_parse_nth_allocation_pool (query, 0, NULL, NULL, &min, NULL);
249
250   min = MAX (2, min);
251
252   self->sink_allocator = gst_v4l2_codec_allocator_new (self->decoder,
253       GST_PAD_SINK, self->min_pool_size + 2);
254   self->src_allocator = gst_v4l2_codec_allocator_new (self->decoder,
255       GST_PAD_SRC, self->min_pool_size + min + 4);
256   self->src_pool = gst_v4l2_codec_pool_new (self->src_allocator, &self->vinfo);
257
258   /* Our buffer pool is internal, we will let the base class create a video
259    * pool, and use it if we are running out of buffers or if downstream does
260    * not support GstVideoMeta */
261   return GST_VIDEO_DECODER_CLASS (parent_class)->decide_allocation
262       (decoder, query);
263 }
264
265 static void
266 gst_v4l2_codec_h264_dec_fill_sequence (GstV4l2CodecH264Dec * self,
267     const GstH264SPS * sps)
268 {
269   gint i;
270
271   /* *INDENT-OFF* */
272   self->sps = (struct v4l2_ctrl_h264_sps) {
273     .profile_idc = sps->profile_idc,
274     .constraint_set_flags = (sps->constraint_set0_flag)
275         | (sps->constraint_set1_flag << 1) | (sps->constraint_set2_flag << 2)
276         | (sps->constraint_set3_flag << 3) | (sps->constraint_set4_flag << 4)
277         | (sps->constraint_set5_flag << 5),
278     .level_idc = sps->level_idc,
279     .seq_parameter_set_id = sps->id,
280     .chroma_format_idc = sps->chroma_format_idc,
281     .bit_depth_luma_minus8 = sps->bit_depth_luma_minus8,
282     .bit_depth_chroma_minus8 = sps->bit_depth_chroma_minus8,
283     .log2_max_frame_num_minus4 = sps->log2_max_frame_num_minus4,
284     .pic_order_cnt_type = sps->pic_order_cnt_type,
285     .log2_max_pic_order_cnt_lsb_minus4 = sps->log2_max_pic_order_cnt_lsb_minus4,
286     .max_num_ref_frames = sps->num_ref_frames,
287     .num_ref_frames_in_pic_order_cnt_cycle = sps->num_ref_frames_in_pic_order_cnt_cycle,
288     .offset_for_non_ref_pic = sps->offset_for_non_ref_pic,
289     .offset_for_top_to_bottom_field = sps->offset_for_top_to_bottom_field,
290     .pic_width_in_mbs_minus1 = sps->pic_width_in_mbs_minus1,
291     .pic_height_in_map_units_minus1 = sps->pic_height_in_map_units_minus1,
292     .flags = (sps->separate_colour_plane_flag ? V4L2_H264_SPS_FLAG_SEPARATE_COLOUR_PLANE : 0)
293         | (sps->qpprime_y_zero_transform_bypass_flag ? V4L2_H264_SPS_FLAG_QPPRIME_Y_ZERO_TRANSFORM_BYPASS : 0)
294         | (sps->delta_pic_order_always_zero_flag ? V4L2_H264_SPS_FLAG_DELTA_PIC_ORDER_ALWAYS_ZERO : 0)
295         | (sps->gaps_in_frame_num_value_allowed_flag ? V4L2_H264_SPS_FLAG_GAPS_IN_FRAME_NUM_VALUE_ALLOWED : 0)
296         | (sps->frame_mbs_only_flag ? V4L2_H264_SPS_FLAG_FRAME_MBS_ONLY : 0)
297         | (sps->mb_adaptive_frame_field_flag ? V4L2_H264_SPS_FLAG_MB_ADAPTIVE_FRAME_FIELD : 0)
298         | (sps->direct_8x8_inference_flag ? V4L2_H264_SPS_FLAG_DIRECT_8X8_INFERENCE : 0),
299   };
300   /* *INDENT-ON* */
301
302   for (i = 0; i < sps->num_ref_frames_in_pic_order_cnt_cycle; i++)
303     self->sps.offset_for_ref_frame[i] = sps->offset_for_ref_frame[i];
304 }
305
306 static void
307 gst_v4l2_codec_h264_dec_fill_pps (GstV4l2CodecH264Dec * self, GstH264PPS * pps)
308 {
309   /* *INDENT-OFF* */
310   self->pps = (struct v4l2_ctrl_h264_pps) {
311     .pic_parameter_set_id = pps->id,
312     .seq_parameter_set_id = pps->sequence->id,
313     .num_slice_groups_minus1 = pps->num_slice_groups_minus1,
314     .num_ref_idx_l0_default_active_minus1 = pps->num_ref_idx_l0_active_minus1,
315     .num_ref_idx_l1_default_active_minus1 = pps->num_ref_idx_l1_active_minus1,
316     .weighted_bipred_idc = pps->weighted_bipred_idc,
317     .pic_init_qp_minus26 = pps->pic_init_qp_minus26,
318     .pic_init_qs_minus26 = pps->pic_init_qs_minus26,
319     .chroma_qp_index_offset = pps->chroma_qp_index_offset,
320     .second_chroma_qp_index_offset = pps->second_chroma_qp_index_offset,
321     .flags = 0
322         | (pps->entropy_coding_mode_flag ? V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE : 0)
323         | (pps->pic_order_present_flag ? V4L2_H264_PPS_FLAG_BOTTOM_FIELD_PIC_ORDER_IN_FRAME_PRESENT : 0)
324         | (pps->weighted_pred_flag ? V4L2_H264_PPS_FLAG_WEIGHTED_PRED : 0)
325         | (pps->deblocking_filter_control_present_flag ? V4L2_H264_PPS_FLAG_DEBLOCKING_FILTER_CONTROL_PRESENT : 0)
326         | (pps->constrained_intra_pred_flag ? V4L2_H264_PPS_FLAG_CONSTRAINED_INTRA_PRED : 0)
327         | (pps->redundant_pic_cnt_present_flag ? V4L2_H264_PPS_FLAG_REDUNDANT_PIC_CNT_PRESENT : 0)
328         | (pps->transform_8x8_mode_flag ? V4L2_H264_PPS_FLAG_TRANSFORM_8X8_MODE : 0)
329         | (pps->pic_scaling_matrix_present_flag ? V4L2_H264_PPS_FLAG_PIC_SCALING_MATRIX_PRESENT : 0),
330   };
331   /* *INDENT-ON* */
332 }
333
334 static void
335 gst_v4l2_codec_h264_dec_fill_scaling_matrix (GstV4l2CodecH264Dec * self,
336     GstH264PPS * pps)
337 {
338   gint i, n;
339
340   for (i = 0; i < G_N_ELEMENTS (pps->scaling_lists_4x4); i++)
341     gst_h264_quant_matrix_4x4_get_raster_from_zigzag (self->
342         scaling_matrix.scaling_list_4x4[i], pps->scaling_lists_4x4[i]);
343
344   /* Avoid uninitialize data passed into ioctl() */
345   memset (self->scaling_matrix.scaling_list_8x8, 0,
346       sizeof (self->scaling_matrix.scaling_list_8x8));
347
348   /* We need the first 2 entries (Y intra and Y inter for YCbCr 4:2:2 and
349    * less, and the full 6 entries for 4:4:4, see Table 7-2 of the spec for
350    * more details */
351   n = (pps->sequence->chroma_format_idc == 3) ? 6 : 2;
352   for (i = 0; i < n; i++)
353     gst_h264_quant_matrix_8x8_get_raster_from_zigzag (self->
354         scaling_matrix.scaling_list_8x8[i], pps->scaling_lists_8x8[i]);
355 }
356
357 static void
358 gst_v4l2_codec_h264_dec_fill_decoder_params (GstV4l2CodecH264Dec * self,
359     GstH264Picture * picture, GstH264Dpb * dpb)
360 {
361   GArray *refs = gst_h264_dpb_get_pictures_all (dpb);
362   gint i;
363
364   /* *INDENT-OFF* */
365   self->decode_params = (struct v4l2_ctrl_h264_decode_params) {
366     .num_slices = 0,            /* will be incremented as we receive slices */
367     .nal_ref_idc = picture->nal_ref_idc,
368     .top_field_order_cnt = picture->top_field_order_cnt,
369     .bottom_field_order_cnt = picture->bottom_field_order_cnt,
370     .flags = picture->idr ? V4L2_H264_DECODE_PARAM_FLAG_IDR_PIC : 0,
371   };
372
373   for (i = 0; i < refs->len; i++) {
374     GstH264Picture *ref_pic = g_array_index (refs, GstH264Picture *, i);
375     self->decode_params.dpb[i] = (struct v4l2_h264_dpb_entry) {
376       /*
377        * The reference is multiplied by 1000 because it's wassed as micro
378        * seconds and this TS is nanosecond.
379        */
380       .reference_ts = ref_pic->system_frame_number * 1000,
381       .frame_num = ref_pic->frame_num,
382       .pic_num = ref_pic->pic_num,
383       .top_field_order_cnt = ref_pic->pic_order_cnt,
384       .bottom_field_order_cnt = ref_pic->bottom_field_order_cnt,
385       .flags = V4L2_H264_DPB_ENTRY_FLAG_VALID
386           | (ref_pic->ref ? V4L2_H264_DPB_ENTRY_FLAG_ACTIVE : 0)
387           | (ref_pic->long_term ? V4L2_H264_DPB_ENTRY_FLAG_LONG_TERM : 0),
388     };
389   }
390   /* *INDENT-ON* */
391
392   g_array_unref (refs);
393 }
394
395 /* FIXME This is from VA-API, need to check if this is what hantro wants */
396 static guint
397 get_slice_header_bit_size (GstH264Slice * slice)
398 {
399   return 8 * slice->nalu.header_bytes
400       + slice->header.header_size - slice->header.n_emulation_prevention_bytes;
401 }
402
403 static void
404 gst_v4l2_codec_h264_dec_fill_slice_params (GstV4l2CodecH264Dec * self,
405     GstH264Slice * slice)
406 {
407   gint n = self->decode_params.num_slices++;
408
409   /* Ensure array is large enough */
410   if (self->slice_params->len < self->decode_params.num_slices)
411     g_array_set_size (self->slice_params, self->slice_params->len * 2);
412
413   /* FIXME This is the subset Hantro uses */
414   /* *INDENT-OFF* */
415   g_array_index (self->slice_params, struct v4l2_ctrl_h264_slice_params, n) =
416       (struct v4l2_ctrl_h264_slice_params) {
417     .size = slice->nalu.size + 3,       /* FIXME HW may not want a start code */
418     .header_bit_size = get_slice_header_bit_size (slice),
419     .first_mb_in_slice = slice->header.first_mb_in_slice,
420     .slice_type = slice->header.type,
421     .pic_parameter_set_id = slice->header.pps->id,
422     .frame_num = slice->header.frame_num,
423     .dec_ref_pic_marking_bit_size = slice->header.dec_ref_pic_marking.bit_size,
424     .idr_pic_id = slice->header.idr_pic_id,
425     .pic_order_cnt_bit_size = slice->header.pic_order_cnt_bit_size,
426   };
427   /* *INDENT-ON* */
428 }
429
430 static gboolean
431 gst_v4l2_codec_h264_dec_new_sequence (GstH264Decoder * decoder,
432     const GstH264SPS * sps, gint max_dpb_size)
433 {
434   GstV4l2CodecH264Dec *self = GST_V4L2_CODEC_H264_DEC (decoder);
435   gint crop_width = sps->width;
436   gint crop_height = sps->height;
437   gboolean negotiation_needed = FALSE;
438
439   if (self->vinfo.finfo->format == GST_VIDEO_FORMAT_UNKNOWN)
440     negotiation_needed = TRUE;
441
442   /* TODO check if CREATE_BUFS is supported, and simply grow the pool */
443   if (self->min_pool_size < max_dpb_size) {
444     self->min_pool_size = max_dpb_size;
445     negotiation_needed = TRUE;
446   }
447
448   if (sps->frame_cropping_flag) {
449     crop_width = sps->crop_rect_width;
450     crop_height = sps->crop_rect_height;
451   }
452
453   /* TODO Check if current buffers are large enough, and reuse them */
454   if (self->display_width != crop_width || self->display_height != crop_height
455       || self->coded_width != sps->width || self->coded_height != sps->height) {
456     self->display_width = crop_width;
457     self->display_height = crop_height;
458     self->coded_width = sps->width;
459     self->coded_height = sps->height;
460     negotiation_needed = TRUE;
461     GST_INFO_OBJECT (self, "Resolution changed to %dx%d (%ix%i)",
462         self->display_width, self->display_height,
463         self->coded_width, self->coded_height);
464   }
465
466   if (self->bitdepth != sps->bit_depth_luma_minus8 + 8) {
467     self->bitdepth = sps->bit_depth_luma_minus8 + 8;
468     negotiation_needed = TRUE;
469     GST_INFO_OBJECT (self, "Bitdepth changed to %u", self->bitdepth);
470   }
471
472   if (self->chroma_format_idc != sps->chroma_format_idc) {
473     self->chroma_format_idc = sps->chroma_format_idc;
474     negotiation_needed = TRUE;
475     GST_INFO_OBJECT (self, "Chroma format changed to %i",
476         self->chroma_format_idc);
477   }
478
479   gst_v4l2_codec_h264_dec_fill_sequence (self, sps);
480
481   if (negotiation_needed) {
482     self->need_negotiation = TRUE;
483     if (!gst_video_decoder_negotiate (GST_VIDEO_DECODER (self))) {
484       GST_ERROR_OBJECT (self, "Failed to negotiate with downstream");
485       return FALSE;
486     }
487   }
488
489   /* Check if we can zero-copy buffers */
490   if (!self->has_videometa) {
491     GstVideoInfo ref_vinfo;
492     gint i;
493
494     gst_video_info_set_format (&ref_vinfo, GST_VIDEO_INFO_FORMAT (&self->vinfo),
495         self->display_width, self->display_height);
496
497     for (i = 0; i < GST_VIDEO_INFO_N_PLANES (&self->vinfo); i++) {
498       if (self->vinfo.stride[i] != ref_vinfo.stride[i] ||
499           self->vinfo.offset[i] != ref_vinfo.offset[i]) {
500         GST_WARNING_OBJECT (self,
501             "GstVideoMeta support required, copying frames.");
502         self->copy_frames = TRUE;
503         break;
504       }
505     }
506   } else {
507     self->copy_frames = FALSE;
508   }
509
510   return TRUE;
511 }
512
513 static gboolean
514 gst_v4l2_codec_h264_dec_start_picture (GstH264Decoder * decoder,
515     GstH264Picture * picture, GstH264Slice * slice, GstH264Dpb * dpb)
516 {
517   GstV4l2CodecH264Dec *self = GST_V4L2_CODEC_H264_DEC (decoder);
518
519   /* FIXME base class should not call us if negotiation failed */
520   if (!self->sink_allocator)
521     return FALSE;
522
523   /* Ensure we have a bitstream to write into */
524   if (!self->bitstream) {
525     self->bitstream = gst_v4l2_codec_allocator_alloc (self->sink_allocator);
526
527     if (!self->bitstream) {
528       GST_ELEMENT_ERROR (decoder, RESOURCE, NO_SPACE_LEFT,
529           ("Not enough memory to decode H264 stream."), (NULL));
530       return FALSE;
531     }
532
533     if (!gst_memory_map (self->bitstream, &self->bitstream_map, GST_MAP_WRITE)) {
534       GST_ELEMENT_ERROR (decoder, RESOURCE, WRITE,
535           ("Could not access bitstream memory for writing"), (NULL));
536       g_clear_pointer (&self->bitstream, gst_memory_unref);
537       return FALSE;
538     }
539   }
540
541   /* We use this field to track how much we have written */
542   self->bitstream_map.size = 0;
543
544   gst_v4l2_codec_h264_dec_fill_pps (self, slice->header.pps);
545   gst_v4l2_codec_h264_dec_fill_scaling_matrix (self, slice->header.pps);
546   gst_v4l2_codec_h264_dec_fill_decoder_params (self, picture, dpb);
547   /* FIXME Move to decode slice */
548   gst_v4l2_codec_h264_dec_fill_slice_params (self, slice);
549
550   return TRUE;
551 }
552
553 static gboolean
554 gst_v4l2_codec_h264_dec_copy_output_buffer (GstV4l2CodecH264Dec * self,
555     GstVideoCodecFrame * codec_frame)
556 {
557   GstVideoFrame src_frame;
558   GstVideoFrame dest_frame;
559   GstVideoInfo dest_vinfo;
560   GstBuffer *buffer;
561
562   gst_video_info_set_format (&dest_vinfo, GST_VIDEO_INFO_FORMAT (&self->vinfo),
563       self->display_width, self->display_height);
564
565   buffer = gst_video_decoder_allocate_output_buffer (GST_VIDEO_DECODER (self));
566   if (!buffer)
567     goto fail;
568
569   if (!gst_video_frame_map (&src_frame, &self->vinfo,
570           codec_frame->output_buffer, GST_MAP_READ))
571     goto fail;
572
573   if (!gst_video_frame_map (&dest_frame, &dest_vinfo, buffer, GST_MAP_WRITE)) {
574     gst_video_frame_unmap (&dest_frame);
575     goto fail;
576   }
577
578   /* gst_video_frame_copy can crop this, but does not know, so let make it
579    * think it's all right */
580   GST_VIDEO_INFO_WIDTH (&src_frame.info) = self->display_width;
581   GST_VIDEO_INFO_HEIGHT (&src_frame.info) = self->display_height;
582
583   if (!gst_video_frame_copy (&dest_frame, &src_frame)) {
584     gst_video_frame_unmap (&src_frame);
585     gst_video_frame_unmap (&dest_frame);
586     goto fail;
587   }
588
589   gst_video_frame_unmap (&src_frame);
590   gst_video_frame_unmap (&dest_frame);
591   gst_buffer_replace (&codec_frame->output_buffer, buffer);
592   gst_buffer_unref (buffer);
593
594   return TRUE;
595
596 fail:
597   GST_ERROR_OBJECT (self, "Failed copy output buffer.");
598   return FALSE;
599 }
600
601 static GstFlowReturn
602 gst_v4l2_codec_h264_dec_output_picture (GstH264Decoder * decoder,
603     GstH264Picture * picture)
604 {
605   GstV4l2CodecH264Dec *self = GST_V4L2_CODEC_H264_DEC (decoder);
606   GstV4l2Request *request = gst_h264_picture_get_user_data (picture);
607   gint ret;
608   guint32 frame_num;
609   GstVideoCodecFrame *frame, *other_frame;
610   GstH264Picture *other_pic;
611   GstV4l2Request *other_request;
612
613   GST_DEBUG_OBJECT (self, "Output picture %u", picture->system_frame_number);
614
615   if (gst_v4l2_request_is_done (request))
616     goto finish_frame;
617
618   ret = gst_v4l2_request_poll (request, GST_SECOND);
619   if (ret == 0) {
620     GST_ELEMENT_ERROR (self, STREAM, DECODE,
621         ("Decoding frame took too long"), (NULL));
622     return GST_FLOW_ERROR;
623   } else if (ret < 0) {
624     GST_ELEMENT_ERROR (self, STREAM, DECODE,
625         ("Decoding request failed: %s", g_strerror (errno)), (NULL));
626     return GST_FLOW_ERROR;
627   }
628
629   while (TRUE) {
630     if (!gst_v4l2_decoder_dequeue_src (self->decoder, &frame_num)) {
631       GST_ELEMENT_ERROR (self, STREAM, DECODE,
632           ("Decoder did not produce a frame"), (NULL));
633       return GST_FLOW_ERROR;
634     }
635
636     if (frame_num == picture->system_frame_number)
637       break;
638
639     other_frame = gst_video_decoder_get_frame (GST_VIDEO_DECODER (self),
640         frame_num);
641     g_return_val_if_fail (other_frame, GST_FLOW_ERROR);
642
643     other_pic = gst_video_codec_frame_get_user_data (other_frame);
644     other_request = gst_h264_picture_get_user_data (other_pic);
645     gst_v4l2_request_set_done (other_request);
646     gst_video_codec_frame_unref (other_frame);
647   }
648
649 finish_frame:
650   gst_v4l2_request_set_done (request);
651   frame = gst_video_decoder_get_frame (GST_VIDEO_DECODER (self),
652       picture->system_frame_number);
653   g_return_val_if_fail (frame, GST_FLOW_ERROR);
654   g_return_val_if_fail (frame->output_buffer, GST_FLOW_ERROR);
655
656   /* Hold on reference buffers for the rest of the picture lifetime */
657   gst_h264_picture_set_user_data (picture,
658       gst_buffer_ref (frame->output_buffer), (GDestroyNotify) gst_buffer_unref);
659
660   if (self->copy_frames)
661     gst_v4l2_codec_h264_dec_copy_output_buffer (self, frame);
662
663   return gst_video_decoder_finish_frame (GST_VIDEO_DECODER (self), frame);
664 }
665
666 static void
667 gst_v4l2_codec_h264_dec_reset_picture (GstV4l2CodecH264Dec * self)
668 {
669   if (self->bitstream) {
670     if (self->bitstream_map.memory)
671       gst_memory_unmap (self->bitstream, &self->bitstream_map);
672     g_clear_pointer (&self->bitstream, gst_memory_unref);
673     self->bitstream_map = (GstMapInfo) GST_MAP_INFO_INIT;
674   }
675
676   self->decode_params.num_slices = 0;
677 }
678
679 static gboolean
680 gst_v4l2_codec_h264_dec_end_picture (GstH264Decoder * decoder,
681     GstH264Picture * picture)
682 {
683   GstV4l2CodecH264Dec *self = GST_V4L2_CODEC_H264_DEC (decoder);
684   GstVideoCodecFrame *frame;
685   GstV4l2Request *request;
686   GstBuffer *buffer;
687   GstFlowReturn flow_ret;
688   gsize bytesused;
689
690   /* *INDENT-OFF* */
691   struct v4l2_ext_control control[] = {
692     {
693       .id = V4L2_CID_MPEG_VIDEO_H264_SPS,
694       .ptr = &self->sps,
695       .size = sizeof (self->sps),
696     },
697     {
698       .id = V4L2_CID_MPEG_VIDEO_H264_PPS,
699       .ptr = &self->pps,
700       .size = sizeof (self->pps),
701     },
702     {
703       .id = V4L2_CID_MPEG_VIDEO_H264_SCALING_MATRIX,
704       .ptr = &self->scaling_matrix,
705       .size = sizeof (self->scaling_matrix),
706     },
707     {
708       .id = V4L2_CID_MPEG_VIDEO_H264_SLICE_PARAMS,
709       .ptr = self->slice_params->data,
710       .size = g_array_get_element_size (self->slice_params)
711               * self->decode_params.num_slices,
712     },
713     {
714       .id = V4L2_CID_MPEG_VIDEO_H264_DECODE_PARAMS,
715       .ptr = &self->decode_params,
716       .size = sizeof (self->decode_params),
717     },
718   };
719   /* *INDENT-ON* */
720
721   request = gst_v4l2_decoder_alloc_request (self->decoder);
722   if (!request) {
723     GST_ELEMENT_ERROR (decoder, RESOURCE, NO_SPACE_LEFT,
724         ("Failed to allocate a media request object."), (NULL));
725     goto fail;
726   }
727
728   gst_h264_picture_set_user_data (picture, request,
729       (GDestroyNotify) gst_v4l2_request_free);
730
731   flow_ret = gst_buffer_pool_acquire_buffer (GST_BUFFER_POOL (self->src_pool),
732       &buffer, NULL);
733   if (flow_ret != GST_FLOW_OK) {
734     if (flow_ret == GST_FLOW_FLUSHING)
735       GST_DEBUG_OBJECT (self, "Frame decoding aborted, we are flushing.");
736     else
737       GST_ELEMENT_ERROR (decoder, RESOURCE, WRITE,
738           ("No more picture buffer available."), (NULL));
739     goto fail;
740   }
741
742   frame = gst_video_decoder_get_frame (GST_VIDEO_DECODER (self),
743       picture->system_frame_number);
744   g_return_val_if_fail (frame, FALSE);
745   g_warn_if_fail (frame->output_buffer == NULL);
746   frame->output_buffer = buffer;
747   gst_video_codec_frame_unref (frame);
748
749   if (!gst_v4l2_decoder_set_controls (self->decoder, request, control,
750           G_N_ELEMENTS (control))) {
751     GST_ELEMENT_ERROR (decoder, RESOURCE, WRITE,
752         ("Driver did not accept the bitstream parameters."), (NULL));
753     goto fail;
754   }
755
756   bytesused = self->bitstream_map.size;
757   gst_memory_unmap (self->bitstream, &self->bitstream_map);
758   self->bitstream_map = (GstMapInfo) GST_MAP_INFO_INIT;
759
760   if (!gst_v4l2_decoder_queue_sink_mem (self->decoder, request, self->bitstream,
761           picture->system_frame_number, bytesused)) {
762     GST_ELEMENT_ERROR (decoder, RESOURCE, WRITE,
763         ("Driver did not accept the bitstream data."), (NULL));
764     goto fail;
765   }
766
767
768   if (!gst_v4l2_decoder_queue_src_buffer (self->decoder, buffer,
769           picture->system_frame_number)) {
770     GST_ELEMENT_ERROR (decoder, RESOURCE, WRITE,
771         ("Driver did not accept the picture buffer."), (NULL));
772     goto fail;
773   }
774
775   if (!gst_v4l2_request_queue (request)) {
776     GST_ELEMENT_ERROR (decoder, RESOURCE, WRITE,
777         ("Driver did not accept the decode request."), (NULL));
778     goto fail;
779   }
780
781   gst_v4l2_codec_h264_dec_reset_picture (self);
782   return TRUE;
783
784 fail:
785   gst_v4l2_codec_h264_dec_reset_picture (self);
786   return FALSE;
787 }
788
789 static gboolean
790 gst_v4l2_codec_h264_dec_decode_slice (GstH264Decoder * decoder,
791     GstH264Picture * picture, GstH264Slice * slice)
792 {
793   GstV4l2CodecH264Dec *self = GST_V4L2_CODEC_H264_DEC (decoder);
794
795   gsize nal_size = 3 + slice->nalu.size;
796   guint8 *bitstream_data = self->bitstream_map.data + self->bitstream_map.size;
797
798   if (self->bitstream_map.size + nal_size > self->bitstream_map.maxsize) {
799     GST_ELEMENT_ERROR (decoder, RESOURCE, NO_SPACE_LEFT,
800         ("Not enough space to send all slice of an H264 frame."), (NULL));
801     return FALSE;
802   }
803
804   /* FIXME check if the HW needs a start code */
805   bitstream_data[0] = 0x00;
806   bitstream_data[1] = 0x00;
807   bitstream_data[2] = 0x01;
808   memcpy (bitstream_data + 3, slice->nalu.data + slice->nalu.offset,
809       slice->nalu.size);
810
811   self->bitstream_map.size += nal_size;
812   return TRUE;
813 }
814
815 static void
816 gst_v4l2_codec_h264_dec_set_flushing (GstV4l2CodecH264Dec * self,
817     gboolean flushing)
818 {
819   if (self->sink_allocator)
820     gst_v4l2_codec_allocator_set_flushing (self->sink_allocator, flushing);
821   if (self->src_allocator)
822     gst_v4l2_codec_allocator_set_flushing (self->src_allocator, flushing);
823 }
824
825 static gboolean
826 gst_v4l2_codec_h264_dec_flush (GstVideoDecoder * decoder)
827 {
828   GstV4l2CodecH264Dec *self = GST_V4L2_CODEC_H264_DEC (decoder);
829
830   GST_DEBUG_OBJECT (self, "Flushing decoder state.");
831
832   gst_v4l2_decoder_flush (self->decoder);
833   gst_v4l2_codec_h264_dec_set_flushing (self, FALSE);
834
835   return GST_VIDEO_DECODER_CLASS (parent_class)->flush (decoder);
836 }
837
838 static gboolean
839 gst_v4l2_codec_h264_dec_sink_event (GstVideoDecoder * decoder, GstEvent * event)
840 {
841   GstV4l2CodecH264Dec *self = GST_V4L2_CODEC_H264_DEC (decoder);
842
843   switch (GST_EVENT_TYPE (event)) {
844     case GST_EVENT_FLUSH_START:
845       GST_DEBUG_OBJECT (self, "flush start");
846       gst_v4l2_codec_h264_dec_set_flushing (self, TRUE);
847       break;
848     default:
849       break;
850   }
851
852   return GST_VIDEO_DECODER_CLASS (parent_class)->sink_event (decoder, event);
853 }
854
855 static GstStateChangeReturn
856 gst_v4l2_codec_h264_dec_change_state (GstElement * element,
857     GstStateChange transition)
858 {
859   GstV4l2CodecH264Dec *self = GST_V4L2_CODEC_H264_DEC (element);
860
861   if (transition == GST_STATE_CHANGE_PAUSED_TO_READY)
862     gst_v4l2_codec_h264_dec_set_flushing (self, TRUE);
863
864   return GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
865 }
866
867 static void
868 gst_v4l2_codec_h264_dec_set_property (GObject * object, guint prop_id,
869     const GValue * value, GParamSpec * pspec)
870 {
871   GstV4l2CodecH264Dec *self = GST_V4L2_CODEC_H264_DEC (object);
872   GObject *dec = G_OBJECT (self->decoder);
873
874   switch (prop_id) {
875     default:
876       gst_v4l2_decoder_set_property (dec, prop_id - PROP_LAST, value, pspec);
877       break;
878   }
879 }
880
881 static void
882 gst_v4l2_codec_h264_dec_get_property (GObject * object, guint prop_id,
883     GValue * value, GParamSpec * pspec)
884 {
885   GstV4l2CodecH264Dec *self = GST_V4L2_CODEC_H264_DEC (object);
886   GObject *dec = G_OBJECT (self->decoder);
887
888   switch (prop_id) {
889     default:
890       gst_v4l2_decoder_get_property (dec, prop_id - PROP_LAST, value, pspec);
891       break;
892   }
893 }
894
895 static void
896 gst_v4l2_codec_h264_dec_init (GstV4l2CodecH264Dec * self)
897 {
898 }
899
900 static void
901 gst_v4l2_codec_h264_dec_subinit (GstV4l2CodecH264Dec * self,
902     GstV4l2CodecH264DecClass * klass)
903 {
904   self->decoder = gst_v4l2_decoder_new (klass->device);
905   gst_video_info_init (&self->vinfo);
906   self->slice_params = g_array_sized_new (FALSE, TRUE,
907       sizeof (struct v4l2_ctrl_h264_slice_params), 4);
908 }
909
910 static void
911 gst_v4l2_codec_h264_dec_dispose (GObject * object)
912 {
913   GstV4l2CodecH264Dec *self = GST_V4L2_CODEC_H264_DEC (object);
914
915   g_clear_object (&self->decoder);
916   g_clear_pointer (&self->slice_params, g_array_unref);
917
918   G_OBJECT_CLASS (parent_class)->dispose (object);
919 }
920
921 static void
922 gst_v4l2_codec_h264_dec_class_init (GstV4l2CodecH264DecClass * klass)
923 {
924 }
925
926 static void
927 gst_v4l2_codec_h264_dec_subclass_init (GstV4l2CodecH264DecClass * klass,
928     GstV4l2CodecDevice * device)
929 {
930   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
931   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
932   GstVideoDecoderClass *decoder_class = GST_VIDEO_DECODER_CLASS (klass);
933   GstH264DecoderClass *h264decoder_class = GST_H264_DECODER_CLASS (klass);
934
935   gobject_class->set_property = gst_v4l2_codec_h264_dec_set_property;
936   gobject_class->get_property = gst_v4l2_codec_h264_dec_get_property;
937   gobject_class->dispose = gst_v4l2_codec_h264_dec_dispose;
938
939   gst_element_class_set_static_metadata (element_class,
940       "V4L2 Stateless H.264 Video Decoder",
941       "Codec/Decoder/Video/Hardware",
942       "A V4L2 based H.264 video decoder",
943       "Nicolas Dufresne <nicolas.dufresne@collabora.com>");
944
945   gst_element_class_add_static_pad_template (element_class, &sink_template);
946   gst_element_class_add_static_pad_template (element_class, &src_template);
947   element_class->change_state =
948       GST_DEBUG_FUNCPTR (gst_v4l2_codec_h264_dec_change_state);
949
950   decoder_class->open = GST_DEBUG_FUNCPTR (gst_v4l2_codec_h264_dec_open);
951   decoder_class->close = GST_DEBUG_FUNCPTR (gst_v4l2_codec_h264_dec_close);
952   decoder_class->stop = GST_DEBUG_FUNCPTR (gst_v4l2_codec_h264_dec_stop);
953   decoder_class->negotiate =
954       GST_DEBUG_FUNCPTR (gst_v4l2_codec_h264_dec_negotiate);
955   decoder_class->decide_allocation =
956       GST_DEBUG_FUNCPTR (gst_v4l2_codec_h264_dec_decide_allocation);
957   decoder_class->flush = GST_DEBUG_FUNCPTR (gst_v4l2_codec_h264_dec_flush);
958   decoder_class->sink_event =
959       GST_DEBUG_FUNCPTR (gst_v4l2_codec_h264_dec_sink_event);
960
961   h264decoder_class->new_sequence =
962       GST_DEBUG_FUNCPTR (gst_v4l2_codec_h264_dec_new_sequence);
963   h264decoder_class->output_picture =
964       GST_DEBUG_FUNCPTR (gst_v4l2_codec_h264_dec_output_picture);
965   h264decoder_class->start_picture =
966       GST_DEBUG_FUNCPTR (gst_v4l2_codec_h264_dec_start_picture);
967   h264decoder_class->decode_slice =
968       GST_DEBUG_FUNCPTR (gst_v4l2_codec_h264_dec_decode_slice);
969   h264decoder_class->end_picture =
970       GST_DEBUG_FUNCPTR (gst_v4l2_codec_h264_dec_end_picture);
971
972   klass->device = device;
973   gst_v4l2_decoder_install_properties (gobject_class, PROP_LAST, device);
974 }
975
976 void
977 gst_v4l2_codec_h264_dec_register (GstPlugin * plugin,
978     GstV4l2CodecDevice * device, guint rank)
979 {
980   GTypeQuery type_query;
981   GTypeInfo type_info = { 0, };
982   GType subtype;
983   gchar *type_name;
984
985   g_type_query (GST_TYPE_V4L2_CODEC_H264_DEC, &type_query);
986   memset (&type_info, 0, sizeof (type_info));
987   type_info.class_size = type_query.class_size;
988   type_info.instance_size = type_query.instance_size;
989   type_info.class_init = (GClassInitFunc) gst_v4l2_codec_h264_dec_subclass_init;
990   type_info.class_data = gst_mini_object_ref (GST_MINI_OBJECT (device));
991   type_info.instance_init = (GInstanceInitFunc) gst_v4l2_codec_h264_dec_subinit;
992   GST_MINI_OBJECT_FLAG_SET (device, GST_MINI_OBJECT_FLAG_MAY_BE_LEAKED);
993
994   /* The first decoder to be registered should use a constant name, like
995    * v4l2slh264dec, for any additional decoders, we create unique names. Decoder
996    * names may change between boots, so this should help gain stable names for
997    * the most common use cases. SL stands for state-less, we differentiate
998    * with v4l2h264dec as this element may not have the same properties */
999   type_name = g_strdup ("v4l2slh264dec");
1000
1001   if (g_type_from_name (type_name) != 0) {
1002     gchar *basename = g_path_get_basename (device->video_device_path);
1003     g_free (type_name);
1004     type_name = g_strdup_printf ("v4l2sl%sh264dec", basename);
1005     g_free (basename);
1006   }
1007
1008   subtype = g_type_register_static (GST_TYPE_V4L2_CODEC_H264_DEC, type_name,
1009       &type_info, 0);
1010
1011   if (!gst_element_register (plugin, type_name, rank, subtype))
1012     GST_WARNING ("Failed to register plugin '%s'", type_name);
1013
1014   g_free (type_name);
1015 }