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 "riff.h"
00024 #include "isom.h"
00025 #include "matroska.h"
00026 #include "avc.h"
00027 #include "flacenc.h"
00028 #include "libavutil/intreadwrite.h"
00029 #include "libavutil/md5.h"
00030 #include "libavcodec/xiph.h"
00031 #include "libavcodec/mpeg4audio.h"
00032
00033 typedef struct ebml_master {
00034 int64_t pos;
00035 int sizebytes;
00036 } ebml_master;
00037
00038 typedef struct mkv_seekhead_entry {
00039 unsigned int elementid;
00040 uint64_t segmentpos;
00041 } mkv_seekhead_entry;
00042
00043 typedef struct mkv_seekhead {
00044 int64_t filepos;
00045 int64_t segment_offset;
00046 int reserved_size;
00047 int max_entries;
00048 mkv_seekhead_entry *entries;
00049 int num_entries;
00050 } mkv_seekhead;
00051
00052 typedef struct {
00053 uint64_t pts;
00054 int tracknum;
00055 int64_t cluster_pos;
00056 } mkv_cuepoint;
00057
00058 typedef struct {
00059 int64_t segment_offset;
00060 mkv_cuepoint *entries;
00061 int num_entries;
00062 } mkv_cues;
00063
00064 typedef struct MatroskaMuxContext {
00065 ebml_master segment;
00066 int64_t segment_offset;
00067 int64_t segment_uid;
00068 ebml_master cluster;
00069 int64_t cluster_pos;
00070 uint64_t cluster_pts;
00071 int64_t duration_offset;
00072 uint64_t duration;
00073 mkv_seekhead *main_seekhead;
00074 mkv_seekhead *cluster_seekhead;
00075 mkv_cues *cues;
00076
00077 struct AVMD5 *md5_ctx;
00078 } MatroskaMuxContext;
00079
00080
00083 #define MAX_SEEKENTRY_SIZE 21
00084
00087 #define MAX_CUETRACKPOS_SIZE 22
00088
00090 #define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE*num_tracks
00091
00092
00093 static int ebml_id_size(unsigned int id)
00094 {
00095 return (av_log2(id+1)-1)/7+1;
00096 }
00097
00098 static void put_ebml_id(ByteIOContext *pb, unsigned int id)
00099 {
00100 int i = ebml_id_size(id);
00101 while (i--)
00102 put_byte(pb, id >> (i*8));
00103 }
00104
00110 static void put_ebml_size_unknown(ByteIOContext *pb, int bytes)
00111 {
00112 assert(bytes <= 8);
00113 put_byte(pb, 0x1ff >> bytes);
00114 while (--bytes)
00115 put_byte(pb, 0xff);
00116 }
00117
00121 static int ebml_num_size(uint64_t num)
00122 {
00123 int bytes = 1;
00124 while ((num+1) >> bytes*7) bytes++;
00125 return bytes;
00126 }
00127
00134 static void put_ebml_num(ByteIOContext *pb, uint64_t num, int bytes)
00135 {
00136 int i, needed_bytes = ebml_num_size(num);
00137
00138
00139 assert(num < (1ULL<<56)-1);
00140
00141 if (bytes == 0)
00142
00143 bytes = needed_bytes;
00144
00145
00146 assert(bytes >= needed_bytes);
00147
00148 num |= 1ULL << bytes*7;
00149 for (i = bytes - 1; i >= 0; i--)
00150 put_byte(pb, num >> i*8);
00151 }
00152
00153 static void put_ebml_uint(ByteIOContext *pb, unsigned int elementid, uint64_t val)
00154 {
00155 int i, bytes = 1;
00156 uint64_t tmp = val;
00157 while (tmp>>=8) bytes++;
00158
00159 put_ebml_id(pb, elementid);
00160 put_ebml_num(pb, bytes, 0);
00161 for (i = bytes - 1; i >= 0; i--)
00162 put_byte(pb, val >> i*8);
00163 }
00164
00165 static void put_ebml_float(ByteIOContext *pb, unsigned int elementid, double val)
00166 {
00167 put_ebml_id(pb, elementid);
00168 put_ebml_num(pb, 8, 0);
00169 put_be64(pb, av_dbl2int(val));
00170 }
00171
00172 static void put_ebml_binary(ByteIOContext *pb, unsigned int elementid,
00173 const uint8_t *buf, int size)
00174 {
00175 put_ebml_id(pb, elementid);
00176 put_ebml_num(pb, size, 0);
00177 put_buffer(pb, buf, size);
00178 }
00179
00180 static void put_ebml_string(ByteIOContext *pb, unsigned int elementid, const char *str)
00181 {
00182 put_ebml_binary(pb, elementid, str, strlen(str));
00183 }
00184
00191 static void put_ebml_void(ByteIOContext *pb, uint64_t size)
00192 {
00193 int64_t currentpos = url_ftell(pb);
00194
00195 assert(size >= 2);
00196
00197 put_ebml_id(pb, EBML_ID_VOID);
00198
00199
00200
00201 if (size < 10)
00202 put_ebml_num(pb, size-1, 0);
00203 else
00204 put_ebml_num(pb, size-9, 8);
00205 while(url_ftell(pb) < currentpos + size)
00206 put_byte(pb, 0);
00207 }
00208
00209 static ebml_master start_ebml_master(ByteIOContext *pb, unsigned int elementid, uint64_t expectedsize)
00210 {
00211 int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
00212 put_ebml_id(pb, elementid);
00213 put_ebml_size_unknown(pb, bytes);
00214 return (ebml_master){ url_ftell(pb), bytes };
00215 }
00216
00217 static void end_ebml_master(ByteIOContext *pb, ebml_master master)
00218 {
00219 int64_t pos = url_ftell(pb);
00220
00221
00222 if (url_is_streamed(pb))
00223 return;
00224
00225 url_fseek(pb, master.pos - master.sizebytes, SEEK_SET);
00226 put_ebml_num(pb, pos - master.pos, master.sizebytes);
00227 url_fseek(pb, pos, SEEK_SET);
00228 }
00229
00230 static void put_xiph_size(ByteIOContext *pb, int size)
00231 {
00232 int i;
00233 for (i = 0; i < size / 255; i++)
00234 put_byte(pb, 255);
00235 put_byte(pb, size % 255);
00236 }
00237
00249 static mkv_seekhead * mkv_start_seekhead(ByteIOContext *pb, int64_t segment_offset, int numelements)
00250 {
00251 mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
00252 if (new_seekhead == NULL)
00253 return NULL;
00254
00255 new_seekhead->segment_offset = segment_offset;
00256
00257 if (numelements > 0) {
00258 new_seekhead->filepos = url_ftell(pb);
00259
00260
00261
00262 new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 13;
00263 new_seekhead->max_entries = numelements;
00264 put_ebml_void(pb, new_seekhead->reserved_size);
00265 }
00266 return new_seekhead;
00267 }
00268
00269 static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
00270 {
00271 mkv_seekhead_entry *entries = seekhead->entries;
00272
00273
00274 if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
00275 return -1;
00276
00277 entries = av_realloc(entries, (seekhead->num_entries + 1) * sizeof(mkv_seekhead_entry));
00278 if (entries == NULL)
00279 return AVERROR(ENOMEM);
00280
00281 entries[seekhead->num_entries ].elementid = elementid;
00282 entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
00283
00284 seekhead->entries = entries;
00285 return 0;
00286 }
00287
00296 static int64_t mkv_write_seekhead(ByteIOContext *pb, mkv_seekhead *seekhead)
00297 {
00298 ebml_master metaseek, seekentry;
00299 int64_t currentpos;
00300 int i;
00301
00302 currentpos = url_ftell(pb);
00303
00304 if (seekhead->reserved_size > 0)
00305 url_fseek(pb, seekhead->filepos, SEEK_SET);
00306
00307 metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
00308 for (i = 0; i < seekhead->num_entries; i++) {
00309 mkv_seekhead_entry *entry = &seekhead->entries[i];
00310
00311 seekentry = start_ebml_master(pb, MATROSKA_ID_SEEKENTRY, MAX_SEEKENTRY_SIZE);
00312
00313 put_ebml_id(pb, MATROSKA_ID_SEEKID);
00314 put_ebml_num(pb, ebml_id_size(entry->elementid), 0);
00315 put_ebml_id(pb, entry->elementid);
00316
00317 put_ebml_uint(pb, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
00318 end_ebml_master(pb, seekentry);
00319 }
00320 end_ebml_master(pb, metaseek);
00321
00322 if (seekhead->reserved_size > 0) {
00323 uint64_t remaining = seekhead->filepos + seekhead->reserved_size - url_ftell(pb);
00324 put_ebml_void(pb, remaining);
00325 url_fseek(pb, currentpos, SEEK_SET);
00326
00327 currentpos = seekhead->filepos;
00328 }
00329 av_free(seekhead->entries);
00330 av_free(seekhead);
00331
00332 return currentpos;
00333 }
00334
00335 static mkv_cues * mkv_start_cues(int64_t segment_offset)
00336 {
00337 mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
00338 if (cues == NULL)
00339 return NULL;
00340
00341 cues->segment_offset = segment_offset;
00342 return cues;
00343 }
00344
00345 static int mkv_add_cuepoint(mkv_cues *cues, AVPacket *pkt, int64_t cluster_pos)
00346 {
00347 mkv_cuepoint *entries = cues->entries;
00348
00349 entries = av_realloc(entries, (cues->num_entries + 1) * sizeof(mkv_cuepoint));
00350 if (entries == NULL)
00351 return AVERROR(ENOMEM);
00352
00353 entries[cues->num_entries ].pts = pkt->pts;
00354 entries[cues->num_entries ].tracknum = pkt->stream_index + 1;
00355 entries[cues->num_entries++].cluster_pos = cluster_pos - cues->segment_offset;
00356
00357 cues->entries = entries;
00358 return 0;
00359 }
00360
00361 static int64_t mkv_write_cues(ByteIOContext *pb, mkv_cues *cues, int num_tracks)
00362 {
00363 ebml_master cues_element;
00364 int64_t currentpos;
00365 int i, j;
00366
00367 currentpos = url_ftell(pb);
00368 cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
00369
00370 for (i = 0; i < cues->num_entries; i++) {
00371 ebml_master cuepoint, track_positions;
00372 mkv_cuepoint *entry = &cues->entries[i];
00373 uint64_t pts = entry->pts;
00374
00375 cuepoint = start_ebml_master(pb, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(num_tracks));
00376 put_ebml_uint(pb, MATROSKA_ID_CUETIME, pts);
00377
00378
00379
00380 for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
00381 track_positions = start_ebml_master(pb, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);
00382 put_ebml_uint(pb, MATROSKA_ID_CUETRACK , entry[j].tracknum );
00383 put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION, entry[j].cluster_pos);
00384 end_ebml_master(pb, track_positions);
00385 }
00386 i += j - 1;
00387 end_ebml_master(pb, cuepoint);
00388 }
00389 end_ebml_master(pb, cues_element);
00390
00391 av_free(cues->entries);
00392 av_free(cues);
00393 return currentpos;
00394 }
00395
00396 static int put_xiph_codecpriv(AVFormatContext *s, ByteIOContext *pb, AVCodecContext *codec)
00397 {
00398 uint8_t *header_start[3];
00399 int header_len[3];
00400 int first_header_size;
00401 int j;
00402
00403 if (codec->codec_id == CODEC_ID_VORBIS)
00404 first_header_size = 30;
00405 else
00406 first_header_size = 42;
00407
00408 if (ff_split_xiph_headers(codec->extradata, codec->extradata_size,
00409 first_header_size, header_start, header_len) < 0) {
00410 av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
00411 return -1;
00412 }
00413
00414 put_byte(pb, 2);
00415 for (j = 0; j < 2; j++) {
00416 put_xiph_size(pb, header_len[j]);
00417 }
00418 for (j = 0; j < 3; j++)
00419 put_buffer(pb, header_start[j], header_len[j]);
00420
00421 return 0;
00422 }
00423
00424 static void get_aac_sample_rates(AVFormatContext *s, AVCodecContext *codec, int *sample_rate, int *output_sample_rate)
00425 {
00426 int sri;
00427
00428 if (codec->extradata_size < 2) {
00429 av_log(s, AV_LOG_WARNING, "No AAC extradata, unable to determine samplerate.\n");
00430 return;
00431 }
00432
00433 sri = ((codec->extradata[0] << 1) & 0xE) | (codec->extradata[1] >> 7);
00434 if (sri > 12) {
00435 av_log(s, AV_LOG_WARNING, "AAC samplerate index out of bounds\n");
00436 return;
00437 }
00438 *sample_rate = ff_mpeg4audio_sample_rates[sri];
00439
00440
00441 if (codec->extradata_size == 5) {
00442 sri = (codec->extradata[4] >> 3) & 0xF;
00443 if (sri > 12) {
00444 av_log(s, AV_LOG_WARNING, "AAC output samplerate index out of bounds\n");
00445 return;
00446 }
00447 *output_sample_rate = ff_mpeg4audio_sample_rates[sri];
00448 }
00449 }
00450
00451 static int mkv_write_codecprivate(AVFormatContext *s, ByteIOContext *pb, AVCodecContext *codec, int native_id, int qt_id)
00452 {
00453 ByteIOContext *dyn_cp;
00454 uint8_t *codecpriv;
00455 int ret, codecpriv_size;
00456
00457 ret = url_open_dyn_buf(&dyn_cp);
00458 if(ret < 0)
00459 return ret;
00460
00461 if (native_id) {
00462 if (codec->codec_id == CODEC_ID_VORBIS || codec->codec_id == CODEC_ID_THEORA)
00463 ret = put_xiph_codecpriv(s, dyn_cp, codec);
00464 else if (codec->codec_id == CODEC_ID_FLAC)
00465 ret = ff_flac_write_header(dyn_cp, codec);
00466 else if (codec->codec_id == CODEC_ID_H264)
00467 ret = ff_isom_write_avcc(dyn_cp, codec->extradata, codec->extradata_size);
00468 else if (codec->extradata_size)
00469 put_buffer(dyn_cp, codec->extradata, codec->extradata_size);
00470 } else if (codec->codec_type == CODEC_TYPE_VIDEO) {
00471 if (qt_id) {
00472 if (!codec->codec_tag)
00473 codec->codec_tag = codec_get_tag(codec_movvideo_tags, codec->codec_id);
00474 if (codec->extradata_size)
00475 put_buffer(dyn_cp, codec->extradata, codec->extradata_size);
00476 } else {
00477 if (!codec->codec_tag)
00478 codec->codec_tag = codec_get_tag(codec_bmp_tags, codec->codec_id);
00479 if (!codec->codec_tag) {
00480 av_log(s, AV_LOG_ERROR, "No bmp codec ID found.");
00481 ret = -1;
00482 }
00483
00484 put_bmp_header(dyn_cp, codec, codec_bmp_tags, 0);
00485 }
00486
00487 } else if (codec->codec_type == CODEC_TYPE_AUDIO) {
00488 if (!codec->codec_tag)
00489 codec->codec_tag = codec_get_tag(codec_wav_tags, codec->codec_id);
00490 if (!codec->codec_tag) {
00491 av_log(s, AV_LOG_ERROR, "No wav codec ID found.");
00492 ret = -1;
00493 }
00494
00495 put_wav_header(dyn_cp, codec);
00496 }
00497
00498 codecpriv_size = url_close_dyn_buf(dyn_cp, &codecpriv);
00499 if (codecpriv_size)
00500 put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv, codecpriv_size);
00501 av_free(codecpriv);
00502 return ret;
00503 }
00504
00505 static int mkv_write_tracks(AVFormatContext *s)
00506 {
00507 MatroskaMuxContext *mkv = s->priv_data;
00508 ByteIOContext *pb = s->pb;
00509 ebml_master tracks;
00510 int i, j, ret;
00511
00512 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, url_ftell(pb));
00513 if (ret < 0) return ret;
00514
00515 tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
00516 for (i = 0; i < s->nb_streams; i++) {
00517 AVStream *st = s->streams[i];
00518 AVCodecContext *codec = st->codec;
00519 ebml_master subinfo, track;
00520 int native_id = 0;
00521 int qt_id = 0;
00522 int bit_depth = av_get_bits_per_sample(codec->codec_id);
00523 int sample_rate = codec->sample_rate;
00524 int output_sample_rate = 0;
00525 AVMetadataTag *tag;
00526
00527 if (!bit_depth)
00528 bit_depth = av_get_bits_per_sample_format(codec->sample_fmt);
00529
00530 if (codec->codec_id == CODEC_ID_AAC)
00531 get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);
00532
00533 track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
00534 put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER , i + 1);
00535 put_ebml_uint (pb, MATROSKA_ID_TRACKUID , i + 1);
00536 put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0);
00537
00538 if ((tag = av_metadata_get(st->metadata, "description", NULL, 0)))
00539 put_ebml_string(pb, MATROSKA_ID_TRACKNAME, tag->value);
00540 tag = av_metadata_get(st->metadata, "language", NULL, 0);
00541 put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag ? tag->value:"und");
00542
00543 if (st->disposition)
00544 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGDEFAULT, !!(st->disposition & AV_DISPOSITION_DEFAULT));
00545
00546
00547
00548 for (j = 0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++) {
00549 if (ff_mkv_codec_tags[j].id == codec->codec_id) {
00550 put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
00551 native_id = 1;
00552 break;
00553 }
00554 }
00555
00556 switch (codec->codec_type) {
00557 case CODEC_TYPE_VIDEO:
00558 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
00559
00560 if (!native_id &&
00561 codec_get_tag(codec_movvideo_tags, codec->codec_id) &&
00562 (!codec_get_tag(codec_bmp_tags, codec->codec_id)
00563 || codec->codec_id == CODEC_ID_SVQ1
00564 || codec->codec_id == CODEC_ID_SVQ3
00565 || codec->codec_id == CODEC_ID_CINEPAK))
00566 qt_id = 1;
00567
00568 if (qt_id)
00569 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
00570 else if (!native_id)
00571
00572 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
00573
00574 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
00575
00576 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
00577 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
00578 if (st->sample_aspect_ratio.num) {
00579 int d_width = codec->width*av_q2d(st->sample_aspect_ratio);
00580 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width);
00581 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height);
00582 }
00583 end_ebml_master(pb, subinfo);
00584 break;
00585
00586 case CODEC_TYPE_AUDIO:
00587 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
00588
00589 if (!native_id)
00590
00591 put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
00592
00593 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
00594 put_ebml_uint (pb, MATROSKA_ID_AUDIOCHANNELS , codec->channels);
00595 put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
00596 if (output_sample_rate)
00597 put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
00598 if (bit_depth)
00599 put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
00600 end_ebml_master(pb, subinfo);
00601 break;
00602
00603 case CODEC_TYPE_SUBTITLE:
00604 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_SUBTITLE);
00605 break;
00606 default:
00607 av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.");
00608 break;
00609 }
00610 ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);
00611 if (ret < 0) return ret;
00612
00613 end_ebml_master(pb, track);
00614
00615
00616 av_set_pts_info(st, 64, 1, 1000);
00617 }
00618 end_ebml_master(pb, tracks);
00619 return 0;
00620 }
00621
00622 static int mkv_write_header(AVFormatContext *s)
00623 {
00624 MatroskaMuxContext *mkv = s->priv_data;
00625 ByteIOContext *pb = s->pb;
00626 ebml_master ebml_header, segment_info;
00627 AVMetadataTag *tag;
00628 int ret;
00629
00630 mkv->md5_ctx = av_mallocz(av_md5_size);
00631 av_md5_init(mkv->md5_ctx);
00632
00633 ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
00634 put_ebml_uint (pb, EBML_ID_EBMLVERSION , 1);
00635 put_ebml_uint (pb, EBML_ID_EBMLREADVERSION , 1);
00636 put_ebml_uint (pb, EBML_ID_EBMLMAXIDLENGTH , 4);
00637 put_ebml_uint (pb, EBML_ID_EBMLMAXSIZELENGTH , 8);
00638 put_ebml_string (pb, EBML_ID_DOCTYPE , "matroska");
00639 put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , 2);
00640 put_ebml_uint (pb, EBML_ID_DOCTYPEREADVERSION , 2);
00641 end_ebml_master(pb, ebml_header);
00642
00643 mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
00644 mkv->segment_offset = url_ftell(pb);
00645
00646
00647
00648
00649
00650
00651 mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
00652 mkv->cluster_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 0);
00653 if (mkv->main_seekhead == NULL || mkv->cluster_seekhead == NULL)
00654 return AVERROR(ENOMEM);
00655
00656 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, url_ftell(pb));
00657 if (ret < 0) return ret;
00658
00659 segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
00660 put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
00661 if ((tag = av_metadata_get(s->metadata, "title", NULL, 0)))
00662 put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
00663 if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
00664 put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , LIBAVFORMAT_IDENT);
00665 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
00666
00667
00668 mkv->segment_uid = url_ftell(pb);
00669 put_ebml_void(pb, 19);
00670 }
00671
00672
00673 mkv->duration = 0;
00674 mkv->duration_offset = url_ftell(pb);
00675 put_ebml_void(pb, 11);
00676 end_ebml_master(pb, segment_info);
00677
00678 ret = mkv_write_tracks(s);
00679 if (ret < 0) return ret;
00680
00681 ret = mkv_add_seekhead_entry(mkv->cluster_seekhead, MATROSKA_ID_CLUSTER, url_ftell(pb));
00682 if (ret < 0) return ret;
00683
00684 mkv->cluster_pos = url_ftell(pb);
00685 mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
00686 put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, 0);
00687 mkv->cluster_pts = 0;
00688
00689 mkv->cues = mkv_start_cues(mkv->segment_offset);
00690 if (mkv->cues == NULL)
00691 return AVERROR(ENOMEM);
00692
00693 put_flush_packet(pb);
00694 return 0;
00695 }
00696
00697 static int mkv_blockgroup_size(int pkt_size)
00698 {
00699 int size = pkt_size + 4;
00700 size += ebml_num_size(size);
00701 size += 2;
00702 size += 8;
00703 size += ebml_num_size(size);
00704 size += 1;
00705 return size;
00706 }
00707
00708 static int ass_get_duration(const uint8_t *p)
00709 {
00710 int sh, sm, ss, sc, eh, em, es, ec;
00711 uint64_t start, end;
00712
00713 if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
00714 &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)
00715 return 0;
00716 start = 3600000*sh + 60000*sm + 1000*ss + 10*sc;
00717 end = 3600000*eh + 60000*em + 1000*es + 10*ec;
00718 return end - start;
00719 }
00720
00721 static int mkv_write_ass_blocks(AVFormatContext *s, AVPacket *pkt)
00722 {
00723 MatroskaMuxContext *mkv = s->priv_data;
00724 ByteIOContext *pb = s->pb;
00725 int i, layer = 0, max_duration = 0, size, line_size, data_size = pkt->size;
00726 uint8_t *start, *end, *data = pkt->data;
00727 ebml_master blockgroup;
00728 char buffer[2048];
00729
00730 while (data_size) {
00731 int duration = ass_get_duration(data);
00732 max_duration = FFMAX(duration, max_duration);
00733 end = memchr(data, '\n', data_size);
00734 size = line_size = end ? end-data+1 : data_size;
00735 size -= end ? (end[-1]=='\r')+1 : 0;
00736 start = data;
00737 for (i=0; i<3; i++, start++)
00738 if (!(start = memchr(start, ',', size-(start-data))))
00739 return max_duration;
00740 size -= start - data;
00741 sscanf(data, "Dialogue: %d,", &layer);
00742 i = snprintf(buffer, sizeof(buffer), "%"PRId64",%d,",
00743 s->streams[pkt->stream_index]->nb_frames++, layer);
00744 size = FFMIN(i+size, sizeof(buffer));
00745 memcpy(buffer+i, start, size-i);
00746
00747 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
00748 "pts %" PRId64 ", duration %d\n",
00749 url_ftell(pb), size, pkt->pts, duration);
00750 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(size));
00751 put_ebml_id(pb, MATROSKA_ID_BLOCK);
00752 put_ebml_num(pb, size+4, 0);
00753 put_byte(pb, 0x80 | (pkt->stream_index + 1));
00754 put_be16(pb, pkt->pts - mkv->cluster_pts);
00755 put_byte(pb, 0);
00756 put_buffer(pb, buffer, size);
00757 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
00758 end_ebml_master(pb, blockgroup);
00759
00760 data += line_size;
00761 data_size -= line_size;
00762 }
00763
00764 return max_duration;
00765 }
00766
00767 static void mkv_write_block(AVFormatContext *s, unsigned int blockid, AVPacket *pkt, int flags)
00768 {
00769 MatroskaMuxContext *mkv = s->priv_data;
00770 ByteIOContext *pb = s->pb;
00771 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
00772 uint8_t *data = NULL;
00773 int size = pkt->size;
00774
00775 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
00776 "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
00777 url_ftell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
00778 if (codec->codec_id == CODEC_ID_H264 && codec->extradata_size > 0 &&
00779 (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
00780 ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
00781 else
00782 data = pkt->data;
00783 put_ebml_id(pb, blockid);
00784 put_ebml_num(pb, size+4, 0);
00785 put_byte(pb, 0x80 | (pkt->stream_index + 1));
00786 put_be16(pb, pkt->pts - mkv->cluster_pts);
00787 put_byte(pb, flags);
00788 put_buffer(pb, data, size);
00789 if (data != pkt->data)
00790 av_free(data);
00791 }
00792
00793 static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
00794 {
00795 MatroskaMuxContext *mkv = s->priv_data;
00796 ByteIOContext *pb = s->pb;
00797 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
00798 int keyframe = !!(pkt->flags & PKT_FLAG_KEY);
00799 int duration = pkt->duration;
00800 int ret;
00801
00802
00803 if (url_ftell(pb) > mkv->cluster_pos + 5*1024*1024 || pkt->pts > mkv->cluster_pts + 5000) {
00804 av_log(s, AV_LOG_DEBUG, "Starting new cluster at offset %" PRIu64
00805 " bytes, pts %" PRIu64 "\n", url_ftell(pb), pkt->pts);
00806 end_ebml_master(pb, mkv->cluster);
00807
00808 ret = mkv_add_seekhead_entry(mkv->cluster_seekhead, MATROSKA_ID_CLUSTER, url_ftell(pb));
00809 if (ret < 0) return ret;
00810
00811 mkv->cluster_pos = url_ftell(pb);
00812 mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
00813 put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, pkt->pts);
00814 mkv->cluster_pts = pkt->pts;
00815 av_md5_update(mkv->md5_ctx, pkt->data, FFMIN(200, pkt->size));
00816 }
00817
00818 if (codec->codec_type != CODEC_TYPE_SUBTITLE) {
00819 mkv_write_block(s, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
00820 } else if (codec->codec_id == CODEC_ID_SSA) {
00821 duration = mkv_write_ass_blocks(s, pkt);
00822 } else {
00823 ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(pkt->size));
00824 duration = pkt->convergence_duration;
00825 mkv_write_block(s, MATROSKA_ID_BLOCK, pkt, 0);
00826 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
00827 end_ebml_master(pb, blockgroup);
00828 }
00829
00830 if (codec->codec_type == CODEC_TYPE_VIDEO && keyframe) {
00831 ret = mkv_add_cuepoint(mkv->cues, pkt, mkv->cluster_pos);
00832 if (ret < 0) return ret;
00833 }
00834
00835 mkv->duration = FFMAX(mkv->duration, pkt->pts + duration);
00836 return 0;
00837 }
00838
00839 static int mkv_write_trailer(AVFormatContext *s)
00840 {
00841 MatroskaMuxContext *mkv = s->priv_data;
00842 ByteIOContext *pb = s->pb;
00843 int64_t currentpos, second_seekhead, cuespos;
00844 int ret;
00845
00846 end_ebml_master(pb, mkv->cluster);
00847
00848 if (!url_is_streamed(pb)) {
00849 cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
00850 second_seekhead = mkv_write_seekhead(pb, mkv->cluster_seekhead);
00851
00852 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES , cuespos);
00853 if (ret < 0) return ret;
00854 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_SEEKHEAD, second_seekhead);
00855 if (ret < 0) return ret;
00856 mkv_write_seekhead(pb, mkv->main_seekhead);
00857
00858
00859 av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
00860 currentpos = url_ftell(pb);
00861 url_fseek(pb, mkv->duration_offset, SEEK_SET);
00862 put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
00863
00864
00865 if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
00866 uint8_t segment_uid[16];
00867 av_md5_final(mkv->md5_ctx, segment_uid);
00868 url_fseek(pb, mkv->segment_uid, SEEK_SET);
00869 put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
00870 }
00871 url_fseek(pb, currentpos, SEEK_SET);
00872 }
00873
00874 end_ebml_master(pb, mkv->segment);
00875 av_free(mkv->md5_ctx);
00876 put_flush_packet(pb);
00877 return 0;
00878 }
00879
00880 AVOutputFormat matroska_muxer = {
00881 "matroska",
00882 NULL_IF_CONFIG_SMALL("Matroska file format"),
00883 "video/x-matroska",
00884 "mkv",
00885 sizeof(MatroskaMuxContext),
00886 CODEC_ID_MP2,
00887 CODEC_ID_MPEG4,
00888 mkv_write_header,
00889 mkv_write_packet,
00890 mkv_write_trailer,
00891 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
00892 .codec_tag = (const AVCodecTag* const []){codec_bmp_tags, codec_wav_tags, 0},
00893 .subtitle_codec = CODEC_ID_TEXT,
00894 };
00895
00896 AVOutputFormat matroska_audio_muxer = {
00897 "matroska",
00898 NULL_IF_CONFIG_SMALL("Matroska file format"),
00899 "audio/x-matroska",
00900 "mka",
00901 sizeof(MatroskaMuxContext),
00902 CODEC_ID_MP2,
00903 CODEC_ID_NONE,
00904 mkv_write_header,
00905 mkv_write_packet,
00906 mkv_write_trailer,
00907 .flags = AVFMT_GLOBALHEADER,
00908 .codec_tag = (const AVCodecTag* const []){codec_wav_tags, 0},
00909 };