flvenc.c 21.3 KB
Newer Older
1
/*
2
 * FLV muxer
3
 * Copyright (c) 2003 The FFmpeg Project
4
 *
5 6 7
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
8 9
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13 14 15 16 17
 * 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
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21 22

#include "libavutil/intreadwrite.h"
23
#include "libavutil/dict.h"
24
#include "libavutil/intfloat.h"
25
#include "libavutil/avassert.h"
26
#include "avc.h"
27
#include "avformat.h"
28
#include "flv.h"
29
#include "internal.h"
Tomás Touceda's avatar
Tomás Touceda committed
30
#include "metadata.h"
31

Michael Niedermayer's avatar
Michael Niedermayer committed
32

33
static const AVCodecTag flv_video_codec_ids[] = {
34
    { AV_CODEC_ID_FLV1,     FLV_CODECID_H263 },
35 36
    { AV_CODEC_ID_H263,     FLV_CODECID_REALH263 },
    { AV_CODEC_ID_MPEG4,    FLV_CODECID_MPEG4 },
37 38 39
    { AV_CODEC_ID_FLASHSV,  FLV_CODECID_SCREEN },
    { AV_CODEC_ID_FLASHSV2, FLV_CODECID_SCREEN2 },
    { AV_CODEC_ID_VP6F,     FLV_CODECID_VP6 },
40
    { AV_CODEC_ID_VP6A,     FLV_CODECID_VP6A },
41 42
    { AV_CODEC_ID_H264,     FLV_CODECID_H264 },
    { AV_CODEC_ID_NONE,     0 }
43 44
};

45
static const AVCodecTag flv_audio_codec_ids[] = {
46 47 48 49 50 51 52 53 54 55 56
    { AV_CODEC_ID_MP3,        FLV_CODECID_MP3        >> FLV_AUDIO_CODECID_OFFSET },
    { AV_CODEC_ID_PCM_U8,     FLV_CODECID_PCM        >> FLV_AUDIO_CODECID_OFFSET },
    { AV_CODEC_ID_PCM_S16BE,  FLV_CODECID_PCM        >> FLV_AUDIO_CODECID_OFFSET },
    { AV_CODEC_ID_PCM_S16LE,  FLV_CODECID_PCM_LE     >> FLV_AUDIO_CODECID_OFFSET },
    { AV_CODEC_ID_ADPCM_SWF,  FLV_CODECID_ADPCM      >> FLV_AUDIO_CODECID_OFFSET },
    { AV_CODEC_ID_AAC,        FLV_CODECID_AAC        >> FLV_AUDIO_CODECID_OFFSET },
    { AV_CODEC_ID_NELLYMOSER, FLV_CODECID_NELLYMOSER >> FLV_AUDIO_CODECID_OFFSET },
    { AV_CODEC_ID_PCM_MULAW,  FLV_CODECID_PCM_MULAW  >> FLV_AUDIO_CODECID_OFFSET },
    { AV_CODEC_ID_PCM_ALAW,   FLV_CODECID_PCM_ALAW   >> FLV_AUDIO_CODECID_OFFSET },
    { AV_CODEC_ID_SPEEX,      FLV_CODECID_SPEEX      >> FLV_AUDIO_CODECID_OFFSET },
    { AV_CODEC_ID_NONE,       0 }
57 58
};

59
typedef struct FLVContext {
60
    int     reserved;
61 62
    int64_t duration_offset;
    int64_t filesize_offset;
63
    int64_t duration;
64
    int64_t delay;      ///< first dts delay (needed for AVC & Speex)
65 66
} FLVContext;

67 68 69 70
typedef struct FLVStreamContext {
    int64_t last_ts;    ///< last timestamp for each stream
} FLVStreamContext;

71 72
static int get_audio_flags(AVFormatContext *s, AVCodecContext *enc)
{
73 74
    int flags = (enc->bits_per_coded_sample == 16) ? FLV_SAMPLESSIZE_16BIT
                                                   : FLV_SAMPLESSIZE_8BIT;
75

76
    if (enc->codec_id == AV_CODEC_ID_AAC) // specs force these parameters
77 78
        return FLV_CODECID_AAC | FLV_SAMPLERATE_44100HZ |
               FLV_SAMPLESSIZE_16BIT | FLV_STEREO;
79
    else if (enc->codec_id == AV_CODEC_ID_SPEEX) {
80
        if (enc->sample_rate != 16000) {
81
            av_log(s, AV_LOG_ERROR,
82
                   "FLV only supports wideband (16kHz) Speex audio\n");
83
            return AVERROR(EINVAL);
84 85
        }
        if (enc->channels != 1) {
86
            av_log(s, AV_LOG_ERROR, "FLV only supports mono Speex audio\n");
87
            return AVERROR(EINVAL);
88 89 90
        }
        return FLV_CODECID_SPEEX | FLV_SAMPLERATE_11025HZ | FLV_SAMPLESSIZE_16BIT;
    } else {
91 92
        switch (enc->sample_rate) {
        case 44100:
93
            flags |= FLV_SAMPLERATE_44100HZ;
94
            break;
95
        case 22050:
96
            flags |= FLV_SAMPLERATE_22050HZ;
97
            break;
98
        case 11025:
99
            flags |= FLV_SAMPLERATE_11025HZ;
100
            break;
101 102 103
        case 16000: // nellymoser only
        case  8000: // nellymoser only
        case  5512: // not MP3
104
            if (enc->codec_id != AV_CODEC_ID_MP3) {
Michael Niedermayer's avatar
Michael Niedermayer committed
105 106
                flags |= FLV_SAMPLERATE_SPECIAL;
                break;
107
            }
108
        default:
109
            av_log(s, AV_LOG_ERROR,
110 111
                   "FLV does not support sample rate %d, "
                   "choose from (44100, 22050, 11025)\n", enc->sample_rate);
112
            return AVERROR(EINVAL);
113
        }
114
    }
115

116
    if (enc->channels > 1)
117
        flags |= FLV_STEREO;
118

119
    switch (enc->codec_id) {
120
    case AV_CODEC_ID_MP3:
121
        flags |= FLV_CODECID_MP3    | FLV_SAMPLESSIZE_16BIT;
122
        break;
123
    case AV_CODEC_ID_PCM_U8:
124
        flags |= FLV_CODECID_PCM    | FLV_SAMPLESSIZE_8BIT;
125
        break;
126
    case AV_CODEC_ID_PCM_S16BE:
127
        flags |= FLV_CODECID_PCM    | FLV_SAMPLESSIZE_16BIT;
128
        break;
129
    case AV_CODEC_ID_PCM_S16LE:
130
        flags |= FLV_CODECID_PCM_LE | FLV_SAMPLESSIZE_16BIT;
131
        break;
132
    case AV_CODEC_ID_ADPCM_SWF:
133
        flags |= FLV_CODECID_ADPCM  | FLV_SAMPLESSIZE_16BIT;
134
        break;
135
    case AV_CODEC_ID_NELLYMOSER:
136 137 138
        if (enc->sample_rate == 8000)
            flags |= FLV_CODECID_NELLYMOSER_8KHZ_MONO  | FLV_SAMPLESSIZE_16BIT;
        else if (enc->sample_rate == 16000)
139
            flags |= FLV_CODECID_NELLYMOSER_16KHZ_MONO | FLV_SAMPLESSIZE_16BIT;
140 141
        else
            flags |= FLV_CODECID_NELLYMOSER            | FLV_SAMPLESSIZE_16BIT;
142
        break;
143
    case AV_CODEC_ID_PCM_MULAW:
144 145
        flags = FLV_CODECID_PCM_MULAW | FLV_SAMPLERATE_SPECIAL | FLV_SAMPLESSIZE_16BIT;
        break;
146
    case AV_CODEC_ID_PCM_ALAW:
147
        flags = FLV_CODECID_PCM_ALAW  | FLV_SAMPLERATE_SPECIAL | FLV_SAMPLESSIZE_16BIT;
148
        break;
149
    case 0:
150
        flags |= enc->codec_tag << 4;
151 152
        break;
    default:
153 154
        av_log(s, AV_LOG_ERROR, "Audio codec '%s' not compatible with FLV\n",
               avcodec_get_name(enc->codec_id));
155
        return AVERROR(EINVAL);
156
    }
157

158 159 160
    return flags;
}

161
static void put_amf_string(AVIOContext *pb, const char *str)
162 163
{
    size_t len = strlen(str);
164 165
    avio_wb16(pb, len);
    avio_write(pb, str, len);
166 167
}

168 169
static void put_avc_eos_tag(AVIOContext *pb, unsigned ts)
{
170
    avio_w8(pb, FLV_TAG_TYPE_VIDEO);
171 172 173 174 175 176 177 178
    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 */
