libavformat/flvenc.c
d4f5d74a
 /*
7fbde343
  * FLV muxer
406792e7
  * Copyright (c) 2003 The FFmpeg Project
d4f5d74a
  *
b78e7197
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
d4f5d74a
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
b78e7197
  * version 2.1 of the License, or (at your option) any later version.
d4f5d74a
  *
b78e7197
  * FFmpeg is distributed in the hope that it will be useful,
d4f5d74a
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
b78e7197
  * License along with FFmpeg; if not, write to the Free Software
5509bffa
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
d4f5d74a
  */
c22f2527
 
 #include "libavutil/intreadwrite.h"
d4f5d74a
 #include "avformat.h"
6cac3a3b
 #include "flv.h"
80b39e1c
 #include "internal.h"
f23496b5
 #include "avc.h"
16f82508
 #include "metadata.h"
d2d67e42
 #include "libavutil/dict.h"
d4f5d74a
 
068f2a22
 #undef NDEBUG
 #include <assert.h>
 
7caf0cc6
 static const AVCodecTag flv_video_codec_ids[] = {
148c9bdb
     {CODEC_ID_FLV1,    FLV_CODECID_H263  },
     {CODEC_ID_FLASHSV, FLV_CODECID_SCREEN},
1b88277b
     {CODEC_ID_FLASHSV2, FLV_CODECID_SCREEN2},
148c9bdb
     {CODEC_ID_VP6F,    FLV_CODECID_VP6   },
09d8c0ae
     {CODEC_ID_VP6,     FLV_CODECID_VP6   },
f23496b5
     {CODEC_ID_H264,    FLV_CODECID_H264  },
148c9bdb
     {CODEC_ID_NONE,    0}
 };
 
7caf0cc6
 static const AVCodecTag flv_audio_codec_ids[] = {
148c9bdb
     {CODEC_ID_MP3,       FLV_CODECID_MP3    >> FLV_AUDIO_CODECID_OFFSET},
8e9efe43
     {CODEC_ID_PCM_U8,    FLV_CODECID_PCM    >> FLV_AUDIO_CODECID_OFFSET},
44de39f9
     {CODEC_ID_PCM_S16BE, FLV_CODECID_PCM    >> FLV_AUDIO_CODECID_OFFSET},
148c9bdb
     {CODEC_ID_PCM_S16LE, FLV_CODECID_PCM_LE >> FLV_AUDIO_CODECID_OFFSET},
     {CODEC_ID_ADPCM_SWF, FLV_CODECID_ADPCM  >> FLV_AUDIO_CODECID_OFFSET},
f23496b5
     {CODEC_ID_AAC,       FLV_CODECID_AAC    >> FLV_AUDIO_CODECID_OFFSET},
b7d1cd02
     {CODEC_ID_NELLYMOSER, FLV_CODECID_NELLYMOSER >> FLV_AUDIO_CODECID_OFFSET},
046c4001
     {CODEC_ID_SPEEX,     FLV_CODECID_SPEEX  >> FLV_AUDIO_CODECID_OFFSET},
148c9bdb
     {CODEC_ID_NONE,      0}
 };
 
d4f5d74a
 typedef struct FLVContext {
11a8e425
     int reserved;
bc5c918e
     int64_t duration_offset;
     int64_t filesize_offset;
634b8cfa
     int64_t duration;
f23496b5
     int delay; ///< first dts delay for AVC
df4f1d51
     int64_t last_video_ts;
d4f5d74a
 } FLVContext;
 
