177849a4efcba085dff37d68c1bbc9478f6c8222
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-bad / gst-libs / gst / codecs / gsth265decoder.c
1 /* GStreamer
2  * Copyright (C) 2015 Intel Corporation
3  *    Author: Sreerenj Balachandran <sreerenj.balachandran@intel.com>
4  * Copyright (C) 2019 Seungha Yang <seungha.yang@navercorp.com>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
19  * Boston, MA 02110-1301, USA.
20  */
21 /**
22  * SECTION:gsth265decoder
23  * @title: GstH265Decoder
24  * @short_description: Base class to implement stateless H.265 decoders
25  * @sources:
26  * - gsth265picture.h
27  */
28
29 #ifdef HAVE_CONFIG_H
30 #include <config.h>
31 #endif
32
33 #include "gsth265decoder.h"
34
35 GST_DEBUG_CATEGORY (gst_h265_decoder_debug);
36 #define GST_CAT_DEFAULT gst_h265_decoder_debug
37
38 typedef enum
39 {
40   GST_H265_DECODER_FORMAT_NONE,
41   GST_H265_DECODER_FORMAT_HVC1,
42   GST_H265_DECODER_FORMAT_HEV1,
43   GST_H265_DECODER_FORMAT_BYTE
44 } GstH265DecoderFormat;
45
46 typedef enum
47 {
48   GST_H265_DECODER_ALIGN_NONE,
49   GST_H265_DECODER_ALIGN_NAL,
50   GST_H265_DECODER_ALIGN_AU
51 } GstH265DecoderAlign;
52
53 struct _GstH265DecoderPrivate
54 {
55   gint width, height;
56
57   guint8 conformance_window_flag;
58   gint crop_rect_width;
59   gint crop_rect_height;
60   gint crop_rect_x;
61   gint crop_rect_y;
62
63   /* input codec_data, if any */
64   GstBuffer *codec_data;
65   guint nal_length_size;
66
67   /* state */
68   GstH265DecoderFormat in_format;
69   GstH265DecoderAlign align;
70   GstH265Parser *parser;
71   GstH265Dpb *dpb;
72
73   /* 0: frame or field-pair interlaced stream
74    * 1: alternating, single field interlaced stream.
75    * When equal to 1, picture timing SEI shall be present in every AU */
76   guint8 field_seq_flag;
77   guint8 progressive_source_flag;
78   guint8 interlaced_source_flag;
79
80   /* Updated/cleared per handle_frame() by using picture timeing SEI */
81   GstH265SEIPicStructType cur_pic_struct;
82   guint8 cur_source_scan_type;
83   guint8 cur_duplicate_flag;
84
85   /* vps/sps/pps of the current slice */
86   const GstH265VPS *active_vps;
87   const GstH265SPS *active_sps;
88   const GstH265PPS *active_pps;
89
90   guint32 SpsMaxLatencyPictures;
91
92   /* Picture currently being processed/decoded */
93   GstH265Picture *current_picture;
94   GstVideoCodecFrame *current_frame;
95
96   /* Slice (slice header + nalu) currently being processed/decoded */
97   GstH265Slice current_slice;
98   GstH265Slice prev_slice;
99   GstH265Slice prev_independent_slice;
100
101   gint32 poc;                   // PicOrderCntVal
102   gint32 poc_msb;               // PicOrderCntMsb
103   gint32 poc_lsb;               // pic_order_cnt_lsb (from slice_header())
104   gint32 prev_poc_msb;          // prevPicOrderCntMsb
105   gint32 prev_poc_lsb;          // prevPicOrderCntLsb
106   gint32 prev_tid0pic_poc_lsb;
107   gint32 prev_tid0pic_poc_msb;
108   gint32 PocStCurrBefore[16];
109   gint32 PocStCurrAfter[16];
110   gint32 PocStFoll[16];
111   gint32 PocLtCurr[16];
112   gint32 PocLtFoll[16];
113
114   /* PicOrderCount of the previously outputted frame */
115   gint last_output_poc;
116
117   gboolean associated_irap_NoRaslOutputFlag;
118   gboolean new_bitstream;
119   gboolean prev_nal_is_eos;
120
121   /* Reference picture lists, constructed for each slice */
122   gboolean process_ref_pic_lists;
123   GArray *ref_pic_list_tmp;
124   GArray *ref_pic_list0;
125   GArray *ref_pic_list1;
126 };
127
128 #define UPDATE_FLOW_RETURN(ret,new_ret) G_STMT_START { \
129   if (*(ret) == GST_FLOW_OK) \
130     *(ret) = new_ret; \
131 } G_STMT_END
132
133 #define parent_class gst_h265_decoder_parent_class
134 G_DEFINE_ABSTRACT_TYPE_WITH_CODE (GstH265Decoder, gst_h265_decoder,
135     GST_TYPE_VIDEO_DECODER,
136     G_ADD_PRIVATE (GstH265Decoder);
137     GST_DEBUG_CATEGORY_INIT (gst_h265_decoder_debug, "h265decoder", 0,
138         "H.265 Video Decoder"));
139
140 static void gst_h265_decoder_finalize (GObject * object);
141
142 static gboolean gst_h265_decoder_start (GstVideoDecoder * decoder);
143 static gboolean gst_h265_decoder_stop (GstVideoDecoder * decoder);
144 static gboolean gst_h265_decoder_set_format (GstVideoDecoder * decoder,
145     GstVideoCodecState * state);
146 static GstFlowReturn gst_h265_decoder_finish (GstVideoDecoder * decoder);
147 static gboolean gst_h265_decoder_flush (GstVideoDecoder * decoder);
148 static GstFlowReturn gst_h265_decoder_drain (GstVideoDecoder * decoder);
149 static GstFlowReturn gst_h265_decoder_handle_frame (GstVideoDecoder * decoder,
150     GstVideoCodecFrame * frame);
151
152 static void gst_h265_decoder_finish_current_picture (GstH265Decoder * self,
153     GstFlowReturn * ret);
154 static void gst_h265_decoder_clear_ref_pic_sets (GstH265Decoder * self);
155 static void gst_h265_decoder_clear_dpb (GstH265Decoder * self, gboolean flush);
156 static GstFlowReturn gst_h265_decoder_drain_internal (GstH265Decoder * self);
157 static GstFlowReturn
158 gst_h265_decoder_start_current_picture (GstH265Decoder * self);
159
160 static void
161 gst_h265_decoder_class_init (GstH265DecoderClass * klass)
162 {
163   GstVideoDecoderClass *decoder_class = GST_VIDEO_DECODER_CLASS (klass);
164   GObjectClass *object_class = G_OBJECT_CLASS (klass);
165
166   object_class->finalize = GST_DEBUG_FUNCPTR (gst_h265_decoder_finalize);
167
168   decoder_class->start = GST_DEBUG_FUNCPTR (gst_h265_decoder_start);
169   decoder_class->stop = GST_DEBUG_FUNCPTR (gst_h265_decoder_stop);
170   decoder_class->set_format = GST_DEBUG_FUNCPTR (gst_h265_decoder_set_format);
171   decoder_class->finish = GST_DEBUG_FUNCPTR (gst_h265_decoder_finish);
172   decoder_class->flush = GST_DEBUG_FUNCPTR (gst_h265_decoder_flush);
173   decoder_class->drain = GST_DEBUG_FUNCPTR (gst_h265_decoder_drain);
174   decoder_class->handle_frame =
175       GST_DEBUG_FUNCPTR (gst_h265_decoder_handle_frame);
176 }
177
178 static void
179 gst_h265_decoder_init (GstH265Decoder * self)
180 {
181   GstH265DecoderPrivate *priv;
182
183   gst_video_decoder_set_packetized (GST_VIDEO_DECODER (self), TRUE);
184
185   self->priv = priv = gst_h265_decoder_get_instance_private (self);
186
187   priv->last_output_poc = G_MININT32;
188
189   priv->ref_pic_list_tmp = g_array_sized_new (FALSE, TRUE,
190       sizeof (GstH265Picture *), 32);
191   priv->ref_pic_list0 = g_array_sized_new (FALSE, TRUE,
192       sizeof (GstH265Picture *), 32);
193   priv->ref_pic_list1 = g_array_sized_new (FALSE, TRUE,
194       sizeof (GstH265Picture *), 32);
195 }
196
197 static void
198 gst_h265_decoder_finalize (GObject * object)
199 {
200   GstH265Decoder *self = GST_H265_DECODER (object);
201   GstH265DecoderPrivate *priv = self->priv;
202
203   g_array_unref (priv->ref_pic_list_tmp);
204   g_array_unref (priv->ref_pic_list0);
205   g_array_unref (priv->ref_pic_list1);
206
207   G_OBJECT_CLASS (parent_class)->finalize (object);
208 }
209
210 static gboolean
211 gst_h265_decoder_start (GstVideoDecoder * decoder)
212 {
213   GstH265Decoder *self = GST_H265_DECODER (decoder);
214   GstH265DecoderPrivate *priv = self->priv;
215
216   priv->parser = gst_h265_parser_new ();
217   priv->dpb = gst_h265_dpb_new ();
218   priv->new_bitstream = TRUE;
219   priv->prev_nal_is_eos = FALSE;
220
221   return TRUE;
222 }
223
224 static gboolean
225 gst_h265_decoder_stop (GstVideoDecoder * decoder)
226 {
227   GstH265Decoder *self = GST_H265_DECODER (decoder);
228   GstH265DecoderPrivate *priv = self->priv;
229
230   if (self->input_state) {
231     gst_video_codec_state_unref (self->input_state);
232     self->input_state = NULL;
233   }
234
235   gst_clear_buffer (&priv->codec_data);
236
237   if (priv->parser) {
238     gst_h265_parser_free (priv->parser);
239     priv->parser = NULL;
240   }
241
242   if (priv->dpb) {
243     gst_h265_dpb_free (priv->dpb);
244     priv->dpb = NULL;
245   }
246
247   gst_h265_decoder_clear_ref_pic_sets (self);
248
249   return TRUE;
250 }
251
252 static GstFlowReturn
253 gst_h265_decoder_parse_vps (GstH265Decoder * self, GstH265NalUnit * nalu)
254 {
255   GstH265DecoderPrivate *priv = self->priv;
256   GstH265VPS vps;
257   GstH265ParserResult pres;
258
259   pres = gst_h265_parser_parse_vps (priv->parser, nalu, &vps);
260   if (pres != GST_H265_PARSER_OK) {
261     GST_WARNING_OBJECT (self, "Failed to parse VPS, result %d", pres);
262     return GST_FLOW_ERROR;
263   }
264
265   GST_LOG_OBJECT (self, "VPS parsed");
266
267   return GST_FLOW_OK;
268 }
269
270 static gboolean
271 gst_h265_decoder_is_crop_rect_changed (GstH265Decoder * self, GstH265SPS * sps)
272 {
273   GstH265DecoderPrivate *priv = self->priv;
274
275   if (priv->conformance_window_flag != sps->conformance_window_flag)
276     return TRUE;
277   if (priv->crop_rect_width != sps->crop_rect_width)
278     return TRUE;
279   if (priv->crop_rect_height != sps->crop_rect_height)
280     return TRUE;
281   if (priv->crop_rect_x != sps->crop_rect_x)
282     return TRUE;
283   if (priv->crop_rect_y != sps->crop_rect_y)
284     return TRUE;
285
286   return FALSE;
287 }
288
289 static GstFlowReturn
290 gst_h265_decoder_process_sps (GstH265Decoder * self, GstH265SPS * sps)
291 {
292   GstH265DecoderPrivate *priv = self->priv;
293   gint max_dpb_size;
294   gint prev_max_dpb_size;
295   gint MaxLumaPS;
296   const gint MaxDpbPicBuf = 6;
297   gint PicSizeInSamplesY;
298   guint8 field_seq_flag = 0;
299   guint8 progressive_source_flag = 0;
300   guint8 interlaced_source_flag = 0;
301   GstFlowReturn ret = GST_FLOW_OK;
302
303   /* A.4.1 */
304   MaxLumaPS = 35651584;
305   PicSizeInSamplesY = sps->width * sps->height;
306   if (PicSizeInSamplesY <= (MaxLumaPS >> 2))
307     max_dpb_size = MaxDpbPicBuf * 4;
308   else if (PicSizeInSamplesY <= (MaxLumaPS >> 1))
309     max_dpb_size = MaxDpbPicBuf * 2;
310   else if (PicSizeInSamplesY <= ((3 * MaxLumaPS) >> 2))
311     max_dpb_size = (MaxDpbPicBuf * 4) / 3;
312   else
313     max_dpb_size = MaxDpbPicBuf;
314
315   max_dpb_size = MIN (max_dpb_size, 16);
316
317   if (sps->vui_parameters_present_flag)
318     field_seq_flag = sps->vui_params.field_seq_flag;
319
320   progressive_source_flag = sps->profile_tier_level.progressive_source_flag;
321   interlaced_source_flag = sps->profile_tier_level.interlaced_source_flag;
322
323   prev_max_dpb_size = gst_h265_dpb_get_max_num_pics (priv->dpb);
324   if (priv->width != sps->width || priv->height != sps->height ||
325       prev_max_dpb_size != max_dpb_size ||
326       priv->field_seq_flag != field_seq_flag ||
327       priv->progressive_source_flag != progressive_source_flag ||
328       priv->interlaced_source_flag != interlaced_source_flag ||
329       gst_h265_decoder_is_crop_rect_changed (self, sps)) {
330     GstH265DecoderClass *klass = GST_H265_DECODER_GET_CLASS (self);
331
332     GST_DEBUG_OBJECT (self,
333         "SPS updated, resolution: %dx%d -> %dx%d, dpb size: %d -> %d, "
334         "field_seq_flag: %d -> %d, progressive_source_flag: %d -> %d, "
335         "interlaced_source_flag: %d -> %d",
336         priv->width, priv->height, sps->width, sps->height,
337         prev_max_dpb_size, max_dpb_size, priv->field_seq_flag, field_seq_flag,
338         priv->progressive_source_flag, progressive_source_flag,
339         priv->interlaced_source_flag, interlaced_source_flag);
340
341     g_assert (klass->new_sequence);
342
343     ret = klass->new_sequence (self, sps, max_dpb_size);
344     if (ret != GST_FLOW_OK) {
345       GST_WARNING_OBJECT (self, "subclass does not want accept new sequence");
346       return ret;
347     }
348
349     priv->width = sps->width;
350     priv->height = sps->height;
351     priv->conformance_window_flag = sps->conformance_window_flag;
352     priv->crop_rect_width = sps->crop_rect_width;
353     priv->crop_rect_height = sps->crop_rect_height;
354     priv->crop_rect_x = sps->crop_rect_x;
355     priv->crop_rect_y = sps->crop_rect_y;
356     priv->field_seq_flag = field_seq_flag;
357     priv->progressive_source_flag = progressive_source_flag;
358     priv->interlaced_source_flag = interlaced_source_flag;
359
360     gst_h265_dpb_set_max_num_pics (priv->dpb, max_dpb_size);
361   }
362
363   if (sps->max_latency_increase_plus1[sps->max_sub_layers_minus1]) {
364     priv->SpsMaxLatencyPictures =
365         sps->max_num_reorder_pics[sps->max_sub_layers_minus1] +
366         sps->max_latency_increase_plus1[sps->max_sub_layers_minus1] - 1;
367   }
368
369   GST_DEBUG_OBJECT (self, "Set DPB max size %d", max_dpb_size);
370
371   return GST_FLOW_OK;
372 }
373
374 static GstFlowReturn
375 gst_h265_decoder_parse_sps (GstH265Decoder * self, GstH265NalUnit * nalu)
376 {
377   GstH265DecoderPrivate *priv = self->priv;
378   GstH265SPS sps;
379   GstH265ParserResult pres;
380   GstFlowReturn ret = GST_FLOW_OK;
381
382   pres = gst_h265_parse_sps (priv->parser, nalu, &sps, TRUE);
383   if (pres != GST_H265_PARSER_OK) {
384     GST_WARNING_OBJECT (self, "Failed to parse SPS, result %d", pres);
385     return GST_FLOW_ERROR;
386   }
387
388   GST_LOG_OBJECT (self, "SPS parsed");
389
390   ret = gst_h265_decoder_process_sps (self, &sps);
391   if (ret != GST_FLOW_OK) {
392     GST_WARNING_OBJECT (self, "Failed to process SPS");
393   } else if (gst_h265_parser_update_sps (priv->parser,
394           &sps) != GST_H265_PARSER_OK) {
395     GST_WARNING_OBJECT (self, "Failed to update SPS");
396     ret = GST_FLOW_ERROR;
397   }
398
399   return ret;
400 }
401
402 static GstFlowReturn
403 gst_h265_decoder_parse_pps (GstH265Decoder * self, GstH265NalUnit * nalu)
404 {
405   GstH265DecoderPrivate *priv = self->priv;
406   GstH265PPS pps;
407   GstH265ParserResult pres;
408
409   pres = gst_h265_parser_parse_pps (priv->parser, nalu, &pps);
410   if (pres != GST_H265_PARSER_OK) {
411     GST_WARNING_OBJECT (self, "Failed to parse PPS, result %d", pres);
412     return GST_FLOW_ERROR;
413   }
414
415   GST_LOG_OBJECT (self, "PPS parsed");
416
417   return GST_FLOW_OK;
418 }
419
420 static GstFlowReturn
421 gst_h265_decoder_parse_sei (GstH265Decoder * self, GstH265NalUnit * nalu)
422 {
423   GstH265DecoderPrivate *priv = self->priv;
424   GstH265ParserResult pres;
425   GArray *messages = NULL;
426   guint i;
427
428   pres = gst_h265_parser_parse_sei (priv->parser, nalu, &messages);
429   if (pres != GST_H265_PARSER_OK) {
430     GST_WARNING_OBJECT (self, "Failed to parse SEI, result %d", pres);
431
432     /* XXX: Ignore error from SEI parsing, it might be malformed bitstream,
433      * or our fault. But shouldn't be critical  */
434     g_clear_pointer (&messages, g_array_unref);
435     return GST_FLOW_OK;
436   }
437
438   for (i = 0; i < messages->len; i++) {
439     GstH265SEIMessage *sei = &g_array_index (messages, GstH265SEIMessage, i);
440
441     switch (sei->payloadType) {
442       case GST_H265_SEI_PIC_TIMING:
443         priv->cur_pic_struct = sei->payload.pic_timing.pic_struct;
444         priv->cur_source_scan_type = sei->payload.pic_timing.source_scan_type;
445         priv->cur_duplicate_flag = sei->payload.pic_timing.duplicate_flag;
446
447         GST_TRACE_OBJECT (self,
448             "Picture Timing SEI, pic_struct: %d, source_scan_type: %d, "
449             "duplicate_flag: %d", priv->cur_pic_struct,
450             priv->cur_source_scan_type, priv->cur_duplicate_flag);
451         break;
452       default:
453         break;
454     }
455   }
456
457   g_array_free (messages, TRUE);
458   GST_LOG_OBJECT (self, "SEI parsed");
459
460   return GST_FLOW_OK;
461 }
462
463 static void
464 gst_h265_decoder_process_ref_pic_lists (GstH265Decoder * self,
465     GstH265Picture * curr_pic, GstH265Slice * slice,
466     GArray ** ref_pic_list0, GArray ** ref_pic_list1)
467 {
468   GstH265DecoderPrivate *priv = self->priv;
469   GstH265RefPicListModification *ref_mod =
470       &slice->header.ref_pic_list_modification;
471   GstH265PPSSccExtensionParams *scc_ext =
472       &slice->header.pps->pps_scc_extension_params;
473   GArray *tmp_refs;
474   gint num_tmp_refs, i;
475
476   *ref_pic_list0 = priv->ref_pic_list0;
477   *ref_pic_list1 = priv->ref_pic_list1;
478
479   /* There is nothing to be done for I slices */
480   if (GST_H265_IS_I_SLICE (&slice->header))
481     return;
482
483   /* Inifinit loop prevention */
484   if (self->NumPocStCurrBefore == 0 && self->NumPocStCurrAfter == 0 &&
485       self->NumPocLtCurr == 0 && !scc_ext->pps_curr_pic_ref_enabled_flag) {
486     GST_WARNING_OBJECT (self,
487         "Expected references, got none, preventing infinit loop.");
488     return;
489   }
490
491   /* 8.3.4 Deriving l0 */
492   tmp_refs = priv->ref_pic_list_tmp;
493
494   /* (8-8)
495    * Deriving l0 consist of appending in loop RefPicSetStCurrBefore,
496    * RefPicSetStCurrAfter and RefPicSetLtCurr until NumRpsCurrTempList0 item
497    * has been reached.
498    */
499
500   /* NumRpsCurrTempList0 */
501   num_tmp_refs = MAX (slice->header.num_ref_idx_l0_active_minus1 + 1,
502       self->NumPicTotalCurr);
503
504   while (tmp_refs->len < num_tmp_refs) {
505     for (i = 0; i < self->NumPocStCurrBefore && tmp_refs->len < num_tmp_refs;
506         i++)
507       g_array_append_val (tmp_refs, self->RefPicSetStCurrBefore[i]);
508     for (i = 0; i < self->NumPocStCurrAfter && tmp_refs->len < num_tmp_refs;
509         i++)
510       g_array_append_val (tmp_refs, self->RefPicSetStCurrAfter[i]);
511     for (i = 0; i < self->NumPocLtCurr && tmp_refs->len < num_tmp_refs; i++)
512       g_array_append_val (tmp_refs, self->RefPicSetLtCurr[i]);
513     if (scc_ext->pps_curr_pic_ref_enabled_flag)
514       g_array_append_val (tmp_refs, curr_pic);
515   }
516
517   /* (8-9)
518    * If needed, apply the modificaiton base on the lookup table found in the
519    * slice header (list_entry_l0).
520    */
521   for (i = 0; i <= slice->header.num_ref_idx_l0_active_minus1; i++) {
522     GstH265Picture **tmp = (GstH265Picture **) tmp_refs->data;
523
524     if (ref_mod->ref_pic_list_modification_flag_l0)
525       g_array_append_val (*ref_pic_list0, tmp[ref_mod->list_entry_l0[i]]);
526     else
527       g_array_append_val (*ref_pic_list0, tmp[i]);
528   }
529
530   if (scc_ext->pps_curr_pic_ref_enabled_flag &&
531       !ref_mod->ref_pic_list_modification_flag_l0 &&
532       num_tmp_refs > (slice->header.num_ref_idx_l0_active_minus1 + 1)) {
533     g_array_index (*ref_pic_list0, GstH265Picture *,
534         slice->header.num_ref_idx_l0_active_minus1) = curr_pic;
535   }
536
537   g_array_set_size (tmp_refs, 0);
538
539   /* For P slices we only need l0 */
540   if (GST_H265_IS_P_SLICE (&slice->header))
541     return;
542
543   /* 8.3.4 Deriving l1 */
544   /* (8-10)
545    * Deriving l1 consist of appending in loop RefPicSetStCurrAfter,
546    * RefPicSetStCurrBefore and RefPicSetLtCurr until NumRpsCurrTempList0 item
547    * has been reached.
548    */
549
550   /* NumRpsCurrTempList1 */
551   num_tmp_refs = MAX (slice->header.num_ref_idx_l1_active_minus1 + 1,
552       self->NumPicTotalCurr);
553
554   while (tmp_refs->len < num_tmp_refs) {
555     for (i = 0; i < self->NumPocStCurrAfter && tmp_refs->len < num_tmp_refs;
556         i++)
557       g_array_append_val (tmp_refs, self->RefPicSetStCurrAfter[i]);
558     for (i = 0; i < self->NumPocStCurrBefore && tmp_refs->len < num_tmp_refs;
559         i++)
560       g_array_append_val (tmp_refs, self->RefPicSetStCurrBefore[i]);
561     for (i = 0; i < self->NumPocLtCurr && tmp_refs->len < num_tmp_refs; i++)
562       g_array_append_val (tmp_refs, self->RefPicSetLtCurr[i]);
563     if (scc_ext->pps_curr_pic_ref_enabled_flag)
564       g_array_append_val (tmp_refs, curr_pic);
565   }
566
567   /* (8-11)
568    * If needed, apply the modificaiton base on the lookup table found in the
569    * slice header (list_entry_l1).
570    */
571   for (i = 0; i <= slice->header.num_ref_idx_l1_active_minus1; i++) {
572     GstH265Picture **tmp = (GstH265Picture **) tmp_refs->data;
573
574     if (ref_mod->ref_pic_list_modification_flag_l1)
575       g_array_append_val (*ref_pic_list1, tmp[ref_mod->list_entry_l1[i]]);
576     else
577       g_array_append_val (*ref_pic_list1, tmp[i]);
578   }
579
580   g_array_set_size (tmp_refs, 0);
581 }
582
583 static GstFlowReturn
584 gst_h265_decoder_decode_slice (GstH265Decoder * self)
585 {
586   GstH265DecoderClass *klass = GST_H265_DECODER_GET_CLASS (self);
587   GstH265DecoderPrivate *priv = self->priv;
588   GstH265Slice *slice = &priv->current_slice;
589   GstH265Picture *picture = priv->current_picture;
590   GArray *l0 = NULL;
591   GArray *l1 = NULL;
592   GstFlowReturn ret = GST_FLOW_OK;
593
594   if (!picture) {
595     GST_ERROR_OBJECT (self, "No current picture");
596     return GST_FLOW_ERROR;
597   }
598
599   g_assert (klass->decode_slice);
600
601   if (priv->process_ref_pic_lists) {
602     l0 = priv->ref_pic_list0;
603     l1 = priv->ref_pic_list1;
604     gst_h265_decoder_process_ref_pic_lists (self, picture, slice, &l0, &l1);
605   }
606
607   ret = klass->decode_slice (self, picture, slice, l0, l1);
608
609   if (priv->process_ref_pic_lists) {
610     g_array_set_size (l0, 0);
611     g_array_set_size (l1, 0);
612   }
613
614   return ret;
615 }
616
617 static GstFlowReturn
618 gst_h265_decoder_preprocess_slice (GstH265Decoder * self, GstH265Slice * slice)
619 {
620   GstH265DecoderPrivate *priv = self->priv;
621   const GstH265SliceHdr *slice_hdr = &slice->header;
622
623   if (priv->current_picture && slice_hdr->first_slice_segment_in_pic_flag) {
624     GST_WARNING_OBJECT (self,
625         "Current picture is not finished but slice header has "
626         "first_slice_segment_in_pic_flag");
627     return GST_FLOW_ERROR;
628   }
629
630   return GST_FLOW_OK;
631 }
632
633 static GstFlowReturn
634 gst_h265_decoder_parse_slice (GstH265Decoder * self, GstH265NalUnit * nalu,
635     GstClockTime pts)
636 {
637   GstH265DecoderPrivate *priv = self->priv;
638   GstH265ParserResult pres = GST_H265_PARSER_OK;
639   GstFlowReturn ret = GST_FLOW_OK;
640
641   memset (&priv->current_slice, 0, sizeof (GstH265Slice));
642
643   pres = gst_h265_parser_parse_slice_hdr (priv->parser, nalu,
644       &priv->current_slice.header);
645
646   if (pres != GST_H265_PARSER_OK) {
647     GST_ERROR_OBJECT (self, "Failed to parse slice header, ret %d", pres);
648     memset (&priv->current_slice, 0, sizeof (GstH265Slice));
649
650     return GST_FLOW_ERROR;
651   }
652
653   priv->current_slice.nalu = *nalu;
654
655   if (priv->current_slice.header.dependent_slice_segment_flag) {
656     GstH265SliceHdr *slice_hdr = &priv->current_slice.header;
657     GstH265SliceHdr *indep_slice_hdr = &priv->prev_independent_slice.header;
658
659     memcpy (&slice_hdr->type, &indep_slice_hdr->type,
660         G_STRUCT_OFFSET (GstH265SliceHdr, num_entry_point_offsets) -
661         G_STRUCT_OFFSET (GstH265SliceHdr, type));
662   } else {
663     priv->prev_independent_slice = priv->current_slice;
664     memset (&priv->prev_independent_slice.nalu, 0, sizeof (GstH265NalUnit));
665   }
666
667   ret = gst_h265_decoder_preprocess_slice (self, &priv->current_slice);
668   if (ret != GST_FLOW_OK)
669     return ret;
670
671   priv->active_pps = priv->current_slice.header.pps;
672   priv->active_sps = priv->active_pps->sps;
673
674   if (!priv->current_picture) {
675     GstH265DecoderClass *klass = GST_H265_DECODER_GET_CLASS (self);
676     GstH265Picture *picture;
677     gboolean ret = TRUE;
678
679     g_assert (priv->current_frame);
680
681     picture = gst_h265_picture_new ();
682     picture->pts = pts;
683     /* This allows accessing the frame from the picture. */
684     picture->system_frame_number = priv->current_frame->system_frame_number;
685
686     priv->current_picture = picture;
687
688     if (klass->new_picture)
689       ret = klass->new_picture (self, priv->current_frame, picture);
690
691     if (ret != GST_FLOW_OK) {
692       GST_WARNING_OBJECT (self, "subclass does not want accept new picture");
693       priv->current_picture = NULL;
694       gst_h265_picture_unref (picture);
695       return ret;
696     }
697
698     ret = gst_h265_decoder_start_current_picture (self);
699     if (ret != GST_FLOW_OK) {
700       GST_WARNING_OBJECT (self, "start picture failed");
701       return ret;
702     }
703
704     /* this picture was dropped */
705     if (!priv->current_picture)
706       return GST_FLOW_OK;
707   }
708
709   return gst_h265_decoder_decode_slice (self);
710 }
711
712 static GstFlowReturn
713 gst_h265_decoder_decode_nal (GstH265Decoder * self, GstH265NalUnit * nalu,
714     GstClockTime pts)
715 {
716   GstH265DecoderPrivate *priv = self->priv;
717   GstFlowReturn ret = GST_FLOW_OK;
718
719   GST_LOG_OBJECT (self, "Parsed nal type: %d, offset %d, size %d",
720       nalu->type, nalu->offset, nalu->size);
721
722   switch (nalu->type) {
723     case GST_H265_NAL_VPS:
724       ret = gst_h265_decoder_parse_vps (self, nalu);
725       break;
726     case GST_H265_NAL_SPS:
727       ret = gst_h265_decoder_parse_sps (self, nalu);
728       break;
729     case GST_H265_NAL_PPS:
730       ret = gst_h265_decoder_parse_pps (self, nalu);
731       break;
732     case GST_H265_NAL_PREFIX_SEI:
733     case GST_H265_NAL_SUFFIX_SEI:
734       ret = gst_h265_decoder_parse_sei (self, nalu);
735       break;
736     case GST_H265_NAL_SLICE_TRAIL_N:
737     case GST_H265_NAL_SLICE_TRAIL_R:
738     case GST_H265_NAL_SLICE_TSA_N:
739     case GST_H265_NAL_SLICE_TSA_R:
740     case GST_H265_NAL_SLICE_STSA_N:
741     case GST_H265_NAL_SLICE_STSA_R:
742     case GST_H265_NAL_SLICE_RADL_N:
743     case GST_H265_NAL_SLICE_RADL_R:
744     case GST_H265_NAL_SLICE_RASL_N:
745     case GST_H265_NAL_SLICE_RASL_R:
746     case GST_H265_NAL_SLICE_BLA_W_LP:
747     case GST_H265_NAL_SLICE_BLA_W_RADL:
748     case GST_H265_NAL_SLICE_BLA_N_LP:
749     case GST_H265_NAL_SLICE_IDR_W_RADL:
750     case GST_H265_NAL_SLICE_IDR_N_LP:
751     case GST_H265_NAL_SLICE_CRA_NUT:
752       ret = gst_h265_decoder_parse_slice (self, nalu, pts);
753       priv->new_bitstream = FALSE;
754       priv->prev_nal_is_eos = FALSE;
755       break;
756     case GST_H265_NAL_EOB:
757       priv->new_bitstream = TRUE;
758       break;
759     case GST_H265_NAL_EOS:
760       priv->prev_nal_is_eos = TRUE;
761       break;
762     default:
763       break;
764   }
765
766   return ret;
767 }
768
769 static void
770 gst_h265_decoder_format_from_caps (GstH265Decoder * self, GstCaps * caps,
771     GstH265DecoderFormat * format, GstH265DecoderAlign * align)
772 {
773   if (format)
774     *format = GST_H265_DECODER_FORMAT_NONE;
775
776   if (align)
777     *align = GST_H265_DECODER_ALIGN_NONE;
778
779   if (!gst_caps_is_fixed (caps)) {
780     GST_WARNING_OBJECT (self, "Caps wasn't fixed");
781     return;
782   }
783
784   GST_DEBUG_OBJECT (self, "parsing caps: %" GST_PTR_FORMAT, caps);
785
786   if (caps && gst_caps_get_size (caps) > 0) {
787     GstStructure *s = gst_caps_get_structure (caps, 0);
788     const gchar *str = NULL;
789
790     if (format) {
791       if ((str = gst_structure_get_string (s, "stream-format"))) {
792         if (strcmp (str, "hvc1") == 0)
793           *format = GST_H265_DECODER_FORMAT_HVC1;
794         else if (strcmp (str, "hev1") == 0)
795           *format = GST_H265_DECODER_FORMAT_HEV1;
796         else if (strcmp (str, "byte-stream") == 0)
797           *format = GST_H265_DECODER_FORMAT_BYTE;
798       }
799     }
800
801     if (align) {
802       if ((str = gst_structure_get_string (s, "alignment"))) {
803         if (strcmp (str, "au") == 0)
804           *align = GST_H265_DECODER_ALIGN_AU;
805         else if (strcmp (str, "nal") == 0)
806           *align = GST_H265_DECODER_ALIGN_NAL;
807       }
808     }
809   }
810 }
811
812 static GstFlowReturn
813 gst_h265_decoder_parse_codec_data (GstH265Decoder * self, const guint8 * data,
814     gsize size)
815 {
816   GstH265DecoderPrivate *priv = self->priv;
817   guint num_nal_arrays;
818   guint off;
819   guint num_nals, i, j;
820   GstH265ParserResult pres;
821   GstH265NalUnit nalu;
822   GstFlowReturn ret = GST_FLOW_OK;
823
824   /* parse the hvcC data */
825   if (size < 23) {
826     GST_WARNING_OBJECT (self, "hvcC too small");
827     return GST_FLOW_ERROR;
828   }
829
830   /* wrong hvcC version */
831   if (data[0] != 0 && data[0] != 1) {
832     return GST_FLOW_ERROR;
833   }
834
835   priv->nal_length_size = (data[21] & 0x03) + 1;
836   GST_DEBUG_OBJECT (self, "nal length size %u", priv->nal_length_size);
837
838   num_nal_arrays = data[22];
839   off = 23;
840
841   for (i = 0; i < num_nal_arrays; i++) {
842     if (off + 3 >= size) {
843       GST_WARNING_OBJECT (self, "hvcC too small");
844       return GST_FLOW_ERROR;
845     }
846
847     num_nals = GST_READ_UINT16_BE (data + off + 1);
848     off += 3;
849     for (j = 0; j < num_nals; j++) {
850       pres = gst_h265_parser_identify_nalu_hevc (priv->parser,
851           data, off, size, 2, &nalu);
852
853       if (pres != GST_H265_PARSER_OK) {
854         GST_WARNING_OBJECT (self, "hvcC too small");
855         return GST_FLOW_ERROR;
856       }
857
858       switch (nalu.type) {
859         case GST_H265_NAL_VPS:
860           ret = gst_h265_decoder_parse_vps (self, &nalu);
861           if (ret != GST_FLOW_OK) {
862             GST_WARNING_OBJECT (self, "Failed to parse VPS");
863             return ret;
864           }
865           break;
866         case GST_H265_NAL_SPS:
867           ret = gst_h265_decoder_parse_sps (self, &nalu);
868           if (ret != GST_FLOW_OK) {
869             GST_WARNING_OBJECT (self, "Failed to parse SPS");
870             return ret;
871           }
872           break;
873         case GST_H265_NAL_PPS:
874           ret = gst_h265_decoder_parse_pps (self, &nalu);
875           if (ret != GST_FLOW_OK) {
876             GST_WARNING_OBJECT (self, "Failed to parse PPS");
877             return ret;
878           }
879           break;
880         default:
881           break;
882       }
883
884       off = nalu.offset + nalu.size;
885     }
886   }
887
888   return GST_FLOW_OK;
889 }
890
891 static gboolean
892 gst_h265_decoder_set_format (GstVideoDecoder * decoder,
893     GstVideoCodecState * state)
894 {
895   GstH265Decoder *self = GST_H265_DECODER (decoder);
896   GstH265DecoderPrivate *priv = self->priv;
897
898   GST_DEBUG_OBJECT (decoder, "Set format");
899
900   if (self->input_state)
901     gst_video_codec_state_unref (self->input_state);
902
903   self->input_state = gst_video_codec_state_ref (state);
904
905   if (state->caps) {
906     GstStructure *str;
907     const GValue *codec_data_value;
908     GstH265DecoderFormat format;
909     GstH265DecoderAlign align;
910
911     gst_h265_decoder_format_from_caps (self, state->caps, &format, &align);
912
913     str = gst_caps_get_structure (state->caps, 0);
914     codec_data_value = gst_structure_get_value (str, "codec_data");
915
916     if (GST_VALUE_HOLDS_BUFFER (codec_data_value)) {
917       gst_buffer_replace (&priv->codec_data,
918           gst_value_get_buffer (codec_data_value));
919     } else {
920       gst_buffer_replace (&priv->codec_data, NULL);
921     }
922
923     if (format == GST_H265_DECODER_FORMAT_NONE) {
924       /* codec_data implies packetized */
925       if (codec_data_value != NULL) {
926         GST_WARNING_OBJECT (self,
927             "video/x-h265 caps with codec_data but no stream-format=hev1 or hvc1");
928         format = GST_H265_DECODER_FORMAT_HEV1;
929       } else {
930         /* otherwise assume bytestream input */
931         GST_WARNING_OBJECT (self,
932             "video/x-h265 caps without codec_data or stream-format");
933         format = GST_H265_DECODER_FORMAT_BYTE;
934       }
935     }
936
937     if (format == GST_H265_DECODER_FORMAT_HEV1 ||
938         format == GST_H265_DECODER_FORMAT_HVC1) {
939       if (codec_data_value == NULL) {
940         /* Try it with size 4 anyway */
941         priv->nal_length_size = 4;
942         GST_WARNING_OBJECT (self,
943             "packetized format without codec data, assuming nal length size is 4");
944       }
945
946       /* AVC implies alignment=au */
947       if (align == GST_H265_DECODER_ALIGN_NONE)
948         align = GST_H265_DECODER_ALIGN_AU;
949     }
950
951     if (format == GST_H265_DECODER_FORMAT_BYTE) {
952       if (codec_data_value != NULL) {
953         GST_WARNING_OBJECT (self, "bytestream with codec data");
954       }
955     }
956
957     priv->in_format = format;
958     priv->align = align;
959   }
960
961   if (priv->codec_data) {
962     GstMapInfo map;
963
964     gst_buffer_map (priv->codec_data, &map, GST_MAP_READ);
965     if (gst_h265_decoder_parse_codec_data (self, map.data, map.size) !=
966         GST_FLOW_OK) {
967       /* keep going without error.
968        * Probably inband SPS/PPS might be valid data */
969       GST_WARNING_OBJECT (self, "Failed to handle codec data");
970     }
971     gst_buffer_unmap (priv->codec_data, &map);
972   }
973
974   return TRUE;
975 }
976
977 static gboolean
978 gst_h265_decoder_flush (GstVideoDecoder * decoder)
979 {
980   GstH265Decoder *self = GST_H265_DECODER (decoder);
981
982   gst_h265_decoder_clear_dpb (self, TRUE);
983
984   return TRUE;
985 }
986
987 static GstFlowReturn
988 gst_h265_decoder_drain (GstVideoDecoder * decoder)
989 {
990   GstH265Decoder *self = GST_H265_DECODER (decoder);
991
992   /* dpb will be cleared by this method */
993   return gst_h265_decoder_drain_internal (self);
994 }
995
996 static GstFlowReturn
997 gst_h265_decoder_finish (GstVideoDecoder * decoder)
998 {
999   return gst_h265_decoder_drain (decoder);
1000 }
1001
1002 static gboolean
1003 gst_h265_decoder_fill_picture_from_slice (GstH265Decoder * self,
1004     const GstH265Slice * slice, GstH265Picture * picture)
1005 {
1006   GstH265DecoderPrivate *priv = self->priv;
1007   const GstH265SliceHdr *slice_hdr = &slice->header;
1008   const GstH265NalUnit *nalu = &slice->nalu;
1009
1010   if (nalu->type >= GST_H265_NAL_SLICE_BLA_W_LP &&
1011       nalu->type <= GST_H265_NAL_SLICE_CRA_NUT)
1012     picture->RapPicFlag = TRUE;
1013
1014   /* NoRaslOutputFlag == 1 if the current picture is
1015    * 1) an IDR picture
1016    * 2) a BLA picture
1017    * 3) a CRA picture that is the first access unit in the bitstream
1018    * 4) first picture that follows an end of sequence NAL unit in decoding order
1019    * 5) has HandleCraAsBlaFlag == 1 (set by external means, so not considering )
1020    */
1021   if (GST_H265_IS_NAL_TYPE_IDR (nalu->type) ||
1022       GST_H265_IS_NAL_TYPE_BLA (nalu->type) ||
1023       (GST_H265_IS_NAL_TYPE_CRA (nalu->type) && priv->new_bitstream) ||
1024       priv->prev_nal_is_eos) {
1025     picture->NoRaslOutputFlag = TRUE;
1026   }
1027
1028   if (GST_H265_IS_NAL_TYPE_IRAP (nalu->type)) {
1029     picture->IntraPicFlag = TRUE;
1030     priv->associated_irap_NoRaslOutputFlag = picture->NoRaslOutputFlag;
1031   }
1032
1033   if (GST_H265_IS_NAL_TYPE_RASL (nalu->type) &&
1034       priv->associated_irap_NoRaslOutputFlag) {
1035     picture->output_flag = FALSE;
1036   } else {
1037     picture->output_flag = slice_hdr->pic_output_flag;
1038   }
1039
1040   return TRUE;
1041 }
1042
1043 #define RSV_VCL_N10 10
1044 #define RSV_VCL_N12 12
1045 #define RSV_VCL_N14 14
1046
1047 static gboolean
1048 nal_is_ref (guint8 nal_type)
1049 {
1050   gboolean ret = FALSE;
1051   switch (nal_type) {
1052     case GST_H265_NAL_SLICE_TRAIL_N:
1053     case GST_H265_NAL_SLICE_TSA_N:
1054     case GST_H265_NAL_SLICE_STSA_N:
1055     case GST_H265_NAL_SLICE_RADL_N:
1056     case GST_H265_NAL_SLICE_RASL_N:
1057     case RSV_VCL_N10:
1058     case RSV_VCL_N12:
1059     case RSV_VCL_N14:
1060       ret = FALSE;
1061       break;
1062     default:
1063       ret = TRUE;
1064       break;
1065   }
1066   return ret;
1067 }
1068
1069 static gboolean
1070 gst_h265_decoder_calculate_poc (GstH265Decoder * self,
1071     const GstH265Slice * slice, GstH265Picture * picture)
1072 {
1073   GstH265DecoderPrivate *priv = self->priv;
1074   const GstH265SliceHdr *slice_hdr = &slice->header;
1075   const GstH265NalUnit *nalu = &slice->nalu;
1076   const GstH265SPS *sps = priv->active_sps;
1077   gint32 MaxPicOrderCntLsb = 1 << (sps->log2_max_pic_order_cnt_lsb_minus4 + 4);
1078   gboolean is_irap;
1079
1080   GST_DEBUG_OBJECT (self, "decode PicOrderCntVal");
1081
1082   priv->prev_poc_lsb = priv->poc_lsb;
1083   priv->prev_poc_msb = priv->poc_msb;
1084
1085   is_irap = GST_H265_IS_NAL_TYPE_IRAP (nalu->type);
1086
1087   if (!(is_irap && picture->NoRaslOutputFlag)) {
1088     priv->prev_poc_lsb = priv->prev_tid0pic_poc_lsb;
1089     priv->prev_poc_msb = priv->prev_tid0pic_poc_msb;
1090   }
1091
1092   /* Finding PicOrderCntMsb */
1093   if (is_irap && picture->NoRaslOutputFlag) {
1094     priv->poc_msb = 0;
1095   } else {
1096     /* (8-1) */
1097     if ((slice_hdr->pic_order_cnt_lsb < priv->prev_poc_lsb) &&
1098         ((priv->prev_poc_lsb - slice_hdr->pic_order_cnt_lsb) >=
1099             (MaxPicOrderCntLsb / 2)))
1100       priv->poc_msb = priv->prev_poc_msb + MaxPicOrderCntLsb;
1101
1102     else if ((slice_hdr->pic_order_cnt_lsb > priv->prev_poc_lsb) &&
1103         ((slice_hdr->pic_order_cnt_lsb - priv->prev_poc_lsb) >
1104             (MaxPicOrderCntLsb / 2)))
1105       priv->poc_msb = priv->prev_poc_msb - MaxPicOrderCntLsb;
1106
1107     else
1108       priv->poc_msb = priv->prev_poc_msb;
1109   }
1110
1111   /* (8-2) */
1112   priv->poc = picture->pic_order_cnt =
1113       priv->poc_msb + slice_hdr->pic_order_cnt_lsb;
1114   priv->poc_lsb = picture->pic_order_cnt_lsb = slice_hdr->pic_order_cnt_lsb;
1115
1116   if (GST_H265_IS_NAL_TYPE_IDR (nalu->type)) {
1117     picture->pic_order_cnt = 0;
1118     picture->pic_order_cnt_lsb = 0;
1119     priv->poc_lsb = 0;
1120     priv->poc_msb = 0;
1121     priv->prev_poc_lsb = 0;
1122     priv->prev_poc_msb = 0;
1123     priv->prev_tid0pic_poc_lsb = 0;
1124     priv->prev_tid0pic_poc_msb = 0;
1125   }
1126
1127   GST_DEBUG_OBJECT (self,
1128       "PicOrderCntVal %d, (lsb %d)", picture->pic_order_cnt,
1129       picture->pic_order_cnt_lsb);
1130
1131   if (nalu->temporal_id_plus1 == 1 && !GST_H265_IS_NAL_TYPE_RASL (nalu->type) &&
1132       !GST_H265_IS_NAL_TYPE_RADL (nalu->type) && nal_is_ref (nalu->type)) {
1133     priv->prev_tid0pic_poc_lsb = slice_hdr->pic_order_cnt_lsb;
1134     priv->prev_tid0pic_poc_msb = priv->poc_msb;
1135   }
1136
1137   return TRUE;
1138 }
1139
1140 static gboolean
1141 gst_h265_decoder_set_buffer_flags (GstH265Decoder * self,
1142     GstH265Picture * picture)
1143 {
1144   GstH265DecoderPrivate *priv = self->priv;
1145
1146   switch (picture->pic_struct) {
1147     case GST_H265_SEI_PIC_STRUCT_FRAME:
1148       break;
1149     case GST_H265_SEI_PIC_STRUCT_TOP_FIELD:
1150     case GST_H265_SEI_PIC_STRUCT_TOP_PAIRED_PREVIOUS_BOTTOM:
1151     case GST_H265_SEI_PIC_STRUCT_TOP_PAIRED_NEXT_BOTTOM:
1152       if (!priv->field_seq_flag) {
1153         GST_FIXME_OBJECT (self,
1154             "top-field with field_seq_flag == 0, what does it mean?");
1155       } else {
1156         picture->buffer_flags = GST_VIDEO_BUFFER_FLAG_TOP_FIELD;
1157       }
1158       break;
1159     case GST_H265_SEI_PIC_STRUCT_BOTTOM_FIELD:
1160     case GST_H265_SEI_PIC_STRUCT_BOTTOM_PAIRED_PREVIOUS_TOP:
1161     case GST_H265_SEI_PIC_STRUCT_BOTTOM_PAIRED_NEXT_TOP:
1162       if (!priv->field_seq_flag) {
1163         GST_FIXME_OBJECT (self,
1164             "bottom-field with field_seq_flag == 0, what does it mean?");
1165       } else {
1166         picture->buffer_flags = GST_VIDEO_BUFFER_FLAG_BOTTOM_FIELD;
1167       }
1168       break;
1169     case GST_H265_SEI_PIC_STRUCT_TOP_BOTTOM:
1170       if (priv->field_seq_flag) {
1171         GST_FIXME_OBJECT (self,
1172             "TFF with field_seq_flag == 1, what does it mean?");
1173       } else {
1174         picture->buffer_flags =
1175             GST_VIDEO_BUFFER_FLAG_INTERLACED | GST_VIDEO_BUFFER_FLAG_TFF;
1176       }
1177       break;
1178     case GST_H265_SEI_PIC_STRUCT_BOTTOM_TOP:
1179       if (priv->field_seq_flag) {
1180         GST_FIXME_OBJECT (self,
1181             "BFF with field_seq_flag == 1, what does it mean?");
1182       } else {
1183         picture->buffer_flags = GST_VIDEO_BUFFER_FLAG_INTERLACED;
1184       }
1185       break;
1186     default:
1187       GST_FIXME_OBJECT (self, "Unhandled picture time SEI pic_struct %d",
1188           picture->pic_struct);
1189       break;
1190   }
1191
1192   return TRUE;
1193 }
1194
1195 static gboolean
1196 gst_h265_decoder_init_current_picture (GstH265Decoder * self)
1197 {
1198   GstH265DecoderPrivate *priv = self->priv;
1199
1200   if (!gst_h265_decoder_fill_picture_from_slice (self, &priv->current_slice,
1201           priv->current_picture)) {
1202     return FALSE;
1203   }
1204
1205   if (!gst_h265_decoder_calculate_poc (self,
1206           &priv->current_slice, priv->current_picture))
1207     return FALSE;
1208
1209   /* Use picture struct parsed from picture timing SEI */
1210   priv->current_picture->pic_struct = priv->cur_pic_struct;
1211   priv->current_picture->source_scan_type = priv->cur_source_scan_type;
1212   priv->current_picture->duplicate_flag = priv->cur_duplicate_flag;
1213   gst_h265_decoder_set_buffer_flags (self, priv->current_picture);
1214
1215   return TRUE;
1216 }
1217
1218 static gboolean
1219 has_entry_in_rps (GstH265Picture * dpb_pic,
1220     GstH265Picture ** rps_list, guint rps_list_length)
1221 {
1222   guint i;
1223
1224   if (!dpb_pic || !rps_list || !rps_list_length)
1225     return FALSE;
1226
1227   for (i = 0; i < rps_list_length; i++) {
1228     if (rps_list[i] && rps_list[i]->pic_order_cnt == dpb_pic->pic_order_cnt)
1229       return TRUE;
1230   }
1231   return FALSE;
1232 }
1233
1234 static void
1235 gst_h265_decoder_clear_ref_pic_sets (GstH265Decoder * self)
1236 {
1237   guint i;
1238
1239   for (i = 0; i < 16; i++) {
1240     gst_h265_picture_replace (&self->RefPicSetLtCurr[i], NULL);
1241     gst_h265_picture_replace (&self->RefPicSetLtFoll[i], NULL);
1242     gst_h265_picture_replace (&self->RefPicSetStCurrBefore[i], NULL);
1243     gst_h265_picture_replace (&self->RefPicSetStCurrAfter[i], NULL);
1244     gst_h265_picture_replace (&self->RefPicSetStFoll[i], NULL);
1245   }
1246 }
1247
1248 static void
1249 gst_h265_decoder_derive_and_mark_rps (GstH265Decoder * self,
1250     GstH265Picture * picture, gint32 * CurrDeltaPocMsbPresentFlag,
1251     gint32 * FollDeltaPocMsbPresentFlag)
1252 {
1253   GstH265DecoderPrivate *priv = self->priv;
1254   guint i;
1255   GArray *dpb_array;
1256
1257   gst_h265_decoder_clear_ref_pic_sets (self);
1258
1259   /* (8-6) */
1260   for (i = 0; i < self->NumPocLtCurr; i++) {
1261     if (!CurrDeltaPocMsbPresentFlag[i]) {
1262       self->RefPicSetLtCurr[i] =
1263           gst_h265_dpb_get_ref_by_poc_lsb (priv->dpb, priv->PocLtCurr[i]);
1264     } else {
1265       self->RefPicSetLtCurr[i] =
1266           gst_h265_dpb_get_ref_by_poc (priv->dpb, priv->PocLtCurr[i]);
1267     }
1268   }
1269
1270   for (i = 0; i < self->NumPocLtFoll; i++) {
1271     if (!FollDeltaPocMsbPresentFlag[i]) {
1272       self->RefPicSetLtFoll[i] =
1273           gst_h265_dpb_get_ref_by_poc_lsb (priv->dpb, priv->PocLtFoll[i]);
1274     } else {
1275       self->RefPicSetLtFoll[i] =
1276           gst_h265_dpb_get_ref_by_poc (priv->dpb, priv->PocLtFoll[i]);
1277     }
1278   }
1279
1280   /* Mark all ref pics in RefPicSetLtCurr and RefPicSetLtFol as long_term_refs */
1281   for (i = 0; i < self->NumPocLtCurr; i++) {
1282     if (self->RefPicSetLtCurr[i]) {
1283       self->RefPicSetLtCurr[i]->ref = TRUE;
1284       self->RefPicSetLtCurr[i]->long_term = TRUE;
1285     }
1286   }
1287
1288   for (i = 0; i < self->NumPocLtFoll; i++) {
1289     if (self->RefPicSetLtFoll[i]) {
1290       self->RefPicSetLtFoll[i]->ref = TRUE;
1291       self->RefPicSetLtFoll[i]->long_term = TRUE;
1292     }
1293   }
1294
1295   /* (8-7) */
1296   for (i = 0; i < self->NumPocStCurrBefore; i++) {
1297     self->RefPicSetStCurrBefore[i] =
1298         gst_h265_dpb_get_short_ref_by_poc (priv->dpb, priv->PocStCurrBefore[i]);
1299   }
1300
1301   for (i = 0; i < self->NumPocStCurrAfter; i++) {
1302     self->RefPicSetStCurrAfter[i] =
1303         gst_h265_dpb_get_short_ref_by_poc (priv->dpb, priv->PocStCurrAfter[i]);
1304   }
1305
1306   for (i = 0; i < self->NumPocStFoll; i++) {
1307     self->RefPicSetStFoll[i] =
1308         gst_h265_dpb_get_short_ref_by_poc (priv->dpb, priv->PocStFoll[i]);
1309   }
1310
1311   /* Mark all dpb pics not beloging to RefPicSet*[] as unused for ref */
1312   dpb_array = gst_h265_dpb_get_pictures_all (priv->dpb);
1313   for (i = 0; i < dpb_array->len; i++) {
1314     GstH265Picture *dpb_pic = g_array_index (dpb_array, GstH265Picture *, i);
1315
1316     if (dpb_pic &&
1317         !has_entry_in_rps (dpb_pic, self->RefPicSetLtCurr, self->NumPocLtCurr)
1318         && !has_entry_in_rps (dpb_pic, self->RefPicSetLtFoll,
1319             self->NumPocLtFoll)
1320         && !has_entry_in_rps (dpb_pic, self->RefPicSetStCurrAfter,
1321             self->NumPocStCurrAfter)
1322         && !has_entry_in_rps (dpb_pic, self->RefPicSetStCurrBefore,
1323             self->NumPocStCurrBefore)
1324         && !has_entry_in_rps (dpb_pic, self->RefPicSetStFoll,
1325             self->NumPocStFoll)) {
1326       GST_LOG_OBJECT (self, "Mark Picture %p (poc %d) as non-ref", dpb_pic,
1327           dpb_pic->pic_order_cnt);
1328       dpb_pic->ref = FALSE;
1329       dpb_pic->long_term = FALSE;
1330     }
1331   }
1332
1333   g_array_unref (dpb_array);
1334 }
1335
1336 static gboolean
1337 gst_h265_decoder_prepare_rps (GstH265Decoder * self, const GstH265Slice * slice,
1338     GstH265Picture * picture)
1339 {
1340   GstH265DecoderPrivate *priv = self->priv;
1341   gint32 CurrDeltaPocMsbPresentFlag[16] = { 0, };
1342   gint32 FollDeltaPocMsbPresentFlag[16] = { 0, };
1343   const GstH265SliceHdr *slice_hdr = &slice->header;
1344   const GstH265NalUnit *nalu = &slice->nalu;
1345   const GstH265SPS *sps = priv->active_sps;
1346   guint32 MaxPicOrderCntLsb = 1 << (sps->log2_max_pic_order_cnt_lsb_minus4 + 4);
1347   gint i, j, k;
1348
1349   /* if it is an irap pic, set all ref pics in dpb as unused for ref */
1350   if (GST_H265_IS_NAL_TYPE_IRAP (nalu->type) && picture->NoRaslOutputFlag) {
1351     GST_DEBUG_OBJECT (self, "Mark all pictures in DPB as non-ref");
1352     gst_h265_dpb_mark_all_non_ref (priv->dpb);
1353   }
1354
1355   /* Reset everything for IDR */
1356   if (GST_H265_IS_NAL_TYPE_IDR (nalu->type)) {
1357     memset (priv->PocStCurrBefore, 0, sizeof (priv->PocStCurrBefore));
1358     memset (priv->PocStCurrAfter, 0, sizeof (priv->PocStCurrAfter));
1359     memset (priv->PocStFoll, 0, sizeof (priv->PocStFoll));
1360     memset (priv->PocLtCurr, 0, sizeof (priv->PocLtCurr));
1361     memset (priv->PocLtFoll, 0, sizeof (priv->PocLtFoll));
1362     self->NumPocStCurrBefore = self->NumPocStCurrAfter = self->NumPocStFoll = 0;
1363     self->NumPocLtCurr = self->NumPocLtFoll = 0;
1364   } else {
1365     const GstH265ShortTermRefPicSet *stRefPic = NULL;
1366     gint32 num_lt_pics, pocLt;
1367     gint32 PocLsbLt[16] = { 0, };
1368     gint32 UsedByCurrPicLt[16] = { 0, };
1369     gint32 DeltaPocMsbCycleLt[16] = { 0, };
1370     gint numtotalcurr = 0;
1371
1372     /* this is based on CurrRpsIdx described in spec */
1373     if (!slice_hdr->short_term_ref_pic_set_sps_flag)
1374       stRefPic = &slice_hdr->short_term_ref_pic_sets;
1375     else if (sps->num_short_term_ref_pic_sets)
1376       stRefPic =
1377           &sps->short_term_ref_pic_set[slice_hdr->short_term_ref_pic_set_idx];
1378
1379     g_assert (stRefPic != NULL);
1380
1381     GST_LOG_OBJECT (self,
1382         "NumDeltaPocs: %d, NumNegativePics: %d, NumPositivePics %d",
1383         stRefPic->NumDeltaPocs, stRefPic->NumNegativePics,
1384         stRefPic->NumPositivePics);
1385
1386     for (i = 0, j = 0, k = 0; i < stRefPic->NumNegativePics; i++) {
1387       if (stRefPic->UsedByCurrPicS0[i]) {
1388         priv->PocStCurrBefore[j++] =
1389             picture->pic_order_cnt + stRefPic->DeltaPocS0[i];
1390         numtotalcurr++;
1391       } else
1392         priv->PocStFoll[k++] = picture->pic_order_cnt + stRefPic->DeltaPocS0[i];
1393     }
1394     self->NumPocStCurrBefore = j;
1395     for (i = 0, j = 0; i < stRefPic->NumPositivePics; i++) {
1396       if (stRefPic->UsedByCurrPicS1[i]) {
1397         priv->PocStCurrAfter[j++] =
1398             picture->pic_order_cnt + stRefPic->DeltaPocS1[i];
1399         numtotalcurr++;
1400       } else
1401         priv->PocStFoll[k++] = picture->pic_order_cnt + stRefPic->DeltaPocS1[i];
1402     }
1403     self->NumPocStCurrAfter = j;
1404     self->NumPocStFoll = k;
1405     num_lt_pics = slice_hdr->num_long_term_sps + slice_hdr->num_long_term_pics;
1406     /* The variables PocLsbLt[i] and UsedByCurrPicLt[i] are derived as follows: */
1407     for (i = 0; i < num_lt_pics; i++) {
1408       if (i < slice_hdr->num_long_term_sps) {
1409         PocLsbLt[i] = sps->lt_ref_pic_poc_lsb_sps[slice_hdr->lt_idx_sps[i]];
1410         UsedByCurrPicLt[i] =
1411             sps->used_by_curr_pic_lt_sps_flag[slice_hdr->lt_idx_sps[i]];
1412       } else {
1413         PocLsbLt[i] = slice_hdr->poc_lsb_lt[i];
1414         UsedByCurrPicLt[i] = slice_hdr->used_by_curr_pic_lt_flag[i];
1415       }
1416       if (UsedByCurrPicLt[i])
1417         numtotalcurr++;
1418     }
1419
1420     self->NumPicTotalCurr = numtotalcurr;
1421
1422     /* The variable DeltaPocMsbCycleLt[i] is derived as follows: (7-38) */
1423     for (i = 0; i < num_lt_pics; i++) {
1424       if (i == 0 || i == slice_hdr->num_long_term_sps)
1425         DeltaPocMsbCycleLt[i] = slice_hdr->delta_poc_msb_cycle_lt[i];
1426       else
1427         DeltaPocMsbCycleLt[i] =
1428             slice_hdr->delta_poc_msb_cycle_lt[i] + DeltaPocMsbCycleLt[i - 1];
1429     }
1430
1431     /* (8-5) */
1432     for (i = 0, j = 0, k = 0; i < num_lt_pics; i++) {
1433       pocLt = PocLsbLt[i];
1434       if (slice_hdr->delta_poc_msb_present_flag[i])
1435         pocLt +=
1436             picture->pic_order_cnt - DeltaPocMsbCycleLt[i] * MaxPicOrderCntLsb -
1437             slice_hdr->pic_order_cnt_lsb;
1438       if (UsedByCurrPicLt[i]) {
1439         priv->PocLtCurr[j] = pocLt;
1440         CurrDeltaPocMsbPresentFlag[j++] =
1441             slice_hdr->delta_poc_msb_present_flag[i];
1442       } else {
1443         priv->PocLtFoll[k] = pocLt;
1444         FollDeltaPocMsbPresentFlag[k++] =
1445             slice_hdr->delta_poc_msb_present_flag[i];
1446       }
1447     }
1448     self->NumPocLtCurr = j;
1449     self->NumPocLtFoll = k;
1450   }
1451
1452   GST_LOG_OBJECT (self, "NumPocStCurrBefore: %d", self->NumPocStCurrBefore);
1453   GST_LOG_OBJECT (self, "NumPocStCurrAfter:  %d", self->NumPocStCurrAfter);
1454   GST_LOG_OBJECT (self, "NumPocStFoll:       %d", self->NumPocStFoll);
1455   GST_LOG_OBJECT (self, "NumPocLtCurr:       %d", self->NumPocLtCurr);
1456   GST_LOG_OBJECT (self, "NumPocLtFoll:       %d", self->NumPocLtFoll);
1457   GST_LOG_OBJECT (self, "NumPicTotalCurr:    %d", self->NumPicTotalCurr);
1458
1459   /* the derivation process for the RPS and the picture marking */
1460   gst_h265_decoder_derive_and_mark_rps (self, picture,
1461       CurrDeltaPocMsbPresentFlag, FollDeltaPocMsbPresentFlag);
1462
1463   return TRUE;
1464 }
1465
1466 static void
1467 gst_h265_decoder_do_output_picture (GstH265Decoder * self,
1468     GstH265Picture * picture, GstFlowReturn * ret)
1469 {
1470   GstH265DecoderPrivate *priv = self->priv;
1471   GstH265DecoderClass *klass;
1472   GstVideoCodecFrame *frame = NULL;
1473   GstFlowReturn flow_ret = GST_FLOW_OK;
1474
1475   g_assert (ret != NULL);
1476
1477   GST_LOG_OBJECT (self, "Output picture %p (poc %d)", picture,
1478       picture->pic_order_cnt);
1479
1480   if (picture->pic_order_cnt < priv->last_output_poc) {
1481     GST_WARNING_OBJECT (self,
1482         "Outputting out of order %d -> %d, likely a broken stream",
1483         priv->last_output_poc, picture->pic_order_cnt);
1484   }
1485
1486   priv->last_output_poc = picture->pic_order_cnt;
1487
1488   frame = gst_video_decoder_get_frame (GST_VIDEO_DECODER (self),
1489       picture->system_frame_number);
1490
1491   if (!frame) {
1492     GST_ERROR_OBJECT (self,
1493         "No available codec frame with frame number %d",
1494         picture->system_frame_number);
1495     UPDATE_FLOW_RETURN (ret, GST_FLOW_ERROR);
1496
1497     gst_h265_picture_unref (picture);
1498     return;
1499   }
1500
1501   klass = GST_H265_DECODER_GET_CLASS (self);
1502
1503   g_assert (klass->output_picture);
1504   flow_ret = klass->output_picture (self, frame, picture);
1505
1506   UPDATE_FLOW_RETURN (ret, flow_ret);
1507 }
1508
1509 static void
1510 gst_h265_decoder_clear_dpb (GstH265Decoder * self, gboolean flush)
1511 {
1512   GstVideoDecoder *decoder = GST_VIDEO_DECODER (self);
1513   GstH265DecoderPrivate *priv = self->priv;
1514   GstH265Picture *picture;
1515
1516   /* If we are not flushing now, videodecoder baseclass will hold
1517    * GstVideoCodecFrame. Release frames manually */
1518   if (!flush) {
1519     while ((picture = gst_h265_dpb_bump (priv->dpb, TRUE)) != NULL) {
1520       GstVideoCodecFrame *frame = gst_video_decoder_get_frame (decoder,
1521           picture->system_frame_number);
1522
1523       if (frame)
1524         gst_video_decoder_release_frame (decoder, frame);
1525       gst_h265_picture_unref (picture);
1526     }
1527   }
1528
1529   gst_h265_dpb_clear (priv->dpb);
1530   priv->last_output_poc = G_MININT32;
1531 }
1532
1533 static GstFlowReturn
1534 gst_h265_decoder_drain_internal (GstH265Decoder * self)
1535 {
1536   GstH265DecoderPrivate *priv = self->priv;
1537   GstH265Picture *picture;
1538   GstFlowReturn ret = GST_FLOW_OK;
1539
1540   while ((picture = gst_h265_dpb_bump (priv->dpb, TRUE)) != NULL)
1541     gst_h265_decoder_do_output_picture (self, picture, &ret);
1542
1543   gst_h265_dpb_clear (priv->dpb);
1544   priv->last_output_poc = G_MININT32;
1545
1546   return ret;
1547 }
1548
1549 /* C.5.2.2 */
1550 static GstFlowReturn
1551 gst_h265_decoder_dpb_init (GstH265Decoder * self, const GstH265Slice * slice,
1552     GstH265Picture * picture)
1553 {
1554   GstH265DecoderPrivate *priv = self->priv;
1555   const GstH265SliceHdr *slice_hdr = &slice->header;
1556   const GstH265NalUnit *nalu = &slice->nalu;
1557   const GstH265SPS *sps = priv->active_sps;
1558   GstH265Picture *to_output;
1559   GstFlowReturn ret = GST_FLOW_OK;
1560
1561   /* C 3.2 */
1562   if (GST_H265_IS_NAL_TYPE_IRAP (nalu->type) && picture->NoRaslOutputFlag
1563       && !priv->new_bitstream) {
1564     if (nalu->type == GST_H265_NAL_SLICE_CRA_NUT)
1565       picture->NoOutputOfPriorPicsFlag = TRUE;
1566     else
1567       picture->NoOutputOfPriorPicsFlag =
1568           slice_hdr->no_output_of_prior_pics_flag;
1569
1570     if (picture->NoOutputOfPriorPicsFlag) {
1571       GST_DEBUG_OBJECT (self, "Clear dpb");
1572       gst_h265_decoder_clear_dpb (self, FALSE);
1573     } else {
1574       gst_h265_dpb_delete_unused (priv->dpb);
1575       while ((to_output = gst_h265_dpb_bump (priv->dpb, FALSE)) != NULL)
1576         gst_h265_decoder_do_output_picture (self, to_output, &ret);
1577
1578       if (gst_h265_dpb_get_size (priv->dpb) > 0) {
1579         GST_WARNING_OBJECT (self, "IDR or BLA frame failed to clear the dpb, "
1580             "there are still %d pictures in the dpb, last output poc is %d",
1581             gst_h265_dpb_get_size (priv->dpb), priv->last_output_poc);
1582       } else {
1583         priv->last_output_poc = G_MININT32;
1584       }
1585     }
1586   } else {
1587     gst_h265_dpb_delete_unused (priv->dpb);
1588     while (gst_h265_dpb_needs_bump (priv->dpb,
1589             sps->max_num_reorder_pics[sps->max_sub_layers_minus1],
1590             priv->SpsMaxLatencyPictures,
1591             sps->max_dec_pic_buffering_minus1[sps->max_sub_layers_minus1] +
1592             1)) {
1593       to_output = gst_h265_dpb_bump (priv->dpb, FALSE);
1594
1595       /* Something wrong... */
1596       if (!to_output) {
1597         GST_WARNING_OBJECT (self, "Bumping is needed but no picture to output");
1598         break;
1599       }
1600
1601       gst_h265_decoder_do_output_picture (self, to_output, &ret);
1602     }
1603   }
1604
1605   return ret;
1606 }
1607
1608 static GstFlowReturn
1609 gst_h265_decoder_start_current_picture (GstH265Decoder * self)
1610 {
1611   GstH265DecoderClass *klass;
1612   GstH265DecoderPrivate *priv = self->priv;
1613   GstFlowReturn ret = GST_FLOW_OK;
1614
1615   g_assert (priv->current_picture != NULL);
1616   g_assert (priv->active_sps != NULL);
1617   g_assert (priv->active_pps != NULL);
1618
1619   if (!gst_h265_decoder_init_current_picture (self))
1620     return GST_FLOW_ERROR;
1621
1622   /* Drop all RASL pictures having NoRaslOutputFlag is TRUE for the
1623    * associated IRAP picture */
1624   if (GST_H265_IS_NAL_TYPE_RASL (priv->current_slice.nalu.type) &&
1625       priv->associated_irap_NoRaslOutputFlag) {
1626     GST_DEBUG_OBJECT (self, "Drop current picture");
1627     gst_h265_picture_replace (&priv->current_picture, NULL);
1628     return GST_FLOW_OK;
1629   }
1630
1631   gst_h265_decoder_prepare_rps (self, &priv->current_slice,
1632       priv->current_picture);
1633
1634   ret = gst_h265_decoder_dpb_init (self,
1635       &priv->current_slice, priv->current_picture);
1636   if (ret != GST_FLOW_OK) {
1637     GST_WARNING_OBJECT (self, "Failed to init dpb");
1638     return ret;
1639   }
1640
1641   klass = GST_H265_DECODER_GET_CLASS (self);
1642   if (klass->start_picture) {
1643     ret = klass->start_picture (self, priv->current_picture,
1644         &priv->current_slice, priv->dpb);
1645
1646     if (ret != GST_FLOW_OK) {
1647       GST_WARNING_OBJECT (self, "subclass does not want to start picture");
1648       return ret;
1649     }
1650   }
1651
1652   return GST_FLOW_OK;
1653 }
1654
1655 static void
1656 gst_h265_decoder_finish_picture (GstH265Decoder * self,
1657     GstH265Picture * picture, GstFlowReturn * ret)
1658 {
1659   GstVideoDecoder *decoder = GST_VIDEO_DECODER (self);
1660   GstH265DecoderPrivate *priv = self->priv;
1661   const GstH265SPS *sps = priv->active_sps;
1662
1663   g_assert (ret != NULL);
1664
1665   GST_LOG_OBJECT (self,
1666       "Finishing picture %p (poc %d), entries in DPB %d",
1667       picture, picture->pic_order_cnt, gst_h265_dpb_get_size (priv->dpb));
1668
1669   gst_h265_dpb_delete_unused (priv->dpb);
1670
1671   /* This picture is decode only, drop corresponding frame */
1672   if (!picture->output_flag) {
1673     GstVideoCodecFrame *frame = gst_video_decoder_get_frame (decoder,
1674         picture->system_frame_number);
1675
1676     gst_video_decoder_release_frame (decoder, frame);
1677   }
1678
1679   /* gst_h265_dpb_add() will take care of pic_latency_cnt increment and
1680    * reference picture marking for this picture */
1681   gst_h265_dpb_add (priv->dpb, picture);
1682
1683   /* NOTE: As per C.5.2.2, bumping by sps_max_dec_pic_buffering_minus1 is
1684    * applied only for the output and removal of pictures from the DPB before
1685    * the decoding of the current picture. So pass zero here */
1686   while (gst_h265_dpb_needs_bump (priv->dpb,
1687           sps->max_num_reorder_pics[sps->max_sub_layers_minus1],
1688           priv->SpsMaxLatencyPictures, 0)) {
1689     GstH265Picture *to_output = gst_h265_dpb_bump (priv->dpb, FALSE);
1690
1691     /* Something wrong... */
1692     if (!to_output) {
1693       GST_WARNING_OBJECT (self, "Bumping is needed but no picture to output");
1694       break;
1695     }
1696
1697     gst_h265_decoder_do_output_picture (self, to_output, ret);
1698   }
1699 }
1700
1701 static void
1702 gst_h265_decoder_finish_current_picture (GstH265Decoder * self,
1703     GstFlowReturn * ret)
1704 {
1705   GstH265DecoderPrivate *priv = self->priv;
1706   GstH265DecoderClass *klass;
1707   GstFlowReturn flow_ret = GST_FLOW_OK;
1708
1709   g_assert (ret != NULL);
1710
1711   if (!priv->current_picture)
1712     return;
1713
1714   klass = GST_H265_DECODER_GET_CLASS (self);
1715
1716   if (klass->end_picture) {
1717     flow_ret = klass->end_picture (self, priv->current_picture);
1718     if (flow_ret != GST_FLOW_OK) {
1719       GST_WARNING_OBJECT (self, "End picture failed");
1720
1721       /* continue to empty dpb */
1722       UPDATE_FLOW_RETURN (ret, flow_ret);
1723     }
1724   }
1725
1726   /* finish picture takes ownership of the picture */
1727   gst_h265_decoder_finish_picture (self, priv->current_picture, &flow_ret);
1728   priv->current_picture = NULL;
1729
1730   UPDATE_FLOW_RETURN (ret, flow_ret);
1731 }
1732
1733 static void
1734 gst_h265_decoder_reset_frame_state (GstH265Decoder * self)
1735 {
1736   GstH265DecoderPrivate *priv = self->priv;
1737
1738   /* Clear picture struct information */
1739   priv->cur_pic_struct = GST_H265_SEI_PIC_STRUCT_FRAME;
1740   priv->cur_source_scan_type = 2;
1741   priv->cur_duplicate_flag = 0;
1742 }
1743
1744 static GstFlowReturn
1745 gst_h265_decoder_handle_frame (GstVideoDecoder * decoder,
1746     GstVideoCodecFrame * frame)
1747 {
1748   GstH265Decoder *self = GST_H265_DECODER (decoder);
1749   GstH265DecoderPrivate *priv = self->priv;
1750   GstBuffer *in_buf = frame->input_buffer;
1751   GstH265NalUnit nalu;
1752   GstH265ParserResult pres;
1753   GstMapInfo map;
1754   GstFlowReturn decode_ret = GST_FLOW_OK;
1755
1756   GST_LOG_OBJECT (self,
1757       "handle frame, PTS: %" GST_TIME_FORMAT ", DTS: %"
1758       GST_TIME_FORMAT, GST_TIME_ARGS (GST_BUFFER_PTS (in_buf)),
1759       GST_TIME_ARGS (GST_BUFFER_DTS (in_buf)));
1760
1761   priv->current_frame = frame;
1762
1763   gst_h265_decoder_reset_frame_state (self);
1764
1765   if (!gst_buffer_map (in_buf, &map, GST_MAP_READ)) {
1766     GST_ELEMENT_ERROR (self, RESOURCE, READ,
1767         ("Failed to map memory for reading"), (NULL));
1768     return GST_FLOW_ERROR;
1769   }
1770
1771   if (priv->in_format == GST_H265_DECODER_FORMAT_HVC1 ||
1772       priv->in_format == GST_H265_DECODER_FORMAT_HEV1) {
1773     pres = gst_h265_parser_identify_nalu_hevc (priv->parser,
1774         map.data, 0, map.size, priv->nal_length_size, &nalu);
1775
1776     while (pres == GST_H265_PARSER_OK && decode_ret == GST_FLOW_OK) {
1777       decode_ret = gst_h265_decoder_decode_nal (self,
1778           &nalu, GST_BUFFER_PTS (in_buf));
1779
1780       pres = gst_h265_parser_identify_nalu_hevc (priv->parser,
1781           map.data, nalu.offset + nalu.size, map.size, priv->nal_length_size,
1782           &nalu);
1783     }
1784   } else {
1785     pres = gst_h265_parser_identify_nalu (priv->parser,
1786         map.data, 0, map.size, &nalu);
1787
1788     if (pres == GST_H265_PARSER_NO_NAL_END)
1789       pres = GST_H265_PARSER_OK;
1790
1791     while (pres == GST_H265_PARSER_OK && decode_ret == GST_FLOW_OK) {
1792       decode_ret = gst_h265_decoder_decode_nal (self,
1793           &nalu, GST_BUFFER_PTS (in_buf));
1794
1795       pres = gst_h265_parser_identify_nalu (priv->parser,
1796           map.data, nalu.offset + nalu.size, map.size, &nalu);
1797
1798       if (pres == GST_H265_PARSER_NO_NAL_END)
1799         pres = GST_H265_PARSER_OK;
1800     }
1801   }
1802
1803   gst_buffer_unmap (in_buf, &map);
1804   priv->current_frame = NULL;
1805
1806   if (decode_ret != GST_FLOW_OK) {
1807     if (decode_ret == GST_FLOW_ERROR) {
1808       GST_VIDEO_DECODER_ERROR (self, 1, STREAM, DECODE,
1809           ("Failed to decode data"), (NULL), decode_ret);
1810     }
1811
1812     gst_video_decoder_drop_frame (decoder, frame);
1813     gst_h265_picture_clear (&priv->current_picture);
1814
1815     return decode_ret;
1816   }
1817
1818   if (priv->current_picture) {
1819     gst_h265_decoder_finish_current_picture (self, &decode_ret);
1820     gst_video_codec_frame_unref (frame);
1821   } else {
1822     /* This picture was dropped */
1823     gst_video_decoder_release_frame (decoder, frame);
1824   }
1825
1826   if (decode_ret == GST_FLOW_ERROR) {
1827     GST_VIDEO_DECODER_ERROR (self, 1, STREAM, DECODE,
1828         ("Failed to decode data"), (NULL), decode_ret);
1829   }
1830
1831   return decode_ret;
1832 }
1833
1834 /**
1835  * gst_h265_decoder_set_process_ref_pic_lists:
1836  * @decoder: a #GstH265Decoder
1837  * @process: whether subclass is requiring reference picture modification process
1838  *
1839  * Called to en/disable reference picture modification process.
1840  *
1841  * Since: 1.20
1842  */
1843 void
1844 gst_h265_decoder_set_process_ref_pic_lists (GstH265Decoder * decoder,
1845     gboolean process)
1846 {
1847   decoder->priv->process_ref_pic_lists = process;
1848 }
1849
1850 /**
1851  * gst_h265_decoder_get_picture:
1852  * @decoder: a #GstH265Decoder
1853  * @system_frame_number: a target system frame number of #GstH265Picture
1854  *
1855  * Retrive DPB and return a #GstH265Picture corresponding to
1856  * the @system_frame_number
1857  *
1858  * Returns: (transfer full): a #GstH265Picture if successful, or %NULL otherwise
1859  *
1860  * Since: 1.20
1861  */
1862 GstH265Picture *
1863 gst_h265_decoder_get_picture (GstH265Decoder * decoder,
1864     guint32 system_frame_number)
1865 {
1866   return gst_h265_dpb_get_picture (decoder->priv->dpb, system_frame_number);
1867 }