]> git.sesse.net Git - ffmpeg/blobdiff - libavformat/flvenc.c
lavf: replace remaining uses of put_tag with avio_write
[ffmpeg] / libavformat / flvenc.c
index 302fc7602c0c2e3a759d8f14f737d5031b5578ab..4d49a966e9216cb54bf32a788fdeca756953c7f1 100644 (file)
 /*
- * FLV encoder.
- * Copyright (c) 2003 The FFmpeg Project.
+ * FLV muxer
+ * Copyright (c) 2003 The FFmpeg Project
  *
- * This library is free software; you can redistribute it and/or
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * version 2.1 of the License, or (at your option) any later version.
  *
- * This library is distributed in the hope that it will be useful,
+ * FFmpeg is distributed in the hope that it will be useful,
  * 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
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #include "avformat.h"
+#include "flv.h"
+#include "internal.h"
+#include "avc.h"
+#include "metadata.h"
+
+#undef NDEBUG
+#include <assert.h>
+
+static const AVCodecTag flv_video_codec_ids[] = {
+    {CODEC_ID_FLV1,    FLV_CODECID_H263  },
+    {CODEC_ID_FLASHSV, FLV_CODECID_SCREEN},
+    {CODEC_ID_FLASHSV2, FLV_CODECID_SCREEN2},
+    {CODEC_ID_VP6F,    FLV_CODECID_VP6   },
+    {CODEC_ID_VP6,     FLV_CODECID_VP6   },
+    {CODEC_ID_H264,    FLV_CODECID_H264  },
+    {CODEC_ID_NONE,    0}
+};
 
-#define VIDEO_FIFO_SIZE 512
-
-typedef struct FLVFrame {
-    int type;
-    int timestamp;
-    int flags;
-    uint8_t *data;
-    int size;
-    struct FLVFrame *next;
-} FLVFrame;
+static const AVCodecTag flv_audio_codec_ids[] = {
+    {CODEC_ID_MP3,       FLV_CODECID_MP3    >> FLV_AUDIO_CODECID_OFFSET},
+    {CODEC_ID_PCM_U8,    FLV_CODECID_PCM    >> FLV_AUDIO_CODECID_OFFSET},
+    {CODEC_ID_PCM_S16BE, FLV_CODECID_PCM    >> FLV_AUDIO_CODECID_OFFSET},
+    {CODEC_ID_PCM_S16LE, FLV_CODECID_PCM_LE >> FLV_AUDIO_CODECID_OFFSET},
+    {CODEC_ID_ADPCM_SWF, FLV_CODECID_ADPCM  >> FLV_AUDIO_CODECID_OFFSET},
+    {CODEC_ID_AAC,       FLV_CODECID_AAC    >> FLV_AUDIO_CODECID_OFFSET},
+    {CODEC_ID_NELLYMOSER, FLV_CODECID_NELLYMOSER >> FLV_AUDIO_CODECID_OFFSET},
+    {CODEC_ID_SPEEX,     FLV_CODECID_SPEEX  >> FLV_AUDIO_CODECID_OFFSET},
+    {CODEC_ID_NONE,      0}
+};
 
 typedef struct FLVContext {
-    int hasAudio;
-    int hasVideo;
-#ifdef CONFIG_MP3LAME
-    int audioTime;
-    int audioInPos;
-    int audioOutPos;
-    int audioSize;
-//    int audioRate;
-    int initDelay;
-    int soundDelay;
-    uint8_t *audioFifo;
-    int64_t sampleCount;
-#endif // CONFIG_MP3LAME
-    int64_t frameCount;
-    FLVFrame *frames;
+    int reserved;
+    int64_t duration_offset;
+    int64_t filesize_offset;
+    int64_t duration;
+    int delay; ///< first dts delay for AVC
+    int64_t last_video_ts;
 } FLVContext;
 
+static int get_audio_flags(AVCodecContext *enc){
+    int flags = (enc->bits_per_coded_sample == 16) ? FLV_SAMPLESSIZE_16BIT : FLV_SAMPLESSIZE_8BIT;
 
-#ifdef CONFIG_MP3LAME
+    if (enc->codec_id == CODEC_ID_AAC) // specs force these parameters
+        return FLV_CODECID_AAC | FLV_SAMPLERATE_44100HZ | FLV_SAMPLESSIZE_16BIT | FLV_STEREO;
+    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) {
+            av_log(enc, AV_LOG_WARNING, "Warning: Speex stream has more than "
+                                        "8 frames per packet. Adobe Flash "
+                                        "Player cannot handle this!\n");
+        }
+        return FLV_CODECID_SPEEX | FLV_SAMPLERATE_11025HZ | FLV_SAMPLESSIZE_16BIT;
+    } else {
+    switch (enc->sample_rate) {
+        case    44100:
+            flags |= FLV_SAMPLERATE_44100HZ;
+            break;
+        case    22050:
+            flags |= FLV_SAMPLERATE_22050HZ;
+            break;
+        case    11025:
+            flags |= FLV_SAMPLERATE_11025HZ;
+            break;
+        case     8000: //nellymoser only
+        case     5512: //not mp3
+            if(enc->codec_id != CODEC_ID_MP3){
+                flags |= FLV_SAMPLERATE_SPECIAL;
+                break;
+            }
+        default:
+            av_log(enc, AV_LOG_ERROR, "flv does not support that sample rate, choose from (44100, 22050, 11025).\n");
+            return -1;
+    }
+    }
 
-#define AUDIO_FIFO_SIZE 65536
+    if (enc->channels > 1) {
+        flags |= FLV_STEREO;
+    }
 
-static const int sSampleRates[3][4] = {
-    {44100, 48000, 32000, 0},
-    {22050, 24000, 16000, 0},
-    {11025, 12000,  8000, 0},
-};
+    switch(enc->codec_id){
+    case CODEC_ID_MP3:
+        flags |= FLV_CODECID_MP3    | FLV_SAMPLESSIZE_16BIT;
+        break;
+    case CODEC_ID_PCM_U8:
+        flags |= FLV_CODECID_PCM    | FLV_SAMPLESSIZE_8BIT;
+        break;
+    case CODEC_ID_PCM_S16BE:
+        flags |= FLV_CODECID_PCM    | FLV_SAMPLESSIZE_16BIT;
+        break;
+    case CODEC_ID_PCM_S16LE:
+        flags |= FLV_CODECID_PCM_LE | FLV_SAMPLESSIZE_16BIT;
+        break;
+    case CODEC_ID_ADPCM_SWF:
+        flags |= FLV_CODECID_ADPCM | FLV_SAMPLESSIZE_16BIT;
+        break;
+    case CODEC_ID_NELLYMOSER:
+        if (enc->sample_rate == 8000) {
+            flags |= FLV_CODECID_NELLYMOSER_8KHZ_MONO | FLV_SAMPLESSIZE_16BIT;
+        } else {
+            flags |= FLV_CODECID_NELLYMOSER | FLV_SAMPLESSIZE_16BIT;
+        }
+        break;
+    case 0:
+        flags |= enc->codec_tag<<4;
+        break;
+    default:
+        av_log(enc, AV_LOG_ERROR, "codec not compatible with flv\n");
+        return -1;
+    }
 
-static const int sBitRates[2][3][15] = {
-    {   {  0, 32, 64, 96,128,160,192,224,256,288,320,352,384,416,448},
-        {  0, 32, 48, 56, 64, 80, 96,112,128,160,192,224,256,320,384},
-        {  0, 32, 40, 48, 56, 64, 80, 96,112,128,160,192,224,256,320}
-    },
-    {   {  0, 32, 48, 56, 64, 80, 96,112,128,144,160,176,192,224,256},
-        {  0,  8, 16, 24, 32, 40, 48, 56, 64, 80, 96,112,128,144,160},
-        {  0,  8, 16, 24, 32, 40, 48, 56, 64, 80, 96,112,128,144,160}
-    },
-};
+    return flags;
+}
 
-static const int sSamplesPerFrame[3][3] =
+static void put_amf_string(AVIOContext *pb, const char *str)
 {
-    {  384,     1152,    1152 },
-    {  384,     1152,     576 },
-    {  384,     1152,     576 }
-};
+    size_t len = strlen(str);
+    avio_wb16(pb, len);
+    avio_write(pb, str, len);
+}
 
-static const int sBitsPerSlot[3] = {
-    32,
-    8,
-    8
-};
+static void put_avc_eos_tag(AVIOContext *pb, unsigned ts) {
+    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 */
+}
 
