1/*
2 * Audio and Video frame extraction
3 * Copyright (c) 2003 Fabrice Bellard
4 * Copyright (c) 2003 Michael Niedermayer
5 *
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23#include "parser.h"
24
25static AVCodecParser *av_first_parser = NULL;
26
27AVCodecParser* av_parser_next(AVCodecParser *p){
28    if(p) return p->next;
29    else  return av_first_parser;
30}
31
32void av_register_codec_parser(AVCodecParser *parser)
33{
34    parser->next = av_first_parser;
35    av_first_parser = parser;
36}
37
38AVCodecParserContext *av_parser_init(int codec_id)
39{
40    AVCodecParserContext *s;
41    AVCodecParser *parser;
42    int ret;
43
44    if(codec_id == CODEC_ID_NONE)
45        return NULL;
46
47    for(parser = av_first_parser; parser != NULL; parser = parser->next) {
48        if (parser->codec_ids[0] == codec_id ||
49            parser->codec_ids[1] == codec_id ||
50            parser->codec_ids[2] == codec_id ||
51            parser->codec_ids[3] == codec_id ||
52            parser->codec_ids[4] == codec_id)
53            goto found;
54    }
55    return NULL;
56 found:
57    s = av_mallocz(sizeof(AVCodecParserContext));
58    if (!s)
59        return NULL;
60    s->parser = parser;
61    s->priv_data = av_mallocz(parser->priv_data_size);
62    if (!s->priv_data) {
63        av_free(s);
64        return NULL;
65    }
66    if (parser->parser_init) {
67        ret = parser->parser_init(s);
68        if (ret != 0) {
69            av_free(s->priv_data);
70            av_free(s);
71            return NULL;
72        }
73    }
74    s->fetch_timestamp=1;
75    s->pict_type = FF_I_TYPE;
76    s->key_frame = -1;
77    s->convergence_duration = AV_NOPTS_VALUE;
78    s->dts_sync_point       = INT_MIN;
79    s->dts_ref_dts_delta    = INT_MIN;
80    s->pts_dts_delta        = INT_MIN;
81    return s;
82}
83
84void ff_fetch_timestamp(AVCodecParserContext *s, int off, int remove){
85    int i;
86
87    s->dts= s->pts= AV_NOPTS_VALUE;
88    s->pos= -1;
89    s->offset= 0;
90    for(i = 0; i < AV_PARSER_PTS_NB; i++) {
91        if (   s->cur_offset + off >= s->cur_frame_offset[i]
92            && (s->frame_offset < s->cur_frame_offset[i] ||
93              (!s->frame_offset && !s->next_frame_offset)) // first field/frame
94            //check is disabled  because mpeg-ts doesnt send complete PES packets
95            && /*s->next_frame_offset + off <*/  s->cur_frame_end[i]){
96            s->dts= s->cur_frame_dts[i];
97            s->pts= s->cur_frame_pts[i];
98            s->pos= s->cur_frame_pos[i];
99            s->offset = s->next_frame_offset - s->cur_frame_offset[i];
100            if(remove)
101                s->cur_frame_offset[i]= INT64_MAX;
102            if(s->cur_offset + off < s->cur_frame_end[i])
103                break;
104        }
105    }
106}
107
108/**
109 *
110 * @param buf           input
111 * @param buf_size      input length, to signal EOF, this should be 0 (so that the last frame can be output)
112 * @param pts           input presentation timestamp
113 * @param dts           input decoding timestamp
114 * @param poutbuf       will contain a pointer to the first byte of the output frame
115 * @param poutbuf_size  will contain the length of the output frame
116 * @return the number of bytes of the input bitstream used
117 *
118 * Example:
119 * @code
120 *   while(in_len){
121 *       len = av_parser_parse(myparser, AVCodecContext, &data, &size,
122 *                                       in_data, in_len,
123 *                                       pts, dts);
124 *       in_data += len;
125 *       in_len  -= len;
126 *
127 *       if(size)
128 *          decode_frame(data, size);
129 *   }
130 * @endcode
131 *
132 * @deprecated Use av_parser_parse2() instead.
133 */
134int av_parser_parse(AVCodecParserContext *s,
135                    AVCodecContext *avctx,
136                    uint8_t **poutbuf, int *poutbuf_size,
137                    const uint8_t *buf, int buf_size,
138                    int64_t pts, int64_t dts)
139{
140    return av_parser_parse2(s, avctx, poutbuf, poutbuf_size, buf, buf_size, pts, dts, AV_NOPTS_VALUE);
141}
142
143int av_parser_parse2(AVCodecParserContext *s,
144                     AVCodecContext *avctx,
145                     uint8_t **poutbuf, int *poutbuf_size,
146                     const uint8_t *buf, int buf_size,
147                     int64_t pts, int64_t dts,
148                     int64_t pos)
149{
150    int index, i;
151    uint8_t dummy_buf[FF_INPUT_BUFFER_PADDING_SIZE];
152
153    if (buf_size == 0) {
154        /* padding is always necessary even if EOF, so we add it here */
155        memset(dummy_buf, 0, sizeof(dummy_buf));
156        buf = dummy_buf;
157    } else if (s->cur_offset + buf_size !=
158               s->cur_frame_end[s->cur_frame_start_index]) { /* skip remainder packets */
159        /* add a new packet descriptor */
160            i = (s->cur_frame_start_index + 1) & (AV_PARSER_PTS_NB - 1);
161            s->cur_frame_start_index = i;
162            s->cur_frame_offset[i] = s->cur_offset;
163            s->cur_frame_end[i] = s->cur_offset + buf_size;
164            s->cur_frame_pts[i] = pts;
165            s->cur_frame_dts[i] = dts;
166            s->cur_frame_pos[i] = pos;
167    }
168
169    if (s->fetch_timestamp){
170        s->fetch_timestamp=0;
171        s->last_pts = s->pts;
172        s->last_dts = s->dts;
173        s->last_pos = s->pos;
174        ff_fetch_timestamp(s, 0, 0);
175    }
176
177    /* WARNING: the returned index can be negative */
178    index = s->parser->parser_parse(s, avctx, (const uint8_t **)poutbuf, poutbuf_size, buf, buf_size);
179//av_log(NULL, AV_LOG_DEBUG, "parser: in:%"PRId64", %"PRId64", out:%"PRId64", %"PRId64", in:%d out:%d id:%d\n", pts, dts, s->last_pts, s->last_dts, buf_size, *poutbuf_size, avctx->codec_id);
180    /* update the file pointer */
181    if (*poutbuf_size) {
182        /* fill the data for the current frame */
183        s->frame_offset = s->next_frame_offset;
184
185        /* offset of the next frame */
186        s->next_frame_offset = s->cur_offset + index;
187        s->fetch_timestamp=1;
188    }
189    if (index < 0)
190        index = 0;
191    s->cur_offset += index;
192    return index;
193}
194
195/**
196 *
197 * @return 0 if the output buffer is a subset of the input, 1 if it is allocated and must be freed
198 * @deprecated use AVBitstreamFilter
199 */
200int av_parser_change(AVCodecParserContext *s,
201                     AVCodecContext *avctx,
202                     uint8_t **poutbuf, int *poutbuf_size,
203                     const uint8_t *buf, int buf_size, int keyframe){
204
205    if(s && s->parser->split){
206        if((avctx->flags & CODEC_FLAG_GLOBAL_HEADER) || (avctx->flags2 & CODEC_FLAG2_LOCAL_HEADER)){
207            int i= s->parser->split(avctx, buf, buf_size);
208            buf += i;
209            buf_size -= i;
210        }
211    }
212
213    /* cast to avoid warning about discarding qualifiers */
214    *poutbuf= (uint8_t *) buf;
215    *poutbuf_size= buf_size;
216    if(avctx->extradata){
217        if(  (keyframe && (avctx->flags2 & CODEC_FLAG2_LOCAL_HEADER))
218            /*||(s->pict_type != FF_I_TYPE && (s->flags & PARSER_FLAG_DUMP_EXTRADATA_AT_NOKEY))*/
219            /*||(? && (s->flags & PARSER_FLAG_DUMP_EXTRADATA_AT_BEGIN)*/){
220            int size= buf_size + avctx->extradata_size;
221            *poutbuf_size= size;
222            *poutbuf= av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
223
224            memcpy(*poutbuf, avctx->extradata, avctx->extradata_size);
225            memcpy((*poutbuf) + avctx->extradata_size, buf, buf_size + FF_INPUT_BUFFER_PADDING_SIZE);
226            return 1;
227        }
228    }
229
230    return 0;
231}
232
233void av_parser_close(AVCodecParserContext *s)
234{
235    if(s){
236        if (s->parser->parser_close)
237            s->parser->parser_close(s);
238        av_free(s->priv_data);
239        av_free(s);
240    }
241}
242
243/*****************************************************/
244
245/**
246 * combines the (truncated) bitstream to a complete frame
247 * @return -1 if no complete frame could be created, AVERROR(ENOMEM) if there was a memory allocation error
248 */
249int ff_combine_frame(ParseContext *pc, int next, const uint8_t **buf, int *buf_size)
250{
251#if 0
252    if(pc->overread){
253        printf("overread %d, state:%X next:%d index:%d o_index:%d\n", pc->overread, pc->state, next, pc->index, pc->overread_index);
254        printf("%X %X %X %X\n", (*buf)[0], (*buf)[1],(*buf)[2],(*buf)[3]);
255    }
256#endif
257
258    /* Copy overread bytes from last frame into buffer. */
259    for(; pc->overread>0; pc->overread--){
260        pc->buffer[pc->index++]= pc->buffer[pc->overread_index++];
261    }
262
263    /* flush remaining if EOF */
264    if(!*buf_size && next == END_NOT_FOUND){
265        next= 0;
266    }
267
268    pc->last_index= pc->index;
269
270    /* copy into buffer end return */
271    if(next == END_NOT_FOUND){
272        void* new_buffer = av_fast_realloc(pc->buffer, &pc->buffer_size, (*buf_size) + pc->index + FF_INPUT_BUFFER_PADDING_SIZE);
273
274        if(!new_buffer)
275            return AVERROR(ENOMEM);
276        pc->buffer = new_buffer;
277        memcpy(&pc->buffer[pc->index], *buf, *buf_size);
278        pc->index += *buf_size;
279        return -1;
280    }
281
282    *buf_size=
283    pc->overread_index= pc->index + next;
284
285    /* append to buffer */
286    if(pc->index){
287        void* new_buffer = av_fast_realloc(pc->buffer, &pc->buffer_size, next + pc->index + FF_INPUT_BUFFER_PADDING_SIZE);
288
289        if(!new_buffer)
290            return AVERROR(ENOMEM);
291        pc->buffer = new_buffer;
292        memcpy(&pc->buffer[pc->index], *buf, next + FF_INPUT_BUFFER_PADDING_SIZE );
293        pc->index = 0;
294        *buf= pc->buffer;
295    }
296
297    /* store overread bytes */
298    for(;next < 0; next++){
299        pc->state = (pc->state<<8) | pc->buffer[pc->last_index + next];
300        pc->state64 = (pc->state64<<8) | pc->buffer[pc->last_index + next];
301        pc->overread++;
302    }
303
304#if 0
305    if(pc->overread){
306        printf("overread %d, state:%X next:%d index:%d o_index:%d\n", pc->overread, pc->state, next, pc->index, pc->overread_index);
307        printf("%X %X %X %X\n", (*buf)[0], (*buf)[1],(*buf)[2],(*buf)[3]);
308    }
309#endif
310
311    return 0;
312}
313
314void ff_parse_close(AVCodecParserContext *s)
315{
316    ParseContext *pc = s->priv_data;
317
318    av_freep(&pc->buffer);
319}
320
321void ff_parse1_close(AVCodecParserContext *s)
322{
323    ParseContext1 *pc1 = s->priv_data;
324
325    av_free(pc1->pc.buffer);
326    av_free(pc1->enc);
327}
328
329/*************************/
330
331int ff_mpeg4video_split(AVCodecContext *avctx,
332                           const uint8_t *buf, int buf_size)
333{
334    int i;
335    uint32_t state= -1;
336
337    for(i=0; i<buf_size; i++){
338        state= (state<<8) | buf[i];
339        if(state == 0x1B3 || state == 0x1B6)
340            return i-3;
341    }
342    return 0;
343}
344