37cdf93d
 static int get_audio_flags(AVCodecContext *enc){
dd1c8f3e
     int flags = (enc->bits_per_coded_sample == 16) ? FLV_SAMPLESSIZE_16BIT : FLV_SAMPLESSIZE_8BIT;
37cdf93d
 
f23496b5
     if (enc->codec_id == CODEC_ID_AAC) // specs force these parameters
         return FLV_CODECID_AAC | FLV_SAMPLERATE_44100HZ | FLV_SAMPLESSIZE_16BIT | FLV_STEREO;
046c4001
     else if (enc->codec_id == CODEC_ID_SPEEX) {
         if (enc->sample_rate != 16000) {
             av_log(enc, AV_LOG_ERROR, "flv only supports wideband (16kHz) Speex audio\n");
             return -1;
         }
         if (enc->channels != 1) {
             av_log(enc, AV_LOG_ERROR, "flv only supports mono Speex audio\n");
             return -1;
         }
         if (enc->frame_size / 320 > 8) {
68677dd8
             av_log(enc, AV_LOG_WARNING, "Warning: Speex stream has more than "
                                         "8 frames per packet. Adobe Flash "
                                         "Player cannot handle this!\n");
046c4001
         }
         return FLV_CODECID_SPEEX | FLV_SAMPLERATE_11025HZ | FLV_SAMPLESSIZE_16BIT;
     } else {
37cdf93d
     switch (enc->sample_rate) {
         case    44100:
6cac3a3b
             flags |= FLV_SAMPLERATE_44100HZ;
37cdf93d
             break;
         case    22050:
6cac3a3b
             flags |= FLV_SAMPLERATE_22050HZ;
37cdf93d
             break;
         case    11025:
6cac3a3b
             flags |= FLV_SAMPLERATE_11025HZ;
37cdf93d
             break;
         case     8000: //nellymoser only
         case     5512: //not mp3
4838727e
             if(enc->codec_id != CODEC_ID_MP3){
ec627278
                 flags |= FLV_SAMPLERATE_SPECIAL;
                 break;
4838727e
             }
37cdf93d
         default:
755bfeab
             av_log(enc, AV_LOG_ERROR, "flv does not support that sample rate, choose from (44100, 22050, 11025).\n");
37cdf93d
             return -1;
     }
f23496b5
     }
37cdf93d
 
     if (enc->channels > 1) {
6cac3a3b
         flags |= FLV_STEREO;
37cdf93d
     }
115329f1
 
37cdf93d
     switch(enc->codec_id){
     case CODEC_ID_MP3:
6cac3a3b
         flags |= FLV_CODECID_MP3    | FLV_SAMPLESSIZE_16BIT;
37cdf93d
         break;
8e9efe43
     case CODEC_ID_PCM_U8:
44de39f9
         flags |= FLV_CODECID_PCM    | FLV_SAMPLESSIZE_8BIT;
bb270c08
         break;
923bd441
     case CODEC_ID_PCM_S16BE:
44de39f9
         flags |= FLV_CODECID_PCM    | FLV_SAMPLESSIZE_16BIT;
bb270c08
         break;
923bd441
     case CODEC_ID_PCM_S16LE:
6cac3a3b
         flags |= FLV_CODECID_PCM_LE | FLV_SAMPLESSIZE_16BIT;
bb270c08
         break;
2fde8aae
     case CODEC_ID_ADPCM_SWF:
e9509536
         flags |= FLV_CODECID_ADPCM | FLV_SAMPLESSIZE_16BIT;
bb270c08
         break;
b7d1cd02
     case CODEC_ID_NELLYMOSER:
8ddd280d
         if (enc->sample_rate == 8000) {
             flags |= FLV_CODECID_NELLYMOSER_8KHZ_MONO | FLV_SAMPLESSIZE_16BIT;
         } else {
             flags |= FLV_CODECID_NELLYMOSER | FLV_SAMPLESSIZE_16BIT;
         }
b7d1cd02
         break;
37cdf93d
     case 0:
         flags |= enc->codec_tag<<4;
         break;
     default:
a254c574
         av_log(enc, AV_LOG_ERROR, "codec not compatible with flv\n");
37cdf93d
         return -1;
     }
115329f1
 
37cdf93d
     return flags;
 }
 
ae628ec1
 static void put_amf_string(AVIOContext *pb, const char *str)
fd0fb306
 {
     size_t len = strlen(str);
77eb5504
     avio_wb16(pb, len);
     avio_write(pb, str, len);
fd0fb306
 }
 
