• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files
  • File List
  • Globals

libavformat/flvdec.c

Go to the documentation of this file.
00001 /*
00002  * FLV demuxer
00003  * Copyright (c) 2003 The FFmpeg Project
00004  *
00005  * This demuxer will generate a 1 byte extradata for VP6F content.
00006  * It is composed of:
00007  *  - upper 4bits: difference between encoded width and visible width
00008  *  - lower 4bits: difference between encoded height and visible height
00009  *
00010  * This file is part of FFmpeg.
00011  *
00012  * FFmpeg is free software; you can redistribute it and/or
00013  * modify it under the terms of the GNU Lesser General Public
00014  * License as published by the Free Software Foundation; either
00015  * version 2.1 of the License, or (at your option) any later version.
00016  *
00017  * FFmpeg is distributed in the hope that it will be useful,
00018  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00019  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00020  * Lesser General Public License for more details.
00021  *
00022  * You should have received a copy of the GNU Lesser General Public
00023  * License along with FFmpeg; if not, write to the Free Software
00024  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00025  */
00026 
00027 #include "libavutil/avstring.h"
00028 #include "libavcodec/bytestream.h"
00029 #include "libavcodec/mpeg4audio.h"
00030 #include "avformat.h"
00031 #include "flv.h"
00032 
00033 typedef struct {
00034     int wrong_dts; 
00035 } FLVContext;
00036 
00037 static int flv_probe(AVProbeData *p)
00038 {
00039     const uint8_t *d;
00040 
00041     d = p->buf;
00042     if (d[0] == 'F' && d[1] == 'L' && d[2] == 'V' && d[3] < 5 && d[5]==0 && AV_RB32(d+5)>8) {
00043         return AVPROBE_SCORE_MAX;
00044     }
00045     return 0;
00046 }
00047 
00048 static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream, int flv_codecid) {
00049     AVCodecContext *acodec = astream->codec;
00050     switch(flv_codecid) {
00051         //no distinction between S16 and S8 PCM codec flags
00052         case FLV_CODECID_PCM:
00053             acodec->codec_id = acodec->bits_per_coded_sample == 8 ? CODEC_ID_PCM_U8 :
00054 #if HAVE_BIGENDIAN
00055                                 CODEC_ID_PCM_S16BE;
00056 #else
00057                                 CODEC_ID_PCM_S16LE;
00058 #endif
00059             break;
00060         case FLV_CODECID_PCM_LE:
00061             acodec->codec_id = acodec->bits_per_coded_sample == 8 ? CODEC_ID_PCM_U8 : CODEC_ID_PCM_S16LE; break;
00062         case FLV_CODECID_AAC  : acodec->codec_id = CODEC_ID_AAC;                                    break;
00063         case FLV_CODECID_ADPCM: acodec->codec_id = CODEC_ID_ADPCM_SWF;                              break;
00064         case FLV_CODECID_SPEEX:
00065             acodec->codec_id = CODEC_ID_SPEEX;
00066             acodec->sample_rate = 16000;
00067             break;
00068         case FLV_CODECID_MP3  : acodec->codec_id = CODEC_ID_MP3      ; astream->need_parsing = AVSTREAM_PARSE_FULL; break;
00069         case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
00070             acodec->sample_rate = 8000; //in case metadata does not otherwise declare samplerate
00071         case FLV_CODECID_NELLYMOSER:
00072             acodec->codec_id = CODEC_ID_NELLYMOSER;
00073             break;
00074         default:
00075             av_log(s, AV_LOG_INFO, "Unsupported audio codec (%x)\n", flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
00076             acodec->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
00077     }
00078 }
00079 
00080 static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream, int flv_codecid) {
00081     AVCodecContext *vcodec = vstream->codec;
00082     switch(flv_codecid) {
00083         case FLV_CODECID_H263  : vcodec->codec_id = CODEC_ID_FLV1   ; break;
00084         case FLV_CODECID_SCREEN: vcodec->codec_id = CODEC_ID_FLASHSV; break;
00085         case FLV_CODECID_SCREEN2: vcodec->codec_id = CODEC_ID_FLASHSV2; break;
00086         case FLV_CODECID_VP6   : vcodec->codec_id = CODEC_ID_VP6F   ;
00087         case FLV_CODECID_VP6A  :
00088             if(flv_codecid == FLV_CODECID_VP6A)
00089                 vcodec->codec_id = CODEC_ID_VP6A;
00090             if(vcodec->extradata_size != 1) {
00091                 vcodec->extradata_size = 1;
00092                 vcodec->extradata = av_malloc(1);
00093             }
00094             vcodec->extradata[0] = get_byte(s->pb);
00095             return 1; // 1 byte body size adjustment for flv_read_packet()
00096         case FLV_CODECID_H264:
00097             vcodec->codec_id = CODEC_ID_H264;
00098             return 3; // not 4, reading packet type will consume one byte
00099         default:
00100             av_log(s, AV_LOG_INFO, "Unsupported video codec (%x)\n", flv_codecid);
00101             vcodec->codec_tag = flv_codecid;
00102     }
00103 
00104     return 0;
00105 }
00106 
00107 static int amf_get_string(ByteIOContext *ioc, char *buffer, int buffsize) {
00108     int length = get_be16(ioc);
00109     if(length >= buffsize) {
00110         url_fskip(ioc, length);
00111         return -1;
00112     }
00113 
00114     get_buffer(ioc, buffer, length);
00115 
00116     buffer[length] = '\0';
00117 
00118     return length;
00119 }
00120 
00121 static int amf_parse_object(AVFormatContext *s, AVStream *astream, AVStream *vstream, const char *key, int64_t max_pos, int depth) {
00122     AVCodecContext *acodec, *vcodec;
00123     ByteIOContext *ioc;
00124     AMFDataType amf_type;
00125     char str_val[256];
00126     double num_val;
00127 
00128     num_val = 0;
00129     ioc = s->pb;
00130 
00131     amf_type = get_byte(ioc);
00132 
00133     switch(amf_type) {
00134         case AMF_DATA_TYPE_NUMBER:
00135             num_val = av_int2dbl(get_be64(ioc)); break;
00136         case AMF_DATA_TYPE_BOOL:
00137             num_val = get_byte(ioc); break;
00138         case AMF_DATA_TYPE_STRING:
00139             if(amf_get_string(ioc, str_val, sizeof(str_val)) < 0)
00140                 return -1;
00141             break;
00142         case AMF_DATA_TYPE_OBJECT: {
00143             unsigned int keylen;
00144 
00145             while(url_ftell(ioc) < max_pos - 2 && (keylen = get_be16(ioc))) {
00146                 url_fskip(ioc, keylen); //skip key string
00147                 if(amf_parse_object(s, NULL, NULL, NULL, max_pos, depth + 1) < 0)
00148                     return -1; //if we couldn't skip, bomb out.
00149             }
00150             if(get_byte(ioc) != AMF_END_OF_OBJECT)
00151                 return -1;
00152         }
00153             break;
00154         case AMF_DATA_TYPE_NULL:
00155         case AMF_DATA_TYPE_UNDEFINED:
00156         case AMF_DATA_TYPE_UNSUPPORTED:
00157             break; //these take up no additional space
00158         case AMF_DATA_TYPE_MIXEDARRAY:
00159             url_fskip(ioc, 4); //skip 32-bit max array index
00160             while(url_ftell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
00161                 //this is the only case in which we would want a nested parse to not skip over the object
00162                 if(amf_parse_object(s, astream, vstream, str_val, max_pos, depth + 1) < 0)
00163                     return -1;
00164             }
00165             if(get_byte(ioc) != AMF_END_OF_OBJECT)
00166                 return -1;
00167             break;
00168         case AMF_DATA_TYPE_ARRAY: {
00169             unsigned int arraylen, i;
00170 
00171             arraylen = get_be32(ioc);
00172             for(i = 0; i < arraylen && url_ftell(ioc) < max_pos - 1; i++) {
00173                 if(amf_parse_object(s, NULL, NULL, NULL, max_pos, depth + 1) < 0)
00174                     return -1; //if we couldn't skip, bomb out.
00175             }
00176         }
00177             break;
00178         case AMF_DATA_TYPE_DATE:
00179             url_fskip(ioc, 8 + 2); //timestamp (double) and UTC offset (int16)
00180             break;
00181         default: //unsupported type, we couldn't skip
00182             return -1;
00183     }
00184 
00185     if(depth == 1 && key) { //only look for metadata values when we are not nested and key != NULL
00186         acodec = astream ? astream->codec : NULL;
00187         vcodec = vstream ? vstream->codec : NULL;
00188 
00189         if(amf_type == AMF_DATA_TYPE_BOOL) {
00190             av_strlcpy(str_val, num_val > 0 ? "true" : "false", sizeof(str_val));
00191             av_metadata_set2(&s->metadata, key, str_val, 0);
00192         } else if(amf_type == AMF_DATA_TYPE_NUMBER) {
00193             snprintf(str_val, sizeof(str_val), "%.f", num_val);
00194             av_metadata_set2(&s->metadata, key, str_val, 0);
00195             if(!strcmp(key, "duration")) s->duration = num_val * AV_TIME_BASE;
00196             else if(!strcmp(key, "videodatarate") && vcodec && 0 <= (int)(num_val * 1024.0))
00197                 vcodec->bit_rate = num_val * 1024.0;
00198             else if(!strcmp(key, "audiodatarate") && acodec && 0 <= (int)(num_val * 1024.0))
00199                 acodec->bit_rate = num_val * 1024.0;
00200         } else if (amf_type == AMF_DATA_TYPE_STRING)
00201             av_metadata_set2(&s->metadata, key, str_val, 0);
00202     }
00203 
00204     return 0;
00205 }
00206 
00207 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos) {
00208     AMFDataType type;
00209     AVStream *stream, *astream, *vstream;
00210     ByteIOContext *ioc;
00211     int i;
00212     char buffer[11]; //only needs to hold the string "onMetaData". Anything longer is something we don't want.
00213 
00214     astream = NULL;
00215     vstream = NULL;
00216     ioc = s->pb;
00217 
00218     //first object needs to be "onMetaData" string
00219     type = get_byte(ioc);
00220     if(type != AMF_DATA_TYPE_STRING || amf_get_string(ioc, buffer, sizeof(buffer)) < 0 || strcmp(buffer, "onMetaData"))
00221         return -1;
00222 
00223     //find the streams now so that amf_parse_object doesn't need to do the lookup every time it is called.
00224     for(i = 0; i < s->nb_streams; i++) {
00225         stream = s->streams[i];
00226         if     (stream->codec->codec_type == AVMEDIA_TYPE_AUDIO) astream = stream;
00227         else if(stream->codec->codec_type == AVMEDIA_TYPE_VIDEO) vstream = stream;
00228     }
00229 
00230     //parse the second object (we want a mixed array)
00231     if(amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
00232         return -1;
00233 
00234     return 0;
00235 }
00236 
00237 static AVStream *create_stream(AVFormatContext *s, int is_audio){
00238     AVStream *st = av_new_stream(s, is_audio);
00239     if (!st)
00240         return NULL;
00241     st->codec->codec_type = is_audio ? AVMEDIA_TYPE_AUDIO : AVMEDIA_TYPE_VIDEO;
00242     av_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
00243     return st;
00244 }
00245 
00246 static int flv_read_header(AVFormatContext *s,
00247                            AVFormatParameters *ap)
00248 {
00249     int offset, flags;
00250 
00251     url_fskip(s->pb, 4);
00252     flags = get_byte(s->pb);
00253     /* old flvtool cleared this field */
00254     /* FIXME: better fix needed */
00255     if (!flags) {
00256         flags = FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO;
00257         av_log(s, AV_LOG_WARNING, "Broken FLV file, which says no streams present, this might fail\n");
00258     }
00259 
00260     if((flags & (FLV_HEADER_FLAG_HASVIDEO|FLV_HEADER_FLAG_HASAUDIO))
00261              != (FLV_HEADER_FLAG_HASVIDEO|FLV_HEADER_FLAG_HASAUDIO))
00262         s->ctx_flags |= AVFMTCTX_NOHEADER;
00263 
00264     if(flags & FLV_HEADER_FLAG_HASVIDEO){
00265         if(!create_stream(s, 0))
00266             return AVERROR(ENOMEM);
00267     }
00268     if(flags & FLV_HEADER_FLAG_HASAUDIO){
00269         if(!create_stream(s, 1))
00270             return AVERROR(ENOMEM);
00271     }
00272 
00273     offset = get_be32(s->pb);
00274     url_fseek(s->pb, offset, SEEK_SET);
00275     url_fskip(s->pb, 4);
00276 
00277     s->start_time = 0;
00278 
00279     return 0;
00280 }
00281 
00282 static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
00283 {
00284     av_free(st->codec->extradata);
00285     st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
00286     if (!st->codec->extradata)
00287         return AVERROR(ENOMEM);
00288     st->codec->extradata_size = size;
00289     get_buffer(s->pb, st->codec->extradata, st->codec->extradata_size);
00290     return 0;
00291 }
00292 
00293 static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
00294 {
00295     FLVContext *flv = s->priv_data;
00296     int ret, i, type, size, flags, is_audio;
00297     int64_t next, pos;
00298     int64_t dts, pts = AV_NOPTS_VALUE;
00299     AVStream *st = NULL;
00300 
00301  for(;;url_fskip(s->pb, 4)){ /* pkt size is repeated at end. skip it */
00302     pos = url_ftell(s->pb);
00303     type = get_byte(s->pb);
00304     size = get_be24(s->pb);
00305     dts = get_be24(s->pb);
00306     dts |= get_byte(s->pb) << 24;
00307 //    av_log(s, AV_LOG_DEBUG, "type:%d, size:%d, dts:%d\n", type, size, dts);
00308     if (url_feof(s->pb))
00309         return AVERROR_EOF;
00310     url_fskip(s->pb, 3); /* stream id, always 0 */
00311     flags = 0;
00312 
00313     if(size == 0)
00314         continue;
00315 
00316     next= size + url_ftell(s->pb);
00317 
00318     if (type == FLV_TAG_TYPE_AUDIO) {
00319         is_audio=1;
00320         flags = get_byte(s->pb);
00321         size--;
00322     } else if (type == FLV_TAG_TYPE_VIDEO) {
00323         is_audio=0;
00324         flags = get_byte(s->pb);
00325         size--;
00326         if ((flags & 0xf0) == 0x50) /* video info / command frame */
00327             goto skip;
00328     } else {
00329         if (type == FLV_TAG_TYPE_META && size > 13+1+4)
00330             flv_read_metabody(s, next);
00331         else /* skip packet */
00332             av_log(s, AV_LOG_DEBUG, "skipping flv packet: type %d, size %d, flags %d\n", type, size, flags);
00333     skip:
00334         url_fseek(s->pb, next, SEEK_SET);
00335         continue;
00336     }
00337 
00338     /* skip empty data packets */
00339     if (!size)
00340         continue;
00341 
00342     /* now find stream */
00343     for(i=0;i<s->nb_streams;i++) {
00344         st = s->streams[i];
00345         if (st->id == is_audio)
00346             break;
00347     }
00348     if(i == s->nb_streams){
00349         av_log(s, AV_LOG_ERROR, "invalid stream\n");
00350         st= create_stream(s, is_audio);
00351         s->ctx_flags &= ~AVFMTCTX_NOHEADER;
00352     }
00353 //    av_log(s, AV_LOG_DEBUG, "%d %X %d \n", is_audio, flags, st->discard);
00354     if(  (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY ||         is_audio))
00355        ||(st->discard >= AVDISCARD_BIDIR  &&  ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && !is_audio))
00356        || st->discard >= AVDISCARD_ALL
00357        ){
00358         url_fseek(s->pb, next, SEEK_SET);
00359         continue;
00360     }
00361     if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY)
00362         av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
00363     break;
00364  }
00365 
00366     // if not streamed and no duration from metadata then seek to end to find the duration from the timestamps
00367     if(!url_is_streamed(s->pb) && (!s->duration || s->duration==AV_NOPTS_VALUE)){
00368         int size;
00369         const int64_t pos= url_ftell(s->pb);
00370         const int64_t fsize= url_fsize(s->pb);
00371         url_fseek(s->pb, fsize-4, SEEK_SET);
00372         size= get_be32(s->pb);
00373         url_fseek(s->pb, fsize-3-size, SEEK_SET);
00374         if(size == get_be24(s->pb) + 11){
00375             uint32_t ts = get_be24(s->pb);
00376             ts |= get_byte(s->pb) << 24;
00377             s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
00378         }
00379         url_fseek(s->pb, pos, SEEK_SET);
00380     }
00381 
00382     if(is_audio){
00383         if(!st->codec->channels || !st->codec->sample_rate || !st->codec->bits_per_coded_sample) {
00384             st->codec->channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
00385             st->codec->sample_rate = (44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >> FLV_AUDIO_SAMPLERATE_OFFSET) >> 3);
00386             st->codec->bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
00387         }
00388         if(!st->codec->codec_id){
00389             flv_set_audio_codec(s, st, flags & FLV_AUDIO_CODECID_MASK);
00390         }
00391     }else{
00392         size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK);
00393     }
00394 
00395     if (st->codec->codec_id == CODEC_ID_AAC ||
00396         st->codec->codec_id == CODEC_ID_H264) {
00397         int type = get_byte(s->pb);
00398         size--;
00399         if (st->codec->codec_id == CODEC_ID_H264) {
00400             int32_t cts = (get_be24(s->pb)+0xff800000)^0xff800000; // sign extension
00401             pts = dts + cts;
00402             if (cts < 0) { // dts are wrong
00403                 flv->wrong_dts = 1;
00404                 av_log(s, AV_LOG_WARNING, "negative cts, previous timestamps might be wrong\n");
00405             }
00406             if (flv->wrong_dts)
00407                 dts = AV_NOPTS_VALUE;
00408         }
00409         if (type == 0) {
00410             if ((ret = flv_get_extradata(s, st, size)) < 0)
00411                 return ret;
00412             if (st->codec->codec_id == CODEC_ID_AAC) {
00413                 MPEG4AudioConfig cfg;
00414                 ff_mpeg4audio_get_config(&cfg, st->codec->extradata,
00415                                          st->codec->extradata_size);
00416                 st->codec->channels = cfg.channels;
00417                 st->codec->sample_rate = cfg.sample_rate;
00418                 dprintf(s, "mp4a config channels %d sample rate %d\n",
00419                         st->codec->channels, st->codec->sample_rate);
00420             }
00421 
00422             ret = AVERROR(EAGAIN);
00423             goto leave;
00424         }
00425     }
00426 
00427     /* skip empty data packets */
00428     if (!size) {
00429         ret = AVERROR(EAGAIN);
00430         goto leave;
00431     }
00432 
00433     ret= av_get_packet(s->pb, pkt, size);
00434     if (ret < 0) {
00435         return AVERROR(EIO);
00436     }
00437     /* note: we need to modify the packet size here to handle the last
00438        packet */
00439     pkt->size = ret;
00440     pkt->dts = dts;
00441     pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
00442     pkt->stream_index = st->index;
00443 
00444     if (is_audio || ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY))
00445         pkt->flags |= AV_PKT_FLAG_KEY;
00446 
00447 leave:
00448     url_fskip(s->pb, 4);
00449     return ret;
00450 }
00451 
00452 static int flv_read_seek(AVFormatContext *s, int stream_index,
00453     int64_t ts, int flags)
00454 {
00455     return av_url_read_fseek(s->pb, stream_index, ts, flags);
00456 }
00457 
00458 #if 0 /* don't know enough to implement this */
00459 static int flv_read_seek2(AVFormatContext *s, int stream_index,
00460     int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
00461 {
00462     int ret = AVERROR(ENOSYS);
00463 
00464     if (ts - min_ts > (uint64_t)(max_ts - ts)) flags |= AVSEEK_FLAG_BACKWARD;
00465 
00466     if (url_is_streamed(s->pb)) {
00467         if (stream_index < 0) {
00468             stream_index = av_find_default_stream_index(s);
00469             if (stream_index < 0)
00470                 return -1;
00471 
00472             /* timestamp for default must be expressed in AV_TIME_BASE units */
00473             ts = av_rescale_rnd(ts, 1000, AV_TIME_BASE,
00474                 flags & AVSEEK_FLAG_BACKWARD ? AV_ROUND_DOWN : AV_ROUND_UP);
00475         }
00476         ret = av_url_read_fseek(s->pb, stream_index, ts, flags);
00477     }
00478 
00479     if (ret == AVERROR(ENOSYS))
00480         ret = av_seek_frame(s, stream_index, ts, flags);
00481     return ret;
00482 }
00483 #endif
00484 
00485 AVInputFormat flv_demuxer = {
00486     "flv",
00487     NULL_IF_CONFIG_SMALL("FLV format"),
00488     sizeof(FLVContext),
00489     flv_probe,
00490     flv_read_header,
00491     flv_read_packet,
00492     .read_seek = flv_read_seek,
00493 #if 0
00494     .read_seek2 = flv_read_seek2,
00495 #endif
00496     .extensions = "flv",
00497     .value = CODEC_ID_FLV1,
00498 };

Generated on Fri Sep 16 2011 17:17:36 for FFmpeg by  doxygen 1.7.1