179 180
}

181
static void put_amf_double(AVIOContext *pb, double d)
182
{
183
    avio_w8(pb, AMF_DATA_TYPE_NUMBER);
184
    avio_wb64(pb, av_double2int(d));
185 186
}

187 188
static void put_amf_bool(AVIOContext *pb, int b)
{
189 190
    avio_w8(pb, AMF_DATA_TYPE_BOOL);
    avio_w8(pb, !!b);
191 192
}

193 194
static int flv_write_header(AVFormatContext *s)
{
195
    AVIOContext *pb = s->pb;
196
    FLVContext *flv = s->priv_data;
197
    AVCodecContext *audio_enc = NULL, *video_enc = NULL, *data_enc = NULL;
198
    int i, metadata_count = 0;
199
    double framerate = 0.0;
200
    int64_t metadata_size_pos, data_size, metadata_count_pos;
201
    AVDictionaryEntry *tag = NULL;
202

203
    for (i = 0; i < s->nb_streams; i++) {
204
        AVCodecContext *enc = s->streams[i]->codec;
205
        FLVStreamContext *sc;
206 207
        switch (enc->codec_type) {
        case AVMEDIA_TYPE_VIDEO:
208 209 210
            if (s->streams[i]->avg_frame_rate.den &&
                s->streams[i]->avg_frame_rate.num) {
                framerate = av_q2d(s->streams[i]->avg_frame_rate);
211
            } else {
212
                framerate = 1 / av_q2d(s->streams[i]->codec->time_base);
213
            }
214 215 216 217 218
            if (video_enc) {
                av_log(s, AV_LOG_ERROR,
                       "at most one video stream is supported in flv\n");
                return AVERROR(EINVAL);
            }
219
            video_enc = enc;
220
            if (enc->codec_tag == 0) {
221 222
                av_log(s, AV_LOG_ERROR, "Video codec '%s' for stream %d is not compatible with FLV\n",
                       avcodec_get_name(enc->codec_id), i);
223
                return AVERROR(EINVAL);
224
            }
225 226
            break;
        case AVMEDIA_TYPE_AUDIO:
227 228 229 230 231
            if (audio_enc) {
                av_log(s, AV_LOG_ERROR,
                       "at most one audio stream is supported in flv\n");
                return AVERROR(EINVAL);
            }
232
            audio_enc = enc;
233
            if (get_audio_flags(s, enc) < 0)
234 235 236
                return AVERROR_INVALIDDATA;
            break;
        case AVMEDIA_TYPE_DATA:
237
            if (enc->codec_id != AV_CODEC_ID_TEXT) {
238 239
                av_log(s, AV_LOG_ERROR, "Data codec '%s' for stream %d is not compatible with FLV\n",
                       avcodec_get_name(enc->codec_id), i);
240 241 242 243 244
                return AVERROR_INVALIDDATA;
            }
            data_enc = enc;
            break;
        default:
245 246
            av_log(s, AV_LOG_ERROR, "Codec type '%s' for stream %d is not compatible with FLV\n",
                   av_get_media_type_string(enc->codec_type), i);
247
            return AVERROR(EINVAL);
248
        }
249
        avpriv_set_pts_info(s->streams[i], 32, 1, 1000); /* 32 bit pts in ms */
250 251 252 253 254 255

        sc = av_mallocz(sizeof(FLVStreamContext));
        if (!sc)
            return AVERROR(ENOMEM);
        s->streams[i]->priv_data = sc;
        sc->last_ts = -1;
256
    }
257

258 259
    flv->delay = AV_NOPTS_VALUE;

260
    avio_write(pb, "FLV", 3);
261 262 263 264 265 266 267 268 269 270 271 272 273 274
    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;
Michael Niedermayer's avatar
Michael Niedermayer committed
275
        }
