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(ff_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(ff_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 if (tag = av_dict_get(s->metadata, "creation_time", NULL, 0)) {
00944
00945 int64_t date_utc = (ff_iso8601_to_unix_time(tag->value) - 978307200) * 1000000000;
00946 uint8_t date_utc_buf[8];
00947 AV_WB64(date_utc_buf, date_utc);
00948 put_ebml_binary(pb, MATROSKA_ID_DATEUTC, date_utc_buf, 8);
00949 }
00950
00951
00952 mkv->duration = 0;
00953 mkv->duration_offset = avio_tell(pb);
00954 put_ebml_void(pb, 11);
00955 end_ebml_master(pb, segment_info);
00956
00957 ret = mkv_write_tracks(s);
00958 if (ret < 0) return ret;
00959
00960 if (mkv->mode != MODE_WEBM) {
00961 ret = mkv_write_chapters(s);
00962 if (ret < 0) return ret;
00963
00964 ret = mkv_write_tags(s);
00965 if (ret < 0) return ret;
00966
00967 ret = mkv_write_attachments(s);
00968 if (ret < 0) return ret;
00969 }
00970
00971 if (!s->pb->seekable)
00972 mkv_write_seekhead(pb, mkv->main_seekhead);
00973
00974 mkv->cues = mkv_start_cues(mkv->segment_offset);
00975 if (mkv->cues == NULL)
00976 return AVERROR(ENOMEM);
00977
00978 av_init_packet(&mkv->cur_audio_pkt);
00979 mkv->cur_audio_pkt.size = 0;
00980 mkv->audio_buffer_size = 0;
00981 mkv->cluster_pos = -1;
00982
00983 avio_flush(pb);
00984 return 0;
00985 }
00986
00987 static int mkv_blockgroup_size(int pkt_size)
00988 {
00989 int size = pkt_size + 4;
00990 size += ebml_num_size(size);
00991 size += 2;
00992 size += 8;
00993 size += ebml_num_size(size);
00994 size += 1;
00995 return size;
00996 }
00997
00998 static int ass_get_duration(const uint8_t *p)
00999 {
01000 int sh, sm, ss, sc, eh, em, es, ec;
01001 uint64_t start, end;
01002
01003 if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
01004 &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)
01005 return 0;
01006 start = 3600000*sh + 60000*sm + 1000*ss + 10*sc;
01007 end = 3600000*eh + 60000*em + 1000*es + 10*ec;
01008 return end - start;
01009 }
01010
01011 static int mkv_write_ass_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
01012 {
01013 MatroskaMuxContext *mkv = s->priv_data;
01014 int i, layer = 0, max_duration = 0, size, line_size, data_size = pkt->size;
01015 uint8_t *start, *end, *data = pkt->data;
01016 ebml_master blockgroup;
01017 char buffer[2048];
01018
01019 while (data_size) {
01020 int duration = ass_get_duration(data);
01021 max_duration = FFMAX(duration, max_duration);
01022 end = memchr(data, '\n', data_size);
01023 size = line_size = end ? end-data+1 : data_size;
01024 size -= end ? (end[-1]=='\r')+1 : 0;
01025 start = data;
01026 for (i=0; i<3; i++, start++)
01027 if (!(start = memchr(start, ',', size-(start-data))))
01028 return max_duration;
01029 size -= start - data;
01030 sscanf(data, "Dialogue: %d,", &layer);
01031 i = snprintf(buffer, sizeof(buffer), "%"PRId64",%d,",
01032 s->streams[pkt->stream_index]->nb_frames, layer);
01033 size = FFMIN(i+size, sizeof(buffer));
01034 memcpy(buffer+i, start, size-i);
01035
01036 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
01037 "pts %" PRId64 ", duration %d\n",
01038 avio_tell(pb), size, pkt->pts, duration);
01039 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(size));
01040 put_ebml_id(pb, MATROSKA_ID_BLOCK);
01041 put_ebml_num(pb, size+4, 0);
01042 avio_w8(pb, 0x80 | (pkt->stream_index + 1));
01043 avio_wb16(pb, pkt->pts - mkv->cluster_pts);
01044 avio_w8(pb, 0);
01045 avio_write(pb, buffer, size);
01046 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
01047 end_ebml_master(pb, blockgroup);
01048
01049 data += line_size;
01050 data_size -= line_size;
01051 }
01052
01053 return max_duration;
01054 }
01055
01056 static void mkv_write_block(AVFormatContext *s, AVIOContext *pb,
01057 unsigned int blockid, AVPacket *pkt, int flags)
01058 {
01059 MatroskaMuxContext *mkv = s->priv_data;
01060 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
01061 uint8_t *data = NULL;
01062 int size = pkt->size;
01063 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
01064
01065 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
01066 "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
01067 avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
01068 if (codec->codec_id == CODEC_ID_H264 && codec->extradata_size > 0 &&
01069 (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
01070 ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
01071 else
01072 data = pkt->data;
01073 put_ebml_id(pb, blockid);
01074 put_ebml_num(pb, size+4, 0);
01075 avio_w8(pb, 0x80 | (pkt->stream_index + 1));
01076 avio_wb16(pb, ts - mkv->cluster_pts);
01077 avio_w8(pb, flags);
01078 avio_write(pb, data, size);
01079 if (data != pkt->data)
01080 av_free(data);
01081 }
01082
01083 static int srt_get_duration(uint8_t **buf)
01084 {
01085 int i, duration = 0;
01086
01087 for (i=0; i<2 && !duration; i++) {
01088 int s_hour, s_min, s_sec, s_hsec, e_hour, e_min, e_sec, e_hsec;
01089 if (sscanf(*buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d",
01090 &s_hour, &s_min, &s_sec, &s_hsec,
01091 &e_hour, &e_min, &e_sec, &e_hsec) == 8) {
01092 s_min += 60*s_hour; e_min += 60*e_hour;
01093 s_sec += 60*s_min; e_sec += 60*e_min;
01094 s_hsec += 1000*s_sec; e_hsec += 1000*e_sec;
01095 duration = e_hsec - s_hsec;
01096 }
01097 *buf += strcspn(*buf, "\n") + 1;
01098 }
01099 return duration;
01100 }
01101
01102 static int mkv_write_srt_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
01103 {
01104 ebml_master blockgroup;
01105 AVPacket pkt2 = *pkt;
01106 int64_t duration = srt_get_duration(&pkt2.data);
01107 pkt2.size -= pkt2.data - pkt->data;
01108
01109 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
01110 mkv_blockgroup_size(pkt2.size));
01111 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, &pkt2, 0);
01112 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
01113 end_ebml_master(pb, blockgroup);
01114
01115 return duration;
01116 }
01117
01118 static void mkv_flush_dynbuf(AVFormatContext *s)
01119 {
01120 MatroskaMuxContext *mkv = s->priv_data;
01121 int bufsize;
01122 uint8_t *dyn_buf;
01123
01124 if (!mkv->dyn_bc)
01125 return;
01126
01127 bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
01128 avio_write(s->pb, dyn_buf, bufsize);
01129 av_free(dyn_buf);
01130 mkv->dyn_bc = NULL;
01131 }
01132
01133 static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
01134 {
01135 MatroskaMuxContext *mkv = s->priv_data;
01136 AVIOContext *pb = s->pb;
01137 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
01138 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
01139 int duration = pkt->duration;
01140 int ret;
01141 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
01142
01143 if (ts == AV_NOPTS_VALUE) {
01144 av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
01145 return AVERROR(EINVAL);
01146 }
01147
01148 if (!s->pb->seekable) {
01149 if (!mkv->dyn_bc)
01150 avio_open_dyn_buf(&mkv->dyn_bc);
01151 pb = mkv->dyn_bc;
01152 }
01153
01154 if (mkv->cluster_pos == -1) {
01155 mkv->cluster_pos = avio_tell(s->pb);
01156 mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
01157 put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, FFMAX(0, ts));
01158 mkv->cluster_pts = FFMAX(0, ts);
01159 }
01160
01161 if (codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
01162 mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
01163 } else if (codec->codec_id == CODEC_ID_SSA) {
01164 duration = mkv_write_ass_blocks(s, pb, pkt);
01165 } else if (codec->codec_id == CODEC_ID_SRT) {
01166 duration = mkv_write_srt_blocks(s, pb, pkt);
01167 } else {
01168 ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(pkt->size));
01169 duration = pkt->convergence_duration;
01170 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 0);
01171 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
01172 end_ebml_master(pb, blockgroup);
01173 }
01174
01175 if (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe) {
01176 ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, ts, mkv->cluster_pos);
01177 if (ret < 0) return ret;
01178 }
01179
01180 mkv->duration = FFMAX(mkv->duration, ts + duration);
01181 return 0;
01182 }
01183
01184 static int mkv_copy_packet(MatroskaMuxContext *mkv, const AVPacket *pkt)
01185 {
01186 uint8_t *data = mkv->cur_audio_pkt.data;
01187 mkv->cur_audio_pkt = *pkt;
01188 mkv->cur_audio_pkt.data = av_fast_realloc(data, &mkv->audio_buffer_size, pkt->size);
01189 if (!mkv->cur_audio_pkt.data)
01190 return AVERROR(ENOMEM);
01191
01192 memcpy(mkv->cur_audio_pkt.data, pkt->data, pkt->size);
01193 mkv->cur_audio_pkt.size = pkt->size;
01194 return 0;
01195 }
01196
01197 static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
01198 {
01199 MatroskaMuxContext *mkv = s->priv_data;
01200 AVIOContext *pb = s->pb->seekable ? s->pb : mkv->dyn_bc;
01201 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
01202 int ret, keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
01203 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
01204 int cluster_size = avio_tell(pb) - (s->pb->seekable ? mkv->cluster_pos : 0);
01205
01206
01207
01208 if (mkv->cluster_pos != -1 &&
01209 ((!s->pb->seekable && (cluster_size > 32*1024 || ts > mkv->cluster_pts + 1000))
01210 || cluster_size > 5*1024*1024 || ts > mkv->cluster_pts + 5000
01211 || (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe && cluster_size > 4*1024))) {
01212 av_log(s, AV_LOG_DEBUG, "Starting new cluster at offset %" PRIu64
01213 " bytes, pts %" PRIu64 "\n", avio_tell(pb), ts);
01214 end_ebml_master(pb, mkv->cluster);
01215 mkv->cluster_pos = -1;
01216 if (mkv->dyn_bc)
01217 mkv_flush_dynbuf(s);
01218 }
01219
01220
01221 if (mkv->cur_audio_pkt.size > 0) {
01222 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
01223 mkv->cur_audio_pkt.size = 0;
01224 if (ret < 0) {
01225 av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
01226 return ret;
01227 }
01228 }
01229
01230
01231
01232 if (codec->codec_type == AVMEDIA_TYPE_AUDIO)
01233 ret = mkv_copy_packet(mkv, pkt);
01234 else
01235 ret = mkv_write_packet_internal(s, pkt);
01236 return ret;
01237 }
01238
01239 static int mkv_write_trailer(AVFormatContext *s)
01240 {
01241 MatroskaMuxContext *mkv = s->priv_data;
01242 AVIOContext *pb = s->pb;
01243 int64_t currentpos, cuespos;
01244 int ret;
01245
01246
01247 if (mkv->cur_audio_pkt.size > 0) {
01248 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
01249 mkv->cur_audio_pkt.size = 0;
01250 if (ret < 0) {
01251 av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
01252 return ret;
01253 }
01254 }
01255
01256 if (mkv->dyn_bc) {
01257 end_ebml_master(mkv->dyn_bc, mkv->cluster);
01258 mkv_flush_dynbuf(s);
01259 } else if (mkv->cluster_pos != -1) {
01260 end_ebml_master(pb, mkv->cluster);
01261 }
01262
01263 if (pb->seekable) {
01264 if (mkv->cues->num_entries) {
01265 cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
01266
01267 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES, cuespos);
01268 if (ret < 0) return ret;
01269 }
01270
01271 mkv_write_seekhead(pb, mkv->main_seekhead);
01272
01273
01274 av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
01275 currentpos = avio_tell(pb);
01276 avio_seek(pb, mkv->duration_offset, SEEK_SET);
01277 put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
01278
01279 avio_seek(pb, currentpos, SEEK_SET);
01280 }
01281
01282 end_ebml_master(pb, mkv->segment);
01283 av_free(mkv->tracks);
01284 av_freep(&mkv->cues->entries);
01285 av_freep(&mkv->cues);
01286 av_destruct_packet(&mkv->cur_audio_pkt);
01287 avio_flush(pb);
01288 return 0;
01289 }
01290
01291 static int mkv_query_codec(enum CodecID codec_id, int std_compliance)
01292 {
01293 int i;
01294 for (i = 0; ff_mkv_codec_tags[i].id != CODEC_ID_NONE; i++)
01295 if (ff_mkv_codec_tags[i].id == codec_id)
01296 return 1;
01297
01298 if (std_compliance < FF_COMPLIANCE_NORMAL) {
01299 enum AVMediaType type = avcodec_get_type(codec_id);
01300 if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
01301 return 1;
01302 }
01303
01304 return 0;
01305 }
01306
01307 #if CONFIG_MATROSKA_MUXER
01308 AVOutputFormat ff_matroska_muxer = {
01309 .name = "matroska",
01310 .long_name = NULL_IF_CONFIG_SMALL("Matroska file format"),
01311 .mime_type = "video/x-matroska",
01312 .extensions = "mkv",
01313 .priv_data_size = sizeof(MatroskaMuxContext),
01314 #if CONFIG_LIBVORBIS_ENCODER
01315 .audio_codec = CODEC_ID_VORBIS,
01316 #else
01317 .audio_codec = CODEC_ID_AC3,
01318 #endif
01319 #if CONFIG_LIBX264_ENCODER
01320 .video_codec = CODEC_ID_H264,
01321 #else
01322 .video_codec = CODEC_ID_MPEG4,
01323 #endif
01324 .write_header = mkv_write_header,
01325 .write_packet = mkv_write_packet,
01326 .write_trailer = mkv_write_trailer,
01327 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
01328 AVFMT_TS_NONSTRICT,
01329 .subtitle_codec = CODEC_ID_SSA,
01330 .query_codec = mkv_query_codec,
01331 };
01332 #endif
01333
01334 #if CONFIG_WEBM_MUXER
01335 AVOutputFormat ff_webm_muxer = {
01336 .name = "webm",
01337 .long_name = NULL_IF_CONFIG_SMALL("WebM file format"),
01338 .mime_type = "video/webm",
01339 .extensions = "webm",
01340 .priv_data_size = sizeof(MatroskaMuxContext),
01341 .audio_codec = CODEC_ID_VORBIS,
01342 .video_codec = CODEC_ID_VP8,
01343 .write_header = mkv_write_header,
01344 .write_packet = mkv_write_packet,
01345 .write_trailer = mkv_write_trailer,
01346 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
01347 AVFMT_TS_NONSTRICT,
01348 };
01349 #endif
01350
01351 #if CONFIG_MATROSKA_AUDIO_MUXER
01352 AVOutputFormat ff_matroska_audio_muxer = {
01353 .name = "matroska",
01354 .long_name = NULL_IF_CONFIG_SMALL("Matroska file format"),
01355 .mime_type = "audio/x-matroska",
01356 .extensions = "mka",
01357 .priv_data_size = sizeof(MatroskaMuxContext),
01358 #if CONFIG_LIBVORBIS_ENCODER
01359 .audio_codec = CODEC_ID_VORBIS,
01360 #else
01361 .audio_codec = CODEC_ID_AC3,
01362 #endif
01363 .video_codec = CODEC_ID_NONE,
01364 .write_header = mkv_write_header,
01365 .write_packet = mkv_write_packet,
01366 .write_trailer = mkv_write_trailer,
01367 .flags = AVFMT_GLOBALHEADER | AVFMT_TS_NONSTRICT,
01368 };
01369 #endif