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