-static int mp3info(void *data, int *byteSize, int *samplesPerFrame, int *sampleRate, int *isMono )
+static void put_amf_double(AVIOContext *pb, double d)
 {
-    uint8_t *dataTmp = (uint8_t *)data;
-    uint32_t header = ( (uint32_t)dataTmp[0] << 24 ) | ( (uint32_t)dataTmp[1] << 16 ) | ( (uint32_t)dataTmp[2] << 8 ) | (uint32_t)dataTmp[3];
-    int layerID = 3 - ((header >> 17) & 0x03);
-    int bitRateID = ((header >> 12) & 0x0f);
-    int sampleRateID = ((header >> 10) & 0x03);
-    int bitRate = 0;
-    int bitsPerSlot = sBitsPerSlot[layerID];
-    int isPadded = ((header >> 9) & 0x01);
-
-    if ( (( header >> 21 ) & 0x7ff) != 0x7ff ) {
-        return 0;
-    }
-
-    if ( !isPadded ) {
-//        printf("Fatal error: mp3 data is not padded!\n");
-//        exit(0);
-    }
-
-    *isMono = ((header >>  6) & 0x03) == 0x03;
+    avio_w8(pb, AMF_DATA_TYPE_NUMBER);
+    avio_wb64(pb, av_dbl2int(d));
+}
 