276

277
    /* write meta_tag */
278 279 280 281 282
    avio_w8(pb, 18);            // tag type META
    metadata_size_pos = avio_tell(pb);
    avio_wb24(pb, 0);           // size of data part (sum of all parts below)
    avio_wb24(pb, 0);           // timestamp
    avio_wb32(pb, 0);           // reserved
283 284 285 286

    /* now data of data_size size */

    /* first event name as a string */
287
    avio_w8(pb, AMF_DATA_TYPE_STRING);
288 289 290
    put_amf_string(pb, "onMetaData"); // 12 bytes

    /* mixed array (hash) with size and string/type/data tuples */
291
    avio_w8(pb, AMF_DATA_TYPE_MIXEDARRAY);
292
    metadata_count_pos = avio_tell(pb);
293 294
    metadata_count = 5 * !!video_enc +
                     5 * !!audio_enc +
295
                     1 * !!data_enc  +
296 297
                     2; // +2 for duration and file size

298
    avio_wb32(pb, metadata_count);
299

300
    put_amf_string(pb, "duration");
301
    flv->duration_offset= avio_tell(pb);
302

303 304 305 306
    // fill in the guessed duration, it'll be corrected later if incorrect
    put_amf_double(pb, s->duration / AV_TIME_BASE);

    if (video_enc) {
307
        put_amf_string(pb, "width");
308
        put_amf_double(pb, video_enc->width);
309 310

        put_amf_string(pb, "height");
311
        put_amf_double(pb, video_enc->height);
312 313

        put_amf_string(pb, "videodatarate");
314
        put_amf_double(pb, video_enc->bit_rate / 1024.0);
315 316 317

        put_amf_string(pb, "framerate");
        put_amf_double(pb, framerate);
318 319

        put_amf_string(pb, "videocodecid");
320
        put_amf_double(pb, video_enc->codec_tag);
321 322
    }

