You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

958 lines
33KB

  1. /*
  2. * Matroska muxer
  3. * Copyright (c) 2007 David Conrad
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "avformat.h"
  22. #include "riff.h"
  23. #include "isom.h"
  24. #include "matroska.h"
  25. #include "avc.h"
  26. #include "flacenc.h"
  27. #include "libavutil/intreadwrite.h"
  28. #include "libavutil/md5.h"
  29. #include "libavcodec/xiph.h"
  30. #include "libavcodec/mpeg4audio.h"
  31. typedef struct ebml_master {
  32. int64_t pos; ///< absolute offset in the file where the master's elements start
  33. int sizebytes; ///< how many bytes were reserved for the size
  34. } ebml_master;
  35. typedef struct mkv_seekhead_entry {
  36. unsigned int elementid;
  37. uint64_t segmentpos;
  38. } mkv_seekhead_entry;
  39. typedef struct mkv_seekhead {
  40. int64_t filepos;
  41. int64_t segment_offset; ///< the file offset to the beginning of the segment
  42. int reserved_size; ///< -1 if appending to file
  43. int max_entries;
  44. mkv_seekhead_entry *entries;
  45. int num_entries;
  46. } mkv_seekhead;
  47. typedef struct {
  48. uint64_t pts;
  49. int tracknum;
  50. int64_t cluster_pos; ///< file offset of the cluster containing the block
  51. } mkv_cuepoint;
  52. typedef struct {
  53. int64_t segment_offset;
  54. mkv_cuepoint *entries;
  55. int num_entries;
  56. } mkv_cues;
  57. typedef struct MatroskaMuxContext {
  58. ebml_master segment;
  59. int64_t segment_offset;
  60. int64_t segment_uid;
  61. ebml_master cluster;
  62. int64_t cluster_pos; ///< file offset of the current cluster
  63. uint64_t cluster_pts;
  64. int64_t duration_offset;
  65. uint64_t duration;
  66. mkv_seekhead *main_seekhead;
  67. mkv_seekhead *cluster_seekhead;
  68. mkv_cues *cues;
  69. struct AVMD5 *md5_ctx;
  70. } MatroskaMuxContext;
  71. /** 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
  72. * offset, 4 bytes for target EBML ID */
  73. #define MAX_SEEKENTRY_SIZE 21
  74. /** per-cuepoint-track - 3 1-byte EBML IDs, 3 1-byte EBML sizes, 2
  75. * 8-byte uint max */
  76. #define MAX_CUETRACKPOS_SIZE 22
  77. /** per-cuepoint - 2 1-byte EBML IDs, 2 1-byte EBML sizes, 8-byte uint max */
  78. #define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE*num_tracks
  79. static int ebml_id_size(unsigned int id)
  80. {
  81. return (av_log2(id+1)-1)/7+1;
  82. }
  83. static void put_ebml_id(ByteIOContext *pb, unsigned int id)
  84. {
  85. int i = ebml_id_size(id);
  86. while (i--)
  87. put_byte(pb, id >> (i*8));
  88. }
  89. /**
  90. * Write an EBML size meaning "unknown size".
  91. *
  92. * @param bytes The number of bytes the size should occupy (maximum: 8).
  93. */
  94. static void put_ebml_size_unknown(ByteIOContext *pb, int bytes)
  95. {
  96. assert(bytes <= 8);
  97. put_byte(pb, 0x1ff >> bytes);
  98. while (--bytes)
  99. put_byte(pb, 0xff);
  100. }
  101. /**
  102. * Calculate how many bytes are needed to represent a given number in EBML.
  103. */
  104. static int ebml_num_size(uint64_t num)
  105. {
  106. int bytes = 1;
  107. while ((num+1) >> bytes*7) bytes++;
  108. return bytes;
  109. }
  110. /**
  111. * Write a number in EBML variable length format.
  112. *
  113. * @param bytes The number of bytes that need to be used to write the number.
  114. * If zero, any number of bytes can be used.
  115. */
  116. static void put_ebml_num(ByteIOContext *pb, uint64_t num, int bytes)
  117. {
  118. int i, needed_bytes = ebml_num_size(num);
  119. // sizes larger than this are currently undefined in EBML
  120. assert(num < (1ULL<<56)-1);
  121. if (bytes == 0)
  122. // don't care how many bytes are used, so use the min
  123. bytes = needed_bytes;
  124. // the bytes needed to write the given size would exceed the bytes
  125. // that we need to use, so write unknown size. This shouldn't happen.
  126. assert(bytes >= needed_bytes);
  127. num |= 1ULL << bytes*7;
  128. for (i = bytes - 1; i >= 0; i--)
  129. put_byte(pb, num >> i*8);
  130. }
  131. static void put_ebml_uint(ByteIOContext *pb, unsigned int elementid, uint64_t val)
  132. {
  133. int i, bytes = 1;
  134. uint64_t tmp = val;
  135. while (tmp>>=8) bytes++;
  136. put_ebml_id(pb, elementid);
  137. put_ebml_num(pb, bytes, 0);
  138. for (i = bytes - 1; i >= 0; i--)
  139. put_byte(pb, val >> i*8);
  140. }
  141. static void put_ebml_float(ByteIOContext *pb, unsigned int elementid, double val)
  142. {
  143. put_ebml_id(pb, elementid);
  144. put_ebml_num(pb, 8, 0);
  145. put_be64(pb, av_dbl2int(val));
  146. }
  147. static void put_ebml_binary(ByteIOContext *pb, unsigned int elementid,
  148. const uint8_t *buf, int size)
  149. {
  150. put_ebml_id(pb, elementid);
  151. put_ebml_num(pb, size, 0);
  152. put_buffer(pb, buf, size);
  153. }
  154. static void put_ebml_string(ByteIOContext *pb, unsigned int elementid, const char *str)
  155. {
  156. put_ebml_binary(pb, elementid, str, strlen(str));
  157. }
  158. /**
  159. * Writes a void element of a given size. Useful for reserving space in
  160. * the file to be written to later.
  161. *
  162. * @param size The number of bytes to reserve, which must be at least 2.
  163. */
  164. static void put_ebml_void(ByteIOContext *pb, uint64_t size)
  165. {
  166. int64_t currentpos = url_ftell(pb);
  167. assert(size >= 2);
  168. put_ebml_id(pb, EBML_ID_VOID);
  169. // we need to subtract the length needed to store the size from the
  170. // size we need to reserve so 2 cases, we use 8 bytes to store the
  171. // size if possible, 1 byte otherwise
  172. if (size < 10)
  173. put_ebml_num(pb, size-1, 0);
  174. else
  175. put_ebml_num(pb, size-9, 8);
  176. while(url_ftell(pb) < currentpos + size)
  177. put_byte(pb, 0);
  178. }
  179. static ebml_master start_ebml_master(ByteIOContext *pb, unsigned int elementid, uint64_t expectedsize)
  180. {
  181. int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
  182. put_ebml_id(pb, elementid);
  183. put_ebml_size_unknown(pb, bytes);
  184. return (ebml_master){ url_ftell(pb), bytes };
  185. }
  186. static void end_ebml_master(ByteIOContext *pb, ebml_master master)
  187. {
  188. int64_t pos = url_ftell(pb);
  189. // leave the unknown size for masters when streaming
  190. if (url_is_streamed(pb))
  191. return;
  192. url_fseek(pb, master.pos - master.sizebytes, SEEK_SET);
  193. put_ebml_num(pb, pos - master.pos, master.sizebytes);
  194. url_fseek(pb, pos, SEEK_SET);
  195. }
  196. static void put_xiph_size(ByteIOContext *pb, int size)
  197. {
  198. int i;
  199. for (i = 0; i < size / 255; i++)
  200. put_byte(pb, 255);
  201. put_byte(pb, size % 255);
  202. }
  203. /**
  204. * Initialize a mkv_seekhead element to be ready to index level 1 Matroska
  205. * elements. If a maximum number of elements is specified, enough space
  206. * will be reserved at the current file location to write a seek head of
  207. * that size.
  208. *
  209. * @param segment_offset The absolute offset to the position in the file
  210. * where the segment begins.
  211. * @param numelements The maximum number of elements that will be indexed
  212. * by this seek head, 0 if unlimited.
  213. */
  214. static mkv_seekhead * mkv_start_seekhead(ByteIOContext *pb, int64_t segment_offset, int numelements)
  215. {
  216. mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
  217. if (new_seekhead == NULL)
  218. return NULL;
  219. new_seekhead->segment_offset = segment_offset;
  220. if (numelements > 0) {
  221. new_seekhead->filepos = url_ftell(pb);
  222. // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
  223. // and size, and 3 bytes to guarantee that an EBML void element
  224. // will fit afterwards
  225. new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 13;
  226. new_seekhead->max_entries = numelements;
  227. put_ebml_void(pb, new_seekhead->reserved_size);
  228. }
  229. return new_seekhead;
  230. }
  231. static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
  232. {
  233. mkv_seekhead_entry *entries = seekhead->entries;
  234. // don't store more elements than we reserved space for
  235. if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
  236. return -1;
  237. entries = av_realloc(entries, (seekhead->num_entries + 1) * sizeof(mkv_seekhead_entry));
  238. if (entries == NULL)
  239. return AVERROR(ENOMEM);
  240. entries[seekhead->num_entries ].elementid = elementid;
  241. entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
  242. seekhead->entries = entries;
  243. return 0;
  244. }
  245. /**
  246. * Write the seek head to the file and free it. If a maximum number of
  247. * elements was specified to mkv_start_seekhead(), the seek head will
  248. * be written at the location reserved for it. Otherwise, it is written
  249. * at the current location in the file.
  250. *
  251. * @return The file offset where the seekhead was written.
  252. */
  253. static int64_t mkv_write_seekhead(ByteIOContext *pb, mkv_seekhead *seekhead)
  254. {
  255. ebml_master metaseek, seekentry;
  256. int64_t currentpos;
  257. int i;
  258. currentpos = url_ftell(pb);
  259. if (seekhead->reserved_size > 0)
  260. url_fseek(pb, seekhead->filepos, SEEK_SET);
  261. metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
  262. for (i = 0; i < seekhead->num_entries; i++) {
  263. mkv_seekhead_entry *entry = &seekhead->entries[i];
  264. seekentry = start_ebml_master(pb, MATROSKA_ID_SEEKENTRY, MAX_SEEKENTRY_SIZE);
  265. put_ebml_id(pb, MATROSKA_ID_SEEKID);
  266. put_ebml_num(pb, ebml_id_size(entry->elementid), 0);
  267. put_ebml_id(pb, entry->elementid);
  268. put_ebml_uint(pb, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
  269. end_ebml_master(pb, seekentry);
  270. }
  271. end_ebml_master(pb, metaseek);
  272. if (seekhead->reserved_size > 0) {
  273. uint64_t remaining = seekhead->filepos + seekhead->reserved_size - url_ftell(pb);
  274. put_ebml_void(pb, remaining);
  275. url_fseek(pb, currentpos, SEEK_SET);
  276. currentpos = seekhead->filepos;
  277. }
  278. av_free(seekhead->entries);
  279. av_free(seekhead);
  280. return currentpos;
  281. }
  282. static mkv_cues * mkv_start_cues(int64_t segment_offset)
  283. {
  284. mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
  285. if (cues == NULL)
  286. return NULL;
  287. cues->segment_offset = segment_offset;
  288. return cues;
  289. }
  290. static int mkv_add_cuepoint(mkv_cues *cues, AVPacket *pkt, int64_t cluster_pos)
  291. {
  292. mkv_cuepoint *entries = cues->entries;
  293. entries = av_realloc(entries, (cues->num_entries + 1) * sizeof(mkv_cuepoint));
  294. if (entries == NULL)
  295. return AVERROR(ENOMEM);
  296. entries[cues->num_entries ].pts = pkt->pts;
  297. entries[cues->num_entries ].tracknum = pkt->stream_index + 1;
  298. entries[cues->num_entries++].cluster_pos = cluster_pos - cues->segment_offset;
  299. cues->entries = entries;
  300. return 0;
  301. }
  302. static int64_t mkv_write_cues(ByteIOContext *pb, mkv_cues *cues, int num_tracks)
  303. {
  304. ebml_master cues_element;
  305. int64_t currentpos;
  306. int i, j;
  307. currentpos = url_ftell(pb);
  308. cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
  309. for (i = 0; i < cues->num_entries; i++) {
  310. ebml_master cuepoint, track_positions;
  311. mkv_cuepoint *entry = &cues->entries[i];
  312. uint64_t pts = entry->pts;
  313. cuepoint = start_ebml_master(pb, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(num_tracks));
  314. put_ebml_uint(pb, MATROSKA_ID_CUETIME, pts);
  315. // put all the entries from different tracks that have the exact same
  316. // timestamp into the same CuePoint
  317. for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
  318. track_positions = start_ebml_master(pb, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);
  319. put_ebml_uint(pb, MATROSKA_ID_CUETRACK , entry[j].tracknum );
  320. put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION, entry[j].cluster_pos);
  321. end_ebml_master(pb, track_positions);
  322. }
  323. i += j - 1;
  324. end_ebml_master(pb, cuepoint);
  325. }
  326. end_ebml_master(pb, cues_element);
  327. av_free(cues->entries);
  328. av_free(cues);
  329. return currentpos;
  330. }
  331. static int put_xiph_codecpriv(AVFormatContext *s, ByteIOContext *pb, AVCodecContext *codec)
  332. {
  333. uint8_t *header_start[3];
  334. int header_len[3];
  335. int first_header_size;
  336. int j;
  337. if (codec->codec_id == CODEC_ID_VORBIS)
  338. first_header_size = 30;
  339. else
  340. first_header_size = 42;
  341. if (ff_split_xiph_headers(codec->extradata, codec->extradata_size,
  342. first_header_size, header_start, header_len) < 0) {
  343. av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
  344. return -1;
  345. }
  346. put_byte(pb, 2); // number packets - 1
  347. for (j = 0; j < 2; j++) {
  348. put_xiph_size(pb, header_len[j]);
  349. }
  350. for (j = 0; j < 3; j++)
  351. put_buffer(pb, header_start[j], header_len[j]);
  352. return 0;
  353. }
  354. static void get_aac_sample_rates(AVFormatContext *s, AVCodecContext *codec, int *sample_rate, int *output_sample_rate)
  355. {
  356. int sri;
  357. if (codec->extradata_size < 2) {
  358. av_log(s, AV_LOG_WARNING, "No AAC extradata, unable to determine samplerate.\n");
  359. return;
  360. }
  361. sri = ((codec->extradata[0] << 1) & 0xE) | (codec->extradata[1] >> 7);
  362. if (sri > 12) {
  363. av_log(s, AV_LOG_WARNING, "AAC samplerate index out of bounds\n");
  364. return;
  365. }
  366. *sample_rate = ff_mpeg4audio_sample_rates[sri];
  367. // if sbr, get output sample rate as well
  368. if (codec->extradata_size == 5) {
  369. sri = (codec->extradata[4] >> 3) & 0xF;
  370. if (sri > 12) {
  371. av_log(s, AV_LOG_WARNING, "AAC output samplerate index out of bounds\n");
  372. return;
  373. }
  374. *output_sample_rate = ff_mpeg4audio_sample_rates[sri];
  375. }
  376. }
  377. static int mkv_write_codecprivate(AVFormatContext *s, ByteIOContext *pb, AVCodecContext *codec, int native_id, int qt_id)
  378. {
  379. ByteIOContext *dyn_cp;
  380. uint8_t *codecpriv;
  381. int ret, codecpriv_size;
  382. ret = url_open_dyn_buf(&dyn_cp);
  383. if(ret < 0)
  384. return ret;
  385. if (native_id) {
  386. if (codec->codec_id == CODEC_ID_VORBIS || codec->codec_id == CODEC_ID_THEORA)
  387. ret = put_xiph_codecpriv(s, dyn_cp, codec);
  388. else if (codec->codec_id == CODEC_ID_FLAC)
  389. ret = ff_flac_write_header(dyn_cp, codec);
  390. else if (codec->codec_id == CODEC_ID_H264)
  391. ret = ff_isom_write_avcc(dyn_cp, codec->extradata, codec->extradata_size);
  392. else if (codec->extradata_size)
  393. put_buffer(dyn_cp, codec->extradata, codec->extradata_size);
  394. } else if (codec->codec_type == CODEC_TYPE_VIDEO) {
  395. if (qt_id) {
  396. if (!codec->codec_tag)
  397. codec->codec_tag = ff_codec_get_tag(codec_movvideo_tags, codec->codec_id);
  398. if (codec->extradata_size)
  399. put_buffer(dyn_cp, codec->extradata, codec->extradata_size);
  400. } else {
  401. if (!codec->codec_tag)
  402. codec->codec_tag = ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id);
  403. if (!codec->codec_tag) {
  404. av_log(s, AV_LOG_ERROR, "No bmp codec ID found.");
  405. ret = -1;
  406. }
  407. ff_put_bmp_header(dyn_cp, codec, ff_codec_bmp_tags, 0);
  408. }
  409. } else if (codec->codec_type == CODEC_TYPE_AUDIO) {
  410. if (!codec->codec_tag)
  411. codec->codec_tag = ff_codec_get_tag(ff_codec_wav_tags, codec->codec_id);
  412. if (!codec->codec_tag) {
  413. av_log(s, AV_LOG_ERROR, "No wav codec ID found.");
  414. ret = -1;
  415. }
  416. ff_put_wav_header(dyn_cp, codec);
  417. }
  418. codecpriv_size = url_close_dyn_buf(dyn_cp, &codecpriv);
  419. if (codecpriv_size)
  420. put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv, codecpriv_size);
  421. av_free(codecpriv);
  422. return ret;
  423. }
  424. static int mkv_write_tracks(AVFormatContext *s)
  425. {
  426. MatroskaMuxContext *mkv = s->priv_data;
  427. ByteIOContext *pb = s->pb;
  428. ebml_master tracks;
  429. int i, j, ret;
  430. ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, url_ftell(pb));
  431. if (ret < 0) return ret;
  432. tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
  433. for (i = 0; i < s->nb_streams; i++) {
  434. AVStream *st = s->streams[i];
  435. AVCodecContext *codec = st->codec;
  436. ebml_master subinfo, track;
  437. int native_id = 0;
  438. int qt_id = 0;
  439. int bit_depth = av_get_bits_per_sample(codec->codec_id);
  440. int sample_rate = codec->sample_rate;
  441. int output_sample_rate = 0;
  442. AVMetadataTag *tag;
  443. if (!bit_depth)
  444. bit_depth = av_get_bits_per_sample_format(codec->sample_fmt);
  445. if (codec->codec_id == CODEC_ID_AAC)
  446. get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);
  447. track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
  448. put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER , i + 1);
  449. put_ebml_uint (pb, MATROSKA_ID_TRACKUID , i + 1);
  450. put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0); // no lacing (yet)
  451. put_ebml_float(pb, MATROSKA_ID_TRACKTIMECODESCALE, 1.0);
  452. if ((tag = av_metadata_get(st->metadata, "description", NULL, 0)))
  453. put_ebml_string(pb, MATROSKA_ID_TRACKNAME, tag->value);
  454. tag = av_metadata_get(st->metadata, "language", NULL, 0);
  455. put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag ? tag->value:"und");
  456. if (st->disposition)
  457. put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGDEFAULT, !!(st->disposition & AV_DISPOSITION_DEFAULT));
  458. // look for a codec ID string specific to mkv to use,
  459. // if none are found, use AVI codes
  460. for (j = 0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++) {
  461. if (ff_mkv_codec_tags[j].id == codec->codec_id) {
  462. put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
  463. native_id = 1;
  464. break;
  465. }
  466. }
  467. switch (codec->codec_type) {
  468. case CODEC_TYPE_VIDEO:
  469. put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
  470. if (!native_id &&
  471. ff_codec_get_tag(codec_movvideo_tags, codec->codec_id) &&
  472. (!ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id)
  473. || codec->codec_id == CODEC_ID_SVQ1
  474. || codec->codec_id == CODEC_ID_SVQ3
  475. || codec->codec_id == CODEC_ID_CINEPAK))
  476. qt_id = 1;
  477. if (qt_id)
  478. put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
  479. else if (!native_id)
  480. // if there is no mkv-specific codec ID, use VFW mode
  481. put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
  482. subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
  483. // XXX: interlace flag?
  484. put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
  485. put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
  486. if (st->sample_aspect_ratio.num) {
  487. int d_width = codec->width*av_q2d(st->sample_aspect_ratio);
  488. put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width);
  489. put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height);
  490. }
  491. end_ebml_master(pb, subinfo);
  492. break;
  493. case CODEC_TYPE_AUDIO:
  494. put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
  495. if (!native_id)
  496. // no mkv-specific ID, use ACM mode
  497. put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
  498. subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
  499. put_ebml_uint (pb, MATROSKA_ID_AUDIOCHANNELS , codec->channels);
  500. put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
  501. if (output_sample_rate)
  502. put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
  503. if (bit_depth)
  504. put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
  505. end_ebml_master(pb, subinfo);
  506. break;
  507. case CODEC_TYPE_SUBTITLE:
  508. put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_SUBTITLE);
  509. break;
  510. default:
  511. av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.");
  512. break;
  513. }
  514. ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);
  515. if (ret < 0) return ret;
  516. end_ebml_master(pb, track);
  517. // ms precision is the de-facto standard timescale for mkv files
  518. av_set_pts_info(st, 64, 1, 1000);
  519. }
  520. end_ebml_master(pb, tracks);
  521. return 0;
  522. }
  523. static int mkv_write_chapters(AVFormatContext *s)
  524. {
  525. MatroskaMuxContext *mkv = s->priv_data;
  526. ByteIOContext *pb = s->pb;
  527. ebml_master chapters, editionentry;
  528. AVRational scale = {1, 1E9};
  529. int i, ret;
  530. if (!s->nb_chapters)
  531. return 0;
  532. ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CHAPTERS, url_ftell(pb));
  533. if (ret < 0) return ret;
  534. chapters = start_ebml_master(pb, MATROSKA_ID_CHAPTERS , 0);
  535. editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);
  536. put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGDEFAULT, 1);
  537. put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGHIDDEN , 0);
  538. for (i = 0; i < s->nb_chapters; i++) {
  539. ebml_master chapteratom, chapterdisplay;
  540. AVChapter *c = s->chapters[i];
  541. AVMetadataTag *t = NULL;
  542. chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
  543. put_ebml_uint(pb, MATROSKA_ID_CHAPTERUID, c->id);
  544. put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMESTART,
  545. av_rescale_q(c->start, c->time_base, scale));
  546. put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMEEND,
  547. av_rescale_q(c->end, c->time_base, scale));
  548. put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGHIDDEN , 0);
  549. put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGENABLED, 1);
  550. if ((t = av_metadata_get(c->metadata, "title", NULL, 0))) {
  551. chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);
  552. put_ebml_string(pb, MATROSKA_ID_CHAPSTRING, t->value);
  553. put_ebml_string(pb, MATROSKA_ID_CHAPLANG , "und");
  554. end_ebml_master(pb, chapterdisplay);
  555. }
  556. end_ebml_master(pb, chapteratom);
  557. }
  558. end_ebml_master(pb, editionentry);
  559. end_ebml_master(pb, chapters);
  560. return 0;
  561. }
  562. static int mkv_write_header(AVFormatContext *s)
  563. {
  564. MatroskaMuxContext *mkv = s->priv_data;
  565. ByteIOContext *pb = s->pb;
  566. ebml_master ebml_header, segment_info;
  567. AVMetadataTag *tag;
  568. int ret;
  569. mkv->md5_ctx = av_mallocz(av_md5_size);
  570. av_md5_init(mkv->md5_ctx);
  571. ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
  572. put_ebml_uint (pb, EBML_ID_EBMLVERSION , 1);
  573. put_ebml_uint (pb, EBML_ID_EBMLREADVERSION , 1);
  574. put_ebml_uint (pb, EBML_ID_EBMLMAXIDLENGTH , 4);
  575. put_ebml_uint (pb, EBML_ID_EBMLMAXSIZELENGTH , 8);
  576. put_ebml_string (pb, EBML_ID_DOCTYPE , "matroska");
  577. put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , 2);
  578. put_ebml_uint (pb, EBML_ID_DOCTYPEREADVERSION , 2);
  579. end_ebml_master(pb, ebml_header);
  580. mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
  581. mkv->segment_offset = url_ftell(pb);
  582. // we write 2 seek heads - one at the end of the file to point to each
  583. // cluster, and one at the beginning to point to all other level one
  584. // elements (including the seek head at the end of the file), which
  585. // isn't more than 10 elements if we only write one of each other
  586. // currently defined level 1 element
  587. mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
  588. mkv->cluster_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 0);
  589. if (mkv->main_seekhead == NULL || mkv->cluster_seekhead == NULL)
  590. return AVERROR(ENOMEM);
  591. ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, url_ftell(pb));
  592. if (ret < 0) return ret;
  593. segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
  594. put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
  595. if ((tag = av_metadata_get(s->metadata, "title", NULL, 0)))
  596. put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
  597. if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
  598. put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , LIBAVFORMAT_IDENT);
  599. put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
  600. // reserve space to write the segment UID later
  601. mkv->segment_uid = url_ftell(pb);
  602. put_ebml_void(pb, 19);
  603. }
  604. // reserve space for the duration
  605. mkv->duration = 0;
  606. mkv->duration_offset = url_ftell(pb);
  607. put_ebml_void(pb, 11); // assumes double-precision float to be written
  608. end_ebml_master(pb, segment_info);
  609. ret = mkv_write_tracks(s);
  610. if (ret < 0) return ret;
  611. ret = mkv_write_chapters(s);
  612. if (ret < 0) return ret;
  613. ret = mkv_add_seekhead_entry(mkv->cluster_seekhead, MATROSKA_ID_CLUSTER, url_ftell(pb));
  614. if (ret < 0) return ret;
  615. mkv->cluster_pos = url_ftell(pb);
  616. mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
  617. put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, 0);
  618. mkv->cluster_pts = 0;
  619. mkv->cues = mkv_start_cues(mkv->segment_offset);
  620. if (mkv->cues == NULL)
  621. return AVERROR(ENOMEM);
  622. put_flush_packet(pb);
  623. return 0;
  624. }
  625. static int mkv_blockgroup_size(int pkt_size)
  626. {
  627. int size = pkt_size + 4;
  628. size += ebml_num_size(size);
  629. size += 2; // EBML ID for block and block duration
  630. size += 8; // max size of block duration
  631. size += ebml_num_size(size);
  632. size += 1; // blockgroup EBML ID
  633. return size;
  634. }
  635. static int ass_get_duration(const uint8_t *p)
  636. {
  637. int sh, sm, ss, sc, eh, em, es, ec;
  638. uint64_t start, end;
  639. if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
  640. &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)
  641. return 0;
  642. start = 3600000*sh + 60000*sm + 1000*ss + 10*sc;
  643. end = 3600000*eh + 60000*em + 1000*es + 10*ec;
  644. return end - start;
  645. }
  646. static int mkv_write_ass_blocks(AVFormatContext *s, AVPacket *pkt)
  647. {
  648. MatroskaMuxContext *mkv = s->priv_data;
  649. ByteIOContext *pb = s->pb;
  650. int i, layer = 0, max_duration = 0, size, line_size, data_size = pkt->size;
  651. uint8_t *start, *end, *data = pkt->data;
  652. ebml_master blockgroup;
  653. char buffer[2048];
  654. while (data_size) {
  655. int duration = ass_get_duration(data);
  656. max_duration = FFMAX(duration, max_duration);
  657. end = memchr(data, '\n', data_size);
  658. size = line_size = end ? end-data+1 : data_size;
  659. size -= end ? (end[-1]=='\r')+1 : 0;
  660. start = data;
  661. for (i=0; i<3; i++, start++)
  662. if (!(start = memchr(start, ',', size-(start-data))))
  663. return max_duration;
  664. size -= start - data;
  665. sscanf(data, "Dialogue: %d,", &layer);
  666. i = snprintf(buffer, sizeof(buffer), "%"PRId64",%d,",
  667. s->streams[pkt->stream_index]->nb_frames++, layer);
  668. size = FFMIN(i+size, sizeof(buffer));
  669. memcpy(buffer+i, start, size-i);
  670. av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
  671. "pts %" PRId64 ", duration %d\n",
  672. url_ftell(pb), size, pkt->pts, duration);
  673. blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(size));
  674. put_ebml_id(pb, MATROSKA_ID_BLOCK);
  675. put_ebml_num(pb, size+4, 0);
  676. put_byte(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
  677. put_be16(pb, pkt->pts - mkv->cluster_pts);
  678. put_byte(pb, 0);
  679. put_buffer(pb, buffer, size);
  680. put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
  681. end_ebml_master(pb, blockgroup);
  682. data += line_size;
  683. data_size -= line_size;
  684. }
  685. return max_duration;
  686. }
  687. static void mkv_write_block(AVFormatContext *s, unsigned int blockid, AVPacket *pkt, int flags)
  688. {
  689. MatroskaMuxContext *mkv = s->priv_data;
  690. ByteIOContext *pb = s->pb;
  691. AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
  692. uint8_t *data = NULL;
  693. int size = pkt->size;
  694. av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
  695. "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
  696. url_ftell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
  697. if (codec->codec_id == CODEC_ID_H264 && codec->extradata_size > 0 &&
  698. (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
  699. ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
  700. else
  701. data = pkt->data;
  702. put_ebml_id(pb, blockid);
  703. put_ebml_num(pb, size+4, 0);
  704. put_byte(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
  705. put_be16(pb, pkt->pts - mkv->cluster_pts);
  706. put_byte(pb, flags);
  707. put_buffer(pb, data, size);
  708. if (data != pkt->data)
  709. av_free(data);
  710. }
  711. static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
  712. {
  713. MatroskaMuxContext *mkv = s->priv_data;
  714. ByteIOContext *pb = s->pb;
  715. AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
  716. int keyframe = !!(pkt->flags & PKT_FLAG_KEY);
  717. int duration = pkt->duration;
  718. int ret;
  719. // start a new cluster every 5 MB or 5 sec
  720. if (url_ftell(pb) > mkv->cluster_pos + 5*1024*1024 || pkt->pts > mkv->cluster_pts + 5000) {
  721. av_log(s, AV_LOG_DEBUG, "Starting new cluster at offset %" PRIu64
  722. " bytes, pts %" PRIu64 "\n", url_ftell(pb), pkt->pts);
  723. end_ebml_master(pb, mkv->cluster);
  724. ret = mkv_add_seekhead_entry(mkv->cluster_seekhead, MATROSKA_ID_CLUSTER, url_ftell(pb));
  725. if (ret < 0) return ret;
  726. mkv->cluster_pos = url_ftell(pb);
  727. mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
  728. put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, pkt->pts);
  729. mkv->cluster_pts = pkt->pts;
  730. av_md5_update(mkv->md5_ctx, pkt->data, FFMIN(200, pkt->size));
  731. }
  732. if (codec->codec_type != CODEC_TYPE_SUBTITLE) {
  733. mkv_write_block(s, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
  734. } else if (codec->codec_id == CODEC_ID_SSA) {
  735. duration = mkv_write_ass_blocks(s, pkt);
  736. } else {
  737. ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(pkt->size));
  738. duration = pkt->convergence_duration;
  739. mkv_write_block(s, MATROSKA_ID_BLOCK, pkt, 0);
  740. put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
  741. end_ebml_master(pb, blockgroup);
  742. }
  743. if (codec->codec_type == CODEC_TYPE_VIDEO && keyframe) {
  744. ret = mkv_add_cuepoint(mkv->cues, pkt, mkv->cluster_pos);
  745. if (ret < 0) return ret;
  746. }
  747. mkv->duration = FFMAX(mkv->duration, pkt->pts + duration);
  748. return 0;
  749. }
  750. static int mkv_write_trailer(AVFormatContext *s)
  751. {
  752. MatroskaMuxContext *mkv = s->priv_data;
  753. ByteIOContext *pb = s->pb;
  754. int64_t currentpos, second_seekhead, cuespos;
  755. int ret;
  756. end_ebml_master(pb, mkv->cluster);
  757. if (!url_is_streamed(pb)) {
  758. cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
  759. second_seekhead = mkv_write_seekhead(pb, mkv->cluster_seekhead);
  760. ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES , cuespos);
  761. if (ret < 0) return ret;
  762. ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_SEEKHEAD, second_seekhead);
  763. if (ret < 0) return ret;
  764. mkv_write_seekhead(pb, mkv->main_seekhead);
  765. // update the duration
  766. av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
  767. currentpos = url_ftell(pb);
  768. url_fseek(pb, mkv->duration_offset, SEEK_SET);
  769. put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
  770. // write the md5sum of some frames as the segment UID
  771. if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
  772. uint8_t segment_uid[16];
  773. av_md5_final(mkv->md5_ctx, segment_uid);
  774. url_fseek(pb, mkv->segment_uid, SEEK_SET);
  775. put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
  776. }
  777. url_fseek(pb, currentpos, SEEK_SET);
  778. }
  779. end_ebml_master(pb, mkv->segment);
  780. av_free(mkv->md5_ctx);
  781. put_flush_packet(pb);
  782. return 0;
  783. }
  784. AVOutputFormat matroska_muxer = {
  785. "matroska",
  786. NULL_IF_CONFIG_SMALL("Matroska file format"),
  787. "video/x-matroska",
  788. "mkv",
  789. sizeof(MatroskaMuxContext),
  790. CODEC_ID_MP2,
  791. CODEC_ID_MPEG4,
  792. mkv_write_header,
  793. mkv_write_packet,
  794. mkv_write_trailer,
  795. .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
  796. .codec_tag = (const AVCodecTag* const []){ff_codec_bmp_tags, ff_codec_wav_tags, 0},
  797. .subtitle_codec = CODEC_ID_TEXT,
  798. };
  799. AVOutputFormat matroska_audio_muxer = {
  800. "matroska",
  801. NULL_IF_CONFIG_SMALL("Matroska file format"),
  802. "audio/x-matroska",
  803. "mka",
  804. sizeof(MatroskaMuxContext),
  805. CODEC_ID_MP2,
  806. CODEC_ID_NONE,
  807. mkv_write_header,
  808. mkv_write_packet,
  809. mkv_write_trailer,
  810. .flags = AVFMT_GLOBALHEADER,
  811. .codec_tag = (const AVCodecTag* const []){ff_codec_wav_tags, 0},
  812. };