-    if ( (header >> 19 ) & 0x01 ) {
-        //MPEG1
-        *sampleRate = sSampleRates[0][sampleRateID];
-        bitRate = sBitRates[0][layerID][bitRateID] * 1000;
-        *samplesPerFrame = sSamplesPerFrame[0][layerID];
-    } else {
-        if ( (header >> 20) & 0x01 ) {
-            //MPEG2
-            *sampleRate = sSampleRates[1][sampleRateID];
-            bitRate = sBitRates[1][layerID][bitRateID] * 1000;
-            *samplesPerFrame = sSamplesPerFrame[1][layerID];
-        } else {
-            //MPEG2.5
-            *sampleRate = sSampleRates[2][sampleRateID];
-            bitRate = sBitRates[1][layerID][bitRateID] * 1000;
-            *samplesPerFrame = sSamplesPerFrame[2][layerID];
-        }
-    }
-    
-    *byteSize = ( ( ( ( *samplesPerFrame * (bitRate / bitsPerSlot) ) / *sampleRate ) + isPadded ) );
-    return 1;
+static void put_amf_bool(AVIOContext *pb, int b) {
+    avio_w8(pb, AMF_DATA_TYPE_BOOL);
+    avio_w8(pb, !!b);
 }
-#endif // CONFIG_MP3LAME
 
 static int flv_write_header(AVFormatContext *s)
 {
-    ByteIOContext *pb = &s->pb;
+    AVIOContext *pb = s->pb;
     FLVContext *flv = s->priv_data;
+    AVCodecContext *audio_enc = NULL, *video_enc = NULL;
+    int i;
+    double framerate = 0.0;
+    int metadata_size_pos, data_size;
+    AVMetadataTag *tag = NULL;
+
+    for(i=0; i<s->nb_streams; i++){
+        AVCodecContext *enc = s->streams[i]->codec;
+        if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
+            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);
+            }
+            video_enc = enc;
+            if(enc->codec_tag == 0) {
+                av_log(enc, AV_LOG_ERROR, "video codec not compatible with flv\n");
+                return -1;
+            }
+        } else {
+            audio_enc = enc;
+            if(get_audio_flags(enc)<0)
+                return -1;
+        }
+        av_set_pts_info(s->streams[i], 32, 1, 1000); /* 32 bit pts in ms */
+    }
+    avio_write(pb, "FLV", 3);
+    avio_w8(pb,1);
+    avio_w8(pb,   FLV_HEADER_FLAG_HASAUDIO * !!audio_enc
+                 + FLV_HEADER_FLAG_HASVIDEO * !!video_enc);
+    avio_wb32(pb,9);
+    avio_wb32(pb,0);
+
+    for(i=0; i<s->nb_streams; i++){
+        if(s->streams[i]->codec->codec_tag == 5){
+            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
+            flv->reserved=5;
+        }
+    }
 
-    av_set_pts_info(s, 24, 1, 1000); /* 24 bit pts in ms */
+    flv->last_video_ts = -1;
 
-    flv->hasAudio = 0;
-    flv->hasVideo = 0;
+    /* write meta_tag */
+    avio_w8(pb, 18);         // tag type META
+    metadata_size_pos= url_ftell(pb);
+    avio_wb24(pb, 0);          // size of data part (sum of all parts below)
+    avio_wb24(pb, 0);          // time stamp
+    avio_wb32(pb, 0);          // reserved
 
