]> git.sesse.net Git - ffmpeg/blob - libavformat/flvdec.c
55ac9dab3f2904a2feca27d130e87d53fe583e15
[ffmpeg] / libavformat / flvdec.c
1 /*
2  * FLV demuxer
3  * Copyright (c) 2003 The Libav Project
4  *
5  * This demuxer will generate a 1 byte extradata for VP6F content.
6  * It is composed of:
7  *  - upper 4bits: difference between encoded width and visible width
8  *  - lower 4bits: difference between encoded height and visible height
9  *
10  * This file is part of Libav.
11  *
12  * Libav is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public
14  * License as published by the Free Software Foundation; either
15  * version 2.1 of the License, or (at your option) any later version.
16  *
17  * Libav is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with Libav; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25  */
26
27 #include "libavutil/avstring.h"
28 #include "libavutil/dict.h"
29 #include "libavutil/intfloat.h"
30 #include "libavutil/mathematics.h"
31 #include "libavcodec/bytestream.h"
32 #include "libavcodec/mpeg4audio.h"
33 #include "avformat.h"
34 #include "internal.h"
35 #include "avio_internal.h"
36 #include "flv.h"
37
38 #define KEYFRAMES_TAG            "keyframes"
39 #define KEYFRAMES_TIMESTAMP_TAG  "times"
40 #define KEYFRAMES_BYTEOFFSET_TAG "filepositions"
41
42 #define VALIDATE_INDEX_TS_THRESH 2500
43
44 typedef struct {
45     int wrong_dts; ///< wrong dts due to negative cts
46     uint8_t *new_extradata[2];
47     int      new_extradata_size[2];
48     int      last_sample_rate;
49     int      last_channels;
50     struct {
51         int64_t dts;
52         int64_t pos;
53     } validate_index[2];
54     int validate_next;
55     int validate_count;
56 } FLVContext;
57
58 static int flv_probe(AVProbeData *p)
59 {
60     const uint8_t *d;
61
62     d = p->buf;
63     if (d[0] == 'F' && d[1] == 'L' && d[2] == 'V' && d[3] < 5 && d[5]==0 && AV_RB32(d+5)>8) {
64         return AVPROBE_SCORE_MAX;
65     }
66     return 0;
67 }
68
69 static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream, AVCodecContext *acodec, int flv_codecid) {
70     switch(flv_codecid) {
71         //no distinction between S16 and S8 PCM codec flags
72         case FLV_CODECID_PCM:
73             acodec->codec_id = acodec->bits_per_coded_sample == 8 ? CODEC_ID_PCM_U8 :
74 #if HAVE_BIGENDIAN
75                                 CODEC_ID_PCM_S16BE;
76 #else
77                                 CODEC_ID_PCM_S16LE;
78 #endif
79             break;
80         case FLV_CODECID_PCM_LE:
81             acodec->codec_id = acodec->bits_per_coded_sample == 8 ? CODEC_ID_PCM_U8 : CODEC_ID_PCM_S16LE; break;
82         case FLV_CODECID_AAC  : acodec->codec_id = CODEC_ID_AAC;                                    break;
83         case FLV_CODECID_ADPCM: acodec->codec_id = CODEC_ID_ADPCM_SWF;                              break;
84         case FLV_CODECID_SPEEX:
85             acodec->codec_id = CODEC_ID_SPEEX;
86             acodec->sample_rate = 16000;
87             break;
88         case FLV_CODECID_MP3  : acodec->codec_id = CODEC_ID_MP3      ; astream->need_parsing = AVSTREAM_PARSE_FULL; break;
89         case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
90             acodec->sample_rate = 8000; //in case metadata does not otherwise declare samplerate
91             acodec->codec_id = CODEC_ID_NELLYMOSER;
92             break;
93         case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
94             acodec->sample_rate = 16000;
95             acodec->codec_id = CODEC_ID_NELLYMOSER;
96             break;
97         case FLV_CODECID_NELLYMOSER:
98             acodec->codec_id = CODEC_ID_NELLYMOSER;
99             break;
100         default:
101             av_log(s, AV_LOG_INFO, "Unsupported audio codec (%x)\n", flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
102             acodec->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
103     }
104 }
105
106 static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream, int flv_codecid) {
107     AVCodecContext *vcodec = vstream->codec;
108     switch(flv_codecid) {
109         case FLV_CODECID_H263  : vcodec->codec_id = CODEC_ID_FLV1   ; break;
110         case FLV_CODECID_SCREEN: vcodec->codec_id = CODEC_ID_FLASHSV; break;
111         case FLV_CODECID_SCREEN2: vcodec->codec_id = CODEC_ID_FLASHSV2; break;
112         case FLV_CODECID_VP6   : vcodec->codec_id = CODEC_ID_VP6F   ;
113         case FLV_CODECID_VP6A  :
114             if(flv_codecid == FLV_CODECID_VP6A)
115                 vcodec->codec_id = CODEC_ID_VP6A;
116             if(vcodec->extradata_size != 1) {
117                 vcodec->extradata_size = 1;
118                 vcodec->extradata = av_malloc(1);
119             }
120             vcodec->extradata[0] = avio_r8(s->pb);
121             return 1; // 1 byte body size adjustment for flv_read_packet()
122         case FLV_CODECID_H264:
123             vcodec->codec_id = CODEC_ID_H264;
124             return 3; // not 4, reading packet type will consume one byte
125         default:
126             av_log(s, AV_LOG_INFO, "Unsupported video codec (%x)\n", flv_codecid);
127             vcodec->codec_tag = flv_codecid;
128     }
129
130     return 0;
131 }
132
133 static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize) {
134     int length = avio_rb16(ioc);
135     if(length >= buffsize) {
136         avio_skip(ioc, length);
137         return -1;
138     }
139
140     avio_read(ioc, buffer, length);
141
142     buffer[length] = '\0';
143
144     return length;
145 }
146
147 static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc, AVStream *vstream, int64_t max_pos) {
148     FLVContext *flv = s->priv_data;
149     unsigned int arraylen = 0, timeslen = 0, fileposlen = 0, i;
150     double num_val;
151     char str_val[256];
152     int64_t *times = NULL;
153     int64_t *filepositions = NULL;
154     int ret = AVERROR(ENOSYS);
155     int64_t initial_pos = avio_tell(ioc);
156
157     if (s->flags & AVFMT_FLAG_IGNIDX)
158         return 0;
159
160     while (avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
161         int64_t* current_array;
162
163         // Expect array object in context
164         if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
165             break;
166
167         arraylen = avio_rb32(ioc);
168         if (arraylen >> 28)
169             break;
170
171         /*
172          * Expect only 'times' or 'filepositions' sub-arrays in other case refuse to use such metadata
173          * for indexing
174          */
175         if (!strcmp(KEYFRAMES_TIMESTAMP_TAG, str_val) && !times) {
176             if (!(times = av_mallocz(sizeof(*times) * arraylen))) {
177                 ret = AVERROR(ENOMEM);
178                 goto finish;
179             }
180             timeslen = arraylen;
181             current_array = times;
182         } else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) && !filepositions) {
183             if (!(filepositions = av_mallocz(sizeof(*filepositions) * arraylen))) {
184                 ret = AVERROR(ENOMEM);
185                 goto finish;
186             }
187             fileposlen = arraylen;
188             current_array = filepositions;
189         } else // unexpected metatag inside keyframes, will not use such metadata for indexing
190             break;
191
192         for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
193             if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
194                 goto finish;
195             num_val = av_int2double(avio_rb64(ioc));
196             current_array[i] = num_val;
197         }
198         if (times && filepositions) {
199             // All done, exiting at a position allowing amf_parse_object
200             // to finish parsing the object
201             ret = 0;
202             break;
203         }
204     }
205
206     if (!ret && timeslen == fileposlen) {
207         for (i = 0; i < fileposlen; i++) {
208             av_add_index_entry(vstream, filepositions[i], times[i]*1000,
209                                0, 0, AVINDEX_KEYFRAME);
210             if (i < 2) {
211                 flv->validate_index[i].pos = filepositions[i];
212                 flv->validate_index[i].dts = times[i] * 1000;
213                 flv->validate_count = i + 1;
214             }
215         }
216     } else
217         av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
218
219 finish:
220     av_freep(&times);
221     av_freep(&filepositions);
222     // If we got unexpected data, but successfully reset back to
223     // the start pos, the caller can continue parsing
224     if (ret < 0 && avio_seek(ioc, initial_pos, SEEK_SET) > 0)
225         return 0;
226     return ret;
227 }
228
229 static int amf_parse_object(AVFormatContext *s, AVStream *astream, AVStream *vstream, const char *key, int64_t max_pos, int depth) {
230     AVCodecContext *acodec, *vcodec;
231     AVIOContext *ioc;
232     AMFDataType amf_type;
233     char str_val[256];
234     double num_val;
235
236     num_val = 0;
237     ioc = s->pb;
238
239     amf_type = avio_r8(ioc);
240
241     switch(amf_type) {
242         case AMF_DATA_TYPE_NUMBER:
243             num_val = av_int2double(avio_rb64(ioc)); break;
244         case AMF_DATA_TYPE_BOOL:
245             num_val = avio_r8(ioc); break;
246         case AMF_DATA_TYPE_STRING:
247             if(amf_get_string(ioc, str_val, sizeof(str_val)) < 0)
248                 return -1;
249             break;
250         case AMF_DATA_TYPE_OBJECT:
251             if ((vstream || astream) && key && !strcmp(KEYFRAMES_TAG, key) && depth == 1)
252                 if (parse_keyframes_index(s, ioc, vstream ? vstream : astream,
253                                           max_pos) < 0)
254                     return -1;
255
256             while (avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
257                 if (amf_parse_object(s, astream, vstream, str_val, max_pos, depth + 1) < 0)
258                     return -1; //if we couldn't skip, bomb out.
259             }
260             if(avio_r8(ioc) != AMF_END_OF_OBJECT)
261                 return -1;
262             break;
263         case AMF_DATA_TYPE_NULL:
264         case AMF_DATA_TYPE_UNDEFINED:
265         case AMF_DATA_TYPE_UNSUPPORTED:
266             break; //these take up no additional space
267         case AMF_DATA_TYPE_MIXEDARRAY:
268             avio_skip(ioc, 4); //skip 32-bit max array index
269             while(avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
270                 //this is the only case in which we would want a nested parse to not skip over the object
271                 if(amf_parse_object(s, astream, vstream, str_val, max_pos, depth + 1) < 0)
272                     return -1;
273             }
274             if(avio_r8(ioc) != AMF_END_OF_OBJECT)
275                 return -1;
276             break;
277         case AMF_DATA_TYPE_ARRAY: {
278             unsigned int arraylen, i;
279
280             arraylen = avio_rb32(ioc);
281             for(i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
282                 if(amf_parse_object(s, NULL, NULL, NULL, max_pos, depth + 1) < 0)
283                     return -1; //if we couldn't skip, bomb out.
284             }
285         }
286             break;
287         case AMF_DATA_TYPE_DATE:
288             avio_skip(ioc, 8 + 2); //timestamp (double) and UTC offset (int16)
289             break;
290         default: //unsupported type, we couldn't skip
291             return -1;
292     }
293
294     if(depth == 1 && key) { //only look for metadata values when we are not nested and key != NULL
295         acodec = astream ? astream->codec : NULL;
296         vcodec = vstream ? vstream->codec : NULL;
297
298         if (amf_type == AMF_DATA_TYPE_NUMBER) {
299             if (!strcmp(key, "duration"))
300                 s->duration = num_val * AV_TIME_BASE;
301             else if (!strcmp(key, "videodatarate") && vcodec && 0 <= (int)(num_val * 1024.0))
302                 vcodec->bit_rate = num_val * 1024.0;
303             else if (!strcmp(key, "audiodatarate") && acodec && 0 <= (int)(num_val * 1024.0))
304                 acodec->bit_rate = num_val * 1024.0;
305         }
306
307         if (!strcmp(key, "duration")        ||
308             !strcmp(key, "filesize")        ||
309             !strcmp(key, "width")           ||
310             !strcmp(key, "height")          ||
311             !strcmp(key, "videodatarate")   ||
312             !strcmp(key, "framerate")       ||
313             !strcmp(key, "videocodecid")    ||
314             !strcmp(key, "audiodatarate")   ||
315             !strcmp(key, "audiosamplerate") ||
316             !strcmp(key, "audiosamplesize") ||
317             !strcmp(key, "stereo")          ||
318             !strcmp(key, "audiocodecid"))
319             return 0;
320
321         if(amf_type == AMF_DATA_TYPE_BOOL) {
322             av_strlcpy(str_val, num_val > 0 ? "true" : "false", sizeof(str_val));
323             av_dict_set(&s->metadata, key, str_val, 0);
324         } else if(amf_type == AMF_DATA_TYPE_NUMBER) {
325             snprintf(str_val, sizeof(str_val), "%.f", num_val);
326             av_dict_set(&s->metadata, key, str_val, 0);
327         } else if (amf_type == AMF_DATA_TYPE_STRING)
328             av_dict_set(&s->metadata, key, str_val, 0);
329     }
330
331     return 0;
332 }
333
334 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos) {
335     AMFDataType type;
336     AVStream *stream, *astream, *vstream;
337     AVIOContext *ioc;
338     int i;
339     char buffer[11]; //only needs to hold the string "onMetaData". Anything longer is something we don't want.
340
341     astream = NULL;
342     vstream = NULL;
343     ioc = s->pb;
344
345     //first object needs to be "onMetaData" string
346     type = avio_r8(ioc);
347     if(type != AMF_DATA_TYPE_STRING || amf_get_string(ioc, buffer, sizeof(buffer)) < 0 || strcmp(buffer, "onMetaData"))
348         return -1;
349
350     //find the streams now so that amf_parse_object doesn't need to do the lookup every time it is called.
351     for(i = 0; i < s->nb_streams; i++) {
352         stream = s->streams[i];
353         if     (stream->codec->codec_type == AVMEDIA_TYPE_AUDIO) astream = stream;
354         else if(stream->codec->codec_type == AVMEDIA_TYPE_VIDEO) vstream = stream;
355     }
356
357     //parse the second object (we want a mixed array)
358     if(amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
359         return -1;
360
361     return 0;
362 }
363
364 static AVStream *create_stream(AVFormatContext *s, int is_audio){
365     AVStream *st = avformat_new_stream(s, NULL);
366     if (!st)
367         return NULL;
368     st->id = is_audio;
369     st->codec->codec_type = is_audio ? AVMEDIA_TYPE_AUDIO : AVMEDIA_TYPE_VIDEO;
370     avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
371     return st;
372 }
373
374 static int flv_read_header(AVFormatContext *s)
375 {
376     int offset, flags;
377
378     avio_skip(s->pb, 4);
379     flags = avio_r8(s->pb);
380     /* old flvtool cleared this field */
381     /* FIXME: better fix needed */
382     if (!flags) {
383         flags = FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO;
384         av_log(s, AV_LOG_WARNING, "Broken FLV file, which says no streams present, this might fail\n");
385     }
386
387     if((flags & (FLV_HEADER_FLAG_HASVIDEO|FLV_HEADER_FLAG_HASAUDIO))
388              != (FLV_HEADER_FLAG_HASVIDEO|FLV_HEADER_FLAG_HASAUDIO))
389         s->ctx_flags |= AVFMTCTX_NOHEADER;
390
391     if(flags & FLV_HEADER_FLAG_HASVIDEO){
392         if(!create_stream(s, 0))
393             return AVERROR(ENOMEM);
394     }
395     if(flags & FLV_HEADER_FLAG_HASAUDIO){
396         if(!create_stream(s, 1))
397             return AVERROR(ENOMEM);
398     }
399
400     offset = avio_rb32(s->pb);
401     avio_seek(s->pb, offset, SEEK_SET);
402     avio_skip(s->pb, 4);
403
404     s->start_time = 0;
405
406     return 0;
407 }
408
409 static int flv_read_close(AVFormatContext *s)
410 {
411     FLVContext *flv = s->priv_data;
412     av_freep(&flv->new_extradata[0]);
413     av_freep(&flv->new_extradata[1]);
414     return 0;
415 }
416
417 static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
418 {
419     av_free(st->codec->extradata);
420     st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
421     if (!st->codec->extradata)
422         return AVERROR(ENOMEM);
423     st->codec->extradata_size = size;
424     avio_read(s->pb, st->codec->extradata, st->codec->extradata_size);
425     return 0;
426 }
427
428 static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
429                                int size)
430 {
431     av_free(flv->new_extradata[stream]);
432     flv->new_extradata[stream] = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
433     if (!flv->new_extradata[stream])
434         return AVERROR(ENOMEM);
435     flv->new_extradata_size[stream] = size;
436     avio_read(pb, flv->new_extradata[stream], size);
437     return 0;
438 }
439
440 static void clear_index_entries(AVFormatContext *s, int64_t pos)
441 {
442     int i, j, out;
443     av_log(s, AV_LOG_WARNING, "Found invalid index entries, clearing the index.\n");
444     for (i = 0; i < s->nb_streams; i++) {
445         AVStream *st = s->streams[i];
446         /* Remove all index entries that point to >= pos */
447         out = 0;
448         for (j = 0; j < st->nb_index_entries; j++) {
449             if (st->index_entries[j].pos < pos)
450                 st->index_entries[out++] = st->index_entries[j];
451         }
452         st->nb_index_entries = out;
453     }
454 }
455
456 static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
457 {
458     FLVContext *flv = s->priv_data;
459     int ret, i, type, size, flags, is_audio;
460     int64_t next, pos;
461     int64_t dts, pts = AV_NOPTS_VALUE;
462     int sample_rate = 0, channels = 0;
463     AVStream *st = NULL;
464
465  for(;;avio_skip(s->pb, 4)){ /* pkt size is repeated at end. skip it */
466     pos = avio_tell(s->pb);
467     type = avio_r8(s->pb);
468     size = avio_rb24(s->pb);
469     dts = avio_rb24(s->pb);
470     dts |= avio_r8(s->pb) << 24;
471     av_dlog(s, "type:%d, size:%d, dts:%"PRId64"\n", type, size, dts);
472     if (s->pb->eof_reached)
473         return AVERROR_EOF;
474     avio_skip(s->pb, 3); /* stream id, always 0 */
475     flags = 0;
476
477     if (flv->validate_next < flv->validate_count) {
478         int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
479         if (pos == validate_pos) {
480             if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
481                 VALIDATE_INDEX_TS_THRESH) {
482                 flv->validate_next++;
483             } else {
484                 clear_index_entries(s, validate_pos);
485                 flv->validate_count = 0;
486             }
487         } else if (pos > validate_pos) {
488             clear_index_entries(s, validate_pos);
489             flv->validate_count = 0;
490         }
491     }
492
493     if(size == 0)
494         continue;
495
496     next= size + avio_tell(s->pb);
497
498     if (type == FLV_TAG_TYPE_AUDIO) {
499         is_audio=1;
500         flags = avio_r8(s->pb);
501         size--;
502     } else if (type == FLV_TAG_TYPE_VIDEO) {
503         is_audio=0;
504         flags = avio_r8(s->pb);
505         size--;
506         if ((flags & 0xf0) == 0x50) /* video info / command frame */
507             goto skip;
508     } else {
509         if (type == FLV_TAG_TYPE_META && size > 13+1+4)
510             flv_read_metabody(s, next);
511         else /* skip packet */
512             av_log(s, AV_LOG_DEBUG, "skipping flv packet: type %d, size %d, flags %d\n", type, size, flags);
513     skip:
514         avio_seek(s->pb, next, SEEK_SET);
515         continue;
516     }
517
518     /* skip empty data packets */
519     if (!size)
520         continue;
521
522     /* now find stream */
523     for(i=0;i<s->nb_streams;i++) {
524         st = s->streams[i];
525         if (st->id == is_audio)
526             break;
527     }
528     if(i == s->nb_streams){
529         av_log(s, AV_LOG_ERROR, "invalid stream\n");
530         st= create_stream(s, is_audio);
531         s->ctx_flags &= ~AVFMTCTX_NOHEADER;
532     }
533     av_dlog(s, "%d %X %d \n", is_audio, flags, st->discard);
534     if(  (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY ||         is_audio))
535        ||(st->discard >= AVDISCARD_BIDIR  &&  ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && !is_audio))
536        || st->discard >= AVDISCARD_ALL
537        ){
538         avio_seek(s->pb, next, SEEK_SET);
539         continue;
540     }
541     if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY)
542         av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
543     break;
544  }
545
546     // if not streamed and no duration from metadata then seek to end to find the duration from the timestamps
547     if(s->pb->seekable && (!s->duration || s->duration==AV_NOPTS_VALUE)){
548         int size;
549         const int64_t pos= avio_tell(s->pb);
550         const int64_t fsize= avio_size(s->pb);
551         avio_seek(s->pb, fsize-4, SEEK_SET);
552         size= avio_rb32(s->pb);
553         avio_seek(s->pb, fsize-3-size, SEEK_SET);
554         if(size == avio_rb24(s->pb) + 11){
555             uint32_t ts = avio_rb24(s->pb);
556             ts |= avio_r8(s->pb) << 24;
557             s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
558         }
559         avio_seek(s->pb, pos, SEEK_SET);
560     }
561
562     if(is_audio){
563         int bits_per_coded_sample;
564         channels    = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
565         sample_rate = (44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >> FLV_AUDIO_SAMPLERATE_OFFSET) >> 3);
566         bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
567         if(!st->codec->channels || !st->codec->sample_rate || !st->codec->bits_per_coded_sample) {
568             st->codec->channels              = channels;
569             st->codec->sample_rate           = sample_rate;
570             st->codec->bits_per_coded_sample = bits_per_coded_sample;
571         }
572         if(!st->codec->codec_id){
573             flv_set_audio_codec(s, st, st->codec, flags & FLV_AUDIO_CODECID_MASK);
574             flv->last_sample_rate = st->codec->sample_rate;
575             flv->last_channels    = st->codec->channels;
576         } else {
577             AVCodecContext ctx;
578             ctx.sample_rate = sample_rate;
579             flv_set_audio_codec(s, st, &ctx, flags & FLV_AUDIO_CODECID_MASK);
580             sample_rate = ctx.sample_rate;
581         }
582     }else{
583         size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK);
584     }
585
586     if (st->codec->codec_id == CODEC_ID_AAC ||
587         st->codec->codec_id == CODEC_ID_H264) {
588         int type = avio_r8(s->pb);
589         size--;
590         if (st->codec->codec_id == CODEC_ID_H264) {
591             int32_t cts = (avio_rb24(s->pb)+0xff800000)^0xff800000; // sign extension
592             pts = dts + cts;
593             if (cts < 0) { // dts are wrong
594                 flv->wrong_dts = 1;
595                 av_log(s, AV_LOG_WARNING, "negative cts, previous timestamps might be wrong\n");
596             }
597             if (flv->wrong_dts)
598                 dts = AV_NOPTS_VALUE;
599         }
600         if (type == 0) {
601             if (st->codec->extradata) {
602                 if ((ret = flv_queue_extradata(flv, s->pb, is_audio, size)) < 0)
603                     return ret;
604                 ret = AVERROR(EAGAIN);
605                 goto leave;
606             }
607             if ((ret = flv_get_extradata(s, st, size)) < 0)
608                 return ret;
609             if (st->codec->codec_id == CODEC_ID_AAC) {
610                 MPEG4AudioConfig cfg;
611                 avpriv_mpeg4audio_get_config(&cfg, st->codec->extradata,
612                                              st->codec->extradata_size * 8, 1);
613                 st->codec->channels = cfg.channels;
614                 if (cfg.ext_sample_rate)
615                     st->codec->sample_rate = cfg.ext_sample_rate;
616                 else
617                     st->codec->sample_rate = cfg.sample_rate;
618                 av_dlog(s, "mp4a config channels %d sample rate %d\n",
619                         st->codec->channels, st->codec->sample_rate);
620             }
621
622             ret = AVERROR(EAGAIN);
623             goto leave;
624         }
625     }
626
627     /* skip empty data packets */
628     if (!size) {
629         ret = AVERROR(EAGAIN);
630         goto leave;
631     }
632
633     ret= av_get_packet(s->pb, pkt, size);
634     if (ret < 0) {
635         return AVERROR(EIO);
636     }
637     /* note: we need to modify the packet size here to handle the last
638        packet */
639     pkt->size = ret;
640     pkt->dts = dts;
641     pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
642     pkt->stream_index = st->index;
643     if (flv->new_extradata[is_audio]) {
644         uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
645                                                 flv->new_extradata_size[is_audio]);
646         if (side) {
647             memcpy(side, flv->new_extradata[is_audio],
648                    flv->new_extradata_size[is_audio]);
649             av_freep(&flv->new_extradata[is_audio]);
650             flv->new_extradata_size[is_audio] = 0;
651         }
652     }
653     if (is_audio && (sample_rate != flv->last_sample_rate ||
654                      channels != flv->last_channels)) {
655         flv->last_sample_rate = sample_rate;
656         flv->last_channels    = channels;
657         ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
658     }
659
660     if (is_audio || ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY))
661         pkt->flags |= AV_PKT_FLAG_KEY;
662
663 leave:
664     avio_skip(s->pb, 4);
665     return ret;
666 }
667
668 static int flv_read_seek(AVFormatContext *s, int stream_index,
669     int64_t ts, int flags)
670 {
671     FLVContext *flv = s->priv_data;
672     flv->validate_count = 0;
673     return avio_seek_time(s->pb, stream_index, ts, flags);
674 }
675
676 #if 0 /* don't know enough to implement this */
677 static int flv_read_seek2(AVFormatContext *s, int stream_index,
678     int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
679 {
680     int ret = AVERROR(ENOSYS);
681
682     if (ts - min_ts > (uint64_t)(max_ts - ts)) flags |= AVSEEK_FLAG_BACKWARD;
683
684     if (!s->pb->seekable) {
685         if (stream_index < 0) {
686             stream_index = av_find_default_stream_index(s);
687             if (stream_index < 0)
688                 return -1;
689
690             /* timestamp for default must be expressed in AV_TIME_BASE units */
691             ts = av_rescale_rnd(ts, 1000, AV_TIME_BASE,
692                 flags & AVSEEK_FLAG_BACKWARD ? AV_ROUND_DOWN : AV_ROUND_UP);
693         }
694         ret = avio_seek_time(s->pb, stream_index, ts, flags);
695     }
696
697     if (ret == AVERROR(ENOSYS))
698         ret = av_seek_frame(s, stream_index, ts, flags);
699     return ret;
700 }
701 #endif
702
703 AVInputFormat ff_flv_demuxer = {
704     .name           = "flv",
705     .long_name      = NULL_IF_CONFIG_SMALL("FLV format"),
706     .priv_data_size = sizeof(FLVContext),
707     .read_probe     = flv_probe,
708     .read_header    = flv_read_header,
709     .read_packet    = flv_read_packet,
710     .read_seek = flv_read_seek,
711 #if 0
712     .read_seek2 = flv_read_seek2,
713 #endif
714     .read_close = flv_read_close,
715     .extensions = "flv",
716 };