00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 #include "avformat.h"
00023 #include "internal.h"
00024 #include "riff.h"
00025 #include "isom.h"
00026 #include "matroska.h"
00027 #include "avc.h"
00028 #include "flacenc.h"
00029 #include "avlanguage.h"
00030 #include "libavutil/samplefmt.h"
00031 #include "libavutil/intreadwrite.h"
00032 #include "libavutil/intfloat.h"
00033 #include "libavutil/mathematics.h"
00034 #include "libavutil/random_seed.h"
00035 #include "libavutil/lfg.h"
00036 #include "libavutil/dict.h"
00037 #include "libavutil/avstring.h"
00038 #include "libavcodec/xiph.h"
00039 #include "libavcodec/mpeg4audio.h"
00040
00041 typedef struct ebml_master {
00042 int64_t pos;
00043 int sizebytes;
00044 } ebml_master;
00045
00046 typedef struct mkv_seekhead_entry {
00047 unsigned int elementid;
00048 uint64_t segmentpos;
00049 } mkv_seekhead_entry;
00050
00051 typedef struct mkv_seekhead {
00052 int64_t filepos;
00053 int64_t segment_offset;
00054 int reserved_size;
00055 int max_entries;
00056 mkv_seekhead_entry *entries;
00057 int num_entries;
00058 } mkv_seekhead;
00059
00060 typedef struct {
00061 uint64_t pts;
00062 int tracknum;
00063 int64_t cluster_pos;
00064 } mkv_cuepoint;
00065
00066 typedef struct {
00067 int64_t segment_offset;
00068 mkv_cuepoint *entries;
00069 int num_entries;
00070 } mkv_cues;
00071
00072 typedef struct {
00073 int write_dts;
00074 } mkv_track;
00075
00076 #define MODE_MATROSKAv2 0x01
00077 #define MODE_WEBM 0x02
00078
00079 typedef struct MatroskaMuxContext {
00080 int mode;
00081 AVIOContext *dyn_bc;
00082 ebml_master segment;
00083 int64_t segment_offset;
00084 ebml_master cluster;
00085 int64_t cluster_pos;
00086 int64_t cluster_pts;
00087 int64_t duration_offset;
00088 int64_t duration;
00089 mkv_seekhead *main_seekhead;
00090 mkv_cues *cues;
00091 mkv_track *tracks;
00092
00093 unsigned int audio_buffer_size;
00094 AVPacket cur_audio_pkt;
00095
00096 int have_attachments;
00097 } MatroskaMuxContext;
00098
00099
00102 #define MAX_SEEKENTRY_SIZE 21
00103
00106 #define MAX_CUETRACKPOS_SIZE 22
00107
00109 #define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE*num_tracks
00110
00111
00112 static int ebml_id_size(unsigned int id)
00113 {
00114 return (av_log2(id+1)-1)/7+1;
00115 }
00116
00117 static void put_ebml_id(AVIOContext *pb, unsigned int id)
00118 {
00119 int i = ebml_id_size(id);
00120 while (i--)
00121 avio_w8(pb, id >> (i*8));
00122 }
00123
00129 static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
00130 {
00131 assert(bytes <= 8);
00132 avio_w8(pb, 0x1ff >> bytes);
00133 while (--bytes)
00134 avio_w8(pb, 0xff);
00135 }
00136
00140 static int ebml_num_size(uint64_t num)
00141 {
00142 int bytes = 1;
00143 while ((num+1) >> bytes*7) bytes++;
00144 return bytes;
00145 }
00146
00153 static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
00154 {
00155 int i, needed_bytes = ebml_num_size(num);
00156
00157
00158 assert(num < (1ULL<<56)-1);
00159
00160 if (bytes == 0)
00161
00162 bytes = needed_bytes;
00163
00164
00165 assert(bytes >= needed_bytes);
00166
00167 num |= 1ULL << bytes*7;
00168 for (i = bytes - 1; i >= 0; i--)
00169 avio_w8(pb, num >> i*8);
00170 }
00171
00172 static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
00173 {
00174 int i, bytes = 1;
00175 uint64_t tmp = val;
00176 while (tmp>>=8) bytes++;
00177
00178 put_ebml_id(pb, elementid);
00179 put_ebml_num(pb, bytes, 0);
00180 for (i = bytes - 1; i >= 0; i--)
00181 avio_w8(pb, val >> i*8);
00182 }
00183
00184 static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
00185 {
00186 put_ebml_id(pb, elementid);
00187 put_ebml_num(pb, 8, 0);
00188 avio_wb64(pb, av_double2int(val));
00189 }
00190
00191 static void put_ebml_binary(AVIOContext *pb, unsigned int elementid,
00192 const void *buf, int size)
00193 {
00194 put_ebml_id(pb, elementid);
00195 put_ebml_num(pb, size, 0);
00196 avio_write(pb, buf, size);
00197 }
00198
00199 static void put_ebml_string(AVIOContext *pb, unsigned int elementid, const char *str)
00200 {
00201 put_ebml_binary(pb, elementid, str, strlen(str));
00202 }
00203
00210 static void put_ebml_void(AVIOContext *pb, uint64_t size)
00211 {
00212 int64_t currentpos = avio_tell(pb);
00213
00214 assert(size >= 2);
00215
00216 put_ebml_id(pb, EBML_ID_VOID);
00217
00218
00219
00220 if (size < 10)
00221 put_ebml_num(pb, size-1, 0);
00222 else
00223 put_ebml_num(pb, size-9, 8);
00224 while(avio_tell(pb) < currentpos + size)
00225 avio_w8(pb, 0);
00226 }
00227
00228 static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid, uint64_t expectedsize)
00229 {
00230 int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
00231 put_ebml_id(pb, elementid);
00232 put_ebml_size_unknown(pb, bytes);
00233 return (ebml_master){ avio_tell(pb), bytes };
00234 }
00235
00236 static void end_ebml_master(AVIOContext *pb, ebml_master master)
00237 {
00238 int64_t pos = avio_tell(pb);
00239
00240 if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
00241 return;
00242 put_ebml_num(pb, pos - master.pos, master.sizebytes);
00243 avio_seek(pb, pos, SEEK_SET);
00244 }
00245
00246 static void put_xiph_size(AVIOContext *pb, int size)
00247 {
00248 int i;
00249 for (i = 0; i < size / 255; i++)
00250 avio_w8(pb, 255);
00251 avio_w8(pb, size % 255);
00252 }
00253
00265 static mkv_seekhead * mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset, int numelements)
00266 {
00267 mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
00268 if (new_seekhead == NULL)
00269 return NULL;
00270
00271 new_seekhead->segment_offset = segment_offset;
00272
00273 if (numelements > 0) {
00274 new_seekhead->filepos = avio_tell(pb);
00275
00276
00277
00278 new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 13;
00279 new_seekhead->max_entries = numelements;
00280 put_ebml_void(pb, new_seekhead->reserved_size);
00281 }
00282 return new_seekhead;
00283 }
00284
00285 static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
00286 {
00287 mkv_seekhead_entry *entries = seekhead->entries;
00288
00289
00290 if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
00291 return -1;
00292
00293 entries = av_realloc(entries, (seekhead->num_entries + 1) * sizeof(mkv_seekhead_entry));
00294 if (entries == NULL)
00295 return AVERROR(ENOMEM);
00296
00297 entries[seekhead->num_entries ].elementid = elementid;
00298 entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
00299
00300 seekhead->entries = entries;
00301 return 0;
00302 }
00303
00313 static int64_t mkv_write_seekhead(AVIOContext *pb, mkv_seekhead *seekhead)
00314 {
00315 ebml_master metaseek, seekentry;
00316 int64_t currentpos;
00317 int i;
00318
00319 currentpos = avio_tell(pb);
00320
00321 if (seekhead->reserved_size > 0) {
00322 if (avio_seek(pb, seekhead->filepos, SEEK_SET) < 0) {
00323 currentpos = -1;
00324 goto fail;
00325 }
00326 }
00327
00328 metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
00329 for (i = 0; i < seekhead->num_entries; i++) {
00330 mkv_seekhead_entry *entry = &seekhead->entries[i];
00331
00332 seekentry = start_ebml_master(pb, MATROSKA_ID_SEEKENTRY, MAX_SEEKENTRY_SIZE);
00333
00334 put_ebml_id(pb, MATROSKA_ID_SEEKID);
00335 put_ebml_num(pb, ebml_id_size(entry->elementid), 0);
00336 put_ebml_id(pb, entry->elementid);
00337
00338 put_ebml_uint(pb, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
00339 end_ebml_master(pb, seekentry);
00340 }
00341 end_ebml_master(pb, metaseek);
00342
00343 if (seekhead->reserved_size > 0) {
00344 uint64_t remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
00345 put_ebml_void(pb, remaining);
00346 avio_seek(pb, currentpos, SEEK_SET);
00347
00348 currentpos = seekhead->filepos;
00349 }
00350 fail:
00351 av_free(seekhead->entries);
00352 av_free(seekhead);
00353
00354 return currentpos;
00355 }
00356
00357 static mkv_cues * mkv_start_cues(int64_t segment_offset)
00358 {
00359 mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
00360 if (cues == NULL)
00361 return NULL;
00362
00363 cues->segment_offset = segment_offset;
00364 return cues;
00365 }
00366
00367 static int mkv_add_cuepoint(mkv_cues *cues, int stream, int64_t ts, int64_t cluster_pos)
00368 {
00369 mkv_cuepoint *entries = cues->entries;
00370
00371 entries = av_realloc(entries, (cues->num_entries + 1) * sizeof(mkv_cuepoint));
00372 if (entries == NULL)
00373 return AVERROR(ENOMEM);
00374
00375 if (ts < 0)
00376 return 0;
00377
00378 entries[cues->num_entries ].pts = ts;
00379 entries[cues->num_entries ].tracknum = stream + 1;
00380 entries[cues->num_entries++].cluster_pos = cluster_pos - cues->segment_offset;
00381
00382 cues->entries = entries;
00383 return 0;
00384 }
00385
00386 static int64_t mkv_write_cues(AVIOContext *pb, mkv_cues *cues, int num_tracks)
00387 {
00388 ebml_master cues_element;
00389 int64_t currentpos;
00390 int i, j;
00391
00392 currentpos = avio_tell(pb);
00393 cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
00394
00395 for (i = 0; i < cues->num_entries; i++) {
00396 ebml_master cuepoint, track_positions;
00397 mkv_cuepoint *entry = &cues->entries[i];
00398 uint64_t pts = entry->pts;
00399
00400 cuepoint = start_ebml_master(pb, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(num_tracks));
00401 put_ebml_uint(pb, MATROSKA_ID_CUETIME, pts);
00402
00403
00404
00405 for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
00406 track_positions = start_ebml_master(pb, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);
00407 put_ebml_uint(pb, MATROSKA_ID_CUETRACK , entry[j].tracknum );
00408 put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION, entry[j].cluster_pos);
00409 end_ebml_master(pb, track_positions);
00410 }
00411 i += j - 1;
00412 end_ebml_master(pb, cuepoint);
00413 }
00414 end_ebml_master(pb, cues_element);
00415
00416 return currentpos;
00417 }
00418
00419 static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec)
00420 {
00421 uint8_t *header_start[3];
00422 int header_len[3];
00423 int first_header_size;
00424 int j;
00425
00426 if (codec->codec_id == CODEC_ID_VORBIS)
00427 first_header_size = 30;
00428 else
00429 first_header_size = 42;
00430
00431 if (avpriv_split_xiph_headers(codec->extradata, codec->extradata_size,
00432 first_header_size, header_start, header_len) < 0) {
00433 av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
00434 return -1;
00435 }
00436
00437 avio_w8(pb, 2);
00438 for (j = 0; j < 2; j++) {
00439 put_xiph_size(pb, header_len[j]);
00440 }
00441 for (j = 0; j < 3; j++)
00442 avio_write(pb, header_start[j], header_len[j]);
00443
00444 return 0;
00445 }
00446
00447 static void get_aac_sample_rates(AVFormatContext *s, AVCodecContext *codec, int *sample_rate, int *output_sample_rate)
00448 {
00449 MPEG4AudioConfig mp4ac;
00450
00451 if (avpriv_mpeg4audio_get_config(&mp4ac, codec->extradata,
00452 codec->extradata_size * 8, 1) < 0) {
00453 av_log(s, AV_LOG_WARNING, "Error parsing AAC extradata, unable to determine samplerate.\n");
00454 return;
00455 }
00456
00457 *sample_rate = mp4ac.sample_rate;
00458 *output_sample_rate = mp4ac.ext_sample_rate;
00459 }
00460
00461 static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec, int native_id, int qt_id)
00462 {
00463 AVIOContext *dyn_cp;
00464 uint8_t *codecpriv;
00465 int ret, codecpriv_size;
00466
00467 ret = avio_open_dyn_buf(&dyn_cp);
00468 if(ret < 0)
00469 return ret;
00470
00471 if (native_id) {
00472 if (codec->codec_id == CODEC_ID_VORBIS || codec->codec_id == CODEC_ID_THEORA)
00473 ret = put_xiph_codecpriv(s, dyn_cp, codec);
00474 else if (codec->codec_id == CODEC_ID_FLAC)
00475 ret = ff_flac_write_header(dyn_cp, codec, 1);
00476 else if (codec->codec_id == CODEC_ID_H264)
00477 ret = ff_isom_write_avcc(dyn_cp, codec->extradata, codec->extradata_size);
00478 else if (codec->extradata_size)
00479 avio_write(dyn_cp, codec->extradata, codec->extradata_size);
00480 } else if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
00481 if (qt_id) {
00482 if (!codec->codec_tag)
00483 codec->codec_tag = ff_codec_get_tag(codec_movvideo_tags, codec->codec_id);
00484 if (codec->extradata_size)
00485 avio_write(dyn_cp, codec->extradata, codec->extradata_size);
00486 } else {
00487 if (!codec->codec_tag)
00488 codec->codec_tag = ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id);
00489 if (!codec->codec_tag) {
00490 av_log(s, AV_LOG_ERROR, "No bmp codec ID found.\n");
00491 ret = -1;
00492 }
00493
00494 ff_put_bmp_header(dyn_cp, codec, ff_codec_bmp_tags, 0);
00495 }
00496
00497 } else if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
00498 unsigned int tag;
00499 tag = ff_codec_get_tag(ff_codec_wav_tags, codec->codec_id);
00500 if (!tag) {
00501 av_log(s, AV_LOG_ERROR, "No wav codec ID found.\n");
00502 ret = -1;
00503 }
00504 if (!codec->codec_tag)
00505 codec->codec_tag = tag;
00506
00507 ff_put_wav_header(dyn_cp, codec);
00508 }
00509
00510 codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
00511 if (codecpriv_size)
00512 put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv, codecpriv_size);
00513 av_free(codecpriv);
00514 return ret;
00515 }
00516
00517 static int mkv_write_tracks(AVFormatContext *s)
00518 {
00519 MatroskaMuxContext *mkv = s->priv_data;
00520 AVIOContext *pb = s->pb;
00521 ebml_master tracks;
00522 int i, j, ret;
00523
00524 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, avio_tell(pb));
00525 if (ret < 0) return ret;
00526
00527 tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
00528 for (i = 0; i < s->nb_streams; i++) {
00529 AVStream *st = s->streams[i];
00530 AVCodecContext *codec = st->codec;
00531 ebml_master subinfo, track;
00532 int native_id = 0;
00533 int qt_id = 0;
00534 int bit_depth = av_get_bits_per_sample(codec->codec_id);
00535 int sample_rate = codec->sample_rate;
00536 int output_sample_rate = 0;
00537 AVDictionaryEntry *tag;
00538
00539 if (codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
00540 mkv->have_attachments = 1;
00541 continue;
00542 }
00543
00544 if (!bit_depth)
00545 bit_depth = av_get_bytes_per_sample(codec->sample_fmt) << 3;
00546
00547 if (codec->codec_id == CODEC_ID_AAC)
00548 get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);
00549
00550 track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
00551 put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER , i + 1);
00552 put_ebml_uint (pb, MATROSKA_ID_TRACKUID , i + 1);
00553 put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0);
00554
00555 if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
00556 put_ebml_string(pb, MATROSKA_ID_TRACKNAME, tag->value);
00557 tag = av_dict_get(st->metadata, "language", NULL, 0);
00558 put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag ? tag->value:"und");
00559
00560 if (st->disposition)
00561 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGDEFAULT, !!(st->disposition & AV_DISPOSITION_DEFAULT));
00562
00563
00564
00565 for (j = 0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++) {
00566 if (ff_mkv_codec_tags[j].id == codec->codec_id) {
00567 put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
00568 native_id = 1;
00569 break;
00570 }
00571 }
00572
00573 if (mkv->mode == MODE_WEBM && !(codec->codec_id == CODEC_ID_VP8 ||
00574 codec->codec_id == CODEC_ID_VORBIS)) {
00575 av_log(s, AV_LOG_ERROR,
00576 "Only VP8 video and Vorbis audio are supported for WebM.\n");
00577 return AVERROR(EINVAL);
00578 }
00579
00580 switch (codec->codec_type) {
00581 case AVMEDIA_TYPE_VIDEO:
00582 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
00583 if(st->avg_frame_rate.num && st->avg_frame_rate.den && 1.0/av_q2d(st->avg_frame_rate) > av_q2d(codec->time_base))
00584 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1E9/av_q2d(st->avg_frame_rate));
00585 else
00586 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, av_q2d(codec->time_base)*1E9);
00587
00588 if (!native_id &&
00589 ff_codec_get_tag(codec_movvideo_tags, codec->codec_id) &&
00590 (!ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id)
00591 || codec->codec_id == CODEC_ID_SVQ1
00592 || codec->codec_id == CODEC_ID_SVQ3
00593 || codec->codec_id == CODEC_ID_CINEPAK))
00594 qt_id = 1;
00595
00596 if (qt_id)
00597 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
00598 else if (!native_id) {
00599
00600 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
00601 mkv->tracks[i].write_dts = 1;
00602 }
00603
00604 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
00605
00606 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
00607 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
00608
00609 if ((tag = av_dict_get(st->metadata, "stereo_mode", NULL, 0)) ||
00610 (tag = av_dict_get( s->metadata, "stereo_mode", NULL, 0))) {
00611
00612 uint64_t st_mode = MATROSKA_VIDEO_STEREO_MODE_COUNT;
00613
00614 for (j=0; j<MATROSKA_VIDEO_STEREO_MODE_COUNT; j++)
00615 if (!strcmp(tag->value, matroska_video_stereo_mode[j])){
00616 st_mode = j;
00617 break;
00618 }
00619
00620 if ((mkv->mode == MODE_WEBM && st_mode > 3 && st_mode != 11)
00621 || st_mode >= MATROSKA_VIDEO_STEREO_MODE_COUNT) {
00622 av_log(s, AV_LOG_ERROR,
00623 "The specified stereo mode is not valid.\n");
00624 return AVERROR(EINVAL);
00625 } else
00626 put_ebml_uint(pb, MATROSKA_ID_VIDEOSTEREOMODE, st_mode);
00627 }
00628
00629 if (st->sample_aspect_ratio.num) {
00630 int d_width = codec->width*av_q2d(st->sample_aspect_ratio);
00631 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width);
00632 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height);
00633 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYUNIT, 3);
00634 }
00635
00636 if (codec->codec_id == CODEC_ID_RAWVIDEO) {
00637 uint32_t color_space = av_le2ne32(codec->codec_tag);
00638 put_ebml_binary(pb, MATROSKA_ID_VIDEOCOLORSPACE, &color_space, sizeof(color_space));
00639 }
00640 end_ebml_master(pb, subinfo);
00641 break;
00642
00643 case AVMEDIA_TYPE_AUDIO:
00644 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
00645
00646 if (!native_id)
00647
00648 put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
00649
00650 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
00651 put_ebml_uint (pb, MATROSKA_ID_AUDIOCHANNELS , codec->channels);
00652 put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
00653 if (output_sample_rate)
00654 put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
00655 if (bit_depth)
00656 put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
00657 end_ebml_master(pb, subinfo);
00658 break;
00659
00660 case AVMEDIA_TYPE_SUBTITLE:
00661 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_SUBTITLE);
00662 if (!native_id) {
00663 av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", codec->codec_id);
00664 return AVERROR(ENOSYS);
00665 }
00666 break;
00667 default:
00668 av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
00669 break;
00670 }
00671 ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);
00672 if (ret < 0) return ret;
00673
00674 end_ebml_master(pb, track);
00675
00676
00677 avpriv_set_pts_info(st, 64, 1, 1000);
00678 }
00679 end_ebml_master(pb, tracks);
00680 return 0;
00681 }
00682
00683 static int mkv_write_chapters(AVFormatContext *s)
00684 {
00685 MatroskaMuxContext *mkv = s->priv_data;
00686 AVIOContext *pb = s->pb;
00687 ebml_master chapters, editionentry;
00688 AVRational scale = {1, 1E9};
00689 int i, ret;
00690
00691 if (!s->nb_chapters)
00692 return 0;
00693
00694 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CHAPTERS, avio_tell(pb));
00695 if (ret < 0) return ret;
00696
00697 chapters = start_ebml_master(pb, MATROSKA_ID_CHAPTERS , 0);
00698 editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);
00699 put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGDEFAULT, 1);
00700 put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGHIDDEN , 0);
00701 for (i = 0; i < s->nb_chapters; i++) {
00702 ebml_master chapteratom, chapterdisplay;
00703 AVChapter *c = s->chapters[i];
00704 AVDictionaryEntry *t = NULL;
00705
00706 chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
00707 put_ebml_uint(pb, MATROSKA_ID_CHAPTERUID, c->id);
00708 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMESTART,
00709 av_rescale_q(c->start, c->time_base, scale));
00710 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMEEND,
00711 av_rescale_q(c->end, c->time_base, scale));
00712 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGHIDDEN , 0);
00713 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGENABLED, 1);
00714 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
00715 chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);
00716 put_ebml_string(pb, MATROSKA_ID_CHAPSTRING, t->value);
00717 put_ebml_string(pb, MATROSKA_ID_CHAPLANG , "und");
00718 end_ebml_master(pb, chapterdisplay);
00719 }
00720 end_ebml_master(pb, chapteratom);
00721 }
00722 end_ebml_master(pb, editionentry);
00723 end_ebml_master(pb, chapters);
00724 return 0;
00725 }
00726
00727 static void mkv_write_simpletag(AVIOContext *pb, AVDictionaryEntry *t)
00728 {
00729 uint8_t *key = av_strdup(t->key);
00730 uint8_t *p = key;
00731 const uint8_t *lang = NULL;
00732 ebml_master tag;
00733
00734 if ((p = strrchr(p, '-')) &&
00735 (lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
00736 *p = 0;
00737
00738 p = key;
00739 while (*p) {
00740 if (*p == ' ')
00741 *p = '_';
00742 else if (*p >= 'a' && *p <= 'z')
00743 *p -= 'a' - 'A';
00744 p++;
00745 }
00746
00747 tag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG, 0);
00748 put_ebml_string(pb, MATROSKA_ID_TAGNAME, key);
00749 if (lang)
00750 put_ebml_string(pb, MATROSKA_ID_TAGLANG, lang);
00751 put_ebml_string(pb, MATROSKA_ID_TAGSTRING, t->value);
00752 end_ebml_master(pb, tag);
00753
00754 av_freep(&key);
00755 }
00756
00757 static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
00758 unsigned int uid, ebml_master *tags)
00759 {
00760 MatroskaMuxContext *mkv = s->priv_data;
00761 ebml_master tag, targets;
00762 AVDictionaryEntry *t = NULL;
00763 int ret;
00764
00765 if (!tags->pos) {
00766 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TAGS, avio_tell(s->pb));
00767 if (ret < 0) return ret;
00768
00769 *tags = start_ebml_master(s->pb, MATROSKA_ID_TAGS, 0);
00770 }
00771
00772 tag = start_ebml_master(s->pb, MATROSKA_ID_TAG, 0);
00773 targets = start_ebml_master(s->pb, MATROSKA_ID_TAGTARGETS, 0);
00774 if (elementid)
00775 put_ebml_uint(s->pb, elementid, uid);
00776 end_ebml_master(s->pb, targets);
00777
00778 while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
00779 if (av_strcasecmp(t->key, "title") && av_strcasecmp(t->key, "stereo_mode"))
00780 mkv_write_simpletag(s->pb, t);
00781
00782 end_ebml_master(s->pb, tag);
00783 return 0;
00784 }
00785
00786 static int mkv_write_tags(AVFormatContext *s)
00787 {
00788 ebml_master tags = {0};
00789 int i, ret;
00790
00791 ff_metadata_conv_ctx(s, ff_mkv_metadata_conv, NULL);
00792
00793 if (av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX)) {
00794 ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);
00795 if (ret < 0) return ret;
00796 }
00797
00798 for (i = 0; i < s->nb_streams; i++) {
00799 AVStream *st = s->streams[i];
00800
00801 if (!av_dict_get(st->metadata, "", 0, AV_DICT_IGNORE_SUFFIX))
00802 continue;
00803
00804 ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);
00805 if (ret < 0) return ret;
00806 }
00807
00808 for (i = 0; i < s->nb_chapters; i++) {
00809 AVChapter *ch = s->chapters[i];
00810
00811 if (!av_dict_get(ch->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
00812 continue;
00813
00814 ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id, &tags);
00815 if (ret < 0) return ret;
00816 }
00817
00818 if (tags.pos)
00819 end_ebml_master(s->pb, tags);
00820 return 0;
00821 }
00822
00823 static int mkv_write_attachments(AVFormatContext *s)
00824 {
00825 MatroskaMuxContext *mkv = s->priv_data;
00826 AVIOContext *pb = s->pb;
00827 ebml_master attachments;
00828 AVLFG c;
00829 int i, ret;
00830
00831 if (!mkv->have_attachments)
00832 return 0;
00833
00834 av_lfg_init(&c, av_get_random_seed());
00835
00836 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_ATTACHMENTS, avio_tell(pb));
00837 if (ret < 0) return ret;
00838
00839 attachments = start_ebml_master(pb, MATROSKA_ID_ATTACHMENTS, 0);
00840
00841 for (i = 0; i < s->nb_streams; i++) {
00842 AVStream *st = s->streams[i];
00843 ebml_master attached_file;
00844 AVDictionaryEntry *t;
00845 const char *mimetype = NULL;
00846
00847 if (st->codec->codec_type != AVMEDIA_TYPE_ATTACHMENT)
00848 continue;
00849
00850 attached_file = start_ebml_master(pb, MATROSKA_ID_ATTACHEDFILE, 0);
00851
00852 if (t = av_dict_get(st->metadata, "title", NULL, 0))
00853 put_ebml_string(pb, MATROSKA_ID_FILEDESC, t->value);
00854 if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
00855 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
00856 return AVERROR(EINVAL);
00857 }
00858 put_ebml_string(pb, MATROSKA_ID_FILENAME, t->value);
00859 if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
00860 mimetype = t->value;
00861 else if (st->codec->codec_id != CODEC_ID_NONE ) {
00862 int i;
00863 for (i = 0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++)
00864 if (ff_mkv_mime_tags[i].id == st->codec->codec_id) {
00865 mimetype = ff_mkv_mime_tags[i].str;
00866 break;
00867 }
00868 }
00869 if (!mimetype) {
00870 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "
00871 "it cannot be deduced from the codec id.\n", i);
00872 return AVERROR(EINVAL);
00873 }
00874
00875 put_ebml_string(pb, MATROSKA_ID_FILEMIMETYPE, mimetype);
00876 put_ebml_binary(pb, MATROSKA_ID_FILEDATA, st->codec->extradata, st->codec->extradata_size);
00877 put_ebml_uint(pb, MATROSKA_ID_FILEUID, av_lfg_get(&c));
00878 end_ebml_master(pb, attached_file);
00879 }
00880 end_ebml_master(pb, attachments);
00881
00882 return 0;
00883 }
00884
00885 static int mkv_write_header(AVFormatContext *s)
00886 {
00887 MatroskaMuxContext *mkv = s->priv_data;
00888 AVIOContext *pb = s->pb;
00889 ebml_master ebml_header, segment_info;
00890 AVDictionaryEntry *tag;
00891 int ret, i;
00892
00893 if (!strcmp(s->oformat->name, "webm")) mkv->mode = MODE_WEBM;
00894 else mkv->mode = MODE_MATROSKAv2;
00895
00896 mkv->tracks = av_mallocz(s->nb_streams * sizeof(*mkv->tracks));
00897 if (!mkv->tracks)
00898 return AVERROR(ENOMEM);
00899
00900 ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
00901 put_ebml_uint (pb, EBML_ID_EBMLVERSION , 1);
00902 put_ebml_uint (pb, EBML_ID_EBMLREADVERSION , 1);
00903 put_ebml_uint (pb, EBML_ID_EBMLMAXIDLENGTH , 4);
00904 put_ebml_uint (pb, EBML_ID_EBMLMAXSIZELENGTH , 8);
00905 put_ebml_string (pb, EBML_ID_DOCTYPE , s->oformat->name);
00906 put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , 2);
00907 put_ebml_uint (pb, EBML_ID_DOCTYPEREADVERSION , 2);
00908 end_ebml_master(pb, ebml_header);
00909
00910 mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
00911 mkv->segment_offset = avio_tell(pb);
00912
00913
00914
00915
00916
00917
00918 mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
00919 if (!mkv->main_seekhead)
00920 return AVERROR(ENOMEM);
00921
00922 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, avio_tell(pb));
00923 if (ret < 0) return ret;
00924
00925 segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
00926 put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
00927 if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
00928 put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
00929 if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
00930 uint32_t segment_uid[4];
00931 AVLFG lfg;
00932
00933 av_lfg_init(&lfg, av_get_random_seed());
00934
00935 for (i = 0; i < 4; i++)
00936 segment_uid[i] = av_lfg_get(&lfg);
00937
00938 put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , LIBAVFORMAT_IDENT);
00939 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
00940 put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
00941 }
00942
00943
00944 mkv->duration = 0;
00945 mkv->duration_offset = avio_tell(pb);
00946 put_ebml_void(pb, 11);
00947 end_ebml_master(pb, segment_info);
00948
00949 ret = mkv_write_tracks(s);
00950 if (ret < 0) return ret;
00951
00952 if (mkv->mode != MODE_WEBM) {
00953 ret = mkv_write_chapters(s);
00954 if (ret < 0) return ret;
00955
00956 ret = mkv_write_tags(s);
00957 if (ret < 0) return ret;
00958
00959 ret = mkv_write_attachments(s);
00960 if (ret < 0) return ret;
00961 }
00962
00963 if (!s->pb->seekable)
00964 mkv_write_seekhead(pb, mkv->main_seekhead);
00965
00966 mkv->cues = mkv_start_cues(mkv->segment_offset);
00967 if (mkv->cues == NULL)
00968 return AVERROR(ENOMEM);
00969
00970 av_init_packet(&mkv->cur_audio_pkt);
00971 mkv->cur_audio_pkt.size = 0;
00972 mkv->audio_buffer_size = 0;
00973
00974 avio_flush(pb);
00975 return 0;
00976 }
00977
00978 static int mkv_blockgroup_size(int pkt_size)
00979 {
00980 int size = pkt_size + 4;
00981 size += ebml_num_size(size);
00982 size += 2;
00983 size += 8;
00984 size += ebml_num_size(size);
00985 size += 1;
00986 return size;
00987 }
00988
00989 static int ass_get_duration(const uint8_t *p)
00990 {
00991 int sh, sm, ss, sc, eh, em, es, ec;
00992 uint64_t start, end;
00993
00994 if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
00995 &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)
00996 return 0;
00997 start = 3600000*sh + 60000*sm + 1000*ss + 10*sc;
00998 end = 3600000*eh + 60000*em + 1000*es + 10*ec;
00999 return end - start;
01000 }
01001
01002 static int mkv_write_ass_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
01003 {
01004 MatroskaMuxContext *mkv = s->priv_data;
01005 int i, layer = 0, max_duration = 0, size, line_size, data_size = pkt->size;
01006 uint8_t *start, *end, *data = pkt->data;
01007 ebml_master blockgroup;
01008 char buffer[2048];
01009
01010 while (data_size) {
01011 int duration = ass_get_duration(data);
01012 max_duration = FFMAX(duration, max_duration);
01013 end = memchr(data, '\n', data_size);
01014 size = line_size = end ? end-data+1 : data_size;
01015 size -= end ? (end[-1]=='\r')+1 : 0;
01016 start = data;
01017 for (i=0; i<3; i++, start++)
01018 if (!(start = memchr(start, ',', size-(start-data))))
01019 return max_duration;
01020 size -= start - data;
01021 sscanf(data, "Dialogue: %d,", &layer);
01022 i = snprintf(buffer, sizeof(buffer), "%"PRId64",%d,",
01023 s->streams[pkt->stream_index]->nb_frames, layer);
01024 size = FFMIN(i+size, sizeof(buffer));
01025 memcpy(buffer+i, start, size-i);
01026
01027 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
01028 "pts %" PRId64 ", duration %d\n",
01029 avio_tell(pb), size, pkt->pts, duration);
01030 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(size));
01031 put_ebml_id(pb, MATROSKA_ID_BLOCK);
01032 put_ebml_num(pb, size+4, 0);
01033 avio_w8(pb, 0x80 | (pkt->stream_index + 1));
01034 avio_wb16(pb, pkt->pts - mkv->cluster_pts);
01035 avio_w8(pb, 0);
01036 avio_write(pb, buffer, size);
01037 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
01038 end_ebml_master(pb, blockgroup);
01039
01040 data += line_size;
01041 data_size -= line_size;
01042 }
01043
01044 return max_duration;
01045 }
01046
01047 static void mkv_write_block(AVFormatContext *s, AVIOContext *pb,
01048 unsigned int blockid, AVPacket *pkt, int flags)
01049 {
01050 MatroskaMuxContext *mkv = s->priv_data;
01051 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
01052 uint8_t *data = NULL;
01053 int size = pkt->size;
01054 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
01055
01056 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
01057 "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
01058 avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
01059 if (codec->codec_id == CODEC_ID_H264 && codec->extradata_size > 0 &&
01060 (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
01061 ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
01062 else
01063 data = pkt->data;
01064 put_ebml_id(pb, blockid);
01065 put_ebml_num(pb, size+4, 0);
01066 avio_w8(pb, 0x80 | (pkt->stream_index + 1));
01067 avio_wb16(pb, ts - mkv->cluster_pts);
01068 avio_w8(pb, flags);
01069 avio_write(pb, data, size);
01070 if (data != pkt->data)
01071 av_free(data);
01072 }
01073
01074 static int srt_get_duration(uint8_t **buf)
01075 {
01076 int i, duration = 0;
01077
01078 for (i=0; i<2 && !duration; i++) {
01079 int s_hour, s_min, s_sec, s_hsec, e_hour, e_min, e_sec, e_hsec;
01080 if (sscanf(*buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d",
01081 &s_hour, &s_min, &s_sec, &s_hsec,
01082 &e_hour, &e_min, &e_sec, &e_hsec) == 8) {
01083 s_min += 60*s_hour; e_min += 60*e_hour;
01084 s_sec += 60*s_min; e_sec += 60*e_min;
01085 s_hsec += 1000*s_sec; e_hsec += 1000*e_sec;
01086 duration = e_hsec - s_hsec;
01087 }
01088 *buf += strcspn(*buf, "\n") + 1;
01089 }
01090 return duration;
01091 }
01092
01093 static int mkv_write_srt_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
01094 {
01095 ebml_master blockgroup;
01096 AVPacket pkt2 = *pkt;
01097 int64_t duration = srt_get_duration(&pkt2.data);
01098 pkt2.size -= pkt2.data - pkt->data;
01099
01100 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
01101 mkv_blockgroup_size(pkt2.size));
01102 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, &pkt2, 0);
01103 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
01104 end_ebml_master(pb, blockgroup);
01105
01106 return duration;
01107 }
01108
01109 static void mkv_flush_dynbuf(AVFormatContext *s)
01110 {
01111 MatroskaMuxContext *mkv = s->priv_data;
01112 int bufsize;
01113 uint8_t *dyn_buf;
01114
01115 if (!mkv->dyn_bc)
01116 return;
01117
01118 bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
01119 avio_write(s->pb, dyn_buf, bufsize);
01120 av_free(dyn_buf);
01121 mkv->dyn_bc = NULL;
01122 }
01123
01124 static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
01125 {
01126 MatroskaMuxContext *mkv = s->priv_data;
01127 AVIOContext *pb = s->pb;
01128 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
01129 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
01130 int duration = pkt->duration;
01131 int ret;
01132 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
01133
01134 if (ts == AV_NOPTS_VALUE) {
01135 av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
01136 return AVERROR(EINVAL);
01137 }
01138
01139 if (!s->pb->seekable) {
01140 if (!mkv->dyn_bc)
01141 avio_open_dyn_buf(&mkv->dyn_bc);
01142 pb = mkv->dyn_bc;
01143 }
01144
01145 if (!mkv->cluster_pos) {
01146 mkv->cluster_pos = avio_tell(s->pb);
01147 mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
01148 put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, FFMAX(0, ts));
01149 mkv->cluster_pts = FFMAX(0, ts);
01150 }
01151
01152 if (codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
01153 mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
01154 } else if (codec->codec_id == CODEC_ID_SSA) {
01155 duration = mkv_write_ass_blocks(s, pb, pkt);
01156 } else if (codec->codec_id == CODEC_ID_SRT) {
01157 duration = mkv_write_srt_blocks(s, pb, pkt);
01158 } else {
01159 ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(pkt->size));
01160 duration = pkt->convergence_duration;
01161 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 0);
01162 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
01163 end_ebml_master(pb, blockgroup);
01164 }
01165
01166 if (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe) {
01167 ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, ts, mkv->cluster_pos);
01168 if (ret < 0) return ret;
01169 }
01170
01171 mkv->duration = FFMAX(mkv->duration, ts + duration);
01172 return 0;
01173 }
01174
01175 static int mkv_copy_packet(MatroskaMuxContext *mkv, const AVPacket *pkt)
01176 {
01177 uint8_t *data = mkv->cur_audio_pkt.data;
01178 mkv->cur_audio_pkt = *pkt;
01179 mkv->cur_audio_pkt.data = av_fast_realloc(data, &mkv->audio_buffer_size, pkt->size);
01180 if (!mkv->cur_audio_pkt.data)
01181 return AVERROR(ENOMEM);
01182
01183 memcpy(mkv->cur_audio_pkt.data, pkt->data, pkt->size);
01184 mkv->cur_audio_pkt.size = pkt->size;
01185 return 0;
01186 }
01187
01188 static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
01189 {
01190 MatroskaMuxContext *mkv = s->priv_data;
01191 AVIOContext *pb = s->pb->seekable ? s->pb : mkv->dyn_bc;
01192 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
01193 int ret, keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
01194 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
01195 int cluster_size = avio_tell(pb) - (s->pb->seekable ? mkv->cluster_pos : 0);
01196
01197
01198
01199 if (mkv->cluster_pos &&
01200 ((!s->pb->seekable && (cluster_size > 32*1024 || ts > mkv->cluster_pts + 1000))
01201 || cluster_size > 5*1024*1024 || ts > mkv->cluster_pts + 5000
01202 || (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe && cluster_size > 4*1024))) {
01203 av_log(s, AV_LOG_DEBUG, "Starting new cluster at offset %" PRIu64
01204 " bytes, pts %" PRIu64 "\n", avio_tell(pb), ts);
01205 end_ebml_master(pb, mkv->cluster);
01206 mkv->cluster_pos = 0;
01207 if (mkv->dyn_bc)
01208 mkv_flush_dynbuf(s);
01209 }
01210
01211
01212 if (mkv->cur_audio_pkt.size > 0) {
01213 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
01214 mkv->cur_audio_pkt.size = 0;
01215 if (ret < 0) {
01216 av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
01217 return ret;
01218 }
01219 }
01220
01221
01222
01223 if (codec->codec_type == AVMEDIA_TYPE_AUDIO)
01224 ret = mkv_copy_packet(mkv, pkt);
01225 else
01226 ret = mkv_write_packet_internal(s, pkt);
01227 return ret;
01228 }
01229
01230 static int mkv_write_trailer(AVFormatContext *s)
01231 {
01232 MatroskaMuxContext *mkv = s->priv_data;
01233 AVIOContext *pb = s->pb;
01234 int64_t currentpos, cuespos;
01235 int ret;
01236
01237
01238 if (mkv->cur_audio_pkt.size > 0) {
01239 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
01240 mkv->cur_audio_pkt.size = 0;
01241 if (ret < 0) {
01242 av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
01243 return ret;
01244 }
01245 }
01246
01247 if (mkv->dyn_bc) {
01248 end_ebml_master(mkv->dyn_bc, mkv->cluster);
01249 mkv_flush_dynbuf(s);
01250 } else if (mkv->cluster_pos) {
01251 end_ebml_master(pb, mkv->cluster);
01252 }
01253
01254 if (pb->seekable) {
01255 if (mkv->cues->num_entries) {
01256 cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
01257
01258 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES, cuespos);
01259 if (ret < 0) return ret;
01260 }
01261
01262 mkv_write_seekhead(pb, mkv->main_seekhead);
01263
01264
01265 av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
01266 currentpos = avio_tell(pb);
01267 avio_seek(pb, mkv->duration_offset, SEEK_SET);
01268 put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
01269
01270 avio_seek(pb, currentpos, SEEK_SET);
01271 }
01272
01273 end_ebml_master(pb, mkv->segment);
01274 av_free(mkv->tracks);
01275 av_freep(&mkv->cues->entries);
01276 av_freep(&mkv->cues);
01277 av_destruct_packet(&mkv->cur_audio_pkt);
01278 avio_flush(pb);
01279 return 0;
01280 }
01281
01282 static int mkv_query_codec(enum CodecID codec_id, int std_compliance)
01283 {
01284 int i;
01285 for (i = 0; ff_mkv_codec_tags[i].id != CODEC_ID_NONE; i++)
01286 if (ff_mkv_codec_tags[i].id == codec_id)
01287 return 1;
01288
01289 if (std_compliance < FF_COMPLIANCE_NORMAL) {
01290 enum AVMediaType type = avcodec_get_type(codec_id);
01291 if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
01292 return 1;
01293 }
01294
01295 return 0;
01296 }
01297
01298 #if CONFIG_MATROSKA_MUXER
01299 AVOutputFormat ff_matroska_muxer = {
01300 .name = "matroska",
01301 .long_name = NULL_IF_CONFIG_SMALL("Matroska file format"),
01302 .mime_type = "video/x-matroska",
01303 .extensions = "mkv",
01304 .priv_data_size = sizeof(MatroskaMuxContext),
01305 #if CONFIG_LIBVORBIS_ENCODER
01306 .audio_codec = CODEC_ID_VORBIS,
01307 #else
01308 .audio_codec = CODEC_ID_AC3,
01309 #endif
01310 #if CONFIG_LIBX264_ENCODER
01311 .video_codec = CODEC_ID_H264,
01312 #else
01313 .video_codec = CODEC_ID_MPEG4,
01314 #endif
01315 .write_header = mkv_write_header,
01316 .write_packet = mkv_write_packet,
01317 .write_trailer = mkv_write_trailer,
01318 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
01319 .subtitle_codec = CODEC_ID_SSA,
01320 .query_codec = mkv_query_codec,
01321 };
01322 #endif
01323
01324 #if CONFIG_WEBM_MUXER
01325 AVOutputFormat ff_webm_muxer = {
01326 .name = "webm",
01327 .long_name = NULL_IF_CONFIG_SMALL("WebM file format"),
01328 .mime_type = "video/webm",
01329 .extensions = "webm",
01330 .priv_data_size = sizeof(MatroskaMuxContext),
01331 .audio_codec = CODEC_ID_VORBIS,
01332 .video_codec = CODEC_ID_VP8,
01333 .write_header = mkv_write_header,
01334 .write_packet = mkv_write_packet,
01335 .write_trailer = mkv_write_trailer,
01336 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS | AVFMT_TS_NONSTRICT,
01337 };
01338 #endif
01339
01340 #if CONFIG_MATROSKA_AUDIO_MUXER
01341 AVOutputFormat ff_matroska_audio_muxer = {
01342 .name = "matroska",
01343 .long_name = NULL_IF_CONFIG_SMALL("Matroska file format"),
01344 .mime_type = "audio/x-matroska",
01345 .extensions = "mka",
01346 .priv_data_size = sizeof(MatroskaMuxContext),
01347 #if CONFIG_LIBVORBIS_ENCODER
01348 .audio_codec = CODEC_ID_VORBIS,
01349 #else
01350 .audio_codec = CODEC_ID_AC3,
01351 #endif
01352 .video_codec = CODEC_ID_NONE,
01353 .write_header = mkv_write_header,
01354 .write_packet = mkv_write_packet,
01355 .write_trailer = mkv_write_trailer,
01356 .flags = AVFMT_GLOBALHEADER,
01357 };
01358 #endif