]> git.sesse.net Git - ffmpeg/blob - libavcodec/h264_refs.c
avcodec: Remove some commented-out debug cruft
[ffmpeg] / libavcodec / h264_refs.c
1 /*
2  * H.26L/H.264/AVC/JVT/14496-10/... reference picture handling
3  * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
4  *
5  * This file is part of Libav.
6  *
7  * Libav is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * Libav is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * H.264 / AVC / MPEG4 part10  reference picture handling.
25  * @author Michael Niedermayer <michaelni@gmx.at>
26  */
27
28 #include "internal.h"
29 #include "avcodec.h"
30 #include "h264.h"
31 #include "golomb.h"
32
33 #include <assert.h>
34
35 #define COPY_PICTURE(dst, src) \
36 do {\
37     *(dst) = *(src);\
38     (dst)->f.extended_data = (dst)->f.data;\
39     (dst)->tf.f = &(dst)->f;\
40 } while (0)
41
42
43 static void pic_as_field(Picture *pic, const int parity){
44     int i;
45     for (i = 0; i < 4; ++i) {
46         if (parity == PICT_BOTTOM_FIELD)
47             pic->f.data[i] += pic->f.linesize[i];
48         pic->reference      = parity;
49         pic->f.linesize[i] *= 2;
50     }
51     pic->poc= pic->field_poc[parity == PICT_BOTTOM_FIELD];
52 }
53
54 static int split_field_copy(Picture *dest, Picture *src, int parity, int id_add)
55 {
56     int match = !!(src->reference & parity);
57
58     if (match) {
59         COPY_PICTURE(dest, src);
60         if (parity != PICT_FRAME) {
61             pic_as_field(dest, parity);
62             dest->pic_id *= 2;
63             dest->pic_id += id_add;
64         }
65     }
66
67     return match;
68 }
69
70 static int build_def_list(Picture *def, Picture **in, int len, int is_long, int sel)
71 {
72     int  i[2] = { 0 };
73     int index = 0;
74
75     while (i[0] < len || i[1] < len) {
76         while (i[0] < len && !(in[i[0]] && (in[i[0]]->reference & sel)))
77             i[0]++;
78         while (i[1] < len && !(in[i[1]] && (in[i[1]]->reference & (sel ^ 3))))
79             i[1]++;
80         if (i[0] < len) {
81             in[i[0]]->pic_id = is_long ? i[0] : in[i[0]]->frame_num;
82             split_field_copy(&def[index++], in[i[0]++], sel, 1);
83         }
84         if (i[1] < len) {
85             in[i[1]]->pic_id = is_long ? i[1] : in[i[1]]->frame_num;
86             split_field_copy(&def[index++], in[i[1]++], sel ^ 3, 0);
87         }
88     }
89
90     return index;
91 }
92
93 static int add_sorted(Picture **sorted, Picture **src, int len, int limit, int dir)
94 {
95     int i, best_poc;
96     int out_i = 0;
97
98     for (;;) {
99         best_poc = dir ? INT_MIN : INT_MAX;
100
101         for (i = 0; i < len; i++) {
102             const int poc = src[i]->poc;
103             if (((poc > limit) ^ dir) && ((poc < best_poc) ^ dir)) {
104                 best_poc      = poc;
105                 sorted[out_i] = src[i];
106             }
107         }
108         if (best_poc == (dir ? INT_MIN : INT_MAX))
109             break;
110         limit = sorted[out_i++]->poc - dir;
111     }
112     return out_i;
113 }
114
115 int ff_h264_fill_default_ref_list(H264Context *h)
116 {
117     int i, len;
118
119     if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
120         Picture *sorted[32];
121         int cur_poc, list;
122         int lens[2];
123
124         if (FIELD_PICTURE(h))
125             cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure == PICT_BOTTOM_FIELD];
126         else
127             cur_poc = h->cur_pic_ptr->poc;
128
129         for (list = 0; list < 2; list++) {
130             len  = add_sorted(sorted,       h->short_ref, h->short_ref_count, cur_poc, 1 ^ list);
131             len += add_sorted(sorted + len, h->short_ref, h->short_ref_count, cur_poc, 0 ^ list);
132             assert(len <= 32);
133             len  = build_def_list(h->default_ref_list[list],       sorted,      len, 0, h->picture_structure);
134             len += build_def_list(h->default_ref_list[list] + len, h->long_ref, 16,  1, h->picture_structure);
135             assert(len <= 32);
136
137             if (len < h->ref_count[list])
138                 memset(&h->default_ref_list[list][len], 0, sizeof(Picture) * (h->ref_count[list] - len));
139             lens[list] = len;
140         }
141
142         if (lens[0] == lens[1] && lens[1] > 1) {
143             for (i = 0; h->default_ref_list[0][i].f.data[0] == h->default_ref_list[1][i].f.data[0] && i < lens[0]; i++);
144             if (i == lens[0]) {
145                 Picture tmp;
146                 COPY_PICTURE(&tmp, &h->default_ref_list[1][0]);
147                 COPY_PICTURE(&h->default_ref_list[1][0], &h->default_ref_list[1][1]);
148                 COPY_PICTURE(&h->default_ref_list[1][1], &tmp);
149             }
150         }
151     } else {
152         len  = build_def_list(h->default_ref_list[0],       h->short_ref, h->short_ref_count, 0, h->picture_structure);
153         len += build_def_list(h->default_ref_list[0] + len, h-> long_ref, 16,                 1, h->picture_structure);
154         assert(len <= 32);
155         if (len < h->ref_count[0])
156             memset(&h->default_ref_list[0][len], 0, sizeof(Picture) * (h->ref_count[0] - len));
157     }
158 #ifdef TRACE
159     for (i = 0; i < h->ref_count[0]; i++) {
160         tprintf(h->avctx, "List0: %s fn:%d 0x%p\n",
161                 (h->default_ref_list[0][i].long_ref ? "LT" : "ST"),
162                 h->default_ref_list[0][i].pic_id,
163                 h->default_ref_list[0][i].f.data[0]);
164     }
165     if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
166         for (i = 0; i < h->ref_count[1]; i++) {
167             tprintf(h->avctx, "List1: %s fn:%d 0x%p\n",
168                     (h->default_ref_list[1][i].long_ref ? "LT" : "ST"),
169                     h->default_ref_list[1][i].pic_id,
170                     h->default_ref_list[1][i].f.data[0]);
171         }
172     }
173 #endif
174     return 0;
175 }
176
177 static void print_short_term(H264Context *h);
178 static void print_long_term(H264Context *h);
179
180 /**
181  * Extract structure information about the picture described by pic_num in
182  * the current decoding context (frame or field). Note that pic_num is
183  * picture number without wrapping (so, 0<=pic_num<max_pic_num).
184  * @param pic_num picture number for which to extract structure information
185  * @param structure one of PICT_XXX describing structure of picture
186  *                      with pic_num
187  * @return frame number (short term) or long term index of picture
188  *         described by pic_num
189  */
190 static int pic_num_extract(H264Context *h, int pic_num, int *structure)
191 {
192     *structure = h->picture_structure;
193     if (FIELD_PICTURE(h)) {
194         if (!(pic_num & 1))
195             /* opposite field */
196             *structure ^= PICT_FRAME;
197         pic_num >>= 1;
198     }
199
200     return pic_num;
201 }
202
203 int ff_h264_decode_ref_pic_list_reordering(H264Context *h)
204 {
205     int list, index, pic_structure, i;
206
207     print_short_term(h);
208     print_long_term(h);
209
210     for (list = 0; list < h->list_count; list++) {
211         for (i = 0; i < h->ref_count[list]; i++)
212             COPY_PICTURE(&h->ref_list[list][i], &h->default_ref_list[list][i]);
213
214         if (get_bits1(&h->gb)) {
215             int pred = h->curr_pic_num;
216
217             for (index = 0; ; index++) {
218                 unsigned int reordering_of_pic_nums_idc = get_ue_golomb_31(&h->gb);
219                 unsigned int pic_id;
220                 int i;
221                 Picture *ref = NULL;
222
223                 if (reordering_of_pic_nums_idc == 3)
224                     break;
225
226                 if (index >= h->ref_count[list]) {
227                     av_log(h->avctx, AV_LOG_ERROR, "reference count overflow\n");
228                     return -1;
229                 }
230
231                 if (reordering_of_pic_nums_idc < 3) {
232                     if (reordering_of_pic_nums_idc < 2) {
233                         const unsigned int abs_diff_pic_num = get_ue_golomb(&h->gb) + 1;
234                         int frame_num;
235
236                         if (abs_diff_pic_num > h->max_pic_num) {
237                             av_log(h->avctx, AV_LOG_ERROR, "abs_diff_pic_num overflow\n");
238                             return -1;
239                         }
240
241                         if (reordering_of_pic_nums_idc == 0)
242                             pred -= abs_diff_pic_num;
243                         else
244                             pred += abs_diff_pic_num;
245                         pred &= h->max_pic_num - 1;
246
247                         frame_num = pic_num_extract(h, pred, &pic_structure);
248
249                         for (i = h->short_ref_count - 1; i >= 0; i--) {
250                             ref = h->short_ref[i];
251                             assert(ref->reference);
252                             assert(!ref->long_ref);
253                             if (ref->frame_num == frame_num &&
254                                 (ref->reference & pic_structure))
255                                 break;
256                         }
257                         if (i >= 0)
258                             ref->pic_id = pred;
259                     } else {
260                         int long_idx;
261                         pic_id = get_ue_golomb(&h->gb); //long_term_pic_idx
262
263                         long_idx = pic_num_extract(h, pic_id, &pic_structure);
264
265                         if (long_idx > 31) {
266                             av_log(h->avctx, AV_LOG_ERROR, "long_term_pic_idx overflow\n");
267                             return -1;
268                         }
269                         ref = h->long_ref[long_idx];
270                         assert(!(ref && !ref->reference));
271                         if (ref && (ref->reference & pic_structure)) {
272                             ref->pic_id = pic_id;
273                             assert(ref->long_ref);
274                             i = 0;
275                         } else {
276                             i = -1;
277                         }
278                     }
279
280                     if (i < 0) {
281                         av_log(h->avctx, AV_LOG_ERROR, "reference picture missing during reorder\n");
282                         memset(&h->ref_list[list][index], 0, sizeof(Picture)); //FIXME
283                     } else {
284                         for (i = index; i + 1 < h->ref_count[list]; i++) {
285                             if (ref->long_ref == h->ref_list[list][i].long_ref &&
286                                 ref->pic_id   == h->ref_list[list][i].pic_id)
287                                 break;
288                         }
289                         for (; i > index; i--) {
290                             COPY_PICTURE(&h->ref_list[list][i], &h->ref_list[list][i - 1]);
291                         }
292                         COPY_PICTURE(&h->ref_list[list][index], ref);
293                         if (FIELD_PICTURE(h)) {
294                             pic_as_field(&h->ref_list[list][index], pic_structure);
295                         }
296                     }
297                 } else {
298                     av_log(h->avctx, AV_LOG_ERROR, "illegal reordering_of_pic_nums_idc\n");
299                     return -1;
300                 }
301             }
302         }
303     }
304     for (list = 0; list < h->list_count; list++) {
305         for (index = 0; index < h->ref_count[list]; index++) {
306             if (!h->ref_list[list][index].f.data[0]) {
307                 av_log(h->avctx, AV_LOG_ERROR, "Missing reference picture\n");
308                 if (h->default_ref_list[list][0].f.data[0])
309                     COPY_PICTURE(&h->ref_list[list][index], &h->default_ref_list[list][0]);
310                 else
311                     return -1;
312             }
313         }
314     }
315
316     return 0;
317 }
318
319 void ff_h264_fill_mbaff_ref_list(H264Context *h)
320 {
321     int list, i, j;
322     for (list = 0; list < 2; list++) { //FIXME try list_count
323         for (i = 0; i < h->ref_count[list]; i++) {
324             Picture *frame = &h->ref_list[list][i];
325             Picture *field = &h->ref_list[list][16 + 2 * i];
326             COPY_PICTURE(field, frame);
327             for (j = 0; j < 3; j++)
328                 field[0].f.linesize[j] <<= 1;
329             field[0].reference = PICT_TOP_FIELD;
330             field[0].poc       = field[0].field_poc[0];
331             COPY_PICTURE(field + 1, field);
332             for (j = 0; j < 3; j++)
333                 field[1].f.data[j] += frame->f.linesize[j];
334             field[1].reference = PICT_BOTTOM_FIELD;
335             field[1].poc       = field[1].field_poc[1];
336
337             h->luma_weight[16 + 2 * i][list][0] = h->luma_weight[16 + 2 * i + 1][list][0] = h->luma_weight[i][list][0];
338             h->luma_weight[16 + 2 * i][list][1] = h->luma_weight[16 + 2 * i + 1][list][1] = h->luma_weight[i][list][1];
339             for (j = 0; j < 2; j++) {
340                 h->chroma_weight[16 + 2 * i][list][j][0] = h->chroma_weight[16 + 2 * i + 1][list][j][0] = h->chroma_weight[i][list][j][0];
341                 h->chroma_weight[16 + 2 * i][list][j][1] = h->chroma_weight[16 + 2 * i + 1][list][j][1] = h->chroma_weight[i][list][j][1];
342             }
343         }
344     }
345 }
346
347 /**
348  * Mark a picture as no longer needed for reference. The refmask
349  * argument allows unreferencing of individual fields or the whole frame.
350  * If the picture becomes entirely unreferenced, but is being held for
351  * display purposes, it is marked as such.
352  * @param refmask mask of fields to unreference; the mask is bitwise
353  *                anded with the reference marking of pic
354  * @return non-zero if pic becomes entirely unreferenced (except possibly
355  *         for display purposes) zero if one of the fields remains in
356  *         reference
357  */
358 static inline int unreference_pic(H264Context *h, Picture *pic, int refmask)
359 {
360     int i;
361     if (pic->reference &= refmask) {
362         return 0;
363     } else {
364         for(i = 0; h->delayed_pic[i]; i++)
365             if(pic == h->delayed_pic[i]){
366                 pic->reference = DELAYED_PIC_REF;
367                 break;
368             }
369         return 1;
370     }
371 }
372
373 /**
374  * Find a Picture in the short term reference list by frame number.
375  * @param frame_num frame number to search for
376  * @param idx the index into h->short_ref where returned picture is found
377  *            undefined if no picture found.
378  * @return pointer to the found picture, or NULL if no pic with the provided
379  *                 frame number is found
380  */
381 static Picture *find_short(H264Context *h, int frame_num, int *idx)
382 {
383     int i;
384
385     for (i = 0; i < h->short_ref_count; i++) {
386         Picture *pic = h->short_ref[i];
387         if (h->avctx->debug & FF_DEBUG_MMCO)
388             av_log(h->avctx, AV_LOG_DEBUG, "%d %d %p\n", i, pic->frame_num, pic);
389         if (pic->frame_num == frame_num) {
390             *idx = i;
391             return pic;
392         }
393     }
394     return NULL;
395 }
396
397 /**
398  * Remove a picture from the short term reference list by its index in
399  * that list.  This does no checking on the provided index; it is assumed
400  * to be valid. Other list entries are shifted down.
401  * @param i index into h->short_ref of picture to remove.
402  */
403 static void remove_short_at_index(H264Context *h, int i)
404 {
405     assert(i >= 0 && i < h->short_ref_count);
406     h->short_ref[i] = NULL;
407     if (--h->short_ref_count)
408         memmove(&h->short_ref[i], &h->short_ref[i + 1],
409                 (h->short_ref_count - i) * sizeof(Picture*));
410 }
411
412 /**
413  *
414  * @return the removed picture or NULL if an error occurs
415  */
416 static Picture *remove_short(H264Context *h, int frame_num, int ref_mask)
417 {
418     Picture *pic;
419     int i;
420
421     if (h->avctx->debug & FF_DEBUG_MMCO)
422         av_log(h->avctx, AV_LOG_DEBUG, "remove short %d count %d\n", frame_num, h->short_ref_count);
423
424     pic = find_short(h, frame_num, &i);
425     if (pic) {
426         if (unreference_pic(h, pic, ref_mask))
427             remove_short_at_index(h, i);
428     }
429
430     return pic;
431 }
432
433 /**
434  * Remove a picture from the long term reference list by its index in
435  * that list.
436  * @return the removed picture or NULL if an error occurs
437  */
438 static Picture *remove_long(H264Context *h, int i, int ref_mask)
439 {
440     Picture *pic;
441
442     pic = h->long_ref[i];
443     if (pic) {
444         if (unreference_pic(h, pic, ref_mask)) {
445             assert(h->long_ref[i]->long_ref == 1);
446             h->long_ref[i]->long_ref = 0;
447             h->long_ref[i]           = NULL;
448             h->long_ref_count--;
449         }
450     }
451
452     return pic;
453 }
454
455 void ff_h264_remove_all_refs(H264Context *h)
456 {
457     int i;
458
459     for (i = 0; i < 16; i++) {
460         remove_long(h, i, 0);
461     }
462     assert(h->long_ref_count == 0);
463
464     for (i = 0; i < h->short_ref_count; i++) {
465         unreference_pic(h, h->short_ref[i], 0);
466         h->short_ref[i] = NULL;
467     }
468     h->short_ref_count = 0;
469 }
470
471 /**
472  * print short term list
473  */
474 static void print_short_term(H264Context *h)
475 {
476     uint32_t i;
477     if (h->avctx->debug & FF_DEBUG_MMCO) {
478         av_log(h->avctx, AV_LOG_DEBUG, "short term list:\n");
479         for (i = 0; i < h->short_ref_count; i++) {
480             Picture *pic = h->short_ref[i];
481             av_log(h->avctx, AV_LOG_DEBUG, "%d fn:%d poc:%d %p\n",
482                    i, pic->frame_num, pic->poc, pic->f.data[0]);
483         }
484     }
485 }
486
487 /**
488  * print long term list
489  */
490 static void print_long_term(H264Context *h)
491 {
492     uint32_t i;
493     if (h->avctx->debug & FF_DEBUG_MMCO) {
494         av_log(h->avctx, AV_LOG_DEBUG, "long term list:\n");
495         for (i = 0; i < 16; i++) {
496             Picture *pic = h->long_ref[i];
497             if (pic) {
498                 av_log(h->avctx, AV_LOG_DEBUG, "%d fn:%d poc:%d %p\n",
499                        i, pic->frame_num, pic->poc, pic->f.data[0]);
500             }
501         }
502     }
503 }
504
505 static int check_opcodes(MMCO *mmco1, MMCO *mmco2, int n_mmcos)
506 {
507     int i;
508
509     for (i = 0; i < n_mmcos; i++) {
510         if (mmco1[i].opcode != mmco2[i].opcode)
511             return -1;
512     }
513
514     return 0;
515 }
516
517 int ff_generate_sliding_window_mmcos(H264Context *h, int first_slice)
518 {
519     MMCO mmco_temp[MAX_MMCO_COUNT], *mmco = first_slice ? h->mmco : mmco_temp;
520     int mmco_index = 0, i;
521
522     assert(h->long_ref_count + h->short_ref_count <= h->sps.ref_frame_count);
523
524     if (h->short_ref_count &&
525         h->long_ref_count + h->short_ref_count == h->sps.ref_frame_count &&
526         !(FIELD_PICTURE(h) && !h->first_field && h->cur_pic_ptr->reference)) {
527         mmco[0].opcode        = MMCO_SHORT2UNUSED;
528         mmco[0].short_pic_num = h->short_ref[h->short_ref_count - 1]->frame_num;
529         mmco_index            = 1;
530         if (FIELD_PICTURE(h)) {
531             mmco[0].short_pic_num *= 2;
532             mmco[1].opcode         = MMCO_SHORT2UNUSED;
533             mmco[1].short_pic_num  = mmco[0].short_pic_num + 1;
534             mmco_index             = 2;
535         }
536     }
537
538     if (first_slice) {
539         h->mmco_index = mmco_index;
540     } else if (!first_slice && mmco_index >= 0 &&
541                (mmco_index != h->mmco_index ||
542                 (i = check_opcodes(h->mmco, mmco_temp, mmco_index)))) {
543         av_log(h->avctx, AV_LOG_ERROR,
544                "Inconsistent MMCO state between slices [%d, %d, %d]\n",
545                mmco_index, h->mmco_index, i);
546         return AVERROR_INVALIDDATA;
547     }
548     return 0;
549 }
550
551 int ff_h264_execute_ref_pic_marking(H264Context *h, MMCO *mmco, int mmco_count)
552 {
553     int i, av_uninit(j);
554     int current_ref_assigned = 0, err = 0;
555     Picture *av_uninit(pic);
556
557     if ((h->avctx->debug & FF_DEBUG_MMCO) && mmco_count == 0)
558         av_log(h->avctx, AV_LOG_DEBUG, "no mmco here\n");
559
560     for (i = 0; i < mmco_count; i++) {
561         int av_uninit(structure), av_uninit(frame_num);
562         if (h->avctx->debug & FF_DEBUG_MMCO)
563             av_log(h->avctx, AV_LOG_DEBUG, "mmco:%d %d %d\n", h->mmco[i].opcode,
564                    h->mmco[i].short_pic_num, h->mmco[i].long_arg);
565
566         if (mmco[i].opcode == MMCO_SHORT2UNUSED ||
567             mmco[i].opcode == MMCO_SHORT2LONG) {
568             frame_num = pic_num_extract(h, mmco[i].short_pic_num, &structure);
569             pic       = find_short(h, frame_num, &j);
570             if (!pic) {
571                 if (mmco[i].opcode != MMCO_SHORT2LONG ||
572                     !h->long_ref[mmco[i].long_arg]    ||
573                     h->long_ref[mmco[i].long_arg]->frame_num != frame_num) {
574                     av_log(h->avctx, AV_LOG_ERROR, "mmco: unref short failure\n");
575                     err = AVERROR_INVALIDDATA;
576                 }
577                 continue;
578             }
579         }
580
581         switch (mmco[i].opcode) {
582         case MMCO_SHORT2UNUSED:
583             if (h->avctx->debug & FF_DEBUG_MMCO)
584                 av_log(h->avctx, AV_LOG_DEBUG, "mmco: unref short %d count %d\n",
585                        h->mmco[i].short_pic_num, h->short_ref_count);
586             remove_short(h, frame_num, structure ^ PICT_FRAME);
587             break;
588         case MMCO_SHORT2LONG:
589                 if (h->long_ref[mmco[i].long_arg] != pic)
590                     remove_long(h, mmco[i].long_arg, 0);
591
592                 remove_short_at_index(h, j);
593                 h->long_ref[ mmco[i].long_arg ] = pic;
594                 if (h->long_ref[mmco[i].long_arg]) {
595                     h->long_ref[mmco[i].long_arg]->long_ref = 1;
596                     h->long_ref_count++;
597                 }
598             break;
599         case MMCO_LONG2UNUSED:
600             j   = pic_num_extract(h, mmco[i].long_arg, &structure);
601             pic = h->long_ref[j];
602             if (pic) {
603                 remove_long(h, j, structure ^ PICT_FRAME);
604             } else if (h->avctx->debug & FF_DEBUG_MMCO)
605                 av_log(h->avctx, AV_LOG_DEBUG, "mmco: unref long failure\n");
606             break;
607         case MMCO_LONG:
608                     // Comment below left from previous code as it is an interresting note.
609                     /* First field in pair is in short term list or
610                      * at a different long term index.
611                      * This is not allowed; see 7.4.3.3, notes 2 and 3.
612                      * Report the problem and keep the pair where it is,
613                      * and mark this field valid.
614                      */
615
616             if (h->long_ref[mmco[i].long_arg] != h->cur_pic_ptr) {
617                 remove_long(h, mmco[i].long_arg, 0);
618
619                 h->long_ref[mmco[i].long_arg]           = h->cur_pic_ptr;
620                 h->long_ref[mmco[i].long_arg]->long_ref = 1;
621                 h->long_ref_count++;
622             }
623
624             h->cur_pic_ptr->reference |= h->picture_structure;
625             current_ref_assigned = 1;
626             break;
627         case MMCO_SET_MAX_LONG:
628             assert(mmco[i].long_arg <= 16);
629             // just remove the long term which index is greater than new max
630             for (j = mmco[i].long_arg; j < 16; j++) {
631                 remove_long(h, j, 0);
632             }
633             break;
634         case MMCO_RESET:
635             while (h->short_ref_count) {
636                 remove_short(h, h->short_ref[0]->frame_num, 0);
637             }
638             for (j = 0; j < 16; j++) {
639                 remove_long(h, j, 0);
640             }
641             h->frame_num  = h->cur_pic_ptr->frame_num = 0;
642             h->mmco_reset = 1;
643             h->cur_pic_ptr->mmco_reset = 1;
644             break;
645         default: assert(0);
646         }
647     }
648
649     if (!current_ref_assigned) {
650         /* Second field of complementary field pair; the first field of
651          * which is already referenced. If short referenced, it
652          * should be first entry in short_ref. If not, it must exist
653          * in long_ref; trying to put it on the short list here is an
654          * error in the encoded bit stream (ref: 7.4.3.3, NOTE 2 and 3).
655          */
656         if (h->short_ref_count && h->short_ref[0] == h->cur_pic_ptr) {
657             /* Just mark the second field valid */
658             h->cur_pic_ptr->reference = PICT_FRAME;
659         } else if (h->cur_pic_ptr->long_ref) {
660             av_log(h->avctx, AV_LOG_ERROR, "illegal short term reference "
661                                            "assignment for second field "
662                                            "in complementary field pair "
663                                            "(first field is long term)\n");
664             err = AVERROR_INVALIDDATA;
665         } else {
666             pic = remove_short(h, h->cur_pic_ptr->frame_num, 0);
667             if (pic) {
668                 av_log(h->avctx, AV_LOG_ERROR, "illegal short term buffer state detected\n");
669                 err = AVERROR_INVALIDDATA;
670             }
671
672             if (h->short_ref_count)
673                 memmove(&h->short_ref[1], &h->short_ref[0],
674                         h->short_ref_count * sizeof(Picture*));
675
676             h->short_ref[0] = h->cur_pic_ptr;
677             h->short_ref_count++;
678             h->cur_pic_ptr->reference |= h->picture_structure;
679         }
680     }
681
682     if (h->long_ref_count + h->short_ref_count -
683         (h->short_ref[0] == h->cur_pic_ptr) > h->sps.ref_frame_count) {
684
685         /* We have too many reference frames, probably due to corrupted
686          * stream. Need to discard one frame. Prevents overrun of the
687          * short_ref and long_ref buffers.
688          */
689         av_log(h->avctx, AV_LOG_ERROR,
690                "number of reference frames (%d+%d) exceeds max (%d; probably "
691                "corrupt input), discarding one\n",
692                h->long_ref_count, h->short_ref_count, h->sps.ref_frame_count);
693         err = AVERROR_INVALIDDATA;
694
695         if (h->long_ref_count && !h->short_ref_count) {
696             for (i = 0; i < 16; ++i)
697                 if (h->long_ref[i])
698                     break;
699
700             assert(i < 16);
701             remove_long(h, i, 0);
702         } else {
703             pic = h->short_ref[h->short_ref_count - 1];
704             remove_short(h, pic->frame_num, 0);
705         }
706     }
707
708     print_short_term(h);
709     print_long_term(h);
710     return (h->avctx->err_recognition & AV_EF_EXPLODE) ? err : 0;
711 }
712
713 int ff_h264_decode_ref_pic_marking(H264Context *h, GetBitContext *gb,
714                                    int first_slice)
715 {
716     int i, ret;
717     MMCO mmco_temp[MAX_MMCO_COUNT], *mmco = first_slice ? h->mmco : mmco_temp;
718     int mmco_index = 0;
719
720     if (h->nal_unit_type == NAL_IDR_SLICE) { // FIXME fields
721         skip_bits1(gb); // broken_link
722         if (get_bits1(gb)) {
723             mmco[0].opcode   = MMCO_LONG;
724             mmco[0].long_arg = 0;
725             mmco_index       = 1;
726         }
727     } else {
728         if (get_bits1(gb)) { // adaptive_ref_pic_marking_mode_flag
729             for (i = 0; i < MAX_MMCO_COUNT; i++) {
730                 MMCOOpcode opcode = get_ue_golomb_31(gb);
731
732                 mmco[i].opcode = opcode;
733                 if (opcode == MMCO_SHORT2UNUSED || opcode == MMCO_SHORT2LONG) {
734                     mmco[i].short_pic_num =
735                         (h->curr_pic_num - get_ue_golomb(gb) - 1) &
736                             (h->max_pic_num - 1);
737 #if 0
738                     if (mmco[i].short_pic_num >= h->short_ref_count ||
739                         h->short_ref[ mmco[i].short_pic_num ] == NULL){
740                         av_log(s->avctx, AV_LOG_ERROR,
741                                "illegal short ref in memory management control "
742                                "operation %d\n", mmco);
743                         return -1;
744                     }
745 #endif
746                 }
747                 if (opcode == MMCO_SHORT2LONG || opcode == MMCO_LONG2UNUSED ||
748                     opcode == MMCO_LONG || opcode == MMCO_SET_MAX_LONG) {
749                     unsigned int long_arg = get_ue_golomb_31(gb);
750                     if (long_arg >= 32 ||
751                         (long_arg >= 16 && !(opcode == MMCO_SET_MAX_LONG &&
752                                              long_arg == 16) &&
753                          !(opcode == MMCO_LONG2UNUSED && FIELD_PICTURE(h)))) {
754                         av_log(h->avctx, AV_LOG_ERROR,
755                                "illegal long ref in memory management control "
756                                "operation %d\n", opcode);
757                         return -1;
758                     }
759                     mmco[i].long_arg = long_arg;
760                 }
761
762                 if (opcode > (unsigned) MMCO_LONG) {
763                     av_log(h->avctx, AV_LOG_ERROR,
764                            "illegal memory management control operation %d\n",
765                            opcode);
766                     return -1;
767                 }
768                 if (opcode == MMCO_END)
769                     break;
770             }
771             mmco_index = i;
772         } else {
773             if (first_slice) {
774                 ret = ff_generate_sliding_window_mmcos(h, first_slice);
775                 if (ret < 0 && h->avctx->err_recognition & AV_EF_EXPLODE)
776                     return ret;
777             }
778             mmco_index = -1;
779         }
780     }
781
782     if (first_slice && mmco_index != -1) {
783         h->mmco_index = mmco_index;
784     } else if (!first_slice && mmco_index >= 0 &&
785                (mmco_index != h->mmco_index ||
786                 check_opcodes(h->mmco, mmco_temp, mmco_index))) {
787         av_log(h->avctx, AV_LOG_ERROR,
788                "Inconsistent MMCO state between slices [%d, %d]\n",
789                mmco_index, h->mmco_index);
790         return AVERROR_INVALIDDATA;
791     }
792
793     return 0;
794 }