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 av_assert0(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 av_assert0(num < (1ULL<<56)-1);
00159
00160 if (bytes == 0)
00161
00162 bytes = needed_bytes;
00163
00164
00165 av_assert0(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 av_assert0(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 == AV_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 == AV_CODEC_ID_VORBIS || codec->codec_id == AV_CODEC_ID_THEORA)
00473 ret = put_xiph_codecpriv(s, dyn_cp, codec);
00474 else if (codec->codec_id == AV_CODEC_ID_FLAC)
00475 ret = ff_flac_write_header(dyn_cp, codec, 1);
00476 else if (codec->codec_id == AV_CODEC_ID_H264)
00477 ret = ff_isom_write_avcc(dyn_cp, codec->extradata, codec->extradata_size);
00478 else if (codec->codec_id == AV_CODEC_ID_ALAC) {
00479 if (codec->extradata_size < 36) {
00480 av_log(s, AV_LOG_ERROR,
00481 "Invalid extradata found, ALAC expects a 36-byte "
00482 "QuickTime atom.");
00483 ret = AVERROR_INVALIDDATA;
00484 } else
00485 avio_write(dyn_cp, codec->extradata + 12,
00486 codec->extradata_size - 12);
00487 }
00488 else if (codec->extradata_size)
00489 avio_write(dyn_cp, codec->extradata, codec->extradata_size);
00490 } else if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
00491 if (qt_id) {
00492 if (!codec->codec_tag)
00493 codec->codec_tag = ff_codec_get_tag(ff_codec_movvideo_tags, codec->codec_id);
00494 if (codec->extradata_size)
00495 avio_write(dyn_cp, codec->extradata, codec->extradata_size);
00496 } else {
00497 if (!codec->codec_tag)
00498 codec->codec_tag = ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id);
00499 if (!codec->codec_tag) {
00500 av_log(s, AV_LOG_ERROR, "No bmp codec ID found.\n");
00501 ret = -1;
00502 }
00503
00504 ff_put_bmp_header(dyn_cp, codec, ff_codec_bmp_tags, 0);
00505 }
00506
00507 } else if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
00508 unsigned int tag;
00509 tag = ff_codec_get_tag(ff_codec_wav_tags, codec->codec_id);
00510 if (!tag) {
00511 av_log(s, AV_LOG_ERROR, "No wav codec ID found.\n");
00512 ret = -1;
00513 }
00514 if (!codec->codec_tag)
00515 codec->codec_tag = tag;
00516
00517 ff_put_wav_header(dyn_cp, codec);
00518 }
00519
00520 codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
00521 if (codecpriv_size)
00522 put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv, codecpriv_size);
00523 av_free(codecpriv);
00524 return ret;
00525 }
00526
00527 static int mkv_write_tracks(AVFormatContext *s)
00528 {
00529 MatroskaMuxContext *mkv = s->priv_data;
00530 AVIOContext *pb = s->pb;
00531 ebml_master tracks;
00532 int i, j, ret;
00533
00534 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, avio_tell(pb));
00535 if (ret < 0) return ret;
00536
00537 tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
00538 for (i = 0; i < s->nb_streams; i++) {
00539 AVStream *st = s->streams[i];
00540 AVCodecContext *codec = st->codec;
00541 ebml_master subinfo, track;
00542 int native_id = 0;
00543 int qt_id = 0;
00544 int bit_depth = av_get_bits_per_sample(codec->codec_id);
00545 int sample_rate = codec->sample_rate;
00546 int output_sample_rate = 0;
00547 AVDictionaryEntry *tag;
00548
00549 if (codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
00550 mkv->have_attachments = 1;
00551 continue;
00552 }
00553
00554 if (!bit_depth)
00555 bit_depth = av_get_bytes_per_sample(codec->sample_fmt) << 3;
00556
00557 if (codec->codec_id == AV_CODEC_ID_AAC)
00558 get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);
00559
00560 track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
00561 put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER , i + 1);
00562 put_ebml_uint (pb, MATROSKA_ID_TRACKUID , i + 1);
00563 put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0);
00564
00565 if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
00566 put_ebml_string(pb, MATROSKA_ID_TRACKNAME, tag->value);
00567 tag = av_dict_get(st->metadata, "language", NULL, 0);
00568 put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag ? tag->value:"und");
00569
00570 if (st->disposition)
00571 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGDEFAULT, !!(st->disposition & AV_DISPOSITION_DEFAULT));
00572
00573
00574
00575 for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
00576 if (ff_mkv_codec_tags[j].id == codec->codec_id) {
00577 put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
00578 native_id = 1;
00579 break;
00580 }
00581 }
00582
00583 if (mkv->mode == MODE_WEBM && !(codec->codec_id == AV_CODEC_ID_VP8 ||
00584 codec->codec_id == AV_CODEC_ID_VORBIS)) {
00585 av_log(s, AV_LOG_ERROR,
00586 "Only VP8 video and Vorbis audio are supported for WebM.\n");
00587 return AVERROR(EINVAL);
00588 }
00589
00590 switch (codec->codec_type) {
00591 case AVMEDIA_TYPE_VIDEO:
00592 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
00593 if(st->avg_frame_rate.num && st->avg_frame_rate.den && 1.0/av_q2d(st->avg_frame_rate) > av_q2d(codec->time_base))
00594 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1E9/av_q2d(st->avg_frame_rate));
00595 else
00596 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, av_q2d(codec->time_base)*1E9);
00597
00598 if (!native_id &&
00599 ff_codec_get_tag(ff_codec_movvideo_tags, codec->codec_id) &&
00600 (!ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id)
00601 || codec->codec_id == AV_CODEC_ID_SVQ1
00602 || codec->codec_id == AV_CODEC_ID_SVQ3
00603 || codec->codec_id == AV_CODEC_ID_CINEPAK))
00604 qt_id = 1;
00605
00606 if (qt_id)
00607 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
00608 else if (!native_id) {
00609
00610 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
00611 mkv->tracks[i].write_dts = 1;
00612 }
00613
00614 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
00615
00616 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
00617 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
00618
00619 if ((tag = av_dict_get(st->metadata, "stereo_mode", NULL, 0)) ||
00620 (tag = av_dict_get( s->metadata, "stereo_mode", NULL, 0))) {
00621
00622 uint64_t st_mode = MATROSKA_VIDEO_STEREO_MODE_COUNT;
00623
00624 for (j=0; j<MATROSKA_VIDEO_STEREO_MODE_COUNT; j++)
00625 if (!strcmp(tag->value, ff_matroska_video_stereo_mode[j])){
00626 st_mode = j;
00627 break;
00628 }
00629
00630 if ((mkv->mode == MODE_WEBM && st_mode > 3 && st_mode != 11)
00631 || st_mode >= MATROSKA_VIDEO_STEREO_MODE_COUNT) {
00632 av_log(s, AV_LOG_ERROR,
00633 "The specified stereo mode is not valid.\n");
00634 return AVERROR(EINVAL);
00635 } else
00636 put_ebml_uint(pb, MATROSKA_ID_VIDEOSTEREOMODE, st_mode);
00637 }
00638
00639 if (st->sample_aspect_ratio.num) {
00640 int d_width = codec->width*av_q2d(st->sample_aspect_ratio);
00641 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width);
00642 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height);
00643 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYUNIT, 3);
00644 }
00645
00646 if (codec->codec_id == AV_CODEC_ID_RAWVIDEO) {
00647 uint32_t color_space = av_le2ne32(codec->codec_tag);
00648 put_ebml_binary(pb, MATROSKA_ID_VIDEOCOLORSPACE, &color_space, sizeof(color_space));
00649 }
00650 end_ebml_master(pb, subinfo);
00651 break;
00652
00653 case AVMEDIA_TYPE_AUDIO:
00654 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
00655
00656 if (!native_id)
00657
00658 put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
00659
00660 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
00661 put_ebml_uint (pb, MATROSKA_ID_AUDIOCHANNELS , codec->channels);
00662 put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
00663 if (output_sample_rate)
00664 put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
00665 if (bit_depth)
00666 put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
00667 end_ebml_master(pb, subinfo);
00668 break;
00669
00670 case AVMEDIA_TYPE_SUBTITLE:
00671 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_SUBTITLE);
00672 if (!native_id) {
00673 av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", codec->codec_id);
00674 return AVERROR(ENOSYS);
00675 }
00676 break;
00677 default:
00678 av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
00679 break;
00680 }
00681 ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);
00682 if (ret < 0) return ret;
00683
00684 end_ebml_master(pb, track);
00685
00686
00687 avpriv_set_pts_info(st, 64, 1, 1000);
00688 }
00689 end_ebml_master(pb, tracks);
00690 return 0;
00691 }
00692
00693 static int mkv_write_chapters(AVFormatContext *s)
00694 {
00695 MatroskaMuxContext *mkv = s->priv_data;
00696 AVIOContext *pb = s->pb;
00697 ebml_master chapters, editionentry;
00698 AVRational scale = {1, 1E9};
00699 int i, ret;
00700
00701 if (!s->nb_chapters)
00702 return 0;
00703
00704 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CHAPTERS, avio_tell(pb));
00705 if (ret < 0) return ret;
00706
00707 chapters = start_ebml_master(pb, MATROSKA_ID_CHAPTERS , 0);
00708 editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);
00709 put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGDEFAULT, 1);
00710 put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGHIDDEN , 0);
00711 for (i = 0; i < s->nb_chapters; i++) {
00712 ebml_master chapteratom, chapterdisplay;
00713 AVChapter *c = s->chapters[i];
00714 AVDictionaryEntry *t = NULL;
00715
00716 chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
00717 put_ebml_uint(pb, MATROSKA_ID_CHAPTERUID, c->id);
00718 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMESTART,
00719 av_rescale_q(c->start, c->time_base, scale));
00720 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMEEND,
00721 av_rescale_q(c->end, c->time_base, scale));
00722 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGHIDDEN , 0);
00723 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGENABLED, 1);
00724 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
00725 chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);
00726 put_ebml_string(pb, MATROSKA_ID_CHAPSTRING, t->value);
00727 put_ebml_string(pb, MATROSKA_ID_CHAPLANG , "und");
00728 end_ebml_master(pb, chapterdisplay);
00729 }
00730 end_ebml_master(pb, chapteratom);
00731 }
00732 end_ebml_master(pb, editionentry);
00733 end_ebml_master(pb, chapters);
00734 return 0;
00735 }
00736
00737 static void mkv_write_simpletag(AVIOContext *pb, AVDictionaryEntry *t)
00738 {
00739 uint8_t *key = av_strdup(t->key);
00740 uint8_t *p = key;
00741 const uint8_t *lang = NULL;
00742 ebml_master tag;
00743
00744 if ((p = strrchr(p, '-')) &&
00745 (lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
00746 *p = 0;
00747
00748 p = key;
00749 while (*p) {
00750 if (*p == ' ')
00751 *p = '_';
00752 else if (*p >= 'a' && *p <= 'z')
00753 *p -= 'a' - 'A';
00754 p++;
00755 }
00756
00757 tag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG, 0);
00758 put_ebml_string(pb, MATROSKA_ID_TAGNAME, key);
00759 if (lang)
00760 put_ebml_string(pb, MATROSKA_ID_TAGLANG, lang);
00761 put_ebml_string(pb, MATROSKA_ID_TAGSTRING, t->value);
00762 end_ebml_master(pb, tag);
00763
00764 av_freep(&key);
00765 }
00766
00767 static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
00768 unsigned int uid, ebml_master *tags)
00769 {
00770 MatroskaMuxContext *mkv = s->priv_data;
00771 ebml_master tag, targets;
00772 AVDictionaryEntry *t = NULL;
00773 int ret;
00774
00775 if (!tags->pos) {
00776 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TAGS, avio_tell(s->pb));
00777 if (ret < 0) return ret;
00778
00779 *tags = start_ebml_master(s->pb, MATROSKA_ID_TAGS, 0);
00780 }
00781
00782 tag = start_ebml_master(s->pb, MATROSKA_ID_TAG, 0);
00783 targets = start_ebml_master(s->pb, MATROSKA_ID_TAGTARGETS, 0);
00784 if (elementid)
00785 put_ebml_uint(s->pb, elementid, uid);
00786 end_ebml_master(s->pb, targets);
00787
00788 while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
00789 if (av_strcasecmp(t->key, "title") && av_strcasecmp(t->key, "stereo_mode"))
00790 mkv_write_simpletag(s->pb, t);
00791
00792 end_ebml_master(s->pb, tag);
00793 return 0;
00794 }
00795
00796 static int mkv_write_tags(AVFormatContext *s)
00797 {
00798 ebml_master tags = {0};
00799 int i, ret;
00800
00801 ff_metadata_conv_ctx(s, ff_mkv_metadata_conv, NULL);
00802
00803 if (av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX)) {
00804 ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);
00805 if (ret < 0) return ret;
00806 }
00807
00808 for (i = 0; i < s->nb_streams; i++) {
00809 AVStream *st = s->streams[i];
00810
00811 if (!av_dict_get(st->metadata, "", 0, AV_DICT_IGNORE_SUFFIX))
00812 continue;
00813
00814 ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);
00815 if (ret < 0) return ret;
00816 }
00817
00818 for (i = 0; i < s->nb_chapters; i++) {
00819 AVChapter *ch = s->chapters[i];
00820
00821 if (!av_dict_get(ch->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
00822 continue;
00823
00824 ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id, &tags);
00825 if (ret < 0) return ret;
00826 }
00827
00828 if (tags.pos)
00829 end_ebml_master(s->pb, tags);
00830 return 0;
00831 }
00832
00833 static int mkv_write_attachments(AVFormatContext *s)
00834 {
00835 MatroskaMuxContext *mkv = s->priv_data;
00836 AVIOContext *pb = s->pb;
00837 ebml_master attachments;
00838 AVLFG c;
00839 int i, ret;
00840
00841 if (!mkv->have_attachments)
00842 return 0;
00843
00844 av_lfg_init(&c, av_get_random_seed());
00845
00846 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_ATTACHMENTS, avio_tell(pb));
00847 if (ret < 0) return ret;
00848
00849 attachments = start_ebml_master(pb, MATROSKA_ID_ATTACHMENTS, 0);
00850
00851 for (i = 0; i < s->nb_streams; i++) {
00852 AVStream *st = s->streams[i];
00853 ebml_master attached_file;
00854 AVDictionaryEntry *t;
00855 const char *mimetype = NULL;
00856
00857 if (st->codec->codec_type != AVMEDIA_TYPE_ATTACHMENT)
00858 continue;
00859
00860 attached_file = start_ebml_master(pb, MATROSKA_ID_ATTACHEDFILE, 0);
00861
00862 if (t = av_dict_get(st->metadata, "title", NULL, 0))
00863 put_ebml_string(pb, MATROSKA_ID_FILEDESC, t->value);
00864 if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
00865 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
00866 return AVERROR(EINVAL);
00867 }
00868 put_ebml_string(pb, MATROSKA_ID_FILENAME, t->value);
00869 if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
00870 mimetype = t->value;
00871 else if (st->codec->codec_id != AV_CODEC_ID_NONE ) {
00872 int i;
00873 for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
00874 if (ff_mkv_mime_tags[i].id == st->codec->codec_id) {
00875 mimetype = ff_mkv_mime_tags[i].str;
00876 break;
00877 }
00878 }
00879 if (!mimetype) {
00880 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "
00881 "it cannot be deduced from the codec id.\n", i);
00882 return AVERROR(EINVAL);
00883 }
00884
00885 put_ebml_string(pb, MATROSKA_ID_FILEMIMETYPE, mimetype);
00886 put_ebml_binary(pb, MATROSKA_ID_FILEDATA, st->codec->extradata, st->codec->extradata_size);
00887 put_ebml_uint(pb, MATROSKA_ID_FILEUID, av_lfg_get(&c));
00888 end_ebml_master(pb, attached_file);
00889 }
00890 end_ebml_master(pb, attachments);
00891
00892 return 0;
00893 }
00894
00895 static int mkv_write_header(AVFormatContext *s)
00896 {
00897 MatroskaMuxContext *mkv = s->priv_data;
00898 AVIOContext *pb = s->pb;
00899 ebml_master ebml_header, segment_info;
00900 AVDictionaryEntry *tag;
00901 int ret, i;
00902
00903 if (!strcmp(s->oformat->name, "webm")) mkv->mode = MODE_WEBM;
00904 else mkv->mode = MODE_MATROSKAv2;
00905
00906 mkv->tracks = av_mallocz(s->nb_streams * sizeof(*mkv->tracks));
00907 if (!mkv->tracks)
00908 return AVERROR(ENOMEM);
00909
00910 ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
00911 put_ebml_uint (pb, EBML_ID_EBMLVERSION , 1);
00912 put_ebml_uint (pb, EBML_ID_EBMLREADVERSION , 1);
00913 put_ebml_uint (pb, EBML_ID_EBMLMAXIDLENGTH , 4);
00914 put_ebml_uint (pb, EBML_ID_EBMLMAXSIZELENGTH , 8);
00915 put_ebml_string (pb, EBML_ID_DOCTYPE , s->oformat->name);
00916 put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , 2);
00917 put_ebml_uint (pb, EBML_ID_DOCTYPEREADVERSION , 2);
00918 end_ebml_master(pb, ebml_header);
00919
00920 mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
00921 mkv->segment_offset = avio_tell(pb);
00922
00923
00924
00925
00926
00927
00928 mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
00929 if (!mkv->main_seekhead)
00930 return AVERROR(ENOMEM);
00931
00932 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, avio_tell(pb));
00933 if (ret < 0) return ret;
00934
00935 segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
00936 put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
00937 if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
00938 put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
00939 if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
00940 uint32_t segment_uid[4];
00941 AVLFG lfg;
00942
00943 av_lfg_init(&lfg, av_get_random_seed());
00944
00945 for (i = 0; i < 4; i++)
00946 segment_uid[i] = av_lfg_get(&lfg);
00947
00948 put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , LIBAVFORMAT_IDENT);
00949 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
00950 put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
00951 }
00952
00953 if (tag = av_dict_get(s->metadata, "creation_time", NULL, 0)) {
00954
00955 int64_t date_utc = (ff_iso8601_to_unix_time(tag->value) - 978307200) * 1000000000;
00956 uint8_t date_utc_buf[8];
00957 AV_WB64(date_utc_buf, date_utc);
00958 put_ebml_binary(pb, MATROSKA_ID_DATEUTC, date_utc_buf, 8);
00959 }
00960
00961
00962 mkv->duration = 0;
00963 mkv->duration_offset = avio_tell(pb);
00964 put_ebml_void(pb, 11);
00965 end_ebml_master(pb, segment_info);
00966
00967 ret = mkv_write_tracks(s);
00968 if (ret < 0) return ret;
00969
00970 if (mkv->mode != MODE_WEBM) {
00971 ret = mkv_write_chapters(s);
00972 if (ret < 0) return ret;
00973
00974 ret = mkv_write_tags(s);
00975 if (ret < 0) return ret;
00976
00977 ret = mkv_write_attachments(s);
00978 if (ret < 0) return ret;
00979 }
00980
00981 if (!s->pb->seekable)
00982 mkv_write_seekhead(pb, mkv->main_seekhead);
00983
00984 mkv->cues = mkv_start_cues(mkv->segment_offset);
00985 if (mkv->cues == NULL)
00986 return AVERROR(ENOMEM);
00987
00988 av_init_packet(&mkv->cur_audio_pkt);
00989 mkv->cur_audio_pkt.size = 0;
00990 mkv->audio_buffer_size = 0;
00991 mkv->cluster_pos = -1;
00992
00993 avio_flush(pb);
00994 return 0;
00995 }
00996
00997 static int mkv_blockgroup_size(int pkt_size)
00998 {
00999 int size = pkt_size + 4;
01000 size += ebml_num_size(size);
01001 size += 2;
01002 size += 8;
01003 size += ebml_num_size(size);
01004 size += 1;
01005 return size;
01006 }
01007
01008 static int ass_get_duration(const uint8_t *p)
01009 {
01010 int sh, sm, ss, sc, eh, em, es, ec;
01011 uint64_t start, end;
01012
01013 if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
01014 &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)
01015 return 0;
01016 start = 3600000*sh + 60000*sm + 1000*ss + 10*sc;
01017 end = 3600000*eh + 60000*em + 1000*es + 10*ec;
01018 return end - start;
01019 }
01020
01021 static int mkv_write_ass_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
01022 {
01023 MatroskaMuxContext *mkv = s->priv_data;
01024 int i, layer = 0, max_duration = 0, size, line_size, data_size = pkt->size;
01025 uint8_t *start, *end, *data = pkt->data;
01026 ebml_master blockgroup;
01027 char buffer[2048];
01028
01029 while (data_size) {
01030 int duration = ass_get_duration(data);
01031 max_duration = FFMAX(duration, max_duration);
01032 end = memchr(data, '\n', data_size);
01033 size = line_size = end ? end-data+1 : data_size;
01034 size -= end ? (end[-1]=='\r')+1 : 0;
01035 start = data;
01036 for (i=0; i<3; i++, start++)
01037 if (!(start = memchr(start, ',', size-(start-data))))
01038 return max_duration;
01039 size -= start - data;
01040 sscanf(data, "Dialogue: %d,", &layer);
01041 i = snprintf(buffer, sizeof(buffer), "%"PRId64",%d,",
01042 s->streams[pkt->stream_index]->nb_frames, layer);
01043 size = FFMIN(i+size, sizeof(buffer));
01044 memcpy(buffer+i, start, size-i);
01045
01046 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
01047 "pts %" PRId64 ", duration %d\n",
01048 avio_tell(pb), size, pkt->pts, duration);
01049 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(size));
01050 put_ebml_id(pb, MATROSKA_ID_BLOCK);
01051 put_ebml_num(pb, size+4, 0);
01052 avio_w8(pb, 0x80 | (pkt->stream_index + 1));
01053 avio_wb16(pb, pkt->pts - mkv->cluster_pts);
01054 avio_w8(pb, 0);
01055 avio_write(pb, buffer, size);
01056 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
01057 end_ebml_master(pb, blockgroup);
01058
01059 data += line_size;
01060 data_size -= line_size;
01061 }
01062
01063 return max_duration;
01064 }
01065
01066 static void mkv_write_block(AVFormatContext *s, AVIOContext *pb,
01067 unsigned int blockid, AVPacket *pkt, int flags)
01068 {
01069 MatroskaMuxContext *mkv = s->priv_data;
01070 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
01071 uint8_t *data = NULL;
01072 int offset = 0, size = pkt->size;
01073 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
01074
01075 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
01076 "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
01077 avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
01078 if (codec->codec_id == AV_CODEC_ID_H264 && codec->extradata_size > 0 &&
01079 (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
01080 ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
01081 else
01082 data = pkt->data;
01083
01084 if (codec->codec_id == AV_CODEC_ID_PRORES) {
01085
01086
01087 size -= 8;
01088 offset = 8;
01089 }
01090
01091 put_ebml_id(pb, blockid);
01092 put_ebml_num(pb, size+4, 0);
01093 avio_w8(pb, 0x80 | (pkt->stream_index + 1));
01094 avio_wb16(pb, ts - mkv->cluster_pts);
01095 avio_w8(pb, flags);
01096 avio_write(pb, data + offset, size);
01097 if (data != pkt->data)
01098 av_free(data);
01099 }
01100
01101 static int srt_get_duration(uint8_t **buf)
01102 {
01103 int i, duration = 0;
01104
01105 for (i=0; i<2 && !duration; i++) {
01106 int s_hour, s_min, s_sec, s_hsec, e_hour, e_min, e_sec, e_hsec;
01107 if (sscanf(*buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d",
01108 &s_hour, &s_min, &s_sec, &s_hsec,
01109 &e_hour, &e_min, &e_sec, &e_hsec) == 8) {
01110 s_min += 60*s_hour; e_min += 60*e_hour;
01111 s_sec += 60*s_min; e_sec += 60*e_min;
01112 s_hsec += 1000*s_sec; e_hsec += 1000*e_sec;
01113 duration = e_hsec - s_hsec;
01114 }
01115 *buf += strcspn(*buf, "\n") + 1;
01116 }
01117 return duration;
01118 }
01119
01120 static int mkv_write_srt_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
01121 {
01122 ebml_master blockgroup;
01123 AVPacket pkt2 = *pkt;
01124 int64_t duration = srt_get_duration(&pkt2.data);
01125 pkt2.size -= pkt2.data - pkt->data;
01126
01127 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
01128 mkv_blockgroup_size(pkt2.size));
01129 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, &pkt2, 0);
01130 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
01131 end_ebml_master(pb, blockgroup);
01132
01133 return duration;
01134 }
01135
01136 static void mkv_flush_dynbuf(AVFormatContext *s)
01137 {
01138 MatroskaMuxContext *mkv = s->priv_data;
01139 int bufsize;
01140 uint8_t *dyn_buf;
01141
01142 if (!mkv->dyn_bc)
01143 return;
01144
01145 bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
01146 avio_write(s->pb, dyn_buf, bufsize);
01147 av_free(dyn_buf);
01148 mkv->dyn_bc = NULL;
01149 }
01150
01151 static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
01152 {
01153 MatroskaMuxContext *mkv = s->priv_data;
01154 AVIOContext *pb = s->pb;
01155 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
01156 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
01157 int duration = pkt->duration;
01158 int ret;
01159 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
01160
01161 if (ts == AV_NOPTS_VALUE) {
01162 av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
01163 return AVERROR(EINVAL);
01164 }
01165
01166 if (!s->pb->seekable) {
01167 if (!mkv->dyn_bc)
01168 avio_open_dyn_buf(&mkv->dyn_bc);
01169 pb = mkv->dyn_bc;
01170 }
01171
01172 if (mkv->cluster_pos == -1) {
01173 mkv->cluster_pos = avio_tell(s->pb);
01174 mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
01175 put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, FFMAX(0, ts));
01176 mkv->cluster_pts = FFMAX(0, ts);
01177 }
01178
01179 if (codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
01180 mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
01181 } else if (codec->codec_id == AV_CODEC_ID_SSA) {
01182 duration = mkv_write_ass_blocks(s, pb, pkt);
01183 } else if (codec->codec_id == AV_CODEC_ID_SRT) {
01184 duration = mkv_write_srt_blocks(s, pb, pkt);
01185 } else {
01186 ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(pkt->size));
01187
01188 if (pkt->convergence_duration > 0) {
01189 duration = pkt->convergence_duration;
01190 }
01191 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 0);
01192 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
01193 end_ebml_master(pb, blockgroup);
01194 }
01195
01196 if (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe) {
01197 ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, ts, mkv->cluster_pos);
01198 if (ret < 0) return ret;
01199 }
01200
01201 mkv->duration = FFMAX(mkv->duration, ts + duration);
01202 return 0;
01203 }
01204
01205 static int mkv_copy_packet(MatroskaMuxContext *mkv, const AVPacket *pkt)
01206 {
01207 uint8_t *data = mkv->cur_audio_pkt.data;
01208 mkv->cur_audio_pkt = *pkt;
01209 mkv->cur_audio_pkt.data = av_fast_realloc(data, &mkv->audio_buffer_size, pkt->size);
01210 if (!mkv->cur_audio_pkt.data)
01211 return AVERROR(ENOMEM);
01212
01213 memcpy(mkv->cur_audio_pkt.data, pkt->data, pkt->size);
01214 mkv->cur_audio_pkt.size = pkt->size;
01215 return 0;
01216 }
01217
01218 static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
01219 {
01220 MatroskaMuxContext *mkv = s->priv_data;
01221 AVIOContext *pb = s->pb->seekable ? s->pb : mkv->dyn_bc;
01222 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
01223 int ret, keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
01224 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
01225 int cluster_size = avio_tell(pb) - (s->pb->seekable ? mkv->cluster_pos : 0);
01226
01227
01228
01229 if (mkv->cluster_pos != -1 &&
01230 ((!s->pb->seekable && (cluster_size > 32*1024 || ts > mkv->cluster_pts + 1000))
01231 || cluster_size > 5*1024*1024 || ts > mkv->cluster_pts + 5000
01232 || (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe && cluster_size > 4*1024))) {
01233 av_log(s, AV_LOG_DEBUG, "Starting new cluster at offset %" PRIu64
01234 " bytes, pts %" PRIu64 "\n", avio_tell(pb), ts);
01235 end_ebml_master(pb, mkv->cluster);
01236 mkv->cluster_pos = -1;
01237 if (mkv->dyn_bc)
01238 mkv_flush_dynbuf(s);
01239 }
01240
01241
01242 if (mkv->cur_audio_pkt.size > 0) {
01243 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
01244 mkv->cur_audio_pkt.size = 0;
01245 if (ret < 0) {
01246 av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
01247 return ret;
01248 }
01249 }
01250
01251
01252
01253 if (codec->codec_type == AVMEDIA_TYPE_AUDIO)
01254 ret = mkv_copy_packet(mkv, pkt);
01255 else
01256 ret = mkv_write_packet_internal(s, pkt);
01257 return ret;
01258 }
01259
01260 static int mkv_write_trailer(AVFormatContext *s)
01261 {
01262 MatroskaMuxContext *mkv = s->priv_data;
01263 AVIOContext *pb = s->pb;
01264 int64_t currentpos, cuespos;
01265 int ret;
01266
01267
01268 if (mkv->cur_audio_pkt.size > 0) {
01269 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
01270 mkv->cur_audio_pkt.size = 0;
01271 if (ret < 0) {
01272 av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
01273 return ret;
01274 }
01275 }
01276
01277 if (mkv->dyn_bc) {
01278 end_ebml_master(mkv->dyn_bc, mkv->cluster);
01279 mkv_flush_dynbuf(s);
01280 } else if (mkv->cluster_pos != -1) {
01281 end_ebml_master(pb, mkv->cluster);
01282 }
01283
01284 if (pb->seekable) {
01285 if (mkv->cues->num_entries) {
01286 cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
01287
01288 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES, cuespos);
01289 if (ret < 0) return ret;
01290 }
01291
01292 mkv_write_seekhead(pb, mkv->main_seekhead);
01293
01294
01295 av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
01296 currentpos = avio_tell(pb);
01297 avio_seek(pb, mkv->duration_offset, SEEK_SET);
01298 put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
01299
01300 avio_seek(pb, currentpos, SEEK_SET);
01301 }
01302
01303 end_ebml_master(pb, mkv->segment);
01304 av_free(mkv->tracks);
01305 av_freep(&mkv->cues->entries);
01306 av_freep(&mkv->cues);
01307 av_destruct_packet(&mkv->cur_audio_pkt);
01308
01309 return 0;
01310 }
01311
01312 static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
01313 {
01314 int i;
01315 for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
01316 if (ff_mkv_codec_tags[i].id == codec_id)
01317 return 1;
01318
01319 if (std_compliance < FF_COMPLIANCE_NORMAL) {
01320 enum AVMediaType type = avcodec_get_type(codec_id);
01321 if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
01322 return 1;
01323 }
01324
01325 return 0;
01326 }
01327
01328 #if CONFIG_MATROSKA_MUXER
01329 AVOutputFormat ff_matroska_muxer = {
01330 .name = "matroska",
01331 .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
01332 .mime_type = "video/x-matroska",
01333 .extensions = "mkv",
01334 .priv_data_size = sizeof(MatroskaMuxContext),
01335 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
01336 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
01337 .video_codec = CONFIG_LIBX264_ENCODER ?
01338 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
01339 .write_header = mkv_write_header,
01340 .write_packet = mkv_write_packet,
01341 .write_trailer = mkv_write_trailer,
01342 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
01343 AVFMT_TS_NONSTRICT,
01344 .subtitle_codec = AV_CODEC_ID_SSA,
01345 .query_codec = mkv_query_codec,
01346 };
01347 #endif
01348
01349 #if CONFIG_WEBM_MUXER
01350 AVOutputFormat ff_webm_muxer = {
01351 .name = "webm",
01352 .long_name = NULL_IF_CONFIG_SMALL("WebM"),
01353 .mime_type = "video/webm",
01354 .extensions = "webm",
01355 .priv_data_size = sizeof(MatroskaMuxContext),
01356 .audio_codec = AV_CODEC_ID_VORBIS,
01357 .video_codec = AV_CODEC_ID_VP8,
01358 .write_header = mkv_write_header,
01359 .write_packet = mkv_write_packet,
01360 .write_trailer = mkv_write_trailer,
01361 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
01362 AVFMT_TS_NONSTRICT,
01363 };
01364 #endif
01365
01366 #if CONFIG_MATROSKA_AUDIO_MUXER
01367 AVOutputFormat ff_matroska_audio_muxer = {
01368 .name = "matroska",
01369 .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
01370 .mime_type = "audio/x-matroska",
01371 .extensions = "mka",
01372 .priv_data_size = sizeof(MatroskaMuxContext),
01373 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
01374 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
01375 .video_codec = AV_CODEC_ID_NONE,
01376 .write_header = mkv_write_header,
01377 .write_packet = mkv_write_packet,
01378 .write_trailer = mkv_write_trailer,
01379 .flags = AVFMT_GLOBALHEADER | AVFMT_TS_NONSTRICT,
01380 };
01381 #endif