-#ifdef CONFIG_MP3LAME
-    flv->audioTime = -1;
-    flv->audioFifo = av_malloc(AUDIO_FIFO_SIZE);
-    flv->audioInPos = 0;
-    flv->audioOutPos = 0;
-    flv->audioSize = 0;
-//    flv->audioRate = 44100;
-    flv->initDelay = -1;
-    flv->soundDelay = 0;
-#endif // CONFIG_MP3LAME
+    /* now data of data_size size */
 
-    flv->frames = 0;
+    /* first event name as a string */
+    avio_w8(pb, AMF_DATA_TYPE_STRING);
+    put_amf_string(pb, "onMetaData"); // 12 bytes
 
-    put_tag(pb,"FLV");
-    put_byte(pb,1);
-    put_byte(pb,0); // delayed write
-    put_be32(pb,9);
-    put_be32(pb,0);
+    /* mixed array (hash) with size and string/type/data tuples */
+    avio_w8(pb, AMF_DATA_TYPE_MIXEDARRAY);
+    avio_wb32(pb, 5*!!video_enc + 5*!!audio_enc + 2); // +2 for duration and file size
 
-    return 0;
-}
+    put_amf_string(pb, "duration");
+    flv->duration_offset= url_ftell(pb);
+    put_amf_double(pb, s->duration / AV_TIME_BASE); // fill in the guessed duration, it'll be corrected later if incorrect
 
