1/*
2 * H.26L/H.264/AVC/JVT/14496-10/... parser
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 parser.
25 * @author Michael Niedermayer <michaelni@gmx.at>
26 */
27
28#include "parser.h"
29#include "h264data.h"
30#include "golomb.h"
31
32#include <assert.h>
33
34
35static int ff_h264_find_frame_end(H264Context *h, const uint8_t *buf, int buf_size)
36{
37    int i;
38    uint32_t state;
39    ParseContext *pc = &(h->s.parse_context);
40//printf("first %02X%02X%02X%02X\n", buf[0], buf[1],buf[2],buf[3]);
41//    mb_addr= pc->mb_addr - 1;
42    state= pc->state;
43    if(state>13)
44        state= 7;
45
46    for(i=0; i<buf_size; i++){
47        if(state==7){
48#if HAVE_FAST_UNALIGNED
49        /* we check i<buf_size instead of i+3/7 because its simpler
50         * and there should be FF_INPUT_BUFFER_PADDING_SIZE bytes at the end
51         */
52#    if HAVE_FAST_64BIT
53            while(i<buf_size && !((~*(const uint64_t*)(buf+i) & (*(const uint64_t*)(buf+i) - 0x0101010101010101ULL)) & 0x8080808080808080ULL))
54                i+=8;
55#    else
56            while(i<buf_size && !((~*(const uint32_t*)(buf+i) & (*(const uint32_t*)(buf+i) - 0x01010101U)) & 0x80808080U))
57                i+=4;
58#    endif
59#endif
60            for(; i<buf_size; i++){
61                if(!buf[i]){
62                    state=2;
63                    break;
64                }
65            }
66        }else if(state<=2){
67            if(buf[i]==1)   state^= 5; //2->7, 1->4, 0->5
68            else if(buf[i]) state = 7;
69            else            state>>=1; //2->1, 1->0, 0->0
70        }else if(state<=5){
71            int v= buf[i] & 0x1F;
72            if(v==6 || v==7 || v==8 || v==9){
73                if(pc->frame_start_found){
74                    i++;
75                    goto found;
76                }
77            }else if(v==1 || v==2 || v==5){
78                if(pc->frame_start_found){
79                    state+=8;
80                    continue;
81                }else
82                    pc->frame_start_found = 1;
83            }
84            state= 7;
85        }else{
86            if(buf[i] & 0x80)
87                goto found;
88            state= 7;
89        }
90    }
91    pc->state= state;
92    return END_NOT_FOUND;
93
94found:
95    pc->state=7;
96    pc->frame_start_found= 0;
97    return i-(state&5);
98}
99
100/**
101 * Parse NAL units of found picture and decode some basic information.
102 *
103 * @param s parser context.
104 * @param avctx codec context.
105 * @param buf buffer with field/frame data.
106 * @param buf_size size of the buffer.
107 */
108static inline int parse_nal_units(AVCodecParserContext *s,
109                                  AVCodecContext *avctx,
110                                  const uint8_t *buf, int buf_size)
111{
112    H264Context *h = s->priv_data;
113    const uint8_t *buf_end = buf + buf_size;
114    unsigned int pps_id;
115    unsigned int slice_type;
116    int state = -1;
117    const uint8_t *ptr;
118
119    /* set some sane default values */
120    s->pict_type = AV_PICTURE_TYPE_I;
121    s->key_frame = 0;
122
123    h->s.avctx= avctx;
124    h->sei_recovery_frame_cnt = -1;
125    h->sei_dpb_output_delay         =  0;
126    h->sei_cpb_removal_delay        = -1;
127    h->sei_buffering_period_present =  0;
128
129    if (!buf_size)
130        return 0;
131
132    for(;;) {
133        int src_length, dst_length, consumed;
134        buf = avpriv_mpv_find_start_code(buf, buf_end, &state);
135        if(buf >= buf_end)
136            break;
137        --buf;
138        src_length = buf_end - buf;
139        switch (state & 0x1f) {
140        case NAL_SLICE:
141        case NAL_IDR_SLICE:
142            // Do not walk the whole buffer just to decode slice header
143            if (src_length > 20)
144                src_length = 20;
145            break;
146        }
147        ptr= ff_h264_decode_nal(h, buf, &dst_length, &consumed, src_length);
148        if (ptr==NULL || dst_length < 0)
149            break;
150
151        init_get_bits(&h->s.gb, ptr, 8*dst_length);
152        switch(h->nal_unit_type) {
153        case NAL_SPS:
154            ff_h264_decode_seq_parameter_set(h);
155            break;
156        case NAL_PPS:
157            ff_h264_decode_picture_parameter_set(h, h->s.gb.size_in_bits);
158            break;
159        case NAL_SEI:
160            ff_h264_decode_sei(h);
161            break;
162        case NAL_IDR_SLICE:
163            s->key_frame = 1;
164            /* fall through */
165        case NAL_SLICE:
166            get_ue_golomb(&h->s.gb);  // skip first_mb_in_slice
167            slice_type = get_ue_golomb_31(&h->s.gb);
168            s->pict_type = golomb_to_pict_type[slice_type % 5];
169            if (h->sei_recovery_frame_cnt >= 0) {
170                /* key frame, since recovery_frame_cnt is set */
171                s->key_frame = 1;
172            }
173            pps_id= get_ue_golomb(&h->s.gb);
174            if(pps_id>=MAX_PPS_COUNT) {
175                av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
176                return -1;
177            }
178            if(!h->pps_buffers[pps_id]) {
179                av_log(h->s.avctx, AV_LOG_ERROR, "non-existing PPS referenced\n");
180                return -1;
181            }
182            h->pps= *h->pps_buffers[pps_id];
183            if(!h->sps_buffers[h->pps.sps_id]) {
184                av_log(h->s.avctx, AV_LOG_ERROR, "non-existing SPS referenced\n");
185                return -1;
186            }
187            h->sps = *h->sps_buffers[h->pps.sps_id];
188            h->frame_num = get_bits(&h->s.gb, h->sps.log2_max_frame_num);
189
190            avctx->profile = ff_h264_get_profile(&h->sps);
191            avctx->level   = h->sps.level_idc;
192
193            if(h->sps.frame_mbs_only_flag){
194                h->s.picture_structure= PICT_FRAME;
195            }else{
196                if(get_bits1(&h->s.gb)) { //field_pic_flag
197                    h->s.picture_structure= PICT_TOP_FIELD + get_bits1(&h->s.gb); //bottom_field_flag
198                } else {
199                    h->s.picture_structure= PICT_FRAME;
200                }
201            }
202
203            if(h->sps.pic_struct_present_flag) {
204                switch (h->sei_pic_struct) {
205                    case SEI_PIC_STRUCT_TOP_FIELD:
206                    case SEI_PIC_STRUCT_BOTTOM_FIELD:
207                        s->repeat_pict = 0;
208                        break;
209                    case SEI_PIC_STRUCT_FRAME:
210                    case SEI_PIC_STRUCT_TOP_BOTTOM:
211                    case SEI_PIC_STRUCT_BOTTOM_TOP:
212                        s->repeat_pict = 1;
213                        break;
214                    case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
215                    case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
216                        s->repeat_pict = 2;
217                        break;
218                    case SEI_PIC_STRUCT_FRAME_DOUBLING:
219                        s->repeat_pict = 3;
220                        break;
221                    case SEI_PIC_STRUCT_FRAME_TRIPLING:
222                        s->repeat_pict = 5;
223                        break;
224                    default:
225                        s->repeat_pict = h->s.picture_structure == PICT_FRAME ? 1 : 0;
226                        break;
227                }
228            } else {
229                s->repeat_pict = h->s.picture_structure == PICT_FRAME ? 1 : 0;
230            }
231
232            return 0; /* no need to evaluate the rest */
233        }
234        buf += consumed;
235    }
236    /* didn't find a picture! */
237    av_log(h->s.avctx, AV_LOG_ERROR, "missing picture in access unit\n");
238    return -1;
239}
240
241static int h264_parse(AVCodecParserContext *s,
242                      AVCodecContext *avctx,
243                      const uint8_t **poutbuf, int *poutbuf_size,
244                      const uint8_t *buf, int buf_size)
245{
246    H264Context *h = s->priv_data;
247    ParseContext *pc = &h->s.parse_context;
248    int next;
249
250    if (!h->got_first) {
251        h->got_first = 1;
252        if (avctx->extradata_size) {
253            h->s.avctx = avctx;
254            // must be done like in the decoder.
255            // otherwise opening the parser, creating extradata,
256            // and then closing and opening again
257            // will cause has_b_frames to be always set.
258            // NB: estimate_timings_from_pts behaves exactly like this.
259            if (!avctx->has_b_frames)
260                h->s.low_delay = 1;
261            ff_h264_decode_extradata(h);
262        }
263    }
264
265    if(s->flags & PARSER_FLAG_COMPLETE_FRAMES){
266        next= buf_size;
267    }else{
268        next= ff_h264_find_frame_end(h, buf, buf_size);
269
270        if (ff_combine_frame(pc, next, &buf, &buf_size) < 0) {
271            *poutbuf = NULL;
272            *poutbuf_size = 0;
273            return buf_size;
274        }
275
276        if(next<0 && next != END_NOT_FOUND){
277            assert(pc->last_index + next >= 0 );
278            ff_h264_find_frame_end(h, &pc->buffer[pc->last_index + next], -next); //update state
279        }
280    }
281
282    parse_nal_units(s, avctx, buf, buf_size);
283
284    if (h->sei_cpb_removal_delay >= 0) {
285        s->dts_sync_point    = h->sei_buffering_period_present;
286        s->dts_ref_dts_delta = h->sei_cpb_removal_delay;
287        s->pts_dts_delta     = h->sei_dpb_output_delay;
288    } else {
289        s->dts_sync_point    = INT_MIN;
290        s->dts_ref_dts_delta = INT_MIN;
291        s->pts_dts_delta     = INT_MIN;
292    }
293
294    if (s->flags & PARSER_FLAG_ONCE) {
295        s->flags &= PARSER_FLAG_COMPLETE_FRAMES;
296    }
297
298    *poutbuf = buf;
299    *poutbuf_size = buf_size;
300    return next;
301}
302
303static int h264_split(AVCodecContext *avctx,
304                      const uint8_t *buf, int buf_size)
305{
306    int i;
307    uint32_t state = -1;
308    int has_sps= 0;
309
310    for(i=0; i<=buf_size; i++){
311        if((state&0xFFFFFF1F) == 0x107)
312            has_sps=1;
313/*        if((state&0xFFFFFF1F) == 0x101 || (state&0xFFFFFF1F) == 0x102 || (state&0xFFFFFF1F) == 0x105){
314        }*/
315        if((state&0xFFFFFF00) == 0x100 && (state&0xFFFFFF1F) != 0x107 && (state&0xFFFFFF1F) != 0x108 && (state&0xFFFFFF1F) != 0x109){
316            if(has_sps){
317                while(i>4 && buf[i-5]==0) i--;
318                return i-4;
319            }
320        }
321        if (i<buf_size)
322            state= (state<<8) | buf[i];
323    }
324    return 0;
325}
326
327static void close(AVCodecParserContext *s)
328{
329    H264Context *h = s->priv_data;
330    ParseContext *pc = &h->s.parse_context;
331
332    av_free(pc->buffer);
333    ff_h264_free_context(h);
334}
335
336static int init(AVCodecParserContext *s)
337{
338    H264Context *h = s->priv_data;
339    h->thread_context[0] = h;
340    h->s.slice_context_count = 1;
341    return 0;
342}
343
344AVCodecParser ff_h264_parser = {
345    .codec_ids      = { CODEC_ID_H264 },
346    .priv_data_size = sizeof(H264Context),
347    .parser_init    = init,
348    .parser_parse   = h264_parse,
349    .parser_close   = close,
350    .split          = h264_split,
351};
352