]> git.sesse.net Git - ffmpeg/blob - libavcodec/parser.c
Fixes:
[ffmpeg] / libavcodec / parser.c
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 #include "avcodec.h"
23 #include "mpegvideo.h"
24 #include "mpegaudio.h"
25
26 AVCodecParser *av_first_parser = NULL;
27
28 void av_register_codec_parser(AVCodecParser *parser)
29 {
30     parser->next = av_first_parser;
31     av_first_parser = parser;
32 }
33
34 AVCodecParserContext *av_parser_init(int codec_id)
35 {
36     AVCodecParserContext *s;
37     AVCodecParser *parser;
38     int ret;
39
40     if(codec_id == CODEC_ID_NONE)
41         return NULL;
42
43     for(parser = av_first_parser; parser != NULL; parser = parser->next) {
44         if (parser->codec_ids[0] == codec_id ||
45             parser->codec_ids[1] == codec_id ||
46             parser->codec_ids[2] == codec_id ||
47             parser->codec_ids[3] == codec_id ||
48             parser->codec_ids[4] == codec_id)
49             goto found;
50     }
51     return NULL;
52  found:
53     s = av_mallocz(sizeof(AVCodecParserContext));
54     if (!s)
55         return NULL;
56     s->parser = parser;
57     s->priv_data = av_mallocz(parser->priv_data_size);
58     if (!s->priv_data) {
59         av_free(s);
60         return NULL;
61     }
62     if (parser->parser_init) {
63         ret = parser->parser_init(s);
64         if (ret != 0) {
65             av_free(s->priv_data);
66             av_free(s);
67             return NULL;
68         }
69     }
70     s->fetch_timestamp=1;
71     return s;
72 }
73
74 /* NOTE: buf_size == 0 is used to signal EOF so that the last frame
75    can be returned if necessary */
76 int av_parser_parse(AVCodecParserContext *s,
77                     AVCodecContext *avctx,
78                     uint8_t **poutbuf, int *poutbuf_size,
79                     const uint8_t *buf, int buf_size,
80                     int64_t pts, int64_t dts)
81 {
82     int index, i, k;
83     uint8_t dummy_buf[FF_INPUT_BUFFER_PADDING_SIZE];
84
85     if (buf_size == 0) {
86         /* padding is always necessary even if EOF, so we add it here */
87         memset(dummy_buf, 0, sizeof(dummy_buf));
88         buf = dummy_buf;
89     } else {
90         /* add a new packet descriptor */
91         k = (s->cur_frame_start_index + 1) & (AV_PARSER_PTS_NB - 1);
92         s->cur_frame_start_index = k;
93         s->cur_frame_offset[k] = s->cur_offset;
94         s->cur_frame_pts[k] = pts;
95         s->cur_frame_dts[k] = dts;
96
97         /* fill first PTS/DTS */
98         if (s->fetch_timestamp){
99             s->fetch_timestamp=0;
100             s->last_pts = pts;
101             s->last_dts = dts;
102             s->cur_frame_pts[k] =
103             s->cur_frame_dts[k] = AV_NOPTS_VALUE;
104         }
105     }
106
107     /* WARNING: the returned index can be negative */
108     index = s->parser->parser_parse(s, avctx, poutbuf, poutbuf_size, buf, buf_size);
109 //av_log(NULL, AV_LOG_DEBUG, "parser: in:%lld, %lld, out:%lld, %lld, in:%d out:%d id:%d\n", pts, dts, s->last_pts, s->last_dts, buf_size, *poutbuf_size, avctx->codec_id);
110     /* update the file pointer */
111     if (*poutbuf_size) {
112         /* fill the data for the current frame */
113         s->frame_offset = s->last_frame_offset;
114         s->pts = s->last_pts;
115         s->dts = s->last_dts;
116
117         /* offset of the next frame */
118         s->last_frame_offset = s->cur_offset + index;
119         /* find the packet in which the new frame starts. It
120            is tricky because of MPEG video start codes
121            which can begin in one packet and finish in
122            another packet. In the worst case, an MPEG
123            video start code could be in 4 different
124            packets. */
125         k = s->cur_frame_start_index;
126         for(i = 0; i < AV_PARSER_PTS_NB; i++) {
127             if (s->last_frame_offset >= s->cur_frame_offset[k])
128                 break;
129             k = (k - 1) & (AV_PARSER_PTS_NB - 1);
130         }
131
132         s->last_pts = s->cur_frame_pts[k];
133         s->last_dts = s->cur_frame_dts[k];
134
135         /* some parsers tell us the packet size even before seeing the first byte of the next packet,
136            so the next pts/dts is in the next chunk */
137         if(index == buf_size){
138             s->fetch_timestamp=1;
139         }
140     }
141     if (index < 0)
142         index = 0;
143     s->cur_offset += index;
144     return index;
145 }
146
147 /**
148  *
149  * @return 0 if the output buffer is a subset of the input, 1 if it is allocated and must be freed
150  * @deprecated use AVBitstreamFilter
151  */
152 int av_parser_change(AVCodecParserContext *s,
153                      AVCodecContext *avctx,
154                      uint8_t **poutbuf, int *poutbuf_size,
155                      const uint8_t *buf, int buf_size, int keyframe){
156
157     if(s && s->parser->split){
158         if((avctx->flags & CODEC_FLAG_GLOBAL_HEADER) || (avctx->flags2 & CODEC_FLAG2_LOCAL_HEADER)){
159             int i= s->parser->split(avctx, buf, buf_size);
160             buf += i;
161             buf_size -= i;
162         }
163     }
164
165     /* cast to avoid warning about discarding qualifiers */
166     *poutbuf= (uint8_t *) buf;
167     *poutbuf_size= buf_size;
168     if(avctx->extradata){
169         if(  (keyframe && (avctx->flags2 & CODEC_FLAG2_LOCAL_HEADER))
170             /*||(s->pict_type != I_TYPE && (s->flags & PARSER_FLAG_DUMP_EXTRADATA_AT_NOKEY))*/
171             /*||(? && (s->flags & PARSER_FLAG_DUMP_EXTRADATA_AT_BEGIN)*/){
172             int size= buf_size + avctx->extradata_size;
173             *poutbuf_size= size;
174             *poutbuf= av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
175
176             memcpy(*poutbuf, avctx->extradata, avctx->extradata_size);
177             memcpy((*poutbuf) + avctx->extradata_size, buf, buf_size + FF_INPUT_BUFFER_PADDING_SIZE);
178             return 1;
179         }
180     }
181
182     return 0;
183 }
184
185 void av_parser_close(AVCodecParserContext *s)
186 {
187     if (s->parser->parser_close)
188         s->parser->parser_close(s);
189     av_free(s->priv_data);
190     av_free(s);
191 }
192
193 /*****************************************************/
194
195 //#define END_NOT_FOUND (-100)
196
197 #define PICTURE_START_CODE      0x00000100
198 #define SEQ_START_CODE          0x000001b3
199 #define EXT_START_CODE          0x000001b5
200 #define SLICE_MIN_START_CODE    0x00000101
201 #define SLICE_MAX_START_CODE    0x000001af
202
203 typedef struct ParseContext1{
204     ParseContext pc;
205 /* XXX/FIXME PC1 vs. PC */
206     /* MPEG2 specific */
207     int frame_rate;
208     int progressive_sequence;
209     int width, height;
210
211     /* XXX: suppress that, needed by MPEG4 */
212     MpegEncContext *enc;
213     int first_picture;
214 } ParseContext1;
215
216 /**
217  * combines the (truncated) bitstream to a complete frame
218  * @returns -1 if no complete frame could be created
219  */
220 int ff_combine_frame(ParseContext *pc, int next, uint8_t **buf, int *buf_size)
221 {
222 #if 0
223     if(pc->overread){
224         printf("overread %d, state:%X next:%d index:%d o_index:%d\n", pc->overread, pc->state, next, pc->index, pc->overread_index);
225         printf("%X %X %X %X\n", (*buf)[0], (*buf)[1],(*buf)[2],(*buf)[3]);
226     }
227 #endif
228
229     /* copy overreaded bytes from last frame into buffer */
230     for(; pc->overread>0; pc->overread--){
231         pc->buffer[pc->index++]= pc->buffer[pc->overread_index++];
232     }
233
234     /* flush remaining if EOF */
235     if(!*buf_size && next == END_NOT_FOUND){
236         next= 0;
237     }
238
239     pc->last_index= pc->index;
240
241     /* copy into buffer end return */
242     if(next == END_NOT_FOUND){
243         pc->buffer= av_fast_realloc(pc->buffer, &pc->buffer_size, (*buf_size) + pc->index + FF_INPUT_BUFFER_PADDING_SIZE);
244
245         memcpy(&pc->buffer[pc->index], *buf, *buf_size);
246         pc->index += *buf_size;
247         return -1;
248     }
249
250     *buf_size=
251     pc->overread_index= pc->index + next;
252
253     /* append to buffer */
254     if(pc->index){
255         pc->buffer= av_fast_realloc(pc->buffer, &pc->buffer_size, next + pc->index + FF_INPUT_BUFFER_PADDING_SIZE);
256
257         memcpy(&pc->buffer[pc->index], *buf, next + FF_INPUT_BUFFER_PADDING_SIZE );
258         pc->index = 0;
259         *buf= pc->buffer;
260     }
261
262     /* store overread bytes */
263     for(;next < 0; next++){
264         pc->state = (pc->state<<8) | pc->buffer[pc->last_index + next];
265         pc->overread++;
266     }
267
268 #if 0
269     if(pc->overread){
270         printf("overread %d, state:%X next:%d index:%d o_index:%d\n", pc->overread, pc->state, next, pc->index, pc->overread_index);
271         printf("%X %X %X %X\n", (*buf)[0], (*buf)[1],(*buf)[2],(*buf)[3]);
272     }
273 #endif
274
275     return 0;
276 }
277
278 /* XXX: merge with libavcodec ? */
279 #define MPEG1_FRAME_RATE_BASE 1001
280
281 static const int frame_rate_tab[16] = {
282         0,
283     24000,
284     24024,
285     25025,
286     30000,
287     30030,
288     50050,
289     60000,
290     60060,
291   // Xing's 15fps: (9)
292     15015,
293   // libmpeg3's "Unofficial economy rates": (10-13)
294      5005,
295     10010,
296     12012,
297     15015,
298   // random, just to avoid segfault !never encode these
299     25025,
300     25025,
301 };
302
303 #ifdef CONFIG_MPEGVIDEO_PARSER
304 //FIXME move into mpeg12.c
305 static void mpegvideo_extract_headers(AVCodecParserContext *s,
306                                       AVCodecContext *avctx,
307                                       const uint8_t *buf, int buf_size)
308 {
309     ParseContext1 *pc = s->priv_data;
310     const uint8_t *buf_end;
311     uint32_t start_code;
312     int frame_rate_index, ext_type, bytes_left;
313     int frame_rate_ext_n, frame_rate_ext_d;
314     int picture_structure, top_field_first, repeat_first_field, progressive_frame;
315     int horiz_size_ext, vert_size_ext, bit_rate_ext;
316 //FIXME replace the crap with get_bits()
317     s->repeat_pict = 0;
318     buf_end = buf + buf_size;
319     while (buf < buf_end) {
320         start_code= -1;
321         buf= ff_find_start_code(buf, buf_end, &start_code);
322         bytes_left = buf_end - buf;
323         switch(start_code) {
324         case PICTURE_START_CODE:
325             if (bytes_left >= 2) {
326                 s->pict_type = (buf[1] >> 3) & 7;
327             }
328             break;
329         case SEQ_START_CODE:
330             if (bytes_left >= 7) {
331                 pc->width  = (buf[0] << 4) | (buf[1] >> 4);
332                 pc->height = ((buf[1] & 0x0f) << 8) | buf[2];
333                 avcodec_set_dimensions(avctx, pc->width, pc->height);
334                 frame_rate_index = buf[3] & 0xf;
335                 pc->frame_rate = avctx->time_base.den = frame_rate_tab[frame_rate_index];
336                 avctx->time_base.num = MPEG1_FRAME_RATE_BASE;
337                 avctx->bit_rate = ((buf[4]<<10) | (buf[5]<<2) | (buf[6]>>6))*400;
338                 avctx->codec_id = CODEC_ID_MPEG1VIDEO;
339                 avctx->sub_id = 1;
340             }
341             break;
342         case EXT_START_CODE:
343             if (bytes_left >= 1) {
344                 ext_type = (buf[0] >> 4);
345                 switch(ext_type) {
346                 case 0x1: /* sequence extension */
347                     if (bytes_left >= 6) {
348                         horiz_size_ext = ((buf[1] & 1) << 1) | (buf[2] >> 7);
349                         vert_size_ext = (buf[2] >> 5) & 3;
350                         bit_rate_ext = ((buf[2] & 0x1F)<<7) | (buf[3]>>1);
351                         frame_rate_ext_n = (buf[5] >> 5) & 3;
352                         frame_rate_ext_d = (buf[5] & 0x1f);
353                         pc->progressive_sequence = buf[1] & (1 << 3);
354                         avctx->has_b_frames= !(buf[5] >> 7);
355
356                         pc->width  |=(horiz_size_ext << 12);
357                         pc->height |=( vert_size_ext << 12);
358                         avctx->bit_rate += (bit_rate_ext << 18) * 400;
359                         avcodec_set_dimensions(avctx, pc->width, pc->height);
360                         avctx->time_base.den = pc->frame_rate * (frame_rate_ext_n + 1);
361                         avctx->time_base.num = MPEG1_FRAME_RATE_BASE * (frame_rate_ext_d + 1);
362                         avctx->codec_id = CODEC_ID_MPEG2VIDEO;
363                         avctx->sub_id = 2; /* forces MPEG2 */
364                     }
365                     break;
366                 case 0x8: /* picture coding extension */
367                     if (bytes_left >= 5) {
368                         picture_structure = buf[2]&3;
369                         top_field_first = buf[3] & (1 << 7);
370                         repeat_first_field = buf[3] & (1 << 1);
371                         progressive_frame = buf[4] & (1 << 7);
372
373                         /* check if we must repeat the frame */
374                         if (repeat_first_field) {
375                             if (pc->progressive_sequence) {
376                                 if (top_field_first)
377                                     s->repeat_pict = 4;
378                                 else
379                                     s->repeat_pict = 2;
380                             } else if (progressive_frame) {
381                                 s->repeat_pict = 1;
382                             }
383                         }
384
385                         /* the packet only represents half a frame
386                            XXX,FIXME maybe find a different solution */
387                         if(picture_structure != 3)
388                             s->repeat_pict = -1;
389                     }
390                     break;
391                 }
392             }
393             break;
394         case -1:
395             goto the_end;
396         default:
397             /* we stop parsing when we encounter a slice. It ensures
398                that this function takes a negligible amount of time */
399             if (start_code >= SLICE_MIN_START_CODE &&
400                 start_code <= SLICE_MAX_START_CODE)
401                 goto the_end;
402             break;
403         }
404     }
405  the_end: ;
406 }
407
408 static int mpegvideo_parse(AVCodecParserContext *s,
409                            AVCodecContext *avctx,
410                            uint8_t **poutbuf, int *poutbuf_size,
411                            const uint8_t *buf, int buf_size)
412 {
413     ParseContext1 *pc1 = s->priv_data;
414     ParseContext *pc= &pc1->pc;
415     int next;
416
417     if(s->flags & PARSER_FLAG_COMPLETE_FRAMES){
418         next= buf_size;
419     }else{
420         next= ff_mpeg1_find_frame_end(pc, buf, buf_size);
421
422         if (ff_combine_frame(pc, next, (uint8_t **)&buf, &buf_size) < 0) {
423             *poutbuf = NULL;
424             *poutbuf_size = 0;
425             return buf_size;
426         }
427
428     }
429     /* we have a full frame : we just parse the first few MPEG headers
430        to have the full timing information. The time take by this
431        function should be negligible for uncorrupted streams */
432     mpegvideo_extract_headers(s, avctx, buf, buf_size);
433 #if 0
434     printf("pict_type=%d frame_rate=%0.3f repeat_pict=%d\n",
435            s->pict_type, (double)avctx->time_base.den / avctx->time_base.num, s->repeat_pict);
436 #endif
437
438     *poutbuf = (uint8_t *)buf;
439     *poutbuf_size = buf_size;
440     return next;
441 }
442
443 static int mpegvideo_split(AVCodecContext *avctx,
444                            const uint8_t *buf, int buf_size)
445 {
446     int i;
447     uint32_t state= -1;
448
449     for(i=0; i<buf_size; i++){
450         state= (state<<8) | buf[i];
451         if(state != 0x1B3 && state != 0x1B5 && state < 0x200 && state >= 0x100)
452             return i-3;
453     }
454     return 0;
455 }
456 #endif /* CONFIG_MPEGVIDEO_PARSER */
457
458 void ff_parse_close(AVCodecParserContext *s)
459 {
460     ParseContext *pc = s->priv_data;
461
462     av_free(pc->buffer);
463 }
464
465 static void parse1_close(AVCodecParserContext *s)
466 {
467     ParseContext1 *pc1 = s->priv_data;
468
469     av_free(pc1->pc.buffer);
470     av_free(pc1->enc);
471 }
472
473 /*************************/
474
475 #ifdef CONFIG_MPEG4VIDEO_PARSER
476 /* used by parser */
477 /* XXX: make it use less memory */
478 static int av_mpeg4_decode_header(AVCodecParserContext *s1,
479                                   AVCodecContext *avctx,
480                                   const uint8_t *buf, int buf_size)
481 {
482     ParseContext1 *pc = s1->priv_data;
483     MpegEncContext *s = pc->enc;
484     GetBitContext gb1, *gb = &gb1;
485     int ret;
486
487     s->avctx = avctx;
488     s->current_picture_ptr = &s->current_picture;
489
490     if (avctx->extradata_size && pc->first_picture){
491         init_get_bits(gb, avctx->extradata, avctx->extradata_size*8);
492         ret = ff_mpeg4_decode_picture_header(s, gb);
493     }
494
495     init_get_bits(gb, buf, 8 * buf_size);
496     ret = ff_mpeg4_decode_picture_header(s, gb);
497     if (s->width) {
498         avcodec_set_dimensions(avctx, s->width, s->height);
499     }
500     s1->pict_type= s->pict_type;
501     pc->first_picture = 0;
502     return ret;
503 }
504
505 static int mpeg4video_parse_init(AVCodecParserContext *s)
506 {
507     ParseContext1 *pc = s->priv_data;
508
509     pc->enc = av_mallocz(sizeof(MpegEncContext));
510     if (!pc->enc)
511         return -1;
512     pc->first_picture = 1;
513     return 0;
514 }
515
516 static int mpeg4video_parse(AVCodecParserContext *s,
517                            AVCodecContext *avctx,
518                            uint8_t **poutbuf, int *poutbuf_size,
519                            const uint8_t *buf, int buf_size)
520 {
521     ParseContext *pc = s->priv_data;
522     int next;
523
524     if(s->flags & PARSER_FLAG_COMPLETE_FRAMES){
525         next= buf_size;
526     }else{
527         next= ff_mpeg4_find_frame_end(pc, buf, buf_size);
528
529         if (ff_combine_frame(pc, next, (uint8_t **)&buf, &buf_size) < 0) {
530             *poutbuf = NULL;
531             *poutbuf_size = 0;
532             return buf_size;
533         }
534     }
535     av_mpeg4_decode_header(s, avctx, buf, buf_size);
536
537     *poutbuf = (uint8_t *)buf;
538     *poutbuf_size = buf_size;
539     return next;
540 }
541 #endif
542
543 #ifdef CONFIG_CAVSVIDEO_PARSER
544 static int cavsvideo_parse(AVCodecParserContext *s,
545                            AVCodecContext *avctx,
546                            uint8_t **poutbuf, int *poutbuf_size,
547                            const uint8_t *buf, int buf_size)
548 {
549     ParseContext *pc = s->priv_data;
550     int next;
551
552     if(s->flags & PARSER_FLAG_COMPLETE_FRAMES){
553         next= buf_size;
554     }else{
555         next= ff_cavs_find_frame_end(pc, buf, buf_size);
556
557         if (ff_combine_frame(pc, next, (uint8_t **)&buf, &buf_size) < 0) {
558             *poutbuf = NULL;
559             *poutbuf_size = 0;
560             return buf_size;
561         }
562     }
563     *poutbuf = (uint8_t *)buf;
564     *poutbuf_size = buf_size;
565     return next;
566 }
567 #endif /* CONFIG_CAVSVIDEO_PARSER */
568
569 static int mpeg4video_split(AVCodecContext *avctx,
570                            const uint8_t *buf, int buf_size)
571 {
572     int i;
573     uint32_t state= -1;
574
575     for(i=0; i<buf_size; i++){
576         state= (state<<8) | buf[i];
577         if(state == 0x1B3 || state == 0x1B6)
578             return i-3;
579     }
580     return 0;
581 }
582
583 /*************************/
584
585 #ifdef CONFIG_MPEGAUDIO_PARSER
586 typedef struct MpegAudioParseContext {
587     uint8_t inbuf[MPA_MAX_CODED_FRAME_SIZE];    /* input buffer */
588     uint8_t *inbuf_ptr;
589     int frame_size;
590     int free_format_frame_size;
591     int free_format_next_header;
592     uint32_t header;
593     int header_count;
594 } MpegAudioParseContext;
595
596 #define MPA_HEADER_SIZE 4
597
598 /* header + layer + bitrate + freq + lsf/mpeg25 */
599 #undef SAME_HEADER_MASK /* mpegaudio.h defines different version */
600 #define SAME_HEADER_MASK \
601    (0xffe00000 | (3 << 17) | (3 << 10) | (3 << 19))
602
603 static int mpegaudio_parse_init(AVCodecParserContext *s1)
604 {
605     MpegAudioParseContext *s = s1->priv_data;
606     s->inbuf_ptr = s->inbuf;
607     return 0;
608 }
609
610 static int mpegaudio_parse(AVCodecParserContext *s1,
611                            AVCodecContext *avctx,
612                            uint8_t **poutbuf, int *poutbuf_size,
613                            const uint8_t *buf, int buf_size)
614 {
615     MpegAudioParseContext *s = s1->priv_data;
616     int len, ret, sr;
617     uint32_t header;
618     const uint8_t *buf_ptr;
619
620     *poutbuf = NULL;
621     *poutbuf_size = 0;
622     buf_ptr = buf;
623     while (buf_size > 0) {
624         len = s->inbuf_ptr - s->inbuf;
625         if (s->frame_size == 0) {
626             /* special case for next header for first frame in free
627                format case (XXX: find a simpler method) */
628             if (s->free_format_next_header != 0) {
629                 s->inbuf[0] = s->free_format_next_header >> 24;
630                 s->inbuf[1] = s->free_format_next_header >> 16;
631                 s->inbuf[2] = s->free_format_next_header >> 8;
632                 s->inbuf[3] = s->free_format_next_header;
633                 s->inbuf_ptr = s->inbuf + 4;
634                 s->free_format_next_header = 0;
635                 goto got_header;
636             }
637             /* no header seen : find one. We need at least MPA_HEADER_SIZE
638                bytes to parse it */
639             len = FFMIN(MPA_HEADER_SIZE - len, buf_size);
640             if (len > 0) {
641                 memcpy(s->inbuf_ptr, buf_ptr, len);
642                 buf_ptr += len;
643                 buf_size -= len;
644                 s->inbuf_ptr += len;
645             }
646             if ((s->inbuf_ptr - s->inbuf) >= MPA_HEADER_SIZE) {
647             got_header:
648                 sr= avctx->sample_rate;
649                 header = (s->inbuf[0] << 24) | (s->inbuf[1] << 16) |
650                     (s->inbuf[2] << 8) | s->inbuf[3];
651
652                 ret = mpa_decode_header(avctx, header);
653                 if (ret < 0) {
654                     s->header_count= -2;
655                     /* no sync found : move by one byte (inefficient, but simple!) */
656                     memmove(s->inbuf, s->inbuf + 1, s->inbuf_ptr - s->inbuf - 1);
657                     s->inbuf_ptr--;
658                     dprintf("skip %x\n", header);
659                     /* reset free format frame size to give a chance
660                        to get a new bitrate */
661                     s->free_format_frame_size = 0;
662                 } else {
663                     if((header&SAME_HEADER_MASK) != (s->header&SAME_HEADER_MASK) && s->header)
664                         s->header_count= -3;
665                     s->header= header;
666                     s->header_count++;
667                     s->frame_size = ret;
668
669 #if 0
670                     /* free format: prepare to compute frame size */
671                     if (decode_header(s, header) == 1) {
672                         s->frame_size = -1;
673                     }
674 #endif
675                 }
676                 if(s->header_count <= 0)
677                     avctx->sample_rate= sr; //FIXME ugly
678             }
679         } else
680 #if 0
681         if (s->frame_size == -1) {
682             /* free format : find next sync to compute frame size */
683             len = MPA_MAX_CODED_FRAME_SIZE - len;
684             if (len > buf_size)
685                 len = buf_size;
686             if (len == 0) {
687                 /* frame too long: resync */
688                 s->frame_size = 0;
689                 memmove(s->inbuf, s->inbuf + 1, s->inbuf_ptr - s->inbuf - 1);
690                 s->inbuf_ptr--;
691             } else {
692                 uint8_t *p, *pend;
693                 uint32_t header1;
694                 int padding;
695
696                 memcpy(s->inbuf_ptr, buf_ptr, len);
697                 /* check for header */
698                 p = s->inbuf_ptr - 3;
699                 pend = s->inbuf_ptr + len - 4;
700                 while (p <= pend) {
701                     header = (p[0] << 24) | (p[1] << 16) |
702                         (p[2] << 8) | p[3];
703                     header1 = (s->inbuf[0] << 24) | (s->inbuf[1] << 16) |
704                         (s->inbuf[2] << 8) | s->inbuf[3];
705                     /* check with high probability that we have a
706                        valid header */
707                     if ((header & SAME_HEADER_MASK) ==
708                         (header1 & SAME_HEADER_MASK)) {
709                         /* header found: update pointers */
710                         len = (p + 4) - s->inbuf_ptr;
711                         buf_ptr += len;
712                         buf_size -= len;
713                         s->inbuf_ptr = p;
714                         /* compute frame size */
715                         s->free_format_next_header = header;
716                         s->free_format_frame_size = s->inbuf_ptr - s->inbuf;
717                         padding = (header1 >> 9) & 1;
718                         if (s->layer == 1)
719                             s->free_format_frame_size -= padding * 4;
720                         else
721                             s->free_format_frame_size -= padding;
722                         dprintf("free frame size=%d padding=%d\n",
723                                 s->free_format_frame_size, padding);
724                         decode_header(s, header1);
725                         goto next_data;
726                     }
727                     p++;
728                 }
729                 /* not found: simply increase pointers */
730                 buf_ptr += len;
731                 s->inbuf_ptr += len;
732                 buf_size -= len;
733             }
734         } else
735 #endif
736         if (len < s->frame_size) {
737             if (s->frame_size > MPA_MAX_CODED_FRAME_SIZE)
738                 s->frame_size = MPA_MAX_CODED_FRAME_SIZE;
739             len = FFMIN(s->frame_size - len, buf_size);
740             memcpy(s->inbuf_ptr, buf_ptr, len);
741             buf_ptr += len;
742             s->inbuf_ptr += len;
743             buf_size -= len;
744         }
745
746         if(s->frame_size > 0 && buf_ptr - buf == s->inbuf_ptr - s->inbuf
747            && buf_size + buf_ptr - buf >= s->frame_size){
748             if(s->header_count > 0){
749                 *poutbuf = buf;
750                 *poutbuf_size = s->frame_size;
751             }
752             buf_ptr = buf + s->frame_size;
753             s->inbuf_ptr = s->inbuf;
754             s->frame_size = 0;
755             break;
756         }
757
758         //    next_data:
759         if (s->frame_size > 0 &&
760             (s->inbuf_ptr - s->inbuf) >= s->frame_size) {
761             if(s->header_count > 0){
762                 *poutbuf = s->inbuf;
763                 *poutbuf_size = s->inbuf_ptr - s->inbuf;
764             }
765             s->inbuf_ptr = s->inbuf;
766             s->frame_size = 0;
767             break;
768         }
769     }
770     return buf_ptr - buf;
771 }
772 #endif /* CONFIG_MPEGAUDIO_PARSER */
773
774 #if defined(CONFIG_AC3_PARSER) || defined(CONFIG_AAC_PARSER)
775 /* also used for ADTS AAC */
776 typedef struct AC3ParseContext {
777     uint8_t *inbuf_ptr;
778     int frame_size;
779     int header_size;
780     int (*sync)(const uint8_t *buf, int *channels, int *sample_rate,
781                 int *bit_rate, int *samples);
782     uint8_t inbuf[8192]; /* input buffer */
783 } AC3ParseContext;
784
785 #define AC3_HEADER_SIZE 7
786 #define AAC_HEADER_SIZE 7
787
788 #ifdef CONFIG_AC3_PARSER
789 static const int ac3_sample_rates[4] = {
790     48000, 44100, 32000, 0
791 };
792
793 static const int ac3_frame_sizes[64][3] = {
794     { 64,   69,   96   },
795     { 64,   70,   96   },
796     { 80,   87,   120  },
797     { 80,   88,   120  },
798     { 96,   104,  144  },
799     { 96,   105,  144  },
800     { 112,  121,  168  },
801     { 112,  122,  168  },
802     { 128,  139,  192  },
803     { 128,  140,  192  },
804     { 160,  174,  240  },
805     { 160,  175,  240  },
806     { 192,  208,  288  },
807     { 192,  209,  288  },
808     { 224,  243,  336  },
809     { 224,  244,  336  },
810     { 256,  278,  384  },
811     { 256,  279,  384  },
812     { 320,  348,  480  },
813     { 320,  349,  480  },
814     { 384,  417,  576  },
815     { 384,  418,  576  },
816     { 448,  487,  672  },
817     { 448,  488,  672  },
818     { 512,  557,  768  },
819     { 512,  558,  768  },
820     { 640,  696,  960  },
821     { 640,  697,  960  },
822     { 768,  835,  1152 },
823     { 768,  836,  1152 },
824     { 896,  975,  1344 },
825     { 896,  976,  1344 },
826     { 1024, 1114, 1536 },
827     { 1024, 1115, 1536 },
828     { 1152, 1253, 1728 },
829     { 1152, 1254, 1728 },
830     { 1280, 1393, 1920 },
831     { 1280, 1394, 1920 },
832 };
833
834 static const int ac3_bitrates[64] = {
835     32, 32, 40, 40, 48, 48, 56, 56, 64, 64, 80, 80, 96, 96, 112, 112,
836     128, 128, 160, 160, 192, 192, 224, 224, 256, 256, 320, 320, 384,
837     384, 448, 448, 512, 512, 576, 576, 640, 640,
838 };
839
840 static const int ac3_channels[8] = {
841     2, 1, 2, 3, 3, 4, 4, 5
842 };
843 #endif /* CONFIG_AC3_PARSER */
844
845 #ifdef CONFIG_AAC_PARSER
846 static const int aac_sample_rates[16] = {
847     96000, 88200, 64000, 48000, 44100, 32000,
848     24000, 22050, 16000, 12000, 11025, 8000, 7350
849 };
850
851 static const int aac_channels[8] = {
852     0, 1, 2, 3, 4, 5, 6, 8
853 };
854 #endif
855
856 #ifdef CONFIG_AC3_PARSER
857 static int ac3_sync(const uint8_t *buf, int *channels, int *sample_rate,
858                     int *bit_rate, int *samples)
859 {
860     unsigned int fscod, frmsizecod, acmod, bsid, lfeon;
861     GetBitContext bits;
862
863     init_get_bits(&bits, buf, AC3_HEADER_SIZE * 8);
864
865     if(get_bits(&bits, 16) != 0x0b77)
866         return 0;
867
868     skip_bits(&bits, 16);       /* crc */
869     fscod = get_bits(&bits, 2);
870     frmsizecod = get_bits(&bits, 6);
871
872     if(!ac3_sample_rates[fscod])
873         return 0;
874
875     bsid = get_bits(&bits, 5);
876     if(bsid > 8)
877         return 0;
878     skip_bits(&bits, 3);        /* bsmod */
879     acmod = get_bits(&bits, 3);
880     if(acmod & 1 && acmod != 1)
881         skip_bits(&bits, 2);    /* cmixlev */
882     if(acmod & 4)
883         skip_bits(&bits, 2);    /* surmixlev */
884     if(acmod & 2)
885         skip_bits(&bits, 2);    /* dsurmod */
886     lfeon = get_bits1(&bits);
887
888     *sample_rate = ac3_sample_rates[fscod];
889     *bit_rate = ac3_bitrates[frmsizecod] * 1000;
890     *channels = ac3_channels[acmod] + lfeon;
891     *samples = 6 * 256;
892
893     return ac3_frame_sizes[frmsizecod][fscod] * 2;
894 }
895 #endif /* CONFIG_AC3_PARSER */
896
897 #ifdef CONFIG_AAC_PARSER
898 static int aac_sync(const uint8_t *buf, int *channels, int *sample_rate,
899                     int *bit_rate, int *samples)
900 {
901     GetBitContext bits;
902     int size, rdb, ch, sr;
903
904     init_get_bits(&bits, buf, AAC_HEADER_SIZE * 8);
905
906     if(get_bits(&bits, 12) != 0xfff)
907         return 0;
908
909     skip_bits1(&bits);          /* id */
910     skip_bits(&bits, 2);        /* layer */
911     skip_bits1(&bits);          /* protection_absent */
912     skip_bits(&bits, 2);        /* profile_objecttype */
913     sr = get_bits(&bits, 4);    /* sample_frequency_index */
914     if(!aac_sample_rates[sr])
915         return 0;
916     skip_bits1(&bits);          /* private_bit */
917     ch = get_bits(&bits, 3);    /* channel_configuration */
918     if(!aac_channels[ch])
919         return 0;
920     skip_bits1(&bits);          /* original/copy */
921     skip_bits1(&bits);          /* home */
922
923     /* adts_variable_header */
924     skip_bits1(&bits);          /* copyright_identification_bit */
925     skip_bits1(&bits);          /* copyright_identification_start */
926     size = get_bits(&bits, 13); /* aac_frame_length */
927     skip_bits(&bits, 11);       /* adts_buffer_fullness */
928     rdb = get_bits(&bits, 2);   /* number_of_raw_data_blocks_in_frame */
929
930     *channels = aac_channels[ch];
931     *sample_rate = aac_sample_rates[sr];
932     *samples = (rdb + 1) * 1024;
933     *bit_rate = size * 8 * *sample_rate / *samples;
934
935     return size;
936 }
937 #endif /* CONFIG_AAC_PARSER */
938
939 #ifdef CONFIG_AC3_PARSER
940 static int ac3_parse_init(AVCodecParserContext *s1)
941 {
942     AC3ParseContext *s = s1->priv_data;
943     s->inbuf_ptr = s->inbuf;
944     s->header_size = AC3_HEADER_SIZE;
945     s->sync = ac3_sync;
946     return 0;
947 }
948 #endif
949
950 #ifdef CONFIG_AAC_PARSER
951 static int aac_parse_init(AVCodecParserContext *s1)
952 {
953     AC3ParseContext *s = s1->priv_data;
954     s->inbuf_ptr = s->inbuf;
955     s->header_size = AAC_HEADER_SIZE;
956     s->sync = aac_sync;
957     return 0;
958 }
959 #endif
960
961 /* also used for ADTS AAC */
962 static int ac3_parse(AVCodecParserContext *s1,
963                      AVCodecContext *avctx,
964                      uint8_t **poutbuf, int *poutbuf_size,
965                      const uint8_t *buf, int buf_size)
966 {
967     AC3ParseContext *s = s1->priv_data;
968     const uint8_t *buf_ptr;
969     int len, sample_rate, bit_rate, channels, samples;
970
971     *poutbuf = NULL;
972     *poutbuf_size = 0;
973
974     buf_ptr = buf;
975     while (buf_size > 0) {
976         len = s->inbuf_ptr - s->inbuf;
977         if (s->frame_size == 0) {
978             /* no header seen : find one. We need at least s->header_size
979                bytes to parse it */
980             len = FFMIN(s->header_size - len, buf_size);
981
982             memcpy(s->inbuf_ptr, buf_ptr, len);
983             buf_ptr += len;
984             s->inbuf_ptr += len;
985             buf_size -= len;
986             if ((s->inbuf_ptr - s->inbuf) == s->header_size) {
987                 len = s->sync(s->inbuf, &channels, &sample_rate, &bit_rate,
988                               &samples);
989                 if (len == 0) {
990                     /* no sync found : move by one byte (inefficient, but simple!) */
991                     memmove(s->inbuf, s->inbuf + 1, s->header_size - 1);
992                     s->inbuf_ptr--;
993                 } else {
994                     s->frame_size = len;
995                     /* update codec info */
996                     avctx->sample_rate = sample_rate;
997                     /* set channels,except if the user explicitly requests 1 or 2 channels, XXX/FIXME this is a bit ugly */
998                     if(avctx->codec_id == CODEC_ID_AC3){
999                         if(avctx->channels!=1 && avctx->channels!=2){
1000                             avctx->channels = channels;
1001                         }
1002                     } else {
1003                         avctx->channels = channels;
1004                     }
1005                     avctx->bit_rate = bit_rate;
1006                     avctx->frame_size = samples;
1007                 }
1008             }
1009         } else {
1010             len = FFMIN(s->frame_size - len, buf_size);
1011
1012             memcpy(s->inbuf_ptr, buf_ptr, len);
1013             buf_ptr += len;
1014             s->inbuf_ptr += len;
1015             buf_size -= len;
1016
1017             if(s->inbuf_ptr - s->inbuf == s->frame_size){
1018                 *poutbuf = s->inbuf;
1019                 *poutbuf_size = s->frame_size;
1020                 s->inbuf_ptr = s->inbuf;
1021                 s->frame_size = 0;
1022                 break;
1023             }
1024         }
1025     }
1026     return buf_ptr - buf;
1027 }
1028 #endif /* CONFIG_AC3_PARSER || CONFIG_AAC_PARSER */
1029
1030 #ifdef CONFIG_MPEGVIDEO_PARSER
1031 AVCodecParser mpegvideo_parser = {
1032     { CODEC_ID_MPEG1VIDEO, CODEC_ID_MPEG2VIDEO },
1033     sizeof(ParseContext1),
1034     NULL,
1035     mpegvideo_parse,
1036     parse1_close,
1037     mpegvideo_split,
1038 };
1039 #endif
1040 #ifdef CONFIG_MPEG4VIDEO_PARSER
1041 AVCodecParser mpeg4video_parser = {
1042     { CODEC_ID_MPEG4 },
1043     sizeof(ParseContext1),
1044     mpeg4video_parse_init,
1045     mpeg4video_parse,
1046     parse1_close,
1047     mpeg4video_split,
1048 };
1049 #endif
1050 #ifdef CONFIG_CAVSVIDEO_PARSER
1051 AVCodecParser cavsvideo_parser = {
1052     { CODEC_ID_CAVS },
1053     sizeof(ParseContext1),
1054     NULL,
1055     cavsvideo_parse,
1056     parse1_close,
1057     mpeg4video_split,
1058 };
1059 #endif
1060 #ifdef CONFIG_MPEGAUDIO_PARSER
1061 AVCodecParser mpegaudio_parser = {
1062     { CODEC_ID_MP2, CODEC_ID_MP3 },
1063     sizeof(MpegAudioParseContext),
1064     mpegaudio_parse_init,
1065     mpegaudio_parse,
1066     NULL,
1067 };
1068 #endif
1069 #ifdef CONFIG_AC3_PARSER
1070 AVCodecParser ac3_parser = {
1071     { CODEC_ID_AC3 },
1072     sizeof(AC3ParseContext),
1073     ac3_parse_init,
1074     ac3_parse,
1075     NULL,
1076 };
1077 #endif
1078 #ifdef CONFIG_AAC_PARSER
1079 AVCodecParser aac_parser = {
1080     { CODEC_ID_AAC },
1081     sizeof(AC3ParseContext),
1082     aac_parse_init,
1083     ac3_parse,
1084     NULL,
1085 };
1086 #endif