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