-static void put_be24(ByteIOContext *pb, int value)
-{
-    put_byte(pb, (value>>16) & 0xFF );
-    put_byte(pb, (value>> 8) & 0xFF );
-    put_byte(pb, (value>> 0) & 0xFF );
-}
+    if(video_enc){
+        put_amf_string(pb, "width");
+        put_amf_double(pb, video_enc->width);
 
-static void InsertSorted(FLVContext *flv, FLVFrame *frame)
-{
-    if ( !flv->frames ) {
-        flv->frames = frame;
-    } else {
-        FLVFrame *trav = flv->frames;
-        FLVFrame *prev = 0;
-        for (;trav;) {
-            if ( trav->timestamp >= frame->timestamp ) {
-                frame->next = trav;
-                if ( prev ) {
-                    prev->next = frame;
-                } else {
-                    flv->frames = frame;
-                }
-                break;
-            }
-            prev = trav;
-            trav = trav->next;
-        }
-        if ( !trav ) {
-            prev->next = frame;
-        }
+        put_amf_string(pb, "height");
+        put_amf_double(pb, video_enc->height);
+
+        put_amf_string(pb, "videodatarate");
+        put_amf_double(pb, video_enc->bit_rate / 1024.0);
+
+        put_amf_string(pb, "framerate");
+        put_amf_double(pb, framerate);
+
+        put_amf_string(pb, "videocodecid");
+        put_amf_double(pb, video_enc->codec_tag);
     }
-}
 
-static void DumpFrame(ByteIOContext *pb, FLVFrame *frame)
-{
-    put_byte(pb,frame->type); // message type
-    put_be24(pb,frame->size+1); // include flags
-    put_be24(pb,frame->timestamp); // time stamp
-    put_be32(pb,0); // reserved
-    put_byte(pb,frame->flags);
-    put_buffer(pb, frame->data, frame->size);
-    put_be32(pb,frame->size+1+11); // reserved
-    av_free(frame->data);
-}
+    if(audio_enc){
+        put_amf_string(pb, "audiodatarate");
+        put_amf_double(pb, audio_enc->bit_rate / 1024.0);
 
-static void Dump(FLVContext *flv, ByteIOContext *pb, int count)
-{
-    int c=0;
-    FLVFrame *trav = flv->frames;
-    FLVFrame *prev = 0;
-    for (;trav;c++) {
-        trav = trav->next;
+        put_amf_string(pb, "audiosamplerate");
+        put_amf_double(pb, audio_enc->sample_rate);
+
+        put_amf_string(pb, "audiosamplesize");
+        put_amf_double(pb, audio_enc->codec_id == CODEC_ID_PCM_U8 ? 8 : 16);
+
+        put_amf_string(pb, "stereo");
+        put_amf_bool(pb, audio_enc->channels == 2);
+
+        put_amf_string(pb, "audiocodecid");
+        put_amf_double(pb, audio_enc->codec_tag);
+    }
+
+    while ((tag = av_metadata_get(s->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX))) {
+        put_amf_string(pb, tag->key);
+        avio_w8(pb, AMF_DATA_TYPE_STRING);
+        put_amf_string(pb, tag->value);
     }
-    trav = flv->frames;
-    for ( ; c >= count; c-- ) {
-        DumpFrame(pb,trav);
-        prev = trav;
-        trav = trav->next;
-        av_free(prev);
+
+    put_amf_string(pb, "filesize");
+    flv->filesize_offset= url_ftell(pb);
+    put_amf_double(pb, 0); // delayed write
+
+    put_amf_string(pb, "");
+    avio_w8(pb, AMF_END_OF_OBJECT);
+
+    /* write total size of tag */
+    data_size= url_ftell(pb) - metadata_size_pos - 10;
+    url_fseek(pb, metadata_size_pos, SEEK_SET);
+    avio_wb24(pb, data_size);
+    url_fseek(pb, data_size + 10 - 3, SEEK_CUR);
+    avio_wb32(pb, data_size + 11);
+
+    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) {
+            int64_t pos;
+            avio_w8(pb, enc->codec_type == AVMEDIA_TYPE_VIDEO ?
+                     FLV_TAG_TYPE_VIDEO : FLV_TAG_TYPE_AUDIO);
+            avio_wb24(pb, 0); // size patched later
+            avio_wb24(pb, 0); // ts
+            avio_w8(pb, 0); // ts ext
+            avio_wb24(pb, 0); // streamid
+            pos = url_ftell(pb);
+            if (enc->codec_id == CODEC_ID_AAC) {
+                avio_w8(pb, get_audio_flags(enc));
+                avio_w8(pb, 0); // AAC sequence header
+                avio_write(pb, enc->extradata, enc->extradata_size);
+            } else {
+                avio_w8(pb, enc->codec_tag | FLV_FRAME_KEY); // flags
+                avio_w8(pb, 0); // AVC sequence header
+                avio_wb24(pb, 0); // composition time
+                ff_isom_write_avcc(pb, enc->extradata, enc->extradata_size);
+            }
+            data_size = url_ftell(pb) - pos;
+            url_fseek(pb, -data_size - 10, SEEK_CUR);
+            avio_wb24(pb, data_size);
+            url_fseek(pb, data_size + 10 - 3, SEEK_CUR);
+            avio_wb32(pb, data_size + 11); // previous tag size
+        }
     }
-     flv->frames = trav;
+
+    return 0;
 }
 
 static int flv_write_trailer(AVFormatContext *s)
 {
     int64_t file_size;
-    int flags = 0;
 
-    ByteIOContext *pb = &s->pb;
+    AVIOContext *pb = s->pb;
     FLVContext *flv = s->priv_data;
-
-    Dump(flv,pb,1);
+    int i;
+
+    /* Add EOS tag */
+    for (i = 0; i < s->nb_streams; i++) {
+        AVCodecContext *enc = s->streams[i]->codec;
+        if (enc->codec_type == AVMEDIA_TYPE_VIDEO &&
+                enc->codec_id == CODEC_ID_H264) {
+            put_avc_eos_tag(pb, flv->last_video_ts);
+        }
+    }
 
     file_size = url_ftell(pb);
-    flags |= flv->hasAudio ? 4 : 0;
-    flags |= flv->hasVideo ? 1 : 0;
-    url_fseek(pb, 4, SEEK_SET);
-    put_byte(pb,flags);
+
+    /* update informations */
+    url_fseek(pb, flv->duration_offset, SEEK_SET);
+    put_amf_double(pb, flv->duration / (double)1000);
+    url_fseek(pb, flv->filesize_offset, SEEK_SET);
+    put_amf_double(pb, file_size);
+
     url_fseek(pb, file_size, SEEK_SET);
     return 0;
 }
 
-static int flv_write_packet(AVFormatContext *s, int stream_index,
-                            const uint8_t *buf, int size, int64_t timestamp)
+static int flv_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
-    ByteIOContext *pb = &s->pb;
-    AVCodecContext *enc = &s->streams[stream_index]->codec;
+    AVIOContext *pb = s->pb;
+    AVCodecContext *enc = s->streams[pkt->stream_index]->codec;
     FLVContext *flv = s->priv_data;
+    unsigned ts;
+    int size= pkt->size;
+    uint8_t *data= NULL;
+    int flags, flags_size;
+
+//    av_log(s, AV_LOG_DEBUG, "type:%d pts: %"PRId64" size:%d\n", enc->codec_type, timestamp, size);
+
+    if(enc->codec_id == CODEC_ID_VP6 || enc->codec_id == CODEC_ID_VP6F ||
+       enc->codec_id == CODEC_ID_AAC)
+        flags_size= 2;
+    else if(enc->codec_id == CODEC_ID_H264)
+        flags_size= 5;
+    else
+        flags_size= 1;
+
+    if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
+        avio_w8(pb, FLV_TAG_TYPE_VIDEO);
+
+        flags = enc->codec_tag;
+        if(flags == 0) {
+            av_log(enc, AV_LOG_ERROR, "video codec %X not compatible with flv\n",enc->codec_id);
+            return -1;
+        }
 
-    if (enc->codec_type == CODEC_TYPE_VIDEO) {
-        FLVFrame *frame = av_malloc(sizeof(FLVFrame));
-        frame->next = 0;
-        frame->type = 9;
-        frame->flags = 2; // choose h263
-        frame->flags |= enc->coded_frame->key_frame ? 0x10 : 0x20; // add keyframe indicator
-        frame->timestamp = timestamp;
-        //frame->timestamp = ( ( flv->frameCount * (int64_t)FRAME_RATE_BASE * (int64_t)1000 ) / (int64_t)enc->frame_rate );
-        //printf("%08x %f %f\n",frame->timestamp,(double)enc->frame_rate/(double)FRAME_RATE_BASE,1000*(double)FRAME_RATE_BASE/(double)enc->frame_rate);
-        frame->size = size;
-        frame->data = av_malloc(size);
-        memcpy(frame->data,buf,size);
-        flv->hasVideo = 1;
-
-        InsertSorted(flv,frame);
-
-        flv->frameCount ++;
-    }
-    else if (enc->codec_type == CODEC_TYPE_AUDIO) {
-#ifdef CONFIG_MP3LAME
-        if (enc->codec_id == CODEC_ID_MP3 ) {
-            int c=0;
+        flags |= pkt->flags & AV_PKT_FLAG_KEY ? FLV_FRAME_KEY : FLV_FRAME_INTER;
+    } else {
+        assert(enc->codec_type == AVMEDIA_TYPE_AUDIO);
+        flags = get_audio_flags(enc);
 
-            for (;c<size;c++) {
-                flv->audioFifo[(flv->audioOutPos+c)%AUDIO_FIFO_SIZE] = buf[c];
-            }
-            flv->audioSize += size;
-            flv->audioOutPos += size;
-            flv->audioOutPos %= AUDIO_FIFO_SIZE;
+        assert(size);
 
-            if ( flv->initDelay == -1 ) {
-                flv->initDelay = timestamp;
-            }
+        avio_w8(pb, FLV_TAG_TYPE_AUDIO);
+    }
 
-//            if ( flv->audioTime == -1 ) {
-                flv->audioTime = timestamp;
-//                flv->audioTime = ( ( ( flv->sampleCount - enc->delay ) * 8000 ) / flv->audioRate ) - flv->initDelay - 250;
-//                if ( flv->audioTime < 0 ) {
-//                    flv->audioTime = 0;
-//                }
-//            }
+    if (enc->codec_id == CODEC_ID_H264) {
+        /* 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;
         }
-        for ( ; flv->audioSize >= 4 ; ) {
-
-            int mp3FrameSize = 0;
-            int mp3SampleRate = 0;
-            int mp3IsMono = 0;
-            int mp3SamplesPerFrame = 0;
-            int c=0;
-
-            /* copy out mp3 header from ring buffer */
-            uint8_t header[4];
-            for (c=0; c<4; c++) {
-                header[c] = flv->audioFifo[(flv->audioInPos+c) % AUDIO_FIFO_SIZE];
-            }
+        if (!flv->delay && pkt->dts < 0)
+            flv->delay = -pkt->dts;
+    }
 
-            if ( mp3info(header,&mp3FrameSize,&mp3SamplesPerFrame,&mp3SampleRate,&mp3IsMono) ) {
-                if ( flv->audioSize >= mp3FrameSize ) {
-
-                    int soundFormat = 0x22;
-                    int c=0;
-                    FLVFrame *frame = av_malloc(sizeof(FLVFrame));
-
-//                    flv->audioRate = mp3SampleRate;
-
-                    switch (mp3SampleRate) {
-                        case    44100:
-                            soundFormat |= 0x0C;
-                            break;
-                        case    22050:
-                            soundFormat |= 0x08;
-                            break;
-                        case    11025:
-                            soundFormat |= 0x04;
-                            break;
-                    }
-
-                    if ( !mp3IsMono ) {
-                        soundFormat |= 0x01;
-                    }
-
-                    frame->next = 0;
-                    frame->type = 8;
-                    frame->flags = soundFormat;
-                    frame->timestamp = flv->audioTime;
-                    frame->timestamp = (1000*flv->sampleCount + mp3SampleRate/2)/(mp3SampleRate);
-                    frame->size = mp3FrameSize;
-                    frame->data = av_malloc(mp3FrameSize);
-
-                    for (;c<mp3FrameSize;c++) {
-                        frame->data[c] = flv->audioFifo[(flv->audioInPos+c)%AUDIO_FIFO_SIZE];
-                    }
-
-                    flv->audioInPos += mp3FrameSize;
-                    flv->audioSize -= mp3FrameSize;
-                    flv->audioInPos %= AUDIO_FIFO_SIZE;
-                    flv->sampleCount += mp3SamplesPerFrame;
-
-                    flv->audioTime += 1000*mp3SamplesPerFrame/mp3SampleRate;
-                    // We got audio! Make sure we set this to the global flags on closure
-                    flv->hasAudio = 1;
-
-                    InsertSorted(flv,frame);
-//                    av_log(NULL,AV_LOG_DEBUG, "insert sound\n");
-                    continue;
-                }
-//                av_log(NULL,AV_LOG_DEBUG, "insuficent data\n");
-                break;
-            }
-            av_log(NULL,AV_LOG_DEBUG, "head trashed\n");
-            flv->audioInPos ++;
-            flv->audioSize --;
-            flv->audioInPos %= AUDIO_FIFO_SIZE;
-            // no audio in here!
-            flv->audioTime = -1;
-        }
-#endif
+    ts = pkt->dts + flv->delay; // add delay to force positive dts
+    if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
+        if (flv->last_video_ts < ts)
+            flv->last_video_ts = ts;
+    }
+    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);
+    if (enc->codec_id == CODEC_ID_VP6)
+        avio_w8(pb,0);
+    if (enc->codec_id == CODEC_ID_VP6F)
+        avio_w8(pb, enc->extradata_size ? enc->extradata[0] : 0);
+    else if (enc->codec_id == CODEC_ID_AAC)
+        avio_w8(pb,1); // AAC raw
+    else if (enc->codec_id == CODEC_ID_H264) {
+        avio_w8(pb,1); // AVC NALU
+        avio_wb24(pb,pkt->pts - pkt->dts);
     }
