4ba8acef7570b45af0e30ba5f2ae329bf5d6bea3
[platform/upstream/gstreamer.git] / gst-libs / gst / codecs / gsth264decoder.c
1 /* GStreamer
2  * Copyright (C) 2019 Seungha Yang <seungha.yang@navercorp.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  * NOTE: some of implementations are copied/modified from Chromium code
20  *
21  * Copyright 2015 The Chromium Authors. All rights reserved.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions are
25  * met:
26  *
27  *    * Redistributions of source code must retain the above copyright
28  * notice, this list of conditions and the following disclaimer.
29  *    * Redistributions in binary form must reproduce the above
30  * copyright notice, this list of conditions and the following disclaimer
31  * in the documentation and/or other materials provided with the
32  * distribution.
33  *    * Neither the name of Google Inc. nor the names of its
34  * contributors may be used to endorse or promote products derived from
35  * this software without specific prior written permission.
36  *
37  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
38  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
39  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
40  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
41  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
43  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
44  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
45  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
46  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
47  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
48  */
49 /**
50  * SECTION:gsth264decoder
51  * @title: GstH264Decoder
52  * @short_description: Base class to implement stateless H.264 decoders
53  * @sources:
54  * - gsth264picture.h
55  */
56
57 #ifdef HAVE_CONFIG_H
58 #include <config.h>
59 #endif
60
61 #include "gsth264decoder.h"
62
63 GST_DEBUG_CATEGORY (gst_h264_decoder_debug);
64 #define GST_CAT_DEFAULT gst_h264_decoder_debug
65
66 typedef enum
67 {
68   GST_H264_DECODER_FORMAT_NONE,
69   GST_H264_DECODER_FORMAT_AVC,
70   GST_H264_DECODER_FORMAT_BYTE
71 } GstH264DecoderFormat;
72
73 typedef enum
74 {
75   GST_H264_DECODER_ALIGN_NONE,
76   GST_H264_DECODER_ALIGN_NAL,
77   GST_H264_DECODER_ALIGN_AU
78 } GstH264DecoderAlign;
79
80 struct _GstH264DecoderPrivate
81 {
82   gint width, height;
83   gint fps_num, fps_den;
84   gint upstream_par_n, upstream_par_d;
85   gint parsed_par_n, parsed_par_d;
86   gint parsed_fps_n, parsed_fps_d;
87   GstVideoColorimetry parsed_colorimetry;
88   /* input codec_data, if any */
89   GstBuffer *codec_data;
90   guint nal_length_size;
91
92   /* state */
93   GstH264DecoderFormat in_format;
94   GstH264DecoderAlign align;
95   GstH264NalParser *parser;
96   GstH264Dpb *dpb;
97   GstFlowReturn last_ret;
98   /* used for low-latency vs. high throughput mode decision */
99   gboolean is_live;
100
101   /* sps/pps of the current slice */
102   const GstH264SPS *active_sps;
103   const GstH264PPS *active_pps;
104
105   /* Picture currently being processed/decoded */
106   GstH264Picture *current_picture;
107   GstVideoCodecFrame *current_frame;
108
109   /* Slice (slice header + nalu) currently being processed/decodec */
110   GstH264Slice current_slice;
111
112   gint max_frame_num;
113   gint max_pic_num;
114   gint max_long_term_frame_idx;
115   gsize max_num_reorder_frames;
116
117   gint prev_frame_num;
118   gint prev_ref_frame_num;
119   gint prev_frame_num_offset;
120   gboolean prev_has_memmgmnt5;
121
122   /* Values related to previously decoded reference picture */
123   gboolean prev_ref_has_memmgmnt5;
124   gint prev_ref_top_field_order_cnt;
125   gint prev_ref_pic_order_cnt_msb;
126   gint prev_ref_pic_order_cnt_lsb;
127
128   GstH264PictureField prev_ref_field;
129
130   /* PicOrderCount of the previously outputted frame */
131   gint last_output_poc;
132
133   gboolean process_ref_pic_lists;
134
135   /* Reference picture lists, constructed for each frame */
136   GArray *ref_pic_list_p0;
137   GArray *ref_pic_list_b0;
138   GArray *ref_pic_list_b1;
139
140   /* Reference picture lists, constructed for each slice */
141   GArray *ref_pic_list0;
142   GArray *ref_pic_list1;
143 };
144
145 #define parent_class gst_h264_decoder_parent_class
146 G_DEFINE_ABSTRACT_TYPE_WITH_CODE (GstH264Decoder, gst_h264_decoder,
147     GST_TYPE_VIDEO_DECODER,
148     G_ADD_PRIVATE (GstH264Decoder);
149     GST_DEBUG_CATEGORY_INIT (gst_h264_decoder_debug, "h264decoder", 0,
150         "H.264 Video Decoder"));
151
152 static void gst_h264_decoder_finalize (GObject * object);
153
154 static gboolean gst_h264_decoder_start (GstVideoDecoder * decoder);
155 static gboolean gst_h264_decoder_stop (GstVideoDecoder * decoder);
156 static gboolean gst_h264_decoder_set_format (GstVideoDecoder * decoder,
157     GstVideoCodecState * state);
158 static GstFlowReturn gst_h264_decoder_finish (GstVideoDecoder * decoder);
159 static gboolean gst_h264_decoder_flush (GstVideoDecoder * decoder);
160 static GstFlowReturn gst_h264_decoder_drain (GstVideoDecoder * decoder);
161 static GstFlowReturn gst_h264_decoder_handle_frame (GstVideoDecoder * decoder,
162     GstVideoCodecFrame * frame);
163
164 /* codec spcific functions */
165 static gboolean gst_h264_decoder_process_sps (GstH264Decoder * self,
166     GstH264SPS * sps);
167 static gboolean gst_h264_decoder_decode_slice (GstH264Decoder * self);
168 static gboolean gst_h264_decoder_decode_nal (GstH264Decoder * self,
169     GstH264NalUnit * nalu);
170 static gboolean gst_h264_decoder_fill_picture_from_slice (GstH264Decoder * self,
171     const GstH264Slice * slice, GstH264Picture * picture);
172 static gboolean gst_h264_decoder_calculate_poc (GstH264Decoder * self,
173     GstH264Picture * picture);
174 static gboolean gst_h264_decoder_init_gap_picture (GstH264Decoder * self,
175     GstH264Picture * picture, gint frame_num);
176 static gboolean gst_h264_decoder_drain_internal (GstH264Decoder * self);
177 static gboolean gst_h264_decoder_finish_current_picture (GstH264Decoder * self);
178 static gboolean gst_h264_decoder_finish_picture (GstH264Decoder * self,
179     GstH264Picture * picture);
180 static void gst_h264_decoder_prepare_ref_pic_lists (GstH264Decoder * self);
181 static void gst_h264_decoder_clear_ref_pic_lists (GstH264Decoder * self);
182 static gboolean gst_h264_decoder_modify_ref_pic_lists (GstH264Decoder * self);
183 static gboolean
184 gst_h264_decoder_sliding_window_picture_marking (GstH264Decoder * self);
185 static void gst_h264_decoder_do_output_picture (GstH264Decoder * self,
186     GstH264Picture * picture);
187
188 static void
189 gst_h264_decoder_class_init (GstH264DecoderClass * klass)
190 {
191   GstVideoDecoderClass *decoder_class = GST_VIDEO_DECODER_CLASS (klass);
192   GObjectClass *object_class = G_OBJECT_CLASS (klass);
193
194   object_class->finalize = GST_DEBUG_FUNCPTR (gst_h264_decoder_finalize);
195
196   decoder_class->start = GST_DEBUG_FUNCPTR (gst_h264_decoder_start);
197   decoder_class->stop = GST_DEBUG_FUNCPTR (gst_h264_decoder_stop);
198   decoder_class->set_format = GST_DEBUG_FUNCPTR (gst_h264_decoder_set_format);
199   decoder_class->finish = GST_DEBUG_FUNCPTR (gst_h264_decoder_finish);
200   decoder_class->flush = GST_DEBUG_FUNCPTR (gst_h264_decoder_flush);
201   decoder_class->drain = GST_DEBUG_FUNCPTR (gst_h264_decoder_drain);
202   decoder_class->handle_frame =
203       GST_DEBUG_FUNCPTR (gst_h264_decoder_handle_frame);
204 }
205
206 static void
207 gst_h264_decoder_init (GstH264Decoder * self)
208 {
209   GstH264DecoderPrivate *priv;
210
211   gst_video_decoder_set_packetized (GST_VIDEO_DECODER (self), TRUE);
212
213   self->priv = priv = gst_h264_decoder_get_instance_private (self);
214
215   priv->ref_pic_list_p0 = g_array_sized_new (FALSE, TRUE,
216       sizeof (GstH264Picture *), 32);
217   g_array_set_clear_func (priv->ref_pic_list_p0,
218       (GDestroyNotify) gst_h264_picture_clear);
219
220   priv->ref_pic_list_b0 = g_array_sized_new (FALSE, TRUE,
221       sizeof (GstH264Picture *), 32);
222   g_array_set_clear_func (priv->ref_pic_list_b0,
223       (GDestroyNotify) gst_h264_picture_clear);
224
225   priv->ref_pic_list_b1 = g_array_sized_new (FALSE, TRUE,
226       sizeof (GstH264Picture *), 32);
227   g_array_set_clear_func (priv->ref_pic_list_b1,
228       (GDestroyNotify) gst_h264_picture_clear);
229
230   priv->ref_pic_list0 = g_array_sized_new (FALSE, TRUE,
231       sizeof (GstH264Picture *), 32);
232   priv->ref_pic_list1 = g_array_sized_new (FALSE, TRUE,
233       sizeof (GstH264Picture *), 32);
234 }
235
236 static void
237 gst_h264_decoder_finalize (GObject * object)
238 {
239   GstH264Decoder *self = GST_H264_DECODER (object);
240   GstH264DecoderPrivate *priv = self->priv;
241
242   g_array_unref (priv->ref_pic_list_p0);
243   g_array_unref (priv->ref_pic_list_b0);
244   g_array_unref (priv->ref_pic_list_b1);
245   g_array_unref (priv->ref_pic_list0);
246   g_array_unref (priv->ref_pic_list1);
247
248   G_OBJECT_CLASS (parent_class)->finalize (object);
249 }
250
251 static gboolean
252 gst_h264_decoder_start (GstVideoDecoder * decoder)
253 {
254   GstH264Decoder *self = GST_H264_DECODER (decoder);
255   GstH264DecoderPrivate *priv = self->priv;
256
257   priv->parser = gst_h264_nal_parser_new ();
258   priv->dpb = gst_h264_dpb_new ();
259
260   return TRUE;
261 }
262
263 static gboolean
264 gst_h264_decoder_stop (GstVideoDecoder * decoder)
265 {
266   GstH264Decoder *self = GST_H264_DECODER (decoder);
267   GstH264DecoderPrivate *priv = self->priv;
268
269   if (self->input_state) {
270     gst_video_codec_state_unref (self->input_state);
271     self->input_state = NULL;
272   }
273
274   gst_clear_buffer (&priv->codec_data);
275
276   if (priv->parser) {
277     gst_h264_nal_parser_free (priv->parser);
278     priv->parser = NULL;
279   }
280
281   if (priv->dpb) {
282     gst_h264_dpb_free (priv->dpb);
283     priv->dpb = NULL;
284   }
285
286   return TRUE;
287 }
288
289 static void
290 gst_h264_decoder_clear_dpb (GstH264Decoder * self, gboolean flush)
291 {
292   GstVideoDecoder *decoder = GST_VIDEO_DECODER (self);
293   GstH264DecoderPrivate *priv = self->priv;
294   GstH264Picture *picture;
295
296   /* If we are not flushing now, videodecoder baseclass will hold
297    * GstVideoCodecFrame. Release frames manually */
298   if (!flush) {
299     while ((picture = gst_h264_dpb_bump (priv->dpb, TRUE)) != NULL) {
300       GstVideoCodecFrame *frame = gst_video_decoder_get_frame (decoder,
301           picture->system_frame_number);
302
303       if (frame)
304         gst_video_decoder_release_frame (decoder, frame);
305       gst_h264_picture_unref (picture);
306     }
307   }
308
309   gst_h264_decoder_clear_ref_pic_lists (self);
310   gst_h264_dpb_clear (priv->dpb);
311   priv->last_output_poc = 0;
312 }
313
314 static gboolean
315 gst_h264_decoder_flush (GstVideoDecoder * decoder)
316 {
317   GstH264Decoder *self = GST_H264_DECODER (decoder);
318
319   gst_h264_decoder_clear_dpb (self, TRUE);
320
321   return TRUE;
322 }
323
324 static GstFlowReturn
325 gst_h264_decoder_drain (GstVideoDecoder * decoder)
326 {
327   GstH264Decoder *self = GST_H264_DECODER (decoder);
328   GstH264DecoderPrivate *priv = self->priv;
329
330   priv->last_ret = GST_FLOW_OK;
331   /* dpb will be cleared by this method */
332   gst_h264_decoder_drain_internal (self);
333
334   return priv->last_ret;
335 }
336
337 static GstFlowReturn
338 gst_h264_decoder_finish (GstVideoDecoder * decoder)
339 {
340   return gst_h264_decoder_drain (decoder);
341 }
342
343 static GstFlowReturn
344 gst_h264_decoder_handle_frame (GstVideoDecoder * decoder,
345     GstVideoCodecFrame * frame)
346 {
347   GstH264Decoder *self = GST_H264_DECODER (decoder);
348   GstH264DecoderPrivate *priv = self->priv;
349   GstBuffer *in_buf = frame->input_buffer;
350   GstH264NalUnit nalu;
351   GstH264ParserResult pres;
352   GstMapInfo map;
353   gboolean decode_ret = TRUE;
354
355   GST_LOG_OBJECT (self,
356       "handle frame, PTS: %" GST_TIME_FORMAT ", DTS: %"
357       GST_TIME_FORMAT, GST_TIME_ARGS (GST_BUFFER_PTS (in_buf)),
358       GST_TIME_ARGS (GST_BUFFER_DTS (in_buf)));
359
360   priv->current_frame = frame;
361   priv->last_ret = GST_FLOW_OK;
362
363   gst_buffer_map (in_buf, &map, GST_MAP_READ);
364   if (priv->in_format == GST_H264_DECODER_FORMAT_AVC) {
365     pres = gst_h264_parser_identify_nalu_avc (priv->parser,
366         map.data, 0, map.size, priv->nal_length_size, &nalu);
367
368     while (pres == GST_H264_PARSER_OK && decode_ret) {
369       decode_ret = gst_h264_decoder_decode_nal (self, &nalu);
370
371       pres = gst_h264_parser_identify_nalu_avc (priv->parser,
372           map.data, nalu.offset + nalu.size, map.size, priv->nal_length_size,
373           &nalu);
374     }
375   } else {
376     pres = gst_h264_parser_identify_nalu (priv->parser,
377         map.data, 0, map.size, &nalu);
378
379     if (pres == GST_H264_PARSER_NO_NAL_END)
380       pres = GST_H264_PARSER_OK;
381
382     while (pres == GST_H264_PARSER_OK && decode_ret) {
383       decode_ret = gst_h264_decoder_decode_nal (self, &nalu);
384
385       pres = gst_h264_parser_identify_nalu (priv->parser,
386           map.data, nalu.offset + nalu.size, map.size, &nalu);
387
388       if (pres == GST_H264_PARSER_NO_NAL_END)
389         pres = GST_H264_PARSER_OK;
390     }
391   }
392
393   gst_buffer_unmap (in_buf, &map);
394
395   if (!decode_ret) {
396     GST_VIDEO_DECODER_ERROR (self, 1, STREAM, DECODE,
397         ("Failed to decode data"), (NULL), priv->last_ret);
398     gst_video_decoder_drop_frame (decoder, frame);
399
400     gst_h264_picture_clear (&priv->current_picture);
401     priv->current_frame = NULL;
402
403     return priv->last_ret;
404   }
405
406   gst_h264_decoder_finish_current_picture (self);
407   gst_video_codec_frame_unref (frame);
408   priv->current_frame = NULL;
409
410   return priv->last_ret;
411 }
412
413 static gboolean
414 gst_h264_decoder_parse_sps (GstH264Decoder * self, GstH264NalUnit * nalu)
415 {
416   GstH264DecoderPrivate *priv = self->priv;
417   GstH264SPS sps;
418   GstH264ParserResult pres;
419   gboolean ret;
420
421   pres = gst_h264_parse_sps (nalu, &sps);
422   if (pres != GST_H264_PARSER_OK) {
423     GST_WARNING_OBJECT (self, "Failed to parse SPS, result %d", pres);
424     return FALSE;
425   }
426
427   GST_LOG_OBJECT (self, "SPS parsed");
428
429   ret = gst_h264_decoder_process_sps (self, &sps);
430   if (!ret) {
431     GST_WARNING_OBJECT (self, "Failed to process SPS");
432   } else if (gst_h264_parser_update_sps (priv->parser,
433           &sps) != GST_H264_PARSER_OK) {
434     GST_WARNING_OBJECT (self, "Failed to update SPS");
435     ret = FALSE;
436   }
437
438   gst_h264_sps_clear (&sps);
439
440   return ret;
441 }
442
443 static gboolean
444 gst_h264_decoder_parse_pps (GstH264Decoder * self, GstH264NalUnit * nalu)
445 {
446   GstH264DecoderPrivate *priv = self->priv;
447   GstH264PPS pps;
448   GstH264ParserResult pres;
449   gboolean ret = TRUE;
450
451   pres = gst_h264_parse_pps (priv->parser, nalu, &pps);
452   if (pres != GST_H264_PARSER_OK) {
453     GST_WARNING_OBJECT (self, "Failed to parse PPS, result %d", pres);
454     return FALSE;
455   }
456
457   GST_LOG_OBJECT (self, "PPS parsed");
458
459   if (pps.num_slice_groups_minus1 > 0) {
460     GST_FIXME_OBJECT (self, "FMO is not supported");
461     ret = FALSE;
462   } else if (gst_h264_parser_update_pps (priv->parser, &pps)
463       != GST_H264_PARSER_OK) {
464     GST_WARNING_OBJECT (self, "Failed to update PPS");
465     ret = FALSE;
466   }
467
468   gst_h264_pps_clear (&pps);
469
470   return ret;
471 }
472
473 static gboolean
474 gst_h264_decoder_parse_codec_data (GstH264Decoder * self, const guint8 * data,
475     gsize size)
476 {
477   GstH264DecoderPrivate *priv = self->priv;
478   guint num_sps, num_pps;
479   guint off;
480   gint i;
481   GstH264ParserResult pres;
482   GstH264NalUnit nalu;
483 #ifndef GST_DISABLE_GST_DEBUG
484   guint profile;
485 #endif
486
487   /* parse the avcC data */
488   if (size < 7) {               /* when numSPS==0 and numPPS==0, length is 7 bytes */
489     return FALSE;
490   }
491
492   /* parse the version, this must be 1 */
493   if (data[0] != 1) {
494     return FALSE;
495   }
496 #ifndef GST_DISABLE_GST_DEBUG
497   /* AVCProfileIndication */
498   /* profile_compat */
499   /* AVCLevelIndication */
500   profile = (data[1] << 16) | (data[2] << 8) | data[3];
501   GST_DEBUG_OBJECT (self, "profile %06x", profile);
502 #endif
503
504   /* 6 bits reserved | 2 bits lengthSizeMinusOne */
505   /* this is the number of bytes in front of the NAL units to mark their
506    * length */
507   priv->nal_length_size = (data[4] & 0x03) + 1;
508   GST_DEBUG_OBJECT (self, "nal length size %u", priv->nal_length_size);
509
510   num_sps = data[5] & 0x1f;
511   off = 6;
512   for (i = 0; i < num_sps; i++) {
513     pres = gst_h264_parser_identify_nalu_avc (priv->parser,
514         data, off, size, 2, &nalu);
515     if (pres != GST_H264_PARSER_OK) {
516       GST_WARNING_OBJECT (self, "Failed to identify SPS nalu");
517       return FALSE;
518     }
519
520     if (!gst_h264_decoder_parse_sps (self, &nalu)) {
521       GST_WARNING_OBJECT (self, "Failed to parse SPS");
522       return FALSE;
523     }
524     off = nalu.offset + nalu.size;
525   }
526
527   if (off >= size) {
528     GST_WARNING_OBJECT (self, "Too small avcC");
529     return FALSE;
530   }
531
532   num_pps = data[off];
533   off++;
534
535   for (i = 0; i < num_pps; i++) {
536     pres = gst_h264_parser_identify_nalu_avc (priv->parser,
537         data, off, size, 2, &nalu);
538     if (pres != GST_H264_PARSER_OK) {
539       GST_WARNING_OBJECT (self, "Failed to identify PPS nalu");
540       return FALSE;
541     }
542
543     if (!gst_h264_decoder_parse_pps (self, &nalu)) {
544       GST_WARNING_OBJECT (self, "Failed to parse PPS");
545       return FALSE;
546     }
547     off = nalu.offset + nalu.size;
548   }
549
550   return TRUE;
551 }
552
553 static gboolean
554 gst_h264_decoder_preprocess_slice (GstH264Decoder * self, GstH264Slice * slice)
555 {
556   GstH264DecoderPrivate *priv = self->priv;
557
558   if (!priv->current_picture) {
559     if (slice->header.first_mb_in_slice != 0) {
560       GST_ERROR_OBJECT (self, "Invalid stream, first_mb_in_slice %d",
561           slice->header.first_mb_in_slice);
562       return FALSE;
563     }
564   }
565
566   return TRUE;
567 }
568
569 static void
570 gst_h264_decoder_update_pic_nums (GstH264Decoder * self, gint frame_num)
571 {
572   GstH264DecoderPrivate *priv = self->priv;
573   GArray *dpb = gst_h264_dpb_get_pictures_all (priv->dpb);
574   gint i;
575
576   for (i = 0; i < dpb->len; i++) {
577     GstH264Picture *picture = g_array_index (dpb, GstH264Picture *, i);
578
579     if (picture->field != GST_H264_PICTURE_FIELD_FRAME) {
580       GST_FIXME_OBJECT (self, "Interlaced video not supported");
581       continue;
582     }
583
584     if (!GST_H264_PICTURE_IS_REF (picture))
585       continue;
586
587     if (GST_H264_PICTURE_IS_LONG_TERM_REF (picture)) {
588       picture->long_term_pic_num = picture->long_term_frame_idx;
589     } else {
590       if (picture->frame_num > frame_num)
591         picture->frame_num_wrap = picture->frame_num - priv->max_frame_num;
592       else
593         picture->frame_num_wrap = picture->frame_num;
594
595       picture->pic_num = picture->frame_num_wrap;
596     }
597   }
598
599   g_array_unref (dpb);
600 }
601
602 static gboolean
603 gst_h264_decoder_handle_frame_num_gap (GstH264Decoder * self, gint frame_num)
604 {
605   GstH264DecoderPrivate *priv = self->priv;
606   const GstH264SPS *sps = priv->active_sps;
607   gint unused_short_term_frame_num;
608
609   if (!sps) {
610     GST_ERROR_OBJECT (self, "No active sps");
611     return FALSE;
612   }
613
614   if (priv->prev_ref_frame_num == frame_num) {
615     GST_TRACE_OBJECT (self,
616         "frame_num == PrevRefFrameNum (%d), not a gap", frame_num);
617     return TRUE;
618   }
619
620   if (((priv->prev_ref_frame_num + 1) % priv->max_frame_num) == frame_num) {
621     GST_TRACE_OBJECT (self,
622         "frame_num ==  (PrevRefFrameNum + 1) %% MaxFrameNum (%d), not a gap",
623         frame_num);
624     return TRUE;
625   }
626
627   if (gst_h264_dpb_get_size (priv->dpb) == 0) {
628     GST_TRACE_OBJECT (self, "DPB is empty, not a gap");
629     return TRUE;
630   }
631
632   if (!sps->gaps_in_frame_num_value_allowed_flag) {
633     /* This is likely the case where some frames were dropped.
634      * then we need to keep decoding without error out */
635     GST_WARNING_OBJECT (self, "Invalid frame num %d, maybe frame drop",
636         frame_num);
637
638     return TRUE;
639   }
640
641   GST_DEBUG_OBJECT (self, "Handling frame num gap %d -> %d (MaxFrameNum: %d)",
642       priv->prev_ref_frame_num, frame_num, priv->max_frame_num);
643
644   /* 7.4.3/7-23 */
645   unused_short_term_frame_num =
646       (priv->prev_ref_frame_num + 1) % priv->max_frame_num;
647   while (unused_short_term_frame_num != frame_num) {
648     GstH264Picture *picture = gst_h264_picture_new ();
649
650     if (!gst_h264_decoder_init_gap_picture (self, picture,
651             unused_short_term_frame_num))
652       return FALSE;
653
654     gst_h264_decoder_update_pic_nums (self, unused_short_term_frame_num);
655
656     /* C.2.1 */
657     if (!gst_h264_decoder_sliding_window_picture_marking (self)) {
658       GST_ERROR_OBJECT (self,
659           "Couldn't perform sliding window picture marking");
660       return FALSE;
661     }
662
663     gst_h264_dpb_delete_unused (priv->dpb);
664     gst_h264_dpb_add (priv->dpb, picture);
665     while (gst_h264_dpb_needs_bump (priv->dpb, priv->max_num_reorder_frames,
666             FALSE)) {
667       GstH264Picture *to_output;
668
669       to_output = gst_h264_dpb_bump (priv->dpb, FALSE);
670
671       if (!to_output) {
672         GST_WARNING_OBJECT (self, "Bumping is needed but no picture to output");
673         break;
674       }
675
676       gst_h264_decoder_do_output_picture (self, to_output);
677     }
678
679     unused_short_term_frame_num++;
680     unused_short_term_frame_num %= priv->max_frame_num;
681   }
682
683   return TRUE;
684 }
685
686 static gboolean
687 gst_h264_decoder_init_current_picture (GstH264Decoder * self)
688 {
689   GstH264DecoderPrivate *priv = self->priv;
690
691   if (!gst_h264_decoder_fill_picture_from_slice (self, &priv->current_slice,
692           priv->current_picture)) {
693     return FALSE;
694   }
695
696   if (!gst_h264_decoder_calculate_poc (self, priv->current_picture))
697     return FALSE;
698
699   /* If the slice header indicates we will have to perform reference marking
700    * process after this picture is decoded, store required data for that
701    * purpose */
702   if (priv->current_slice.header.
703       dec_ref_pic_marking.adaptive_ref_pic_marking_mode_flag) {
704     priv->current_picture->dec_ref_pic_marking =
705         priv->current_slice.header.dec_ref_pic_marking;
706   }
707
708   return TRUE;
709 }
710
711 static gboolean
712 gst_h264_decoder_start_current_picture (GstH264Decoder * self)
713 {
714   GstH264DecoderClass *klass;
715   GstH264DecoderPrivate *priv = self->priv;
716   const GstH264SPS *sps;
717   gint frame_num;
718   gboolean ret = TRUE;
719   GstH264Picture *current_picture;
720
721   g_assert (priv->current_picture != NULL);
722   g_assert (priv->active_sps != NULL);
723   g_assert (priv->active_pps != NULL);
724
725   sps = priv->active_sps;
726
727   priv->max_frame_num = sps->max_frame_num;
728   frame_num = priv->current_slice.header.frame_num;
729   if (priv->current_slice.nalu.idr_pic_flag)
730     priv->prev_ref_frame_num = 0;
731
732   if (!gst_h264_decoder_handle_frame_num_gap (self, frame_num))
733     return FALSE;
734
735   if (!gst_h264_decoder_init_current_picture (self))
736     return FALSE;
737
738   current_picture = priv->current_picture;
739
740   /* If the new picture is an IDR, flush DPB */
741   if (current_picture->idr) {
742     if (!current_picture->dec_ref_pic_marking.no_output_of_prior_pics_flag) {
743       gst_h264_decoder_drain_internal (self);
744     } else {
745       /* C.4.4 Removal of pictures from the DPB before possible insertion
746        * of the current picture
747        *
748        * If decoded picture is IDR and no_output_of_prior_pics_flag is equal to 1
749        * or is inferred to be equal to 1, all frame buffers in the DPB
750        * are emptied without output of the pictures they contain,
751        * and DPB fullness is set to 0.
752        */
753       gst_h264_decoder_clear_dpb (self, FALSE);
754     }
755   }
756
757   gst_h264_decoder_update_pic_nums (self, frame_num);
758
759   if (priv->process_ref_pic_lists)
760     gst_h264_decoder_prepare_ref_pic_lists (self);
761
762   klass = GST_H264_DECODER_GET_CLASS (self);
763   if (klass->start_picture)
764     ret = klass->start_picture (self, priv->current_picture,
765         &priv->current_slice, priv->dpb);
766
767   if (!ret) {
768     GST_ERROR_OBJECT (self, "subclass does not want to start picture");
769     return FALSE;
770   }
771
772   return TRUE;
773 }
774
775 static gboolean
776 gst_h264_decoder_parse_slice (GstH264Decoder * self, GstH264NalUnit * nalu)
777 {
778   GstH264DecoderPrivate *priv = self->priv;
779   GstH264ParserResult pres = GST_H264_PARSER_OK;
780
781   memset (&priv->current_slice, 0, sizeof (GstH264Slice));
782
783   pres = gst_h264_parser_parse_slice_hdr (priv->parser, nalu,
784       &priv->current_slice.header, TRUE, TRUE);
785
786   if (pres != GST_H264_PARSER_OK) {
787     GST_ERROR_OBJECT (self, "Failed to parse slice header, ret %d", pres);
788     memset (&priv->current_slice, 0, sizeof (GstH264Slice));
789
790     return FALSE;
791   }
792
793   priv->current_slice.nalu = *nalu;
794
795   if (!gst_h264_decoder_preprocess_slice (self, &priv->current_slice))
796     return FALSE;
797
798   priv->active_pps = priv->current_slice.header.pps;
799   priv->active_sps = priv->active_pps->sequence;
800
801   if (!priv->current_picture) {
802     GstH264DecoderClass *klass = GST_H264_DECODER_GET_CLASS (self);
803     GstH264Picture *picture;
804     gboolean ret = TRUE;
805
806     picture = gst_h264_picture_new ();
807     /* This allows accessing the frame from the picture. */
808     picture->system_frame_number = priv->current_frame->system_frame_number;
809
810     priv->current_picture = picture;
811     g_assert (priv->current_frame);
812
813     if (klass->new_picture)
814       ret = klass->new_picture (self, priv->current_frame, picture);
815
816     if (!ret) {
817       GST_ERROR_OBJECT (self, "subclass does not want accept new picture");
818       priv->current_picture = NULL;
819       gst_h264_picture_unref (picture);
820       return FALSE;
821     }
822
823     if (!gst_h264_decoder_start_current_picture (self)) {
824       GST_ERROR_OBJECT (self, "start picture failed");
825       return FALSE;
826     }
827   }
828
829   return gst_h264_decoder_decode_slice (self);
830 }
831
832 static gboolean
833 gst_h264_decoder_decode_nal (GstH264Decoder * self, GstH264NalUnit * nalu)
834 {
835   gboolean ret = TRUE;
836
837   GST_LOG_OBJECT (self, "Parsed nal type: %d, offset %d, size %d",
838       nalu->type, nalu->offset, nalu->size);
839
840   switch (nalu->type) {
841     case GST_H264_NAL_SPS:
842       ret = gst_h264_decoder_parse_sps (self, nalu);
843       break;
844     case GST_H264_NAL_PPS:
845       ret = gst_h264_decoder_parse_pps (self, nalu);
846       break;
847     case GST_H264_NAL_SLICE:
848     case GST_H264_NAL_SLICE_DPA:
849     case GST_H264_NAL_SLICE_DPB:
850     case GST_H264_NAL_SLICE_DPC:
851     case GST_H264_NAL_SLICE_IDR:
852     case GST_H264_NAL_SLICE_EXT:
853       ret = gst_h264_decoder_parse_slice (self, nalu);
854       break;
855     default:
856       break;
857   }
858
859   return ret;
860 }
861
862 static void
863 gst_h264_decoder_format_from_caps (GstH264Decoder * self, GstCaps * caps,
864     GstH264DecoderFormat * format, GstH264DecoderAlign * align)
865 {
866   if (format)
867     *format = GST_H264_DECODER_FORMAT_NONE;
868
869   if (align)
870     *align = GST_H264_DECODER_ALIGN_NONE;
871
872   if (!gst_caps_is_fixed (caps)) {
873     GST_WARNING_OBJECT (self, "Caps wasn't fixed");
874     return;
875   }
876
877   GST_DEBUG_OBJECT (self, "parsing caps: %" GST_PTR_FORMAT, caps);
878
879   if (caps && gst_caps_get_size (caps) > 0) {
880     GstStructure *s = gst_caps_get_structure (caps, 0);
881     const gchar *str = NULL;
882
883     if (format) {
884       if ((str = gst_structure_get_string (s, "stream-format"))) {
885         if (strcmp (str, "avc") == 0 || strcmp (str, "avc3") == 0)
886           *format = GST_H264_DECODER_FORMAT_AVC;
887         else if (strcmp (str, "byte-stream") == 0)
888           *format = GST_H264_DECODER_FORMAT_BYTE;
889       }
890     }
891
892     if (align) {
893       if ((str = gst_structure_get_string (s, "alignment"))) {
894         if (strcmp (str, "au") == 0)
895           *align = GST_H264_DECODER_ALIGN_AU;
896         else if (strcmp (str, "nal") == 0)
897           *align = GST_H264_DECODER_ALIGN_NAL;
898       }
899     }
900   }
901 }
902
903 static gboolean
904 gst_h264_decoder_set_format (GstVideoDecoder * decoder,
905     GstVideoCodecState * state)
906 {
907   GstH264Decoder *self = GST_H264_DECODER (decoder);
908   GstH264DecoderPrivate *priv = self->priv;
909   GstQuery *query;
910
911   GST_DEBUG_OBJECT (decoder, "Set format");
912
913   if (self->input_state)
914     gst_video_codec_state_unref (self->input_state);
915
916   self->input_state = gst_video_codec_state_ref (state);
917
918   if (state->caps) {
919     GstStructure *str;
920     const GValue *codec_data_value;
921     GstH264DecoderFormat format;
922     GstH264DecoderAlign align;
923
924     gst_h264_decoder_format_from_caps (self, state->caps, &format, &align);
925
926     str = gst_caps_get_structure (state->caps, 0);
927     codec_data_value = gst_structure_get_value (str, "codec_data");
928
929     if (GST_VALUE_HOLDS_BUFFER (codec_data_value)) {
930       gst_buffer_replace (&priv->codec_data,
931           gst_value_get_buffer (codec_data_value));
932     } else {
933       gst_buffer_replace (&priv->codec_data, NULL);
934     }
935
936     if (format == GST_H264_DECODER_FORMAT_NONE) {
937       /* codec_data implies avc */
938       if (codec_data_value != NULL) {
939         GST_WARNING_OBJECT (self,
940             "video/x-h264 caps with codec_data but no stream-format=avc");
941         format = GST_H264_DECODER_FORMAT_AVC;
942       } else {
943         /* otherwise assume bytestream input */
944         GST_WARNING_OBJECT (self,
945             "video/x-h264 caps without codec_data or stream-format");
946         format = GST_H264_DECODER_FORMAT_BYTE;
947       }
948     }
949
950     if (format == GST_H264_DECODER_FORMAT_AVC) {
951       /* AVC requires codec_data, AVC3 might have one and/or SPS/PPS inline */
952       if (codec_data_value == NULL) {
953         /* Try it with size 4 anyway */
954         priv->nal_length_size = 4;
955         GST_WARNING_OBJECT (self,
956             "avc format without codec data, assuming nal length size is 4");
957       }
958
959       /* AVC implies alignment=au */
960       if (align == GST_H264_DECODER_ALIGN_NONE)
961         align = GST_H264_DECODER_ALIGN_AU;
962     }
963
964     if (format == GST_H264_DECODER_FORMAT_BYTE) {
965       if (codec_data_value != NULL) {
966         GST_WARNING_OBJECT (self, "bytestream with codec data");
967       }
968     }
969
970     priv->in_format = format;
971     priv->align = align;
972   }
973
974   if (priv->codec_data) {
975     GstMapInfo map;
976
977     gst_buffer_map (priv->codec_data, &map, GST_MAP_READ);
978     if (!gst_h264_decoder_parse_codec_data (self, map.data, map.size)) {
979       /* keep going without error.
980        * Probably inband SPS/PPS might be valid data */
981       GST_WARNING_OBJECT (self, "Failed to handle codec data");
982     }
983     gst_buffer_unmap (priv->codec_data, &map);
984   }
985
986   /* in case live streaming, we will run on low-latency mode */
987   priv->is_live = FALSE;
988   query = gst_query_new_latency ();
989   if (gst_pad_peer_query (GST_VIDEO_DECODER_SINK_PAD (self), query))
990     gst_query_parse_latency (query, &priv->is_live, NULL, NULL);
991   gst_query_unref (query);
992
993   if (priv->is_live)
994     GST_DEBUG_OBJECT (self, "Live source, will run on low-latency mode");
995
996   return TRUE;
997 }
998
999 static gboolean
1000 gst_h264_decoder_fill_picture_from_slice (GstH264Decoder * self,
1001     const GstH264Slice * slice, GstH264Picture * picture)
1002 {
1003   const GstH264SliceHdr *slice_hdr = &slice->header;
1004   const GstH264PPS *pps;
1005   const GstH264SPS *sps;
1006
1007   pps = slice_hdr->pps;
1008   if (!pps) {
1009     GST_ERROR_OBJECT (self, "No pps in slice header");
1010     return FALSE;
1011   }
1012
1013   sps = pps->sequence;
1014   if (!sps) {
1015     GST_ERROR_OBJECT (self, "No sps in pps");
1016     return FALSE;
1017   }
1018
1019   picture->idr = slice->nalu.idr_pic_flag;
1020   picture->dec_ref_pic_marking = slice_hdr->dec_ref_pic_marking;
1021   if (picture->idr)
1022     picture->idr_pic_id = slice_hdr->idr_pic_id;
1023
1024   if (slice_hdr->field_pic_flag)
1025     picture->field =
1026         slice_hdr->bottom_field_flag ?
1027         GST_H264_PICTURE_FIELD_BOTTOM_FIELD : GST_H264_PICTURE_FIELD_TOP_FIELD;
1028   else
1029     picture->field = GST_H264_PICTURE_FIELD_FRAME;
1030
1031   if (picture->field != GST_H264_PICTURE_FIELD_FRAME) {
1032     GST_FIXME ("Interlace video not supported");
1033     return FALSE;
1034   }
1035
1036   picture->nal_ref_idc = slice->nalu.ref_idc;
1037   if (slice->nalu.ref_idc != 0)
1038     gst_h264_picture_set_reference (picture, GST_H264_PICTURE_REF_SHORT_TERM);
1039
1040   /* This assumes non-interlaced stream */
1041   picture->frame_num = picture->pic_num = slice_hdr->frame_num;
1042
1043   picture->pic_order_cnt_type = sps->pic_order_cnt_type;
1044   switch (picture->pic_order_cnt_type) {
1045     case 0:
1046       picture->pic_order_cnt_lsb = slice_hdr->pic_order_cnt_lsb;
1047       picture->delta_pic_order_cnt_bottom =
1048           slice_hdr->delta_pic_order_cnt_bottom;
1049       break;
1050     case 1:
1051       picture->delta_pic_order_cnt0 = slice_hdr->delta_pic_order_cnt[0];
1052       picture->delta_pic_order_cnt1 = slice_hdr->delta_pic_order_cnt[1];
1053       break;
1054     case 2:
1055       break;
1056     default:
1057       g_assert_not_reached ();
1058       return FALSE;
1059   }
1060
1061   return TRUE;
1062 }
1063
1064 static gboolean
1065 gst_h264_decoder_calculate_poc (GstH264Decoder * self, GstH264Picture * picture)
1066 {
1067   GstH264DecoderPrivate *priv = self->priv;
1068   const GstH264SPS *sps = priv->active_sps;
1069
1070   if (!sps) {
1071     GST_ERROR_OBJECT (self, "No active SPS");
1072     return FALSE;
1073   }
1074
1075   switch (picture->pic_order_cnt_type) {
1076     case 0:{
1077       /* See spec 8.2.1.1 */
1078       gint prev_pic_order_cnt_msb, prev_pic_order_cnt_lsb;
1079       gint max_pic_order_cnt_lsb;
1080
1081       if (picture->idr) {
1082         prev_pic_order_cnt_msb = prev_pic_order_cnt_lsb = 0;
1083       } else {
1084         if (priv->prev_ref_has_memmgmnt5) {
1085           if (priv->prev_ref_field != GST_H264_PICTURE_FIELD_BOTTOM_FIELD) {
1086             prev_pic_order_cnt_msb = 0;
1087             prev_pic_order_cnt_lsb = priv->prev_ref_top_field_order_cnt;
1088           } else {
1089             prev_pic_order_cnt_msb = 0;
1090             prev_pic_order_cnt_lsb = 0;
1091           }
1092         } else {
1093           prev_pic_order_cnt_msb = priv->prev_ref_pic_order_cnt_msb;
1094           prev_pic_order_cnt_lsb = priv->prev_ref_pic_order_cnt_lsb;
1095         }
1096       }
1097
1098       max_pic_order_cnt_lsb = 1 << (sps->log2_max_pic_order_cnt_lsb_minus4 + 4);
1099
1100       if ((picture->pic_order_cnt_lsb < prev_pic_order_cnt_lsb) &&
1101           (prev_pic_order_cnt_lsb - picture->pic_order_cnt_lsb >=
1102               max_pic_order_cnt_lsb / 2)) {
1103         picture->pic_order_cnt_msb =
1104             prev_pic_order_cnt_msb + max_pic_order_cnt_lsb;
1105       } else if ((picture->pic_order_cnt_lsb > prev_pic_order_cnt_lsb)
1106           && (picture->pic_order_cnt_lsb - prev_pic_order_cnt_lsb >
1107               max_pic_order_cnt_lsb / 2)) {
1108         picture->pic_order_cnt_msb =
1109             prev_pic_order_cnt_msb - max_pic_order_cnt_lsb;
1110       } else {
1111         picture->pic_order_cnt_msb = prev_pic_order_cnt_msb;
1112       }
1113
1114       if (picture->field != GST_H264_PICTURE_FIELD_BOTTOM_FIELD) {
1115         picture->top_field_order_cnt =
1116             picture->pic_order_cnt_msb + picture->pic_order_cnt_lsb;
1117       }
1118
1119       if (picture->field != GST_H264_PICTURE_FIELD_TOP_FIELD) {
1120         if (picture->field == GST_H264_PICTURE_FIELD_FRAME) {
1121           picture->bottom_field_order_cnt =
1122               picture->top_field_order_cnt +
1123               picture->delta_pic_order_cnt_bottom;
1124         } else {
1125           picture->bottom_field_order_cnt =
1126               picture->pic_order_cnt_msb + picture->pic_order_cnt_lsb;
1127         }
1128       }
1129       break;
1130     }
1131
1132     case 1:{
1133       gint abs_frame_num = 0;
1134       gint expected_pic_order_cnt = 0;
1135       gint i;
1136
1137       /* See spec 8.2.1.2 */
1138       if (priv->prev_has_memmgmnt5)
1139         priv->prev_frame_num_offset = 0;
1140
1141       if (picture->idr)
1142         picture->frame_num_offset = 0;
1143       else if (priv->prev_frame_num > picture->frame_num)
1144         picture->frame_num_offset =
1145             priv->prev_frame_num_offset + priv->max_frame_num;
1146       else
1147         picture->frame_num_offset = priv->prev_frame_num_offset;
1148
1149       if (sps->num_ref_frames_in_pic_order_cnt_cycle != 0)
1150         abs_frame_num = picture->frame_num_offset + picture->frame_num;
1151       else
1152         abs_frame_num = 0;
1153
1154       if (picture->nal_ref_idc == 0 && abs_frame_num > 0)
1155         --abs_frame_num;
1156
1157       if (abs_frame_num > 0) {
1158         gint pic_order_cnt_cycle_cnt, frame_num_in_pic_order_cnt_cycle;
1159         gint expected_delta_per_pic_order_cnt_cycle = 0;
1160
1161         if (sps->num_ref_frames_in_pic_order_cnt_cycle == 0) {
1162           GST_WARNING_OBJECT (self,
1163               "Invalid num_ref_frames_in_pic_order_cnt_cycle in stream");
1164           return FALSE;
1165         }
1166
1167         pic_order_cnt_cycle_cnt =
1168             (abs_frame_num - 1) / sps->num_ref_frames_in_pic_order_cnt_cycle;
1169         frame_num_in_pic_order_cnt_cycle =
1170             (abs_frame_num - 1) % sps->num_ref_frames_in_pic_order_cnt_cycle;
1171
1172         for (i = 0; i < sps->num_ref_frames_in_pic_order_cnt_cycle; i++) {
1173           expected_delta_per_pic_order_cnt_cycle +=
1174               sps->offset_for_ref_frame[i];
1175         }
1176
1177         expected_pic_order_cnt = pic_order_cnt_cycle_cnt *
1178             expected_delta_per_pic_order_cnt_cycle;
1179         /* frame_num_in_pic_order_cnt_cycle is verified < 255 in parser */
1180         for (i = 0; i <= frame_num_in_pic_order_cnt_cycle; ++i)
1181           expected_pic_order_cnt += sps->offset_for_ref_frame[i];
1182       }
1183
1184       if (!picture->nal_ref_idc)
1185         expected_pic_order_cnt += sps->offset_for_non_ref_pic;
1186
1187       if (picture->field == GST_H264_PICTURE_FIELD_FRAME) {
1188         picture->top_field_order_cnt =
1189             expected_pic_order_cnt + picture->delta_pic_order_cnt0;
1190         picture->bottom_field_order_cnt = picture->top_field_order_cnt +
1191             sps->offset_for_top_to_bottom_field + picture->delta_pic_order_cnt1;
1192       } else if (picture->field != GST_H264_PICTURE_FIELD_BOTTOM_FIELD) {
1193         picture->top_field_order_cnt =
1194             expected_pic_order_cnt + picture->delta_pic_order_cnt0;
1195       } else {
1196         picture->bottom_field_order_cnt = expected_pic_order_cnt +
1197             sps->offset_for_top_to_bottom_field + picture->delta_pic_order_cnt0;
1198       }
1199       break;
1200     }
1201
1202     case 2:{
1203       gint temp_pic_order_cnt;
1204
1205       /* See spec 8.2.1.3 */
1206       if (priv->prev_has_memmgmnt5)
1207         priv->prev_frame_num_offset = 0;
1208
1209       if (picture->idr)
1210         picture->frame_num_offset = 0;
1211       else if (priv->prev_frame_num > picture->frame_num)
1212         picture->frame_num_offset =
1213             priv->prev_frame_num_offset + priv->max_frame_num;
1214       else
1215         picture->frame_num_offset = priv->prev_frame_num_offset;
1216
1217       if (picture->idr) {
1218         temp_pic_order_cnt = 0;
1219       } else if (!picture->nal_ref_idc) {
1220         temp_pic_order_cnt =
1221             2 * (picture->frame_num_offset + picture->frame_num) - 1;
1222       } else {
1223         temp_pic_order_cnt =
1224             2 * (picture->frame_num_offset + picture->frame_num);
1225       }
1226
1227       if (picture->field == GST_H264_PICTURE_FIELD_FRAME) {
1228         picture->top_field_order_cnt = temp_pic_order_cnt;
1229         picture->bottom_field_order_cnt = temp_pic_order_cnt;
1230       } else if (picture->field == GST_H264_PICTURE_FIELD_BOTTOM_FIELD) {
1231         picture->bottom_field_order_cnt = temp_pic_order_cnt;
1232       } else {
1233         picture->top_field_order_cnt = temp_pic_order_cnt;
1234       }
1235       break;
1236     }
1237
1238     default:
1239       GST_WARNING_OBJECT (self,
1240           "Invalid pic_order_cnt_type: %d", sps->pic_order_cnt_type);
1241       return FALSE;
1242   }
1243
1244   switch (picture->field) {
1245     case GST_H264_PICTURE_FIELD_FRAME:
1246       picture->pic_order_cnt =
1247           MIN (picture->top_field_order_cnt, picture->bottom_field_order_cnt);
1248       break;
1249     case GST_H264_PICTURE_FIELD_TOP_FIELD:
1250       picture->pic_order_cnt = picture->top_field_order_cnt;
1251       break;
1252     case GST_H264_PICTURE_FIELD_BOTTOM_FIELD:
1253       picture->pic_order_cnt = picture->bottom_field_order_cnt;
1254       break;
1255     default:
1256       g_assert_not_reached ();
1257       return FALSE;
1258   }
1259
1260   return TRUE;
1261 }
1262
1263 static void
1264 gst_h264_decoder_do_output_picture (GstH264Decoder * self,
1265     GstH264Picture * picture)
1266 {
1267   GstH264DecoderPrivate *priv = self->priv;
1268   GstH264DecoderClass *klass;
1269   GstVideoCodecFrame *frame = NULL;
1270
1271   GST_LOG_OBJECT (self, "Outputting picture %p (frame_num %d, poc %d)",
1272       picture, picture->frame_num, picture->pic_order_cnt);
1273
1274   if (picture->pic_order_cnt < priv->last_output_poc) {
1275     GST_WARNING_OBJECT (self,
1276         "Outputting out of order %d -> %d, likely a broken stream",
1277         priv->last_output_poc, picture->pic_order_cnt);
1278   }
1279
1280   priv->last_output_poc = picture->pic_order_cnt;
1281
1282   frame = gst_video_decoder_get_frame (GST_VIDEO_DECODER (self),
1283       picture->system_frame_number);
1284
1285   if (!frame) {
1286     GST_ERROR_OBJECT (self,
1287         "No available codec frame with frame number %d",
1288         picture->system_frame_number);
1289     priv->last_ret = GST_FLOW_ERROR;
1290     gst_h264_picture_unref (picture);
1291
1292     return;
1293   }
1294
1295   klass = GST_H264_DECODER_GET_CLASS (self);
1296
1297   g_assert (klass->output_picture);
1298   priv->last_ret = klass->output_picture (self, frame, picture);
1299 }
1300
1301 static gboolean
1302 gst_h264_decoder_finish_current_picture (GstH264Decoder * self)
1303 {
1304   GstH264DecoderPrivate *priv = self->priv;
1305   GstH264DecoderClass *klass;
1306   gboolean ret = TRUE;
1307
1308   if (!priv->current_picture)
1309     return TRUE;
1310
1311   klass = GST_H264_DECODER_GET_CLASS (self);
1312
1313   if (klass->end_picture) {
1314     if (!klass->end_picture (self, priv->current_picture)) {
1315       GST_WARNING_OBJECT (self,
1316           "end picture failed, marking picture %p non-existing "
1317           "(frame_num %d, poc %d)", priv->current_picture,
1318           priv->current_picture->frame_num,
1319           priv->current_picture->pic_order_cnt);
1320       priv->current_picture->nonexisting = TRUE;
1321
1322       /* this fake nonexisting picture will not trigger ouput_picture() */
1323       gst_video_decoder_drop_frame (GST_VIDEO_DECODER (self),
1324           gst_video_codec_frame_ref (priv->current_frame));
1325     }
1326   }
1327
1328   /* We no longer need the per frame reference lists */
1329   gst_h264_decoder_clear_ref_pic_lists (self);
1330
1331   /* finish picture takes ownership of the picture */
1332   ret = gst_h264_decoder_finish_picture (self, priv->current_picture);
1333   priv->current_picture = NULL;
1334
1335   if (!ret) {
1336     GST_ERROR_OBJECT (self, "Failed to finish picture");
1337     return FALSE;
1338   }
1339
1340   return TRUE;
1341 }
1342
1343 static gint
1344 poc_asc_compare (const GstH264Picture ** a, const GstH264Picture ** b)
1345 {
1346   return (*a)->pic_order_cnt - (*b)->pic_order_cnt;
1347 }
1348
1349 static gint
1350 poc_desc_compare (const GstH264Picture ** a, const GstH264Picture ** b)
1351 {
1352   return (*b)->pic_order_cnt - (*a)->pic_order_cnt;
1353 }
1354
1355 static gboolean
1356 gst_h264_decoder_drain_internal (GstH264Decoder * self)
1357 {
1358   GstH264DecoderPrivate *priv = self->priv;
1359   GstH264Picture *picture;
1360
1361   while ((picture = gst_h264_dpb_bump (priv->dpb, TRUE)) != NULL) {
1362     gst_h264_decoder_do_output_picture (self, picture);
1363   }
1364
1365   gst_h264_dpb_clear (priv->dpb);
1366   priv->last_output_poc = 0;
1367
1368   return TRUE;
1369 }
1370
1371 static gboolean
1372 gst_h264_decoder_handle_memory_management_opt (GstH264Decoder * self,
1373     GstH264Picture * picture)
1374 {
1375   GstH264DecoderPrivate *priv = self->priv;
1376   gint i;
1377
1378   for (i = 0; i < G_N_ELEMENTS (picture->dec_ref_pic_marking.ref_pic_marking);
1379       i++) {
1380     GstH264RefPicMarking *ref_pic_marking =
1381         &picture->dec_ref_pic_marking.ref_pic_marking[i];
1382     guint8 type = ref_pic_marking->memory_management_control_operation;
1383
1384     GST_TRACE_OBJECT (self, "memory management operation %d, type %d", i, type);
1385
1386     /* Normal end of operations' specification */
1387     if (type == 0)
1388       return TRUE;
1389
1390     switch (type) {
1391       case 4:
1392         priv->max_long_term_frame_idx =
1393             ref_pic_marking->max_long_term_frame_idx_plus1 - 1;
1394         break;
1395       case 5:
1396         priv->max_long_term_frame_idx = -1;
1397         break;
1398       default:
1399         break;
1400     }
1401
1402     if (!gst_h264_dpb_perform_memory_management_control_operation (priv->dpb,
1403             ref_pic_marking, picture)) {
1404       GST_WARNING_OBJECT (self, "memory management operation type %d failed",
1405           type);
1406       /* Most likely our implementation fault, but let's just perform
1407        * next MMCO if any */
1408     }
1409   }
1410
1411   return TRUE;
1412 }
1413
1414 static gboolean
1415 gst_h264_decoder_sliding_window_picture_marking (GstH264Decoder * self)
1416 {
1417   GstH264DecoderPrivate *priv = self->priv;
1418   const GstH264SPS *sps = priv->active_sps;
1419   gint num_ref_pics;
1420   gint max_num_ref_frames;
1421
1422   if (!sps) {
1423     GST_ERROR_OBJECT (self, "No active sps");
1424     return FALSE;
1425   }
1426
1427   /* 8.2.5.3. Ensure the DPB doesn't overflow by discarding the oldest picture */
1428   num_ref_pics = gst_h264_dpb_num_ref_pictures (priv->dpb);
1429   max_num_ref_frames = MAX (1, sps->num_ref_frames);
1430
1431   if (num_ref_pics < max_num_ref_frames)
1432     return TRUE;
1433
1434   /* In theory, num_ref_pics shouldn't be larger than max_num_ref_frames
1435    * but it could happen if our implementation is wrong somehow or so.
1436    * Just try to remove reference pictures as many as possible in order to
1437    * avoid DPB overflow.
1438    */
1439   while (num_ref_pics >= max_num_ref_frames) {
1440     /* Max number of reference pics reached, need to remove one of the short
1441      * term ones. Find smallest frame_num_wrap short reference picture and mark
1442      * it as unused */
1443     GstH264Picture *to_unmark =
1444         gst_h264_dpb_get_lowest_frame_num_short_ref (priv->dpb);
1445
1446     if (num_ref_pics > max_num_ref_frames) {
1447       GST_WARNING_OBJECT (self,
1448           "num_ref_pics %d is larger than allowed maximum %d",
1449           num_ref_pics, max_num_ref_frames);
1450     }
1451
1452     if (!to_unmark) {
1453       GST_WARNING_OBJECT (self, "Could not find a short ref picture to unmark");
1454       return FALSE;
1455     }
1456
1457     GST_TRACE_OBJECT (self,
1458         "Unmark reference flag of picture %p (frame_num %d, poc %d)",
1459         to_unmark, to_unmark->frame_num, to_unmark->pic_order_cnt);
1460
1461     gst_h264_picture_set_reference (to_unmark, GST_H264_PICTURE_REF_NONE);
1462     gst_h264_picture_unref (to_unmark);
1463
1464     num_ref_pics--;
1465   }
1466
1467   return TRUE;
1468 }
1469
1470 /* This method ensures that DPB does not overflow, either by removing
1471  * reference pictures as specified in the stream, or using a sliding window
1472  * procedure to remove the oldest one.
1473  * It also performs marking and unmarking pictures as reference.
1474  * See spac 8.2.5.1 */
1475 static gboolean
1476 gst_h264_decoder_reference_picture_marking (GstH264Decoder * self,
1477     GstH264Picture * picture)
1478 {
1479   GstH264DecoderPrivate *priv = self->priv;
1480
1481   /* If the current picture is an IDR, all reference pictures are unmarked */
1482   if (picture->idr) {
1483     gst_h264_dpb_mark_all_non_ref (priv->dpb);
1484
1485     if (picture->dec_ref_pic_marking.long_term_reference_flag) {
1486       gst_h264_picture_set_reference (picture, GST_H264_PICTURE_REF_LONG_TERM);
1487       picture->long_term_frame_idx = 0;
1488       priv->max_long_term_frame_idx = 0;
1489     } else {
1490       gst_h264_picture_set_reference (picture, GST_H264_PICTURE_REF_SHORT_TERM);
1491       priv->max_long_term_frame_idx = -1;
1492     }
1493
1494     return TRUE;
1495   }
1496
1497   /* Not an IDR. If the stream contains instructions on how to discard pictures
1498    * from DPB and how to mark/unmark existing reference pictures, do so.
1499    * Otherwise, fall back to default sliding window process */
1500   if (picture->dec_ref_pic_marking.adaptive_ref_pic_marking_mode_flag) {
1501     if (picture->nonexisting) {
1502       GST_WARNING_OBJECT (self,
1503           "Invalid memory management operation for non-existing picture "
1504           "%p (frame_num %d, poc %d", picture, picture->frame_num,
1505           picture->pic_order_cnt);
1506     }
1507
1508     return gst_h264_decoder_handle_memory_management_opt (self, picture);
1509   }
1510
1511   return gst_h264_decoder_sliding_window_picture_marking (self);
1512 }
1513
1514 static gboolean
1515 gst_h264_decoder_finish_picture (GstH264Decoder * self,
1516     GstH264Picture * picture)
1517 {
1518   GstH264DecoderPrivate *priv = self->priv;
1519
1520   /* Finish processing the picture.
1521    * Start by storing previous picture data for later use */
1522   if (picture->ref) {
1523     gst_h264_decoder_reference_picture_marking (self, picture);
1524     priv->prev_ref_has_memmgmnt5 = picture->mem_mgmt_5;
1525     priv->prev_ref_top_field_order_cnt = picture->top_field_order_cnt;
1526     priv->prev_ref_pic_order_cnt_msb = picture->pic_order_cnt_msb;
1527     priv->prev_ref_pic_order_cnt_lsb = picture->pic_order_cnt_lsb;
1528     priv->prev_ref_field = picture->field;
1529     priv->prev_ref_frame_num = picture->frame_num;
1530   }
1531
1532   priv->prev_frame_num = picture->frame_num;
1533   priv->prev_has_memmgmnt5 = picture->mem_mgmt_5;
1534   priv->prev_frame_num_offset = picture->frame_num_offset;
1535
1536   /* Remove unused (for reference or later output) pictures from DPB, marking
1537    * them as such */
1538   gst_h264_dpb_delete_unused (priv->dpb);
1539   gst_h264_dpb_add (priv->dpb, picture);
1540
1541   GST_LOG_OBJECT (self,
1542       "Finishing picture %p (frame_num %d, poc %d), entries in DPB %d",
1543       picture, picture->frame_num, picture->pic_order_cnt,
1544       gst_h264_dpb_get_size (priv->dpb));
1545
1546   while (gst_h264_dpb_needs_bump (priv->dpb, priv->max_num_reorder_frames,
1547           priv->is_live)) {
1548     GstH264Picture *to_output;
1549
1550     to_output = gst_h264_dpb_bump (priv->dpb, FALSE);
1551
1552     if (!to_output) {
1553       GST_WARNING_OBJECT (self, "Bumping is needed but no picture to output");
1554       break;
1555     }
1556
1557     gst_h264_decoder_do_output_picture (self, to_output);
1558   }
1559
1560   return TRUE;
1561 }
1562
1563 static gboolean
1564 gst_h264_decoder_update_max_num_reorder_frames (GstH264Decoder * self,
1565     GstH264SPS * sps)
1566 {
1567   GstH264DecoderPrivate *priv = self->priv;
1568
1569   if (sps->vui_parameters_present_flag
1570       && sps->vui_parameters.bitstream_restriction_flag) {
1571     priv->max_num_reorder_frames = sps->vui_parameters.num_reorder_frames;
1572     if (priv->max_num_reorder_frames >
1573         gst_h264_dpb_get_max_num_pics (priv->dpb)) {
1574       GST_WARNING
1575           ("max_num_reorder_frames present, but larger than MaxDpbFrames (%d > %d)",
1576           (gint) priv->max_num_reorder_frames,
1577           gst_h264_dpb_get_max_num_pics (priv->dpb));
1578
1579       priv->max_num_reorder_frames = 0;
1580       return FALSE;
1581     }
1582
1583     return TRUE;
1584   }
1585
1586   /* max_num_reorder_frames not present, infer from profile/constraints
1587    * (see VUI semantics in spec) */
1588   if (sps->constraint_set3_flag) {
1589     switch (sps->profile_idc) {
1590       case 44:
1591       case 86:
1592       case 100:
1593       case 110:
1594       case 122:
1595       case 244:
1596         priv->max_num_reorder_frames = 0;
1597         break;
1598       default:
1599         priv->max_num_reorder_frames =
1600             gst_h264_dpb_get_max_num_pics (priv->dpb);
1601         break;
1602     }
1603   } else {
1604     priv->max_num_reorder_frames = gst_h264_dpb_get_max_num_pics (priv->dpb);
1605   }
1606
1607   return TRUE;
1608 }
1609
1610 typedef enum
1611 {
1612   GST_H264_LEVEL_L1 = 10,
1613   GST_H264_LEVEL_L1B = 9,
1614   GST_H264_LEVEL_L1_1 = 11,
1615   GST_H264_LEVEL_L1_2 = 12,
1616   GST_H264_LEVEL_L1_3 = 13,
1617   GST_H264_LEVEL_L2_0 = 20,
1618   GST_H264_LEVEL_L2_1 = 21,
1619   GST_H264_LEVEL_L2_2 = 22,
1620   GST_H264_LEVEL_L3 = 30,
1621   GST_H264_LEVEL_L3_1 = 31,
1622   GST_H264_LEVEL_L3_2 = 32,
1623   GST_H264_LEVEL_L4 = 40,
1624   GST_H264_LEVEL_L4_1 = 41,
1625   GST_H264_LEVEL_L4_2 = 42,
1626   GST_H264_LEVEL_L5 = 50,
1627   GST_H264_LEVEL_L5_1 = 51,
1628   GST_H264_LEVEL_L5_2 = 52,
1629   GST_H264_LEVEL_L6 = 60,
1630   GST_H264_LEVEL_L6_1 = 61,
1631   GST_H264_LEVEL_L6_2 = 62,
1632 } GstH264DecoderLevel;
1633
1634 typedef struct
1635 {
1636   GstH264DecoderLevel level;
1637
1638   guint32 max_mbps;
1639   guint32 max_fs;
1640   guint32 max_dpb_mbs;
1641   guint32 max_main_br;
1642 } LevelLimits;
1643
1644 static const LevelLimits level_limits_map[] = {
1645   {GST_H264_LEVEL_L1, 1485, 99, 396, 64},
1646   {GST_H264_LEVEL_L1B, 1485, 99, 396, 128},
1647   {GST_H264_LEVEL_L1_1, 3000, 396, 900, 192},
1648   {GST_H264_LEVEL_L1_2, 6000, 396, 2376, 384},
1649   {GST_H264_LEVEL_L1_3, 11800, 396, 2376, 768},
1650   {GST_H264_LEVEL_L2_0, 11880, 396, 2376, 2000},
1651   {GST_H264_LEVEL_L2_1, 19800, 792, 4752, 4000},
1652   {GST_H264_LEVEL_L2_2, 20250, 1620, 8100, 4000},
1653   {GST_H264_LEVEL_L3, 40500, 1620, 8100, 10000},
1654   {GST_H264_LEVEL_L3_1, 108000, 3600, 18000, 14000},
1655   {GST_H264_LEVEL_L3_2, 216000, 5120, 20480, 20000},
1656   {GST_H264_LEVEL_L4, 245760, 8192, 32768, 20000},
1657   {GST_H264_LEVEL_L4_1, 245760, 8192, 32768, 50000},
1658   {GST_H264_LEVEL_L4_2, 522240, 8704, 34816, 50000},
1659   {GST_H264_LEVEL_L5, 589824, 22080, 110400, 135000},
1660   {GST_H264_LEVEL_L5_1, 983040, 36864, 184320, 240000},
1661   {GST_H264_LEVEL_L5_2, 2073600, 36864, 184320, 240000},
1662   {GST_H264_LEVEL_L6, 4177920, 139264, 696320, 240000},
1663   {GST_H264_LEVEL_L6_1, 8355840, 139264, 696320, 480000},
1664   {GST_H264_LEVEL_L6_2, 16711680, 139264, 696320, 800000}
1665 };
1666
1667 static gint
1668 h264_level_to_max_dpb_mbs (GstH264DecoderLevel level)
1669 {
1670   gint i;
1671   for (i = 0; i < G_N_ELEMENTS (level_limits_map); i++) {
1672     if (level == level_limits_map[i].level)
1673       return level_limits_map[i].max_dpb_mbs;
1674   }
1675
1676   return 0;
1677 }
1678
1679 static void
1680 gst_h264_decoder_set_latency (GstH264Decoder * self, const GstH264SPS * sps,
1681     gint max_dpb_size)
1682 {
1683   GstH264DecoderPrivate *priv = self->priv;
1684   GstCaps *caps;
1685   GstClockTime min, max;
1686   GstStructure *structure;
1687   gint fps_d = 1, fps_n = 0;
1688   guint32 num_reorder_frames;
1689
1690   caps = gst_pad_get_current_caps (GST_VIDEO_DECODER_SRC_PAD (self));
1691   if (!caps)
1692     return;
1693
1694   structure = gst_caps_get_structure (caps, 0);
1695   if (gst_structure_get_fraction (structure, "framerate", &fps_n, &fps_d)) {
1696     if (fps_n == 0) {
1697       /* variable framerate: see if we have a max-framerate */
1698       gst_structure_get_fraction (structure, "max-framerate", &fps_n, &fps_d);
1699     }
1700   }
1701   gst_caps_unref (caps);
1702
1703   /* if no fps or variable, then 25/1 */
1704   if (fps_n == 0) {
1705     fps_n = 25;
1706     fps_d = 1;
1707   }
1708
1709   num_reorder_frames = priv->is_live ? 0 : 1;
1710   if (sps->vui_parameters_present_flag
1711       && sps->vui_parameters.bitstream_restriction_flag)
1712     num_reorder_frames = sps->vui_parameters.num_reorder_frames;
1713   if (num_reorder_frames > max_dpb_size)
1714     num_reorder_frames = priv->is_live ? 0 : 1;
1715
1716   min = gst_util_uint64_scale_int (num_reorder_frames * GST_SECOND, fps_d,
1717       fps_n);
1718   max = gst_util_uint64_scale_int (max_dpb_size * GST_SECOND, fps_d, fps_n);
1719
1720   GST_LOG_OBJECT (self,
1721       "latency min %" G_GUINT64_FORMAT " max %" G_GUINT64_FORMAT, min, max);
1722
1723   gst_video_decoder_set_latency (GST_VIDEO_DECODER (self), min, max);
1724 }
1725
1726 static gboolean
1727 gst_h264_decoder_process_sps (GstH264Decoder * self, GstH264SPS * sps)
1728 {
1729   GstH264DecoderPrivate *priv = self->priv;
1730   guint8 level;
1731   gint max_dpb_mbs;
1732   gint width_mb, height_mb;
1733   gint max_dpb_frames;
1734   gint max_dpb_size;
1735   gint prev_max_dpb_size;
1736
1737   if (sps->frame_mbs_only_flag == 0) {
1738     GST_FIXME_OBJECT (self, "frame_mbs_only_flag != 1 not supported");
1739     return FALSE;
1740   }
1741
1742   /* Spec A.3.1 and A.3.2
1743    * For Baseline, Constrained Baseline and Main profile, the indicated level is
1744    * Level 1b if level_idc is equal to 11 and constraint_set3_flag is equal to 1
1745    */
1746   level = sps->level_idc;
1747   if (level == 11 && (sps->profile_idc == 66 || sps->profile_idc == 77) &&
1748       sps->constraint_set3_flag) {
1749     /* Level 1b */
1750     level = 9;
1751   }
1752
1753   max_dpb_mbs = h264_level_to_max_dpb_mbs ((GstH264DecoderLevel) level);
1754   if (!max_dpb_mbs)
1755     return FALSE;
1756
1757   width_mb = sps->width / 16;
1758   height_mb = sps->height / 16;
1759
1760   max_dpb_frames = MIN (max_dpb_mbs / (width_mb * height_mb),
1761       GST_H264_DPB_MAX_SIZE);
1762
1763   if (sps->vui_parameters_present_flag
1764       && sps->vui_parameters.bitstream_restriction_flag)
1765     max_dpb_frames = MAX (1, sps->vui_parameters.max_dec_frame_buffering);
1766
1767   /* Case 1) There might be some non-conforming streams that require more DPB
1768    * size than that of specified one by SPS
1769    * Case 2) If bitstream_restriction_flag is not present,
1770    * max_dec_frame_buffering should be inferred
1771    * to be equal to MaxDpbFrames, then MaxDpbFrames can exceed num_ref_frames
1772    * See https://chromium-review.googlesource.com/c/chromium/src/+/760276/
1773    */
1774   max_dpb_size = MAX (max_dpb_frames, sps->num_ref_frames);
1775   if (max_dpb_size > GST_H264_DPB_MAX_SIZE) {
1776     GST_WARNING_OBJECT (self, "Too large calculated DPB size %d", max_dpb_size);
1777     max_dpb_size = GST_H264_DPB_MAX_SIZE;
1778   }
1779
1780   /* Safety, so that subclass don't need bound checking */
1781   g_return_val_if_fail (max_dpb_size <= GST_H264_DPB_MAX_SIZE, FALSE);
1782
1783   prev_max_dpb_size = gst_h264_dpb_get_max_num_pics (priv->dpb);
1784   if (priv->width != sps->width || priv->height != sps->height ||
1785       prev_max_dpb_size != max_dpb_size) {
1786     GstH264DecoderClass *klass = GST_H264_DECODER_GET_CLASS (self);
1787
1788     GST_DEBUG_OBJECT (self,
1789         "SPS updated, resolution: %dx%d -> %dx%d, dpb size: %d -> %d",
1790         priv->width, priv->height, sps->width, sps->height,
1791         prev_max_dpb_size, max_dpb_size);
1792
1793     if (gst_h264_decoder_drain (GST_VIDEO_DECODER (self)) != GST_FLOW_OK)
1794       return FALSE;
1795
1796     g_assert (klass->new_sequence);
1797
1798     if (!klass->new_sequence (self, sps, max_dpb_size)) {
1799       GST_ERROR_OBJECT (self, "subclass does not want accept new sequence");
1800       return FALSE;
1801     }
1802
1803     priv->width = sps->width;
1804     priv->height = sps->height;
1805
1806     gst_h264_decoder_set_latency (self, sps, max_dpb_size);
1807     gst_h264_dpb_set_max_num_pics (priv->dpb, max_dpb_size);
1808   }
1809
1810   return gst_h264_decoder_update_max_num_reorder_frames (self, sps);
1811 }
1812
1813 static gboolean
1814 gst_h264_decoder_init_gap_picture (GstH264Decoder * self,
1815     GstH264Picture * picture, gint frame_num)
1816 {
1817   picture->nonexisting = TRUE;
1818   picture->nal_ref_idc = 1;
1819   picture->frame_num = picture->pic_num = frame_num;
1820   picture->dec_ref_pic_marking.adaptive_ref_pic_marking_mode_flag = FALSE;
1821   picture->ref = GST_H264_PICTURE_REF_SHORT_TERM;
1822   picture->dec_ref_pic_marking.long_term_reference_flag = FALSE;
1823   picture->field = GST_H264_PICTURE_FIELD_FRAME;
1824
1825   return gst_h264_decoder_calculate_poc (self, picture);
1826 }
1827
1828 static gboolean
1829 gst_h264_decoder_decode_slice (GstH264Decoder * self)
1830 {
1831   GstH264DecoderClass *klass = GST_H264_DECODER_GET_CLASS (self);
1832   GstH264DecoderPrivate *priv = self->priv;
1833   GstH264Slice *slice = &priv->current_slice;
1834   GstH264Picture *picture = priv->current_picture;
1835   GArray *ref_pic_list0 = NULL;
1836   GArray *ref_pic_list1 = NULL;
1837   gboolean ret = FALSE;
1838
1839   if (!picture) {
1840     GST_ERROR_OBJECT (self, "No current picture");
1841     return FALSE;
1842   }
1843
1844   GST_LOG_OBJECT (self, "Decode picture %p (frame_num %d, poc %d)",
1845       picture, picture->frame_num, picture->pic_order_cnt);
1846
1847   priv->max_pic_num = slice->header.max_pic_num;
1848
1849   if (priv->process_ref_pic_lists) {
1850     if (!gst_h264_decoder_modify_ref_pic_lists (self))
1851       goto beach;
1852
1853     ref_pic_list0 = priv->ref_pic_list0;
1854     ref_pic_list1 = priv->ref_pic_list1;
1855   }
1856
1857   g_assert (klass->decode_slice);
1858
1859   ret = klass->decode_slice (self, picture, slice, ref_pic_list0,
1860       ref_pic_list1);
1861   if (!ret) {
1862     GST_WARNING_OBJECT (self,
1863         "Subclass didn't want to decode picture %p (frame_num %d, poc %d)",
1864         picture, picture->frame_num, picture->pic_order_cnt);
1865   }
1866
1867 beach:
1868   g_array_set_size (priv->ref_pic_list0, 0);
1869   g_array_set_size (priv->ref_pic_list1, 0);
1870
1871   return ret;
1872 }
1873
1874 static gint
1875 pic_num_desc_compare (const GstH264Picture ** a, const GstH264Picture ** b)
1876 {
1877   return (*b)->pic_num - (*a)->pic_num;
1878 }
1879
1880 static gint
1881 long_term_pic_num_asc_compare (const GstH264Picture ** a,
1882     const GstH264Picture ** b)
1883 {
1884   return (*a)->long_term_pic_num - (*b)->long_term_pic_num;
1885 }
1886
1887 static void
1888 construct_ref_pic_lists_p (GstH264Decoder * self)
1889 {
1890   GstH264DecoderPrivate *priv = self->priv;
1891   gint pos;
1892
1893   /* RefPicList0 (8.2.4.2.1) [[1] [2]], where:
1894    * [1] shortterm ref pics sorted by descending pic_num,
1895    * [2] longterm ref pics by ascending long_term_pic_num.
1896    */
1897   g_array_set_size (priv->ref_pic_list_p0, 0);
1898
1899   gst_h264_dpb_get_pictures_short_term_ref (priv->dpb, priv->ref_pic_list_p0);
1900   g_array_sort (priv->ref_pic_list_p0, (GCompareFunc) pic_num_desc_compare);
1901
1902   pos = priv->ref_pic_list_p0->len;
1903   gst_h264_dpb_get_pictures_long_term_ref (priv->dpb, priv->ref_pic_list_p0);
1904   g_qsort_with_data (&g_array_index (priv->ref_pic_list_p0, gpointer, pos),
1905       priv->ref_pic_list_p0->len - pos, sizeof (gpointer),
1906       (GCompareDataFunc) long_term_pic_num_asc_compare, NULL);
1907
1908 #ifndef GST_DISABLE_GST_DEBUG
1909   if (gst_debug_category_get_threshold (GST_CAT_DEFAULT) >= GST_LEVEL_DEBUG) {
1910     GString *str = g_string_new (NULL);
1911     for (pos = 0; pos < priv->ref_pic_list_p0->len; pos++) {
1912       GstH264Picture *ref =
1913           g_array_index (priv->ref_pic_list_p0, GstH264Picture *, pos);
1914       if (!GST_H264_PICTURE_IS_LONG_TERM_REF (ref))
1915         g_string_append_printf (str, "|%i", ref->pic_num);
1916       else
1917         g_string_append_printf (str, "|%is", ref->pic_num);
1918     }
1919     GST_DEBUG_OBJECT (self, "ref_pic_list_p0: %s|", str->str);
1920     g_string_free (str, TRUE);
1921   }
1922 #endif
1923 }
1924
1925 static gboolean
1926 lists_are_equal (GArray * l1, GArray * l2)
1927 {
1928   gint i;
1929
1930   if (l1->len != l2->len)
1931     return FALSE;
1932
1933   for (i = 0; i < l1->len; i++)
1934     if (g_array_index (l1, gpointer, i) != g_array_index (l2, gpointer, i))
1935       return FALSE;
1936
1937   return TRUE;
1938 }
1939
1940 static gint
1941 split_ref_pic_list_b (GstH264Decoder * self, GArray * ref_pic_list_b,
1942     GCompareFunc compare_func)
1943 {
1944   gint pos;
1945
1946   for (pos = 0; pos < ref_pic_list_b->len; pos++) {
1947     GstH264Picture *pic = g_array_index (ref_pic_list_b, GstH264Picture *, pos);
1948     if (compare_func (&pic, &self->priv->current_picture) > 0)
1949       break;
1950   }
1951
1952   return pos;
1953 }
1954
1955 static void
1956 print_ref_pic_list_b (GstH264Decoder * self, GArray * ref_list_b, gint index)
1957 {
1958 #ifndef GST_DISABLE_GST_DEBUG
1959   GString *str;
1960   gint i;
1961
1962   if (gst_debug_category_get_threshold (GST_CAT_DEFAULT) < GST_LEVEL_DEBUG)
1963     return;
1964
1965   str = g_string_new (NULL);
1966
1967   for (i = 0; i < ref_list_b->len; i++) {
1968     GstH264Picture *ref = g_array_index (ref_list_b, GstH264Picture *, i);
1969
1970     if (!GST_H264_PICTURE_IS_LONG_TERM_REF (ref))
1971       g_string_append_printf (str, "|%i", ref->pic_order_cnt);
1972     else
1973       g_string_append_printf (str, "|%il", ref->long_term_pic_num);
1974   }
1975
1976   GST_DEBUG_OBJECT (self, "ref_pic_list_b%i: %s| curr %i", index, str->str,
1977       self->priv->current_picture->pic_order_cnt);
1978   g_string_free (str, TRUE);
1979 #endif
1980 }
1981
1982 static void
1983 construct_ref_pic_lists_b (GstH264Decoder * self)
1984 {
1985   GstH264DecoderPrivate *priv = self->priv;
1986   gint pos;
1987
1988   /* RefPicList0 (8.2.4.2.3) [[1] [2] [3]], where:
1989    * [1] shortterm ref pics with POC < current_picture's POC sorted by descending POC,
1990    * [2] shortterm ref pics with POC > current_picture's POC by ascending POC,
1991    * [3] longterm ref pics by ascending long_term_pic_num.
1992    */
1993   g_array_set_size (priv->ref_pic_list_b0, 0);
1994   g_array_set_size (priv->ref_pic_list_b1, 0);
1995   gst_h264_dpb_get_pictures_short_term_ref (priv->dpb, priv->ref_pic_list_b0);
1996
1997   /* First sort ascending, this will put [1] in right place and finish
1998    * [2]. */
1999   print_ref_pic_list_b (self, priv->ref_pic_list_b0, 0);
2000   g_array_sort (priv->ref_pic_list_b0, (GCompareFunc) poc_asc_compare);
2001   print_ref_pic_list_b (self, priv->ref_pic_list_b0, 0);
2002
2003   /* Find first with POC > current_picture's POC to get first element
2004    * in [2]... */
2005   pos = split_ref_pic_list_b (self, priv->ref_pic_list_b0,
2006       (GCompareFunc) poc_asc_compare);
2007
2008   GST_DEBUG_OBJECT (self, "split point %i", pos);
2009
2010   /* and sort [1] descending, thus finishing sequence [1] [2]. */
2011   g_qsort_with_data (priv->ref_pic_list_b0->data, pos, sizeof (gpointer),
2012       (GCompareDataFunc) poc_desc_compare, NULL);
2013
2014   /* Now add [3] and sort by ascending long_term_pic_num. */
2015   pos = priv->ref_pic_list_b0->len;
2016   gst_h264_dpb_get_pictures_long_term_ref (priv->dpb, priv->ref_pic_list_b0);
2017   g_qsort_with_data (&g_array_index (priv->ref_pic_list_b0, gpointer, pos),
2018       priv->ref_pic_list_b0->len - pos, sizeof (gpointer),
2019       (GCompareDataFunc) long_term_pic_num_asc_compare, NULL);
2020
2021   /* RefPicList1 (8.2.4.2.4) [[1] [2] [3]], where:
2022    * [1] shortterm ref pics with POC > curr_pic's POC sorted by ascending POC,
2023    * [2] shortterm ref pics with POC < curr_pic's POC by descending POC,
2024    * [3] longterm ref pics by ascending long_term_pic_num.
2025    */
2026   gst_h264_dpb_get_pictures_short_term_ref (priv->dpb, priv->ref_pic_list_b1);
2027
2028   /* First sort by descending POC. */
2029   g_array_sort (priv->ref_pic_list_b1, (GCompareFunc) poc_desc_compare);
2030
2031   /* Split at first with POC < current_picture's POC to get first element
2032    * in [2]... */
2033   pos = split_ref_pic_list_b (self, priv->ref_pic_list_b1,
2034       (GCompareFunc) poc_desc_compare);
2035
2036   /* and sort [1] ascending. */
2037   g_qsort_with_data (priv->ref_pic_list_b1->data, pos, sizeof (gpointer),
2038       (GCompareDataFunc) poc_asc_compare, NULL);
2039
2040   /* Now add [3] and sort by ascending long_term_pic_num */
2041   pos = priv->ref_pic_list_b1->len;
2042   gst_h264_dpb_get_pictures_long_term_ref (priv->dpb, priv->ref_pic_list_b1);
2043   g_qsort_with_data (&g_array_index (priv->ref_pic_list_b1, gpointer, pos),
2044       priv->ref_pic_list_b1->len - pos, sizeof (gpointer),
2045       (GCompareDataFunc) long_term_pic_num_asc_compare, NULL);
2046
2047   /* If lists identical, swap first two entries in RefPicList1 (spec
2048    * 8.2.4.2.3) */
2049   if (priv->ref_pic_list_b1->len > 1
2050       && lists_are_equal (priv->ref_pic_list_b0, priv->ref_pic_list_b1)) {
2051     /* swap */
2052     GstH264Picture **list = (GstH264Picture **) priv->ref_pic_list_b1->data;
2053     GstH264Picture *pic = list[0];
2054     list[0] = list[1];
2055     list[1] = pic;
2056   }
2057
2058   print_ref_pic_list_b (self, priv->ref_pic_list_b0, 0);
2059   print_ref_pic_list_b (self, priv->ref_pic_list_b1, 1);
2060 }
2061
2062 static void
2063 gst_h264_decoder_prepare_ref_pic_lists (GstH264Decoder * self)
2064 {
2065   construct_ref_pic_lists_p (self);
2066   construct_ref_pic_lists_b (self);
2067 }
2068
2069 static void
2070 gst_h264_decoder_clear_ref_pic_lists (GstH264Decoder * self)
2071 {
2072   GstH264DecoderPrivate *priv = self->priv;
2073
2074   g_array_set_size (priv->ref_pic_list_p0, 0);
2075   g_array_set_size (priv->ref_pic_list_b0, 0);
2076   g_array_set_size (priv->ref_pic_list_b1, 0);
2077 }
2078
2079 static gint
2080 long_term_pic_num_f (GstH264Decoder * self, const GstH264Picture * picture)
2081 {
2082   if (GST_H264_PICTURE_IS_LONG_TERM_REF (picture))
2083     return picture->long_term_pic_num;
2084   return 2 * (self->priv->max_long_term_frame_idx + 1);
2085 }
2086
2087 static gint
2088 pic_num_f (GstH264Decoder * self, const GstH264Picture * picture)
2089 {
2090   if (!GST_H264_PICTURE_IS_LONG_TERM_REF (picture))
2091     return picture->pic_num;
2092   return self->priv->max_pic_num;
2093 }
2094
2095 /* shift elements on the |array| starting from |from| to |to|,
2096  * inclusive, one position to the right and insert pic at |from| */
2097 static void
2098 shift_right_and_insert (GArray * array, gint from, gint to,
2099     GstH264Picture * picture)
2100 {
2101   g_return_if_fail (from <= to);
2102   g_return_if_fail (array && picture);
2103
2104   g_array_set_size (array, to + 2);
2105   g_array_insert_val (array, from, picture);
2106 }
2107
2108 /* This can process either ref_pic_list0 or ref_pic_list1, depending
2109  * on the list argument. Set up pointers to proper list to be
2110  * processed here. */
2111 static gboolean
2112 modify_ref_pic_list (GstH264Decoder * self, int list)
2113 {
2114   GstH264DecoderPrivate *priv = self->priv;
2115   GstH264Picture *picture = priv->current_picture;
2116   GArray *ref_pic_listx;
2117   const GstH264SliceHdr *slice_hdr = &priv->current_slice.header;
2118   const GstH264RefPicListModification *list_mod;
2119   gboolean ref_pic_list_modification_flag_lX;
2120   gint num_ref_idx_lX_active_minus1;
2121   guint num_ref_pic_list_modifications;
2122   gint i;
2123   gint pic_num_lx_pred = picture->pic_num;
2124   gint ref_idx_lx = 0, src, dst;
2125   gint pic_num_lx_no_wrap;
2126   gint pic_num_lx;
2127   gboolean done = FALSE;
2128   GstH264Picture *pic;
2129
2130   if (list == 0) {
2131     ref_pic_listx = priv->ref_pic_list0;
2132     ref_pic_list_modification_flag_lX =
2133         slice_hdr->ref_pic_list_modification_flag_l0;
2134     num_ref_pic_list_modifications = slice_hdr->n_ref_pic_list_modification_l0;
2135     num_ref_idx_lX_active_minus1 = slice_hdr->num_ref_idx_l0_active_minus1;
2136     list_mod = slice_hdr->ref_pic_list_modification_l0;
2137   } else {
2138     ref_pic_listx = priv->ref_pic_list1;
2139     ref_pic_list_modification_flag_lX =
2140         slice_hdr->ref_pic_list_modification_flag_l1;
2141     num_ref_pic_list_modifications = slice_hdr->n_ref_pic_list_modification_l1;
2142     num_ref_idx_lX_active_minus1 = slice_hdr->num_ref_idx_l1_active_minus1;
2143     list_mod = slice_hdr->ref_pic_list_modification_l1;
2144   }
2145
2146   /* Resize the list to the size requested in the slice header.
2147    *
2148    * Note that per 8.2.4.2 it's possible for
2149    * num_ref_idx_lX_active_minus1 to indicate there should be more ref
2150    * pics on list than we constructed.  Those superfluous ones should
2151    * be treated as non-reference and will be initialized to null,
2152    * which must be handled by clients */
2153   g_assert (num_ref_idx_lX_active_minus1 >= 0);
2154   if (ref_pic_listx->len > num_ref_idx_lX_active_minus1 + 1)
2155     g_array_set_size (ref_pic_listx, num_ref_idx_lX_active_minus1 + 1);
2156
2157   if (!ref_pic_list_modification_flag_lX)
2158     return TRUE;
2159
2160   /* Spec 8.2.4.3:
2161    * Reorder pictures on the list in a way specified in the stream. */
2162   for (i = 0; i < num_ref_pic_list_modifications && !done; i++) {
2163     switch (list_mod->modification_of_pic_nums_idc) {
2164         /* 8.2.4.3.1 - Modify short reference picture position. */
2165       case 0:
2166       case 1:
2167         /* 8-34 */
2168         if (list_mod->modification_of_pic_nums_idc == 0) {
2169           /* Substract given value from predicted PicNum. */
2170           pic_num_lx_no_wrap = pic_num_lx_pred -
2171               (list_mod->value.abs_diff_pic_num_minus1 + 1);
2172           /* Wrap around max_pic_num if it becomes < 0 as result of
2173            * subtraction */
2174           if (pic_num_lx_no_wrap < 0)
2175             pic_num_lx_no_wrap += priv->max_pic_num;
2176         } else {                /* 8-35 */
2177           /* Add given value to predicted PicNum. */
2178           pic_num_lx_no_wrap = pic_num_lx_pred +
2179               (list_mod->value.abs_diff_pic_num_minus1 + 1);
2180           /* Wrap around max_pic_num if it becomes >= max_pic_num as
2181            * result of the addition */
2182           if (pic_num_lx_no_wrap >= priv->max_pic_num)
2183             pic_num_lx_no_wrap -= priv->max_pic_num;
2184         }
2185
2186         /* For use in next iteration */
2187         pic_num_lx_pred = pic_num_lx_no_wrap;
2188
2189         /* 8-36 */
2190         if (pic_num_lx_no_wrap > picture->pic_num)
2191           pic_num_lx = pic_num_lx_no_wrap - priv->max_pic_num;
2192         else
2193           pic_num_lx = pic_num_lx_no_wrap;
2194
2195         /* 8-37 */
2196         g_assert (num_ref_idx_lX_active_minus1 + 1 < 32);
2197         pic = gst_h264_dpb_get_short_ref_by_pic_num (priv->dpb, pic_num_lx);
2198         if (!pic) {
2199           GST_WARNING_OBJECT (self, "Malformed stream, no pic num %d",
2200               pic_num_lx);
2201           return FALSE;
2202         }
2203         shift_right_and_insert (ref_pic_listx, ref_idx_lx,
2204             num_ref_idx_lX_active_minus1, pic);
2205         ref_idx_lx++;
2206
2207         for (src = ref_idx_lx, dst = ref_idx_lx;
2208             src <= num_ref_idx_lX_active_minus1 + 1; src++) {
2209           GstH264Picture *src_pic =
2210               g_array_index (ref_pic_listx, GstH264Picture *, src);
2211           gint src_pic_num_lx = src_pic ? pic_num_f (self, src_pic) : -1;
2212           if (src_pic_num_lx != pic_num_lx)
2213             g_array_index (ref_pic_listx, GstH264Picture *, dst++) = src_pic;
2214         }
2215
2216         break;
2217
2218         /* 8.2.4.3.2 - Long-term reference pictures */
2219       case 2:
2220         /* (8-28) */
2221         g_assert (num_ref_idx_lX_active_minus1 + 1 < 32);
2222         pic = gst_h264_dpb_get_long_ref_by_long_term_pic_num (priv->dpb,
2223             list_mod->value.long_term_pic_num);
2224         if (!pic) {
2225           GST_WARNING_OBJECT (self, "Malformed stream, no pic num %d",
2226               list_mod->value.long_term_pic_num);
2227           return FALSE;
2228         }
2229         shift_right_and_insert (ref_pic_listx, ref_idx_lx,
2230             num_ref_idx_lX_active_minus1, pic);
2231         ref_idx_lx++;
2232
2233         for (src = ref_idx_lx, dst = ref_idx_lx;
2234             src <= num_ref_idx_lX_active_minus1 + 1; src++) {
2235           GstH264Picture *src_pic =
2236               g_array_index (ref_pic_listx, GstH264Picture *, src);
2237           if (long_term_pic_num_f (self, src_pic) !=
2238               list_mod->value.long_term_pic_num)
2239             g_array_index (ref_pic_listx, GstH264Picture *, dst++) = src_pic;
2240         }
2241
2242         break;
2243
2244         /* End of modification list */
2245       case 3:
2246         done = TRUE;
2247         break;
2248
2249       default:
2250         /* may be recoverable */
2251         GST_WARNING ("Invalid modification_of_pic_nums_idc = %d",
2252             list_mod->modification_of_pic_nums_idc);
2253         break;
2254     }
2255
2256     list_mod++;
2257   }
2258
2259   /* Per NOTE 2 in 8.2.4.3.2, the ref_pic_listx in the above loop is
2260    * temporarily made one element longer than the required final list.
2261    * Resize the list back to its required size. */
2262   if (ref_pic_listx->len > num_ref_idx_lX_active_minus1 + 1)
2263     g_array_set_size (ref_pic_listx, num_ref_idx_lX_active_minus1 + 1);
2264
2265   return TRUE;
2266 }
2267
2268 static void
2269 copy_pic_list_into (GArray * dest, GArray * src)
2270 {
2271   gint i;
2272   g_array_set_size (dest, 0);
2273
2274   for (i = 0; i < src->len; i++)
2275     g_array_append_val (dest, g_array_index (src, gpointer, i));
2276 }
2277
2278 static gboolean
2279 gst_h264_decoder_modify_ref_pic_lists (GstH264Decoder * self)
2280 {
2281   GstH264DecoderPrivate *priv = self->priv;
2282   GstH264SliceHdr *slice_hdr = &priv->current_slice.header;
2283
2284   /* fill reference picture lists for B and S/SP slices */
2285   if (GST_H264_IS_P_SLICE (slice_hdr) || GST_H264_IS_SP_SLICE (slice_hdr)) {
2286     copy_pic_list_into (priv->ref_pic_list0, priv->ref_pic_list_p0);
2287     return modify_ref_pic_list (self, 0);
2288   } else {
2289     copy_pic_list_into (priv->ref_pic_list0, priv->ref_pic_list_b0);
2290     copy_pic_list_into (priv->ref_pic_list1, priv->ref_pic_list_b1);
2291     return modify_ref_pic_list (self, 0)
2292         && modify_ref_pic_list (self, 1);
2293   }
2294
2295   return TRUE;
2296 }
2297
2298 /**
2299  * gst_h264_decoder_set_process_ref_pic_lists:
2300  * @decoder: a #GstH264Decoder
2301  * @process: whether subclass is requiring reference picture modification process
2302  *
2303  * Called to en/disable reference picture modification process.
2304  *
2305  * Since: 1.18
2306  */
2307 void
2308 gst_h264_decoder_set_process_ref_pic_lists (GstH264Decoder * decoder,
2309     gboolean process)
2310 {
2311   decoder->priv->process_ref_pic_lists = process;
2312 }
2313
2314 /**
2315  * gst_h264_decoder_get_picture:
2316  * @decoder: a #GstH264Decoder
2317  * @system_frame_number: a target system frame number of #GstH264Picture
2318  *
2319  * Retrive DPB and return a #GstH264Picture corresponding to
2320  * the @system_frame_number
2321  *
2322  * Returns: (transfer full): a #GstH264Picture if successful, or %NULL otherwise
2323  *
2324  * Since: 1.18
2325  */
2326 GstH264Picture *
2327 gst_h264_decoder_get_picture (GstH264Decoder * decoder,
2328     guint32 system_frame_number)
2329 {
2330   return gst_h264_dpb_get_picture (decoder->priv->dpb, system_frame_number);
2331 }