ae628ec1
 static void put_avc_eos_tag(AVIOContext *pb, unsigned ts) {
77eb5504
     avio_w8(pb, FLV_TAG_TYPE_VIDEO);
     avio_wb24(pb, 5);  /* Tag Data Size */
     avio_wb24(pb, ts);  /* lower 24 bits of timestamp in ms*/
     avio_w8(pb, (ts >> 24) & 0x7F);  /* MSB of ts in ms*/
     avio_wb24(pb, 0);  /* StreamId = 0 */
     avio_w8(pb, 23);  /* ub[4] FrameType = 1, ub[4] CodecId = 7 */
     avio_w8(pb, 2);  /* AVC end of sequence */
     avio_wb24(pb, 0);  /* Always 0 for AVC EOS. */
     avio_wb32(pb, 16);  /* Size of FLV tag */
df4f1d51
 }
 
ae628ec1
 static void put_amf_double(AVIOContext *pb, double d)
fd0fb306
 {
77eb5504
     avio_w8(pb, AMF_DATA_TYPE_NUMBER);
     avio_wb64(pb, av_dbl2int(d));
fd0fb306
 }
 
ae628ec1
 static void put_amf_bool(AVIOContext *pb, int b) {
77eb5504
     avio_w8(pb, AMF_DATA_TYPE_BOOL);
     avio_w8(pb, !!b);
148c9bdb
 }
 
d4f5d74a
 static int flv_write_header(AVFormatContext *s)
 {
ae628ec1
     AVIOContext *pb = s->pb;
d4f5d74a
     FLVContext *flv = s->priv_data;
5366f15d
     AVCodecContext *audio_enc = NULL, *video_enc = NULL;
     int i;
fd0fb306
     double framerate = 0.0;
e30e0a16
     int64_t metadata_size_pos, data_size;
d2d67e42
     AVDictionaryEntry *tag = NULL;
d4f5d74a
 
11a8e425
     for(i=0; i<s->nb_streams; i++){
01f4895c
         AVCodecContext *enc = s->streams[i]->codec;
72415b2a
         if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
fd0fb306
             if (s->streams[i]->r_frame_rate.den && s->streams[i]->r_frame_rate.num) {
                 framerate = av_q2d(s->streams[i]->r_frame_rate);
             } else {
                 framerate = 1/av_q2d(s->streams[i]->codec->time_base);
             }
5366f15d
             video_enc = enc;
             if(enc->codec_tag == 0) {
148c9bdb
                 av_log(enc, AV_LOG_ERROR, "video codec not compatible with flv\n");
                 return -1;
             }
fd0fb306
         } else {
5366f15d
             audio_enc = enc;
c45388b1
             if(get_audio_flags(enc)<0)
                 return -1;
fd0fb306
         }
254629b1
         av_set_pts_info(s->streams[i], 32, 1, 1000); /* 32 bit pts in ms */
c45388b1
     }
bbc413f9
     avio_write(pb, "FLV", 3);
77eb5504
     avio_w8(pb,1);
     avio_w8(pb,   FLV_HEADER_FLAG_HASAUDIO * !!audio_enc
5366f15d
                  + FLV_HEADER_FLAG_HASVIDEO * !!video_enc);
77eb5504
     avio_wb32(pb,9);
     avio_wb32(pb,0);
c45388b1
 
     for(i=0; i<s->nb_streams; i++){
         if(s->streams[i]->codec->codec_tag == 5){
77eb5504
             avio_w8(pb,8); // message type
             avio_wb24(pb,0); // include flags
             avio_wb24(pb,0); // time stamp
             avio_wb32(pb,0); // reserved
             avio_wb32(pb,11); // size
11a8e425
             flv->reserved=5;
         }
     }
d4f5d74a
 
df4f1d51
     flv->last_video_ts = -1;
 
fd0fb306
     /* write meta_tag */
77eb5504
     avio_w8(pb, 18);         // tag type META
a2704c97
     metadata_size_pos= avio_tell(pb);