-    Dump(flv,pb,128);
+
+    avio_write(pb, data ? data : pkt->data, size);
+
+    avio_wb32(pb,size+flags_size+11); // previous tag size
+    flv->duration = FFMAX(flv->duration, pkt->pts + flv->delay + pkt->duration);
+
     put_flush_packet(pb);
+
+    av_free(data);
+
     return 0;
 }
 
-static AVOutputFormat flv_oformat = {
+AVOutputFormat ff_flv_muxer = {
     "flv",
-    "flv format",
-    "video/x-flashvideo",
+    NULL_IF_CONFIG_SMALL("FLV format"),
+    "video/x-flv",
     "flv",
     sizeof(FLVContext),
-#ifdef CONFIG_MP3LAME
+#if CONFIG_LIBMP3LAME
     CODEC_ID_MP3,
-#else // CONFIG_MP3LAME
-    CODEC_ID_NONE,
-#endif // CONFIG_MP3LAME
+#else // CONFIG_LIBMP3LAME
+    CODEC_ID_ADPCM_SWF,
+#endif // CONFIG_LIBMP3LAME
     CODEC_ID_FLV1,
     flv_write_header,
     flv_write_packet,
     flv_write_trailer,
+    .codec_tag= (const AVCodecTag* const []){flv_video_codec_ids, flv_audio_codec_ids, 0},
+    .flags= AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
 };
-
-int flvenc_init(void)
-{
-    av_register_output_format(&flv_oformat);
-    return 0;
-}