323
    if (audio_enc) {
324 325 326
        put_amf_string(pb, "audiodatarate");
        put_amf_double(pb, audio_enc->bit_rate / 1024.0);

327
        put_amf_string(pb, "audiosamplerate");
328
        put_amf_double(pb, audio_enc->sample_rate);
329 330

        put_amf_string(pb, "audiosamplesize");
331
        put_amf_double(pb, audio_enc->codec_id == AV_CODEC_ID_PCM_U8 ? 8 : 16);
332 333

        put_amf_string(pb, "stereo");
334
        put_amf_bool(pb, audio_enc->channels == 2);
335 336

        put_amf_string(pb, "audiocodecid");
337
        put_amf_double(pb, audio_enc->codec_tag);
338 339
    }

340 341 342 343 344
    if (data_enc) {
        put_amf_string(pb, "datastream");
        put_amf_double(pb, 0.0);
    }

345
    while ((tag = av_dict_get(s->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {
346 347 348 349 350 351 352 353 354 355 356 357 358
        if(   !strcmp(tag->key, "width")
            ||!strcmp(tag->key, "height")
            ||!strcmp(tag->key, "videodatarate")
            ||!strcmp(tag->key, "framerate")
            ||!strcmp(tag->key, "videocodecid")
            ||!strcmp(tag->key, "audiodatarate")
            ||!strcmp(tag->key, "audiosamplerate")
            ||!strcmp(tag->key, "audiosamplesize")
            ||!strcmp(tag->key, "stereo")
            ||!strcmp(tag->key, "audiocodecid")
            ||!strcmp(tag->key, "duration")
            ||!strcmp(tag->key, "onMetaData")
        ){
359
            av_log(s, AV_LOG_DEBUG, "Ignoring metadata for %s\n", tag->key);
360 361
            continue;
        }
Tomás Touceda's avatar
Tomás Touceda committed
362
        put_amf_string(pb, tag->key);
363
        avio_w8(pb, AMF_DATA_TYPE_STRING);
Tomás Touceda's avatar
Tomás Touceda committed
364
        put_amf_string(pb, tag->value);
365
        metadata_count++;
Tomás Touceda's avatar
Tomás Touceda committed
366 367
    }

368
    put_amf_string(pb, "filesize");
369
    flv->filesize_offset = avio_tell(pb);
370
    put_amf_double(pb, 0); // delayed write
371 372

    put_amf_string(pb, "");
373
    avio_w8(pb, AMF_END_OF_OBJECT);
374 375

    /* write total size of tag */
376
    data_size = avio_tell(pb) - metadata_size_pos - 10;
377 378 379 380

    avio_seek(pb, metadata_count_pos, SEEK_SET);
    avio_wb32(pb, metadata_count);

381
    avio_seek(pb, metadata_size_pos, SEEK_SET);
382
    avio_wb24(pb, data_size);
383
    avio_skip(pb, data_size + 10 - 3);
384
    avio_wb32(pb, data_size + 11);
385

386 387
    for (i = 0; i < s->nb_streams; i++) {
        AVCodecContext *enc = s->streams[i]->codec;
388
        if (enc->codec_id == AV_CODEC_ID_AAC || enc->codec_id == AV_CODEC_ID_H264 || enc->codec_id == AV_CODEC_ID_MPEG4) {
389
            int64_t pos;
390
            avio_w8(pb, enc->codec_type == AVMEDIA_TYPE_VIDEO ?
391
                    FLV_TAG_TYPE_VIDEO : FLV_TAG_TYPE_AUDIO);
392 393
            avio_wb24(pb, 0); // size patched later
            avio_wb24(pb, 0); // ts
394
            avio_w8(pb, 0);   // ts ext
395
            avio_wb24(pb, 0); // streamid
396
            pos = avio_tell(pb);
397
            if (enc->codec_id == AV_CODEC_ID_AAC) {
398
                avio_w8(pb, get_audio_flags(s, enc));
399 400
                avio_w8(pb, 0); // AAC sequence header
                avio_write(pb, enc->extradata, enc->extradata_size);
401
            } else {
402 403 404
                avio_w8(pb, enc->codec_tag | FLV_FRAME_KEY); // flags
                avio_w8(pb, 0); // AVC sequence header
                avio_wb24(pb, 0); // composition time
405 406
                ff_isom_write_avcc(pb, enc->extradata, enc->extradata_size);
            }
407
            data_size = avio_tell(pb) - pos;
408
            avio_seek(pb, -data_size - 10, SEEK_CUR);
409
            avio_wb24(pb, data_size);
410
            avio_skip(pb, data_size + 10 - 3);
411
            avio_wb32(pb, data_size + 11); // previous tag size
412 413 414
        }
    }

415 416 417 418 419
    return 0;
}

static int flv_write_trailer(AVFormatContext *s)
{
420 421
    int64_t file_size;

422
    AVIOContext *pb = s->pb;
423
    FLVContext *flv = s->priv_data;
424 425 426 427 428
    int i;

    /* Add EOS tag */
    for (i = 0; i < s->nb_streams; i++) {
        AVCodecContext *enc = s->streams[i]->codec;
429
        FLVStreamContext *sc = s->streams[i]->priv_data;
430
        if (enc->codec_type == AVMEDIA_TYPE_VIDEO &&
431
                (enc->codec_id == AV_CODEC_ID_H264 || enc->codec_id == AV_CODEC_ID_MPEG4))
432
            put_avc_eos_tag(pb, sc->last_ts);
433
    }
434

435
    file_size = avio_tell(pb);
436

437
    /* update information */
438
    if (avio_seek(pb, flv->duration_offset, SEEK_SET) < 0)
439 440 441
        av_log(s, AV_LOG_WARNING, "Failed to update header with correct duration.\n");
    else
        put_amf_double(pb, flv->duration / (double)1000);
442
    if (avio_seek(pb, flv->filesize_offset, SEEK_SET) < 0)
443 444 445
        av_log(s, AV_LOG_WARNING, "Failed to update header with correct filesize.\n");
    else
        put_amf_double(pb, file_size);
446

447
    avio_seek(pb, file_size, SEEK_SET);
448 449 450
    return 0;
}

451
static int flv_write_packet(AVFormatContext *s, AVPacket *pkt)
452
{
453 454 455
    AVIOContext *pb      = s->pb;
    AVCodecContext *enc  = s->streams[pkt->stream_index]->codec;
    FLVContext *flv      = s->priv_data;
456
    FLVStreamContext *sc = s->streams[pkt->stream_index]->priv_data;
457
    unsigned ts;
458 459
    int size = pkt->size;
    uint8_t *data = NULL;
460
    int flags = -1, flags_size, ret;
461

462
    if (enc->codec_id == AV_CODEC_ID_VP6F || enc->codec_id == AV_CODEC_ID_VP6A ||
463
        enc->codec_id == AV_CODEC_ID_AAC)
464
        flags_size = 2;
465
    else if (enc->codec_id == AV_CODEC_ID_H264 || enc->codec_id == AV_CODEC_ID_MPEG4)
466
        flags_size = 5;
467
    else
468
        flags_size = 1;
469

470 471
    switch (enc->codec_type) {
    case AVMEDIA_TYPE_VIDEO:
472
        avio_w8(pb, FLV_TAG_TYPE_VIDEO);
473

474
        flags = enc->codec_tag;
475 476
        if (flags == 0) {
            av_log(s, AV_LOG_ERROR,
477
                   "Video codec '%s' is not compatible with FLV\n",
478
                   avcodec_get_name(enc->codec_id));
479
            return AVERROR(EINVAL);
480 481
        }

482
        flags |= pkt->flags & AV_PKT_FLAG_KEY ? FLV_FRAME_KEY : FLV_FRAME_INTER;
483 484
        break;
    case AVMEDIA_TYPE_AUDIO:
485
        flags = get_audio_flags(s, enc);
486

487
        av_assert0(size);
Michael Niedermayer's avatar
Michael Niedermayer committed
488

489
        avio_w8(pb, FLV_TAG_TYPE_AUDIO);
490 491
        break;
    case AVMEDIA_TYPE_DATA:
492
        avio_w8(pb, FLV_TAG_TYPE_META);
493 494 495
        break;
    default:
        return AVERROR(EINVAL);
Michael Niedermayer's avatar
Michael Niedermayer committed
496
    }
497

498
    if (enc->codec_id == AV_CODEC_ID_H264 || enc->codec_id == AV_CODEC_ID_MPEG4) {
499
        /* check if extradata looks like mp4 formated */
500
        if (enc->extradata_size > 0 && *(uint8_t*)enc->extradata != 1)
501 502
            if ((ret = ff_avc_parse_nal_units_buf(pkt->data, &data, &size)) < 0)
                return ret;
503
    } else if (enc->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
504
               (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
505
        if (!s->streams[pkt->stream_index]->nb_frames) {
506
        av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
507
               "use audio bitstream filter 'aac_adtstoasc' to fix it "
508
               "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
509
        return AVERROR_INVALIDDATA;
510 511
        }
        av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
512
    }
513

514 515
    if (flv->delay == AV_NOPTS_VALUE)
        flv->delay = -pkt->dts;
516

517
    if (pkt->dts < -flv->delay) {
518 519
        av_log(s, AV_LOG_WARNING,
               "Packets are not in the proper order with respect to DTS\n");
520 521
        return AVERROR(EINVAL);
    }
522

523
    ts = pkt->dts + flv->delay; // add delay to force positive dts
524 525

    /* check Speex packet duration */
526
    if (enc->codec_id == AV_CODEC_ID_SPEEX && ts - sc->last_ts > 160)
527 528 529 530
        av_log(s, AV_LOG_WARNING, "Warning: Speex stream has more than "
                                  "8 frames per packet. Adobe Flash "
                                  "Player cannot handle this!\n");

531 532
    if (sc->last_ts < ts)
        sc->last_ts = ts;
533

534 535 536 537
    avio_wb24(pb, size + flags_size);
    avio_wb24(pb, ts);
    avio_w8(pb, (ts >> 24) & 0x7F); // timestamps are 32 bits _signed_
    avio_wb24(pb, flv->reserved);
538

539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
    if (enc->codec_type == AVMEDIA_TYPE_DATA) {
        int data_size;
        int metadata_size_pos = avio_tell(pb);
        avio_w8(pb, AMF_DATA_TYPE_STRING);
        put_amf_string(pb, "onTextData");
        avio_w8(pb, AMF_DATA_TYPE_MIXEDARRAY);
        avio_wb32(pb, 2);
        put_amf_string(pb, "type");
        avio_w8(pb, AMF_DATA_TYPE_STRING);
        put_amf_string(pb, "Text");
        put_amf_string(pb, "text");
        avio_w8(pb, AMF_DATA_TYPE_STRING);
        put_amf_string(pb, pkt->data);
        put_amf_string(pb, "");
        avio_w8(pb, AMF_END_OF_OBJECT);
        /* write total size of tag */
        data_size = avio_tell(pb) - metadata_size_pos;
        avio_seek(pb, metadata_size_pos - 10, SEEK_SET);
        avio_wb24(pb, data_size);
        avio_seek(pb, data_size + 10 - 3, SEEK_CUR);
        avio_wb32(pb, data_size + 11);
    } else {
561
        av_assert1(flags>=0);
562
        avio_w8(pb,flags);
563 564 565 566 567 568 569
        if (enc->codec_id == AV_CODEC_ID_VP6F || enc->codec_id == AV_CODEC_ID_VP6A) {
            if (enc->extradata_size)
                avio_w8(pb, enc->extradata[0]);
            else
                avio_w8(pb, ((FFALIGN(enc->width,  16) - enc->width) << 4) |
                             (FFALIGN(enc->height, 16) - enc->height));
        } else if (enc->codec_id == AV_CODEC_ID_AAC)
570
            avio_w8(pb, 1); // AAC raw
571
        else if (enc->codec_id == AV_CODEC_ID_H264 || enc->codec_id == AV_CODEC_ID_MPEG4) {
572 573 574
            avio_w8(pb, 1); // AVC NALU
            avio_wb24(pb, pkt->pts - pkt->dts);
        }
575

576
        avio_write(pb, data ? data : pkt->data, size);
577

578 579 580
        avio_wb32(pb, size + flags_size + 11); // previous tag size
        flv->duration = FFMAX(flv->duration,
                              pkt->pts + flv->delay + pkt->duration);
581
    }
582 583 584

    av_free(data);

585
    return pb->error;
586 587
}

588
AVOutputFormat ff_flv_muxer = {
589
    .name           = "flv",
590
    .long_name      = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
591 592 593
    .mime_type      = "video/x-flv",
    .extensions     = "flv",
    .priv_data_size = sizeof(FLVContext),
594 595
    .audio_codec    = CONFIG_LIBMP3LAME ? AV_CODEC_ID_MP3 : AV_CODEC_ID_ADPCM_SWF,
    .video_codec    = AV_CODEC_ID_FLV1,
596 597 598
    .write_header   = flv_write_header,
    .write_packet   = flv_write_packet,
    .write_trailer  = flv_write_trailer,
599 600 601
    .codec_tag      = (const AVCodecTag* const []) {
                          flv_video_codec_ids, flv_audio_codec_ids, 0
                      },
602 603
    .flags          = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
                      AVFMT_TS_NONSTRICT,
604
};