77eb5504
     avio_wb24(pb, 0);          // size of data part (sum of all parts below)
     avio_wb24(pb, 0);          // time stamp
     avio_wb32(pb, 0);          // reserved
fd0fb306
 
     /* now data of data_size size */
 
     /* first event name as a string */
77eb5504
     avio_w8(pb, AMF_DATA_TYPE_STRING);
fd0fb306
     put_amf_string(pb, "onMetaData"); // 12 bytes
 
     /* mixed array (hash) with size and string/type/data tuples */
77eb5504
     avio_w8(pb, AMF_DATA_TYPE_MIXEDARRAY);
     avio_wb32(pb, 5*!!video_enc + 5*!!audio_enc + 2); // +2 for duration and file size
fd0fb306
 
634b8cfa
     put_amf_string(pb, "duration");
a2704c97
     flv->duration_offset= avio_tell(pb);
c5e1e982
     put_amf_double(pb, s->duration / AV_TIME_BASE); // fill in the guessed duration, it'll be corrected later if incorrect
fd0fb306
 
5366f15d
     if(video_enc){
fd0fb306
         put_amf_string(pb, "width");
5366f15d
         put_amf_double(pb, video_enc->width);
fd0fb306
 
         put_amf_string(pb, "height");
5366f15d
         put_amf_double(pb, video_enc->height);
fd0fb306
 
         put_amf_string(pb, "videodatarate");
426a6f34
         put_amf_double(pb, video_enc->bit_rate / 1024.0);
fd0fb306
 
         put_amf_string(pb, "framerate");
         put_amf_double(pb, framerate);
148c9bdb
 
         put_amf_string(pb, "videocodecid");
5366f15d
         put_amf_double(pb, video_enc->codec_tag);
fd0fb306
     }
 
5366f15d
     if(audio_enc){
426a6f34
         put_amf_string(pb, "audiodatarate");
         put_amf_double(pb, audio_enc->bit_rate / 1024.0);
 
fd0fb306
         put_amf_string(pb, "audiosamplerate");
5366f15d
         put_amf_double(pb, audio_enc->sample_rate);
148c9bdb
 
         put_amf_string(pb, "audiosamplesize");
8e9efe43
         put_amf_double(pb, audio_enc->codec_id == CODEC_ID_PCM_U8 ? 8 : 16);
148c9bdb
 
         put_amf_string(pb, "stereo");
5366f15d
         put_amf_bool(pb, audio_enc->channels == 2);
148c9bdb
 
         put_amf_string(pb, "audiocodecid");
5366f15d
         put_amf_double(pb, audio_enc->codec_tag);
fd0fb306
     }
 
