libavformat/flvenc.c
Go to the documentation of this file.
00001 /*
00002  * FLV muxer
00003  * Copyright (c) 2003 The Libav Project
00004  *
00005  * This file is part of Libav.
00006  *
00007  * Libav is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * Libav is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with Libav; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 
00022 #include "libavutil/intfloat.h"
00023 #include "avformat.h"
00024 #include "flv.h"
00025 #include "internal.h"
00026 #include "avc.h"
00027 #include "metadata.h"
00028 #include "libavutil/dict.h"
00029 
00030 #undef NDEBUG
00031 #include <assert.h>
00032 
00033 static const AVCodecTag flv_video_codec_ids[] = {
00034     {CODEC_ID_FLV1,    FLV_CODECID_H263  },
00035     {CODEC_ID_FLASHSV, FLV_CODECID_SCREEN},
00036     {CODEC_ID_FLASHSV2, FLV_CODECID_SCREEN2},
00037     {CODEC_ID_VP6F,    FLV_CODECID_VP6   },
00038     {CODEC_ID_VP6,     FLV_CODECID_VP6   },
00039     {CODEC_ID_H264,    FLV_CODECID_H264  },
00040     {CODEC_ID_NONE,    0}
00041 };
00042 
00043 static const AVCodecTag flv_audio_codec_ids[] = {
00044     {CODEC_ID_MP3,       FLV_CODECID_MP3    >> FLV_AUDIO_CODECID_OFFSET},
00045     {CODEC_ID_PCM_U8,    FLV_CODECID_PCM    >> FLV_AUDIO_CODECID_OFFSET},
00046     {CODEC_ID_PCM_S16BE, FLV_CODECID_PCM    >> FLV_AUDIO_CODECID_OFFSET},
00047     {CODEC_ID_PCM_S16LE, FLV_CODECID_PCM_LE >> FLV_AUDIO_CODECID_OFFSET},
00048     {CODEC_ID_ADPCM_SWF, FLV_CODECID_ADPCM  >> FLV_AUDIO_CODECID_OFFSET},
00049     {CODEC_ID_AAC,       FLV_CODECID_AAC    >> FLV_AUDIO_CODECID_OFFSET},
00050     {CODEC_ID_NELLYMOSER, FLV_CODECID_NELLYMOSER >> FLV_AUDIO_CODECID_OFFSET},
00051     {CODEC_ID_SPEEX,     FLV_CODECID_SPEEX  >> FLV_AUDIO_CODECID_OFFSET},
00052     {CODEC_ID_NONE,      0}
00053 };
00054 
00055 typedef struct FLVContext {
00056     int reserved;
00057     int64_t duration_offset;
00058     int64_t filesize_offset;
00059     int64_t duration;
00060     int64_t delay;      
00061 } FLVContext;
00062 
00063 typedef struct FLVStreamContext {
00064     int64_t last_ts;    
00065 } FLVStreamContext;
00066 
00067 static int get_audio_flags(AVCodecContext *enc){
00068     int flags = (enc->bits_per_coded_sample == 16) ? FLV_SAMPLESSIZE_16BIT : FLV_SAMPLESSIZE_8BIT;
00069 
00070     if (enc->codec_id == CODEC_ID_AAC) // specs force these parameters
00071         return FLV_CODECID_AAC | FLV_SAMPLERATE_44100HZ | FLV_SAMPLESSIZE_16BIT | FLV_STEREO;
00072     else if (enc->codec_id == CODEC_ID_SPEEX) {
00073         if (enc->sample_rate != 16000) {
00074             av_log(enc, AV_LOG_ERROR, "flv only supports wideband (16kHz) Speex audio\n");
00075             return -1;
00076         }
00077         if (enc->channels != 1) {
00078             av_log(enc, AV_LOG_ERROR, "flv only supports mono Speex audio\n");
00079             return -1;
00080         }
00081         return FLV_CODECID_SPEEX | FLV_SAMPLERATE_11025HZ | FLV_SAMPLESSIZE_16BIT;
00082     } else {
00083     switch (enc->sample_rate) {
00084         case    44100:
00085             flags |= FLV_SAMPLERATE_44100HZ;
00086             break;
00087         case    22050:
00088             flags |= FLV_SAMPLERATE_22050HZ;
00089             break;
00090         case    11025:
00091             flags |= FLV_SAMPLERATE_11025HZ;
00092             break;
00093         case    16000: //nellymoser only
00094         case     8000: //nellymoser only
00095         case     5512: //not mp3
00096             if(enc->codec_id != CODEC_ID_MP3){
00097                 flags |= FLV_SAMPLERATE_SPECIAL;
00098                 break;
00099             }
00100         default:
00101             av_log(enc, AV_LOG_ERROR, "flv does not support that sample rate, choose from (44100, 22050, 11025).\n");
00102             return -1;
00103     }
00104     }
00105 
00106     if (enc->channels > 1) {
00107         flags |= FLV_STEREO;
00108     }
00109 
00110     switch(enc->codec_id){
00111     case CODEC_ID_MP3:
00112         flags |= FLV_CODECID_MP3    | FLV_SAMPLESSIZE_16BIT;
00113         break;
00114     case CODEC_ID_PCM_U8:
00115         flags |= FLV_CODECID_PCM    | FLV_SAMPLESSIZE_8BIT;
00116         break;
00117     case CODEC_ID_PCM_S16BE:
00118         flags |= FLV_CODECID_PCM    | FLV_SAMPLESSIZE_16BIT;
00119         break;
00120     case CODEC_ID_PCM_S16LE:
00121         flags |= FLV_CODECID_PCM_LE | FLV_SAMPLESSIZE_16BIT;
00122         break;
00123     case CODEC_ID_ADPCM_SWF:
00124         flags |= FLV_CODECID_ADPCM | FLV_SAMPLESSIZE_16BIT;
00125         break;
00126     case CODEC_ID_NELLYMOSER:
00127         if (enc->sample_rate == 8000) {
00128             flags |= FLV_CODECID_NELLYMOSER_8KHZ_MONO | FLV_SAMPLESSIZE_16BIT;
00129         } else if (enc->sample_rate == 16000) {
00130             flags |= FLV_CODECID_NELLYMOSER_16KHZ_MONO | FLV_SAMPLESSIZE_16BIT;
00131         } else {
00132             flags |= FLV_CODECID_NELLYMOSER | FLV_SAMPLESSIZE_16BIT;
00133         }
00134         break;
00135     case 0:
00136         flags |= enc->codec_tag<<4;
00137         break;
00138     default:
00139         av_log(enc, AV_LOG_ERROR, "codec not compatible with flv\n");
00140         return -1;
00141     }
00142 
00143     return flags;
00144 }
00145 
00146 static void put_amf_string(AVIOContext *pb, const char *str)
00147 {
00148     size_t len = strlen(str);
00149     avio_wb16(pb, len);
00150     avio_write(pb, str, len);
00151 }
00152 
00153 static void put_avc_eos_tag(AVIOContext *pb, unsigned ts) {
00154     avio_w8(pb, FLV_TAG_TYPE_VIDEO);
00155     avio_wb24(pb, 5);  /* Tag Data Size */
00156     avio_wb24(pb, ts);  /* lower 24 bits of timestamp in ms*/
00157     avio_w8(pb, (ts >> 24) & 0x7F);  /* MSB of ts in ms*/
00158     avio_wb24(pb, 0);  /* StreamId = 0 */
00159     avio_w8(pb, 23);  /* ub[4] FrameType = 1, ub[4] CodecId = 7 */
00160     avio_w8(pb, 2);  /* AVC end of sequence */
00161     avio_wb24(pb, 0);  /* Always 0 for AVC EOS. */
00162     avio_wb32(pb, 16);  /* Size of FLV tag */
00163 }
00164 
00165 static void put_amf_double(AVIOContext *pb, double d)
00166 {
00167     avio_w8(pb, AMF_DATA_TYPE_NUMBER);
00168     avio_wb64(pb, av_double2int(d));
00169 }
00170 
00171 static void put_amf_bool(AVIOContext *pb, int b) {
00172     avio_w8(pb, AMF_DATA_TYPE_BOOL);
00173     avio_w8(pb, !!b);
00174 }
00175 
00176 static int flv_write_header(AVFormatContext *s)
00177 {
00178     AVIOContext *pb = s->pb;
00179     FLVContext *flv = s->priv_data;
00180     AVCodecContext *audio_enc = NULL, *video_enc = NULL;
00181     int i, metadata_count = 0;
00182     double framerate = 0.0;
00183     int64_t metadata_size_pos, data_size, metadata_count_pos;
00184     AVDictionaryEntry *tag = NULL;
00185 
00186     for(i=0; i<s->nb_streams; i++){
00187         AVCodecContext *enc = s->streams[i]->codec;
00188         FLVStreamContext *sc;
00189         if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
00190             if (s->streams[i]->r_frame_rate.den && s->streams[i]->r_frame_rate.num) {
00191                 framerate = av_q2d(s->streams[i]->r_frame_rate);
00192             } else {
00193                 framerate = 1/av_q2d(s->streams[i]->codec->time_base);
00194             }
00195             video_enc = enc;
00196             if(enc->codec_tag == 0) {
00197                 av_log(enc, AV_LOG_ERROR, "video codec not compatible with flv\n");
00198                 return -1;
00199             }
00200         } else {
00201             audio_enc = enc;
00202             if(get_audio_flags(enc)<0)
00203                 return -1;
00204         }
00205         avpriv_set_pts_info(s->streams[i], 32, 1, 1000); /* 32 bit pts in ms */
00206 
00207         sc = av_mallocz(sizeof(FLVStreamContext));
00208         if (!sc)
00209             return AVERROR(ENOMEM);
00210         s->streams[i]->priv_data = sc;
00211         sc->last_ts = -1;
00212     }
00213     flv->delay = AV_NOPTS_VALUE;
00214 
00215     avio_write(pb, "FLV", 3);
00216     avio_w8(pb,1);
00217     avio_w8(pb,   FLV_HEADER_FLAG_HASAUDIO * !!audio_enc
00218                  + FLV_HEADER_FLAG_HASVIDEO * !!video_enc);
00219     avio_wb32(pb,9);
00220     avio_wb32(pb,0);
00221 
00222     for(i=0; i<s->nb_streams; i++){
00223         if(s->streams[i]->codec->codec_tag == 5){
00224             avio_w8(pb,8); // message type
00225             avio_wb24(pb,0); // include flags
00226             avio_wb24(pb,0); // time stamp
00227             avio_wb32(pb,0); // reserved
00228             avio_wb32(pb,11); // size
00229             flv->reserved=5;
00230         }
00231     }
00232 
00233     /* write meta_tag */
00234     avio_w8(pb, 18);         // tag type META
00235     metadata_size_pos= avio_tell(pb);
00236     avio_wb24(pb, 0);          // size of data part (sum of all parts below)
00237     avio_wb24(pb, 0);          // time stamp
00238     avio_wb32(pb, 0);          // reserved
00239 
00240     /* now data of data_size size */
00241 
00242     /* first event name as a string */
00243     avio_w8(pb, AMF_DATA_TYPE_STRING);
00244     put_amf_string(pb, "onMetaData"); // 12 bytes
00245 
00246     /* mixed array (hash) with size and string/type/data tuples */
00247     avio_w8(pb, AMF_DATA_TYPE_MIXEDARRAY);
00248     metadata_count_pos = avio_tell(pb);
00249     metadata_count = 5*!!video_enc + 5*!!audio_enc + 2; // +2 for duration and file size
00250     avio_wb32(pb, metadata_count);
00251 
00252     put_amf_string(pb, "duration");
00253     flv->duration_offset= avio_tell(pb);
00254     put_amf_double(pb, s->duration / AV_TIME_BASE); // fill in the guessed duration, it'll be corrected later if incorrect
00255 
00256     if(video_enc){
00257         put_amf_string(pb, "width");
00258         put_amf_double(pb, video_enc->width);
00259 
00260         put_amf_string(pb, "height");
00261         put_amf_double(pb, video_enc->height);
00262 
00263         put_amf_string(pb, "videodatarate");
00264         put_amf_double(pb, video_enc->bit_rate / 1024.0);
00265 
00266         put_amf_string(pb, "framerate");
00267         put_amf_double(pb, framerate);
00268 
00269         put_amf_string(pb, "videocodecid");
00270         put_amf_double(pb, video_enc->codec_tag);
00271     }
00272 
00273     if(audio_enc){
00274         put_amf_string(pb, "audiodatarate");
00275         put_amf_double(pb, audio_enc->bit_rate / 1024.0);
00276 
00277         put_amf_string(pb, "audiosamplerate");
00278         put_amf_double(pb, audio_enc->sample_rate);
00279 
00280         put_amf_string(pb, "audiosamplesize");
00281         put_amf_double(pb, audio_enc->codec_id == CODEC_ID_PCM_U8 ? 8 : 16);
00282 
00283         put_amf_string(pb, "stereo");
00284         put_amf_bool(pb, audio_enc->channels == 2);
00285 
00286         put_amf_string(pb, "audiocodecid");
00287         put_amf_double(pb, audio_enc->codec_tag);
00288     }
00289 
00290     while ((tag = av_dict_get(s->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {
00291         put_amf_string(pb, tag->key);
00292         avio_w8(pb, AMF_DATA_TYPE_STRING);
00293         put_amf_string(pb, tag->value);
00294         metadata_count++;
00295     }
00296 
00297     put_amf_string(pb, "filesize");
00298     flv->filesize_offset= avio_tell(pb);
00299     put_amf_double(pb, 0); // delayed write
00300 
00301     put_amf_string(pb, "");
00302     avio_w8(pb, AMF_END_OF_OBJECT);
00303 
00304     /* write total size of tag */
00305     data_size= avio_tell(pb) - metadata_size_pos - 10;
00306 
00307     avio_seek(pb, metadata_count_pos, SEEK_SET);
00308     avio_wb32(pb, metadata_count);
00309 
00310     avio_seek(pb, metadata_size_pos, SEEK_SET);
00311     avio_wb24(pb, data_size);
00312     avio_skip(pb, data_size + 10 - 3);
00313     avio_wb32(pb, data_size + 11);
00314 
00315     for (i = 0; i < s->nb_streams; i++) {
00316         AVCodecContext *enc = s->streams[i]->codec;
00317         if (enc->codec_id == CODEC_ID_AAC || enc->codec_id == CODEC_ID_H264) {
00318             int64_t pos;
00319             avio_w8(pb, enc->codec_type == AVMEDIA_TYPE_VIDEO ?
00320                      FLV_TAG_TYPE_VIDEO : FLV_TAG_TYPE_AUDIO);
00321             avio_wb24(pb, 0); // size patched later
00322             avio_wb24(pb, 0); // ts
00323             avio_w8(pb, 0); // ts ext
00324             avio_wb24(pb, 0); // streamid
00325             pos = avio_tell(pb);
00326             if (enc->codec_id == CODEC_ID_AAC) {
00327                 avio_w8(pb, get_audio_flags(enc));
00328                 avio_w8(pb, 0); // AAC sequence header
00329                 avio_write(pb, enc->extradata, enc->extradata_size);
00330             } else {
00331                 avio_w8(pb, enc->codec_tag | FLV_FRAME_KEY); // flags
00332                 avio_w8(pb, 0); // AVC sequence header
00333                 avio_wb24(pb, 0); // composition time
00334                 ff_isom_write_avcc(pb, enc->extradata, enc->extradata_size);
00335             }
00336             data_size = avio_tell(pb) - pos;
00337             avio_seek(pb, -data_size - 10, SEEK_CUR);
00338             avio_wb24(pb, data_size);
00339             avio_skip(pb, data_size + 10 - 3);
00340             avio_wb32(pb, data_size + 11); // previous tag size
00341         }
00342     }
00343 
00344     return 0;
00345 }
00346 
00347 static int flv_write_trailer(AVFormatContext *s)
00348 {
00349     int64_t file_size;
00350 
00351     AVIOContext *pb = s->pb;
00352     FLVContext *flv = s->priv_data;
00353     int i;
00354 
00355     /* Add EOS tag */
00356     for (i = 0; i < s->nb_streams; i++) {
00357         AVCodecContext *enc = s->streams[i]->codec;
00358         FLVStreamContext *sc = s->streams[i]->priv_data;
00359         if (enc->codec_type == AVMEDIA_TYPE_VIDEO &&
00360                 enc->codec_id == CODEC_ID_H264) {
00361             put_avc_eos_tag(pb, sc->last_ts);
00362         }
00363     }
00364 
00365     file_size = avio_tell(pb);
00366 
00367     /* update information */
00368     avio_seek(pb, flv->duration_offset, SEEK_SET);
00369     put_amf_double(pb, flv->duration / (double)1000);
00370     avio_seek(pb, flv->filesize_offset, SEEK_SET);
00371     put_amf_double(pb, file_size);
00372 
00373     avio_seek(pb, file_size, SEEK_SET);
00374     return 0;
00375 }
00376 
00377 static int flv_write_packet(AVFormatContext *s, AVPacket *pkt)
00378 {
00379     AVIOContext *pb = s->pb;
00380     AVCodecContext *enc = s->streams[pkt->stream_index]->codec;
00381     FLVContext *flv = s->priv_data;
00382     FLVStreamContext *sc = s->streams[pkt->stream_index]->priv_data;
00383     unsigned ts;
00384     int size= pkt->size;
00385     uint8_t *data= NULL;
00386     int flags, flags_size;
00387 
00388 //    av_log(s, AV_LOG_DEBUG, "type:%d pts: %"PRId64" size:%d\n", enc->codec_type, timestamp, size);
00389 
00390     if(enc->codec_id == CODEC_ID_VP6 || enc->codec_id == CODEC_ID_VP6F ||
00391        enc->codec_id == CODEC_ID_AAC)
00392         flags_size= 2;
00393     else if(enc->codec_id == CODEC_ID_H264)
00394         flags_size= 5;
00395     else
00396         flags_size= 1;
00397 
00398     if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
00399         avio_w8(pb, FLV_TAG_TYPE_VIDEO);
00400 
00401         flags = enc->codec_tag;
00402         if(flags == 0) {
00403             av_log(enc, AV_LOG_ERROR, "video codec %X not compatible with flv\n",enc->codec_id);
00404             return -1;
00405         }
00406 
00407         flags |= pkt->flags & AV_PKT_FLAG_KEY ? FLV_FRAME_KEY : FLV_FRAME_INTER;
00408     } else {
00409         assert(enc->codec_type == AVMEDIA_TYPE_AUDIO);
00410         flags = get_audio_flags(enc);
00411 
00412         assert(size);
00413 
00414         avio_w8(pb, FLV_TAG_TYPE_AUDIO);
00415     }
00416 
00417     if (enc->codec_id == CODEC_ID_H264) {
00418         /* check if extradata looks like MP4 */
00419         if (enc->extradata_size > 0 && *(uint8_t*)enc->extradata != 1) {
00420             if (ff_avc_parse_nal_units_buf(pkt->data, &data, &size) < 0)
00421                 return -1;
00422         }
00423     }
00424     if (flv->delay == AV_NOPTS_VALUE)
00425         flv->delay = -pkt->dts;
00426     if (pkt->dts < -flv->delay) {
00427         av_log(s, AV_LOG_WARNING, "Packets are not in the proper order with "
00428                                   "respect to DTS\n");
00429         return AVERROR(EINVAL);
00430     }
00431 
00432     ts = pkt->dts + flv->delay; // add delay to force positive dts
00433 
00434     /* check Speex packet duration */
00435     if (enc->codec_id == CODEC_ID_SPEEX && ts - sc->last_ts > 160) {
00436         av_log(s, AV_LOG_WARNING, "Warning: Speex stream has more than "
00437                                   "8 frames per packet. Adobe Flash "
00438                                   "Player cannot handle this!\n");
00439     }
00440 
00441     if (sc->last_ts < ts)
00442         sc->last_ts = ts;
00443 
00444     avio_wb24(pb,size + flags_size);
00445     avio_wb24(pb,ts);
00446     avio_w8(pb,(ts >> 24) & 0x7F); // timestamps are 32bits _signed_
00447     avio_wb24(pb,flv->reserved);
00448     avio_w8(pb,flags);
00449     if (enc->codec_id == CODEC_ID_VP6)
00450         avio_w8(pb,0);
00451     if (enc->codec_id == CODEC_ID_VP6F)
00452         avio_w8(pb, enc->extradata_size ? enc->extradata[0] : 0);
00453     else if (enc->codec_id == CODEC_ID_AAC)
00454         avio_w8(pb,1); // AAC raw
00455     else if (enc->codec_id == CODEC_ID_H264) {
00456         avio_w8(pb,1); // AVC NALU
00457         avio_wb24(pb,pkt->pts - pkt->dts);
00458     }
00459 
00460     avio_write(pb, data ? data : pkt->data, size);
00461 
00462     avio_wb32(pb,size+flags_size+11); // previous tag size
00463     flv->duration = FFMAX(flv->duration, pkt->pts + flv->delay + pkt->duration);
00464 
00465     avio_flush(pb);
00466 
00467     av_free(data);
00468 
00469     return pb->error;
00470 }
00471 
00472 AVOutputFormat ff_flv_muxer = {
00473     .name           = "flv",
00474     .long_name      = NULL_IF_CONFIG_SMALL("FLV format"),
00475     .mime_type      = "video/x-flv",
00476     .extensions     = "flv",
00477     .priv_data_size = sizeof(FLVContext),
00478 #if CONFIG_LIBMP3LAME
00479     .audio_codec    = CODEC_ID_MP3,
00480 #else // CONFIG_LIBMP3LAME
00481     .audio_codec    = CODEC_ID_ADPCM_SWF,
00482 #endif // CONFIG_LIBMP3LAME
00483     .video_codec    = CODEC_ID_FLV1,
00484     .write_header   = flv_write_header,
00485     .write_packet   = flv_write_packet,
00486     .write_trailer  = flv_write_trailer,
00487     .codec_tag= (const AVCodecTag* const []){flv_video_codec_ids, flv_audio_codec_ids, 0},
00488     .flags= AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
00489 };