d2d67e42
     while ((tag = av_dict_get(s->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {
16f82508
         put_amf_string(pb, tag->key);
77eb5504
         avio_w8(pb, AMF_DATA_TYPE_STRING);
16f82508
         put_amf_string(pb, tag->value);
     }
 
634b8cfa
     put_amf_string(pb, "filesize");
a2704c97
     flv->filesize_offset= avio_tell(pb);
634b8cfa
     put_amf_double(pb, 0); // delayed write
fd0fb306
 
     put_amf_string(pb, "");
77eb5504
     avio_w8(pb, AMF_END_OF_OBJECT);
fd0fb306
 
     /* write total size of tag */
a2704c97
     data_size= avio_tell(pb) - metadata_size_pos - 10;
6b4aa5da
     avio_seek(pb, metadata_size_pos, SEEK_SET);
77eb5504
     avio_wb24(pb, data_size);
45a8a02a
     avio_skip(pb, data_size + 10 - 3);
77eb5504
     avio_wb32(pb, data_size + 11);
fd0fb306
 
f23496b5
     for (i = 0; i < s->nb_streams; i++) {
         AVCodecContext *enc = s->streams[i]->codec;
         if (enc->codec_id == CODEC_ID_AAC || enc->codec_id == CODEC_ID_H264) {
bc5c918e
             int64_t pos;
77eb5504
             avio_w8(pb, enc->codec_type == AVMEDIA_TYPE_VIDEO ?
f23496b5
                      FLV_TAG_TYPE_VIDEO : FLV_TAG_TYPE_AUDIO);
77eb5504
             avio_wb24(pb, 0); // size patched later
             avio_wb24(pb, 0); // ts
             avio_w8(pb, 0); // ts ext
             avio_wb24(pb, 0); // streamid
a2704c97
             pos = avio_tell(pb);
f23496b5
             if (enc->codec_id == CODEC_ID_AAC) {
77eb5504
                 avio_w8(pb, get_audio_flags(enc));
                 avio_w8(pb, 0); // AAC sequence header
                 avio_write(pb, enc->extradata, enc->extradata_size);
f23496b5
             } else {
77eb5504
                 avio_w8(pb, enc->codec_tag | FLV_FRAME_KEY); // flags
                 avio_w8(pb, 0); // AVC sequence header
                 avio_wb24(pb, 0); // composition time
f23496b5
                 ff_isom_write_avcc(pb, enc->extradata, enc->extradata_size);
             }
a2704c97
             data_size = avio_tell(pb) - pos;
6b4aa5da
             avio_seek(pb, -data_size - 10, SEEK_CUR);
77eb5504
             avio_wb24(pb, data_size);
45a8a02a
             avio_skip(pb, data_size + 10 - 3);
77eb5504
             avio_wb32(pb, data_size + 11); // previous tag size
f23496b5
         }
     }
 
d4f5d74a
     return 0;
 }
 
 static int flv_write_trailer(AVFormatContext *s)
 {
14b32253
     int64_t file_size;
 
ae628ec1
     AVIOContext *pb = s->pb;
d4f5d74a
     FLVContext *flv = s->priv_data;
df4f1d51
     int i;
 
     /* Add EOS tag */
     for (i = 0; i < s->nb_streams; i++) {
         AVCodecContext *enc = s->streams[i]->codec;
b9f9e59a
         if (enc->codec_type == AVMEDIA_TYPE_VIDEO &&
df4f1d51
                 enc->codec_id == CODEC_ID_H264) {
             put_avc_eos_tag(pb, flv->last_video_ts);
         }
     }
d4f5d74a
 
a2704c97
     file_size = avio_tell(pb);
634b8cfa
 
     /* update informations */
6b4aa5da
     avio_seek(pb, flv->duration_offset, SEEK_SET);
634b8cfa
     put_amf_double(pb, flv->duration / (double)1000);
6b4aa5da
     avio_seek(pb, flv->filesize_offset, SEEK_SET);
634b8cfa
     put_amf_double(pb, file_size);
 
6b4aa5da
     avio_seek(pb, file_size, SEEK_SET);
d4f5d74a
     return 0;
 }
 
e928649b
 static int flv_write_packet(AVFormatContext *s, AVPacket *pkt)
d4f5d74a
 {
ae628ec1
     AVIOContext *pb = s->pb;
01f4895c
     AVCodecContext *enc = s->streams[pkt->stream_index]->codec;
d4f5d74a
     FLVContext *flv = s->priv_data;
f23496b5
     unsigned ts;
e928649b
     int size= pkt->size;
71e685b0
     uint8_t *data= NULL;
f683dbdc
     int flags, flags_size;
d4f5d74a
 
949b1a13
 //    av_log(s, AV_LOG_DEBUG, "type:%d pts: %"PRId64" size:%d\n", enc->codec_type, timestamp, size);
115329f1
 
f23496b5
     if(enc->codec_id == CODEC_ID_VP6 || enc->codec_id == CODEC_ID_VP6F ||
        enc->codec_id == CODEC_ID_AAC)
f683dbdc
         flags_size= 2;
f23496b5
     else if(enc->codec_id == CODEC_ID_H264)
         flags_size= 5;
f683dbdc
     else
         flags_size= 1;
 
72415b2a
     if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
77eb5504
         avio_w8(pb, FLV_TAG_TYPE_VIDEO);
09d8c0ae
 
bb85077f
         flags = enc->codec_tag;
09d8c0ae
         if(flags == 0) {
             av_log(enc, AV_LOG_ERROR, "video codec %X not compatible with flv\n",enc->codec_id);
             return -1;
         }
 
cc947f04
         flags |= pkt->flags & AV_PKT_FLAG_KEY ? FLV_FRAME_KEY : FLV_FRAME_INTER;
75293f05
     } else {
72415b2a
         assert(enc->codec_type == AVMEDIA_TYPE_AUDIO);
37cdf93d
         flags = get_audio_flags(enc);
115329f1
 
068f2a22
         assert(size);
 
77eb5504
         avio_w8(pb, FLV_TAG_TYPE_AUDIO);
75293f05
     }
 
7d637efa
     if (enc->codec_id == CODEC_ID_H264) {
71e685b0
         /* check if extradata looks like mp4 formated */
         if (enc->extradata_size > 0 && *(uint8_t*)enc->extradata != 1) {
             if (ff_avc_parse_nal_units_buf(pkt->data, &data, &size) < 0)
                 return -1;
         }
6f4eb12d
         if (!flv->delay && pkt->dts < 0)
             flv->delay = -pkt->dts;
c22f2527
     } else if (enc->codec_id == CODEC_ID_AAC && pkt->size > 2 &&
                (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
         av_log(s, AV_LOG_ERROR, "malformated aac bitstream, use -absf aac_adtstoasc\n");
         return -1;
f23496b5
     }
 
     ts = pkt->dts + flv->delay; // add delay to force positive dts
b9f9e59a
     if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
df4f1d51
         if (flv->last_video_ts < ts)
             flv->last_video_ts = ts;
     }
77eb5504
     avio_wb24(pb,size + flags_size);
     avio_wb24(pb,ts);
     avio_w8(pb,(ts >> 24) & 0x7F); // timestamps are 32bits _signed_
     avio_wb24(pb,flv->reserved);
     avio_w8(pb,flags);
09d8c0ae
     if (enc->codec_id == CODEC_ID_VP6)
77eb5504
         avio_w8(pb,0);
09d8c0ae
     if (enc->codec_id == CODEC_ID_VP6F)
77eb5504
         avio_w8(pb, enc->extradata_size ? enc->extradata[0] : 0);
f23496b5
     else if (enc->codec_id == CODEC_ID_AAC)
77eb5504
         avio_w8(pb,1); // AAC raw
f23496b5
     else if (enc->codec_id == CODEC_ID_H264) {
77eb5504
         avio_w8(pb,1); // AVC NALU
         avio_wb24(pb,pkt->pts - pkt->dts);
f23496b5
     }
71e685b0
 
77eb5504
     avio_write(pb, data ? data : pkt->data, size);
71e685b0
 
77eb5504
     avio_wb32(pb,size+flags_size+11); // previous tag size
f23496b5
     flv->duration = FFMAX(flv->duration, pkt->pts + flv->delay + pkt->duration);
115329f1
 
b7f2fdde
     avio_flush(pb);
71e685b0
 
     av_free(data);
 
0e28e9ca
     return pb->error;
d4f5d74a
 }
 
c6610a21
 AVOutputFormat ff_flv_muxer = {
d4f5d74a
     "flv",
bde15e74
     NULL_IF_CONFIG_SMALL("FLV format"),
e817a73d
     "video/x-flv",
d4f5d74a
     "flv",
     sizeof(FLVContext),
b250f9c6
 #if CONFIG_LIBMP3LAME
80783dc2
     CODEC_ID_MP3,
6ebe07fb
 #else // CONFIG_LIBMP3LAME
964ff354
     CODEC_ID_ADPCM_SWF,
6ebe07fb
 #endif // CONFIG_LIBMP3LAME
d4f5d74a
     CODEC_ID_FLV1,
     flv_write_header,
     flv_write_packet,
     flv_write_trailer,
c1854592
     .codec_tag= (const AVCodecTag* const []){flv_video_codec_ids, flv_audio_codec_ids, 0},
e458dd0b
     .flags= AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
d4f5d74a
 };