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.

4517 lines
159KB

  1. /*
  2. * MOV, 3GP, MP4 muxer
  3. * Copyright (c) 2003 Thomas Raivio
  4. * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org>
  5. * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
  6. *
  7. * This file is part of FFmpeg.
  8. *
  9. * FFmpeg is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU Lesser General Public
  11. * License as published by the Free Software Foundation; either
  12. * version 2.1 of the License, or (at your option) any later version.
  13. *
  14. * FFmpeg is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * Lesser General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Lesser General Public
  20. * License along with FFmpeg; if not, write to the Free Software
  21. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  22. */
  23. #include <stdint.h>
  24. #include <inttypes.h>
  25. #include "movenc.h"
  26. #include "avformat.h"
  27. #include "avio_internal.h"
  28. #include "riff.h"
  29. #include "avio.h"
  30. #include "isom.h"
  31. #include "avc.h"
  32. #include "libavcodec/get_bits.h"
  33. #include "libavcodec/put_bits.h"
  34. #include "libavcodec/vc1.h"
  35. #include "libavcodec/raw.h"
  36. #include "internal.h"
  37. #include "libavutil/avstring.h"
  38. #include "libavutil/intfloat.h"
  39. #include "libavutil/mathematics.h"
  40. #include "libavutil/opt.h"
  41. #include "libavutil/dict.h"
  42. #include "libavutil/pixdesc.h"
  43. #include "hevc.h"
  44. #include "rtpenc.h"
  45. #include "mov_chan.h"
  46. #undef NDEBUG
  47. #include <assert.h>
  48. static const AVOption options[] = {
  49. { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  50. { "rtphint", "Add RTP hint tracks", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_RTP_HINT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  51. { "moov_size", "maximum moov size so it can be placed at the begin", offsetof(MOVMuxContext, reserved_moov_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, 0 },
  52. { "empty_moov", "Make the initial moov atom empty (not supported by QuickTime)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  53. { "frag_keyframe", "Fragment at video keyframes", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_KEYFRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  54. { "separate_moof", "Write separate moof/mdat atoms for each track", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SEPARATE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  55. { "frag_custom", "Flush fragments on caller requests", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_CUSTOM}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  56. { "isml", "Create a live smooth streaming feed (for pushing to a publishing point)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_ISML}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  57. { "faststart", "Run a second pass to put the index (moov atom) at the beginning of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FASTSTART}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  58. { "omit_tfhd_offset", "Omit the base data offset in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_OMIT_TFHD_OFFSET}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  59. FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
  60. { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
  61. { "iods_audio_profile", "iods audio profile atom.", offsetof(MOVMuxContext, iods_audio_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM},
  62. { "iods_video_profile", "iods video profile atom.", offsetof(MOVMuxContext, iods_video_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM},
  63. { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
  64. { "min_frag_duration", "Minimum fragment duration", offsetof(MOVMuxContext, min_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
  65. { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
  66. { "ism_lookahead", "Number of lookahead entries for ISM files", offsetof(MOVMuxContext, ism_lookahead), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
  67. { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
  68. { "video_track_timescale", "set timescale of all video tracks", offsetof(MOVMuxContext, video_track_timescale), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
  69. { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
  70. { NULL },
  71. };
  72. #define MOV_CLASS(flavor)\
  73. static const AVClass flavor ## _muxer_class = {\
  74. .class_name = #flavor " muxer",\
  75. .item_name = av_default_item_name,\
  76. .option = options,\
  77. .version = LIBAVUTIL_VERSION_INT,\
  78. };
  79. static int get_moov_size(AVFormatContext *s);
  80. //FIXME support 64 bit variant with wide placeholders
  81. static int64_t update_size(AVIOContext *pb, int64_t pos)
  82. {
  83. int64_t curpos = avio_tell(pb);
  84. avio_seek(pb, pos, SEEK_SET);
  85. avio_wb32(pb, curpos - pos); /* rewrite size */
  86. avio_seek(pb, curpos, SEEK_SET);
  87. return curpos - pos;
  88. }
  89. static int supports_edts(MOVMuxContext *mov)
  90. {
  91. // EDTS with fragments is tricky as we don't know the duration when its written
  92. return (mov->use_editlist<0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) || mov->use_editlist>0;
  93. }
  94. static int co64_required(const MOVTrack *track)
  95. {
  96. if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
  97. return 1;
  98. return 0;
  99. }
  100. /* Chunk offset atom */
  101. static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
  102. {
  103. int i;
  104. int mode64 = co64_required(track); // use 32 bit size variant if possible
  105. int64_t pos = avio_tell(pb);
  106. avio_wb32(pb, 0); /* size */
  107. if (mode64)
  108. ffio_wfourcc(pb, "co64");
  109. else
  110. ffio_wfourcc(pb, "stco");
  111. avio_wb32(pb, 0); /* version & flags */
  112. avio_wb32(pb, track->chunkCount); /* entry count */
  113. for (i = 0; i < track->entry; i++) {
  114. if (!track->cluster[i].chunkNum)
  115. continue;
  116. if (mode64 == 1)
  117. avio_wb64(pb, track->cluster[i].pos + track->data_offset);
  118. else
  119. avio_wb32(pb, track->cluster[i].pos + track->data_offset);
  120. }
  121. return update_size(pb, pos);
  122. }
  123. /* Sample size atom */
  124. static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
  125. {
  126. int equalChunks = 1;
  127. int i, j, entries = 0, tst = -1, oldtst = -1;
  128. int64_t pos = avio_tell(pb);
  129. avio_wb32(pb, 0); /* size */
  130. ffio_wfourcc(pb, "stsz");
  131. avio_wb32(pb, 0); /* version & flags */
  132. for (i = 0; i < track->entry; i++) {
  133. tst = track->cluster[i].size / track->cluster[i].entries;
  134. if (oldtst != -1 && tst != oldtst)
  135. equalChunks = 0;
  136. oldtst = tst;
  137. entries += track->cluster[i].entries;
  138. }
  139. if (equalChunks && track->entry) {
  140. int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
  141. sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
  142. avio_wb32(pb, sSize); // sample size
  143. avio_wb32(pb, entries); // sample count
  144. } else {
  145. avio_wb32(pb, 0); // sample size
  146. avio_wb32(pb, entries); // sample count
  147. for (i = 0; i < track->entry; i++) {
  148. for (j = 0; j < track->cluster[i].entries; j++) {
  149. avio_wb32(pb, track->cluster[i].size /
  150. track->cluster[i].entries);
  151. }
  152. }
  153. }
  154. return update_size(pb, pos);
  155. }
  156. /* Sample to chunk atom */
  157. static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
  158. {
  159. int index = 0, oldval = -1, i;
  160. int64_t entryPos, curpos;
  161. int64_t pos = avio_tell(pb);
  162. avio_wb32(pb, 0); /* size */
  163. ffio_wfourcc(pb, "stsc");
  164. avio_wb32(pb, 0); // version & flags
  165. entryPos = avio_tell(pb);
  166. avio_wb32(pb, track->chunkCount); // entry count
  167. for (i = 0; i < track->entry; i++) {
  168. if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
  169. avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
  170. avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
  171. avio_wb32(pb, 0x1); // sample description index
  172. oldval = track->cluster[i].samples_in_chunk;
  173. index++;
  174. }
  175. }
  176. curpos = avio_tell(pb);
  177. avio_seek(pb, entryPos, SEEK_SET);
  178. avio_wb32(pb, index); // rewrite size
  179. avio_seek(pb, curpos, SEEK_SET);
  180. return update_size(pb, pos);
  181. }
  182. /* Sync sample atom */
  183. static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
  184. {
  185. int64_t curpos, entryPos;
  186. int i, index = 0;
  187. int64_t pos = avio_tell(pb);
  188. avio_wb32(pb, 0); // size
  189. ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
  190. avio_wb32(pb, 0); // version & flags
  191. entryPos = avio_tell(pb);
  192. avio_wb32(pb, track->entry); // entry count
  193. for (i = 0; i < track->entry; i++) {
  194. if (track->cluster[i].flags & flag) {
  195. avio_wb32(pb, i + 1);
  196. index++;
  197. }
  198. }
  199. curpos = avio_tell(pb);
  200. avio_seek(pb, entryPos, SEEK_SET);
  201. avio_wb32(pb, index); // rewrite size
  202. avio_seek(pb, curpos, SEEK_SET);
  203. return update_size(pb, pos);
  204. }
  205. static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
  206. {
  207. avio_wb32(pb, 0x11); /* size */
  208. if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
  209. else ffio_wfourcc(pb, "damr");
  210. ffio_wfourcc(pb, "FFMP");
  211. avio_w8(pb, 0); /* decoder version */
  212. avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
  213. avio_w8(pb, 0x00); /* Mode change period (no restriction) */
  214. avio_w8(pb, 0x01); /* Frames per sample */
  215. return 0x11;
  216. }
  217. static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
  218. {
  219. GetBitContext gbc;
  220. PutBitContext pbc;
  221. uint8_t buf[3];
  222. int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
  223. if (track->vos_len < 7)
  224. return -1;
  225. avio_wb32(pb, 11);
  226. ffio_wfourcc(pb, "dac3");
  227. init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
  228. fscod = get_bits(&gbc, 2);
  229. frmsizecod = get_bits(&gbc, 6);
  230. bsid = get_bits(&gbc, 5);
  231. bsmod = get_bits(&gbc, 3);
  232. acmod = get_bits(&gbc, 3);
  233. if (acmod == 2) {
  234. skip_bits(&gbc, 2); // dsurmod
  235. } else {
  236. if ((acmod & 1) && acmod != 1)
  237. skip_bits(&gbc, 2); // cmixlev
  238. if (acmod & 4)
  239. skip_bits(&gbc, 2); // surmixlev
  240. }
  241. lfeon = get_bits1(&gbc);
  242. init_put_bits(&pbc, buf, sizeof(buf));
  243. put_bits(&pbc, 2, fscod);
  244. put_bits(&pbc, 5, bsid);
  245. put_bits(&pbc, 3, bsmod);
  246. put_bits(&pbc, 3, acmod);
  247. put_bits(&pbc, 1, lfeon);
  248. put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
  249. put_bits(&pbc, 5, 0); // reserved
  250. flush_put_bits(&pbc);
  251. avio_write(pb, buf, sizeof(buf));
  252. return 11;
  253. }
  254. /**
  255. * This function writes extradata "as is".
  256. * Extradata must be formatted like a valid atom (with size and tag).
  257. */
  258. static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
  259. {
  260. avio_write(pb, track->enc->extradata, track->enc->extradata_size);
  261. return track->enc->extradata_size;
  262. }
  263. static int mov_write_enda_tag(AVIOContext *pb)
  264. {
  265. avio_wb32(pb, 10);
  266. ffio_wfourcc(pb, "enda");
  267. avio_wb16(pb, 1); /* little endian */
  268. return 10;
  269. }
  270. static int mov_write_enda_tag_be(AVIOContext *pb)
  271. {
  272. avio_wb32(pb, 10);
  273. ffio_wfourcc(pb, "enda");
  274. avio_wb16(pb, 0); /* big endian */
  275. return 10;
  276. }
  277. static void put_descr(AVIOContext *pb, int tag, unsigned int size)
  278. {
  279. int i = 3;
  280. avio_w8(pb, tag);
  281. for (; i > 0; i--)
  282. avio_w8(pb, (size >> (7 * i)) | 0x80);
  283. avio_w8(pb, size & 0x7F);
  284. }
  285. static unsigned compute_avg_bitrate(MOVTrack *track)
  286. {
  287. uint64_t size = 0;
  288. int i;
  289. if (!track->track_duration)
  290. return 0;
  291. for (i = 0; i < track->entry; i++)
  292. size += track->cluster[i].size;
  293. return size * 8 * track->timescale / track->track_duration;
  294. }
  295. static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
  296. {
  297. int64_t pos = avio_tell(pb);
  298. int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
  299. unsigned avg_bitrate;
  300. avio_wb32(pb, 0); // size
  301. ffio_wfourcc(pb, "esds");
  302. avio_wb32(pb, 0); // Version
  303. // ES descriptor
  304. put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
  305. avio_wb16(pb, track->track_id);
  306. avio_w8(pb, 0x00); // flags (= no flags)
  307. // DecoderConfig descriptor
  308. put_descr(pb, 0x04, 13 + decoder_specific_info_len);
  309. // Object type indication
  310. if ((track->enc->codec_id == AV_CODEC_ID_MP2 ||
  311. track->enc->codec_id == AV_CODEC_ID_MP3) &&
  312. track->enc->sample_rate > 24000)
  313. avio_w8(pb, 0x6B); // 11172-3
  314. else
  315. avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id));
  316. // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
  317. // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
  318. if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
  319. avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
  320. else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
  321. avio_w8(pb, 0x15); // flags (= Audiostream)
  322. else
  323. avio_w8(pb, 0x11); // flags (= Visualstream)
  324. avio_wb24(pb, track->enc->rc_buffer_size >> 3); // Buffersize DB
  325. avg_bitrate = compute_avg_bitrate(track);
  326. // maxbitrate (FIXME should be max rate in any 1 sec window)
  327. avio_wb32(pb, FFMAX3(track->enc->bit_rate, track->enc->rc_max_rate, avg_bitrate));
  328. avio_wb32(pb, avg_bitrate);
  329. if (track->vos_len) {
  330. // DecoderSpecific info descriptor
  331. put_descr(pb, 0x05, track->vos_len);
  332. avio_write(pb, track->vos_data, track->vos_len);
  333. }
  334. // SL descriptor
  335. put_descr(pb, 0x06, 1);
  336. avio_w8(pb, 0x02);
  337. return update_size(pb, pos);
  338. }
  339. static int mov_pcm_le_gt16(enum AVCodecID codec_id)
  340. {
  341. return codec_id == AV_CODEC_ID_PCM_S24LE ||
  342. codec_id == AV_CODEC_ID_PCM_S32LE ||
  343. codec_id == AV_CODEC_ID_PCM_F32LE ||
  344. codec_id == AV_CODEC_ID_PCM_F64LE;
  345. }
  346. static int mov_pcm_be_gt16(enum AVCodecID codec_id)
  347. {
  348. return codec_id == AV_CODEC_ID_PCM_S24BE ||
  349. codec_id == AV_CODEC_ID_PCM_S32BE ||
  350. codec_id == AV_CODEC_ID_PCM_F32BE ||
  351. codec_id == AV_CODEC_ID_PCM_F64BE;
  352. }
  353. static int mov_write_ms_tag(AVIOContext *pb, MOVTrack *track)
  354. {
  355. int ret;
  356. int64_t pos = avio_tell(pb);
  357. avio_wb32(pb, 0);
  358. avio_wl32(pb, track->tag); // store it byteswapped
  359. track->enc->codec_tag = av_bswap16(track->tag >> 16);
  360. if ((ret = ff_put_wav_header(pb, track->enc, 0)) < 0)
  361. return ret;
  362. return update_size(pb, pos);
  363. }
  364. static int mov_write_wfex_tag(AVIOContext *pb, MOVTrack *track)
  365. {
  366. int ret;
  367. int64_t pos = avio_tell(pb);
  368. avio_wb32(pb, 0);
  369. ffio_wfourcc(pb, "wfex");
  370. if ((ret = ff_put_wav_header(pb, track->enc, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
  371. return ret;
  372. return update_size(pb, pos);
  373. }
  374. static int mov_write_chan_tag(AVIOContext *pb, MOVTrack *track)
  375. {
  376. uint32_t layout_tag, bitmap;
  377. int64_t pos = avio_tell(pb);
  378. layout_tag = ff_mov_get_channel_layout_tag(track->enc->codec_id,
  379. track->enc->channel_layout,
  380. &bitmap);
  381. if (!layout_tag) {
  382. av_log(track->enc, AV_LOG_WARNING, "not writing 'chan' tag due to "
  383. "lack of channel information\n");
  384. return 0;
  385. }
  386. avio_wb32(pb, 0); // Size
  387. ffio_wfourcc(pb, "chan"); // Type
  388. avio_w8(pb, 0); // Version
  389. avio_wb24(pb, 0); // Flags
  390. avio_wb32(pb, layout_tag); // mChannelLayoutTag
  391. avio_wb32(pb, bitmap); // mChannelBitmap
  392. avio_wb32(pb, 0); // mNumberChannelDescriptions
  393. return update_size(pb, pos);
  394. }
  395. static int mov_write_wave_tag(AVIOContext *pb, MOVTrack *track)
  396. {
  397. int64_t pos = avio_tell(pb);
  398. avio_wb32(pb, 0); /* size */
  399. ffio_wfourcc(pb, "wave");
  400. if (track->enc->codec_id != AV_CODEC_ID_QDM2) {
  401. avio_wb32(pb, 12); /* size */
  402. ffio_wfourcc(pb, "frma");
  403. avio_wl32(pb, track->tag);
  404. }
  405. if (track->enc->codec_id == AV_CODEC_ID_AAC) {
  406. /* useless atom needed by mplayer, ipod, not needed by quicktime */
  407. avio_wb32(pb, 12); /* size */
  408. ffio_wfourcc(pb, "mp4a");
  409. avio_wb32(pb, 0);
  410. mov_write_esds_tag(pb, track);
  411. } else if (mov_pcm_le_gt16(track->enc->codec_id)) {
  412. mov_write_enda_tag(pb);
  413. } else if (mov_pcm_be_gt16(track->enc->codec_id)) {
  414. mov_write_enda_tag_be(pb);
  415. } else if (track->enc->codec_id == AV_CODEC_ID_AMR_NB) {
  416. mov_write_amr_tag(pb, track);
  417. } else if (track->enc->codec_id == AV_CODEC_ID_AC3) {
  418. mov_write_ac3_tag(pb, track);
  419. } else if (track->enc->codec_id == AV_CODEC_ID_ALAC ||
  420. track->enc->codec_id == AV_CODEC_ID_QDM2) {
  421. mov_write_extradata_tag(pb, track);
  422. } else if (track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
  423. track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
  424. mov_write_ms_tag(pb, track);
  425. }
  426. avio_wb32(pb, 8); /* size */
  427. avio_wb32(pb, 0); /* null tag */
  428. return update_size(pb, pos);
  429. }
  430. static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
  431. {
  432. uint8_t *unescaped;
  433. const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
  434. int unescaped_size, seq_found = 0;
  435. int level = 0, interlace = 0;
  436. int packet_seq = track->vc1_info.packet_seq;
  437. int packet_entry = track->vc1_info.packet_entry;
  438. int slices = track->vc1_info.slices;
  439. PutBitContext pbc;
  440. if (track->start_dts == AV_NOPTS_VALUE) {
  441. /* No packets written yet, vc1_info isn't authoritative yet. */
  442. /* Assume inline sequence and entry headers. This will be
  443. * overwritten at the end if the file is seekable. */
  444. packet_seq = packet_entry = 1;
  445. }
  446. unescaped = av_mallocz(track->vos_len + FF_INPUT_BUFFER_PADDING_SIZE);
  447. if (!unescaped)
  448. return AVERROR(ENOMEM);
  449. start = find_next_marker(track->vos_data, end);
  450. for (next = start; next < end; start = next) {
  451. GetBitContext gb;
  452. int size;
  453. next = find_next_marker(start + 4, end);
  454. size = next - start - 4;
  455. if (size <= 0)
  456. continue;
  457. unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
  458. init_get_bits(&gb, unescaped, 8 * unescaped_size);
  459. if (AV_RB32(start) == VC1_CODE_SEQHDR) {
  460. int profile = get_bits(&gb, 2);
  461. if (profile != PROFILE_ADVANCED) {
  462. av_free(unescaped);
  463. return AVERROR(ENOSYS);
  464. }
  465. seq_found = 1;
  466. level = get_bits(&gb, 3);
  467. /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
  468. * width, height */
  469. skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
  470. skip_bits(&gb, 1); /* broadcast */
  471. interlace = get_bits1(&gb);
  472. skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
  473. }
  474. }
  475. if (!seq_found) {
  476. av_free(unescaped);
  477. return AVERROR(ENOSYS);
  478. }
  479. init_put_bits(&pbc, buf, 7);
  480. /* VC1DecSpecStruc */
  481. put_bits(&pbc, 4, 12); /* profile - advanced */
  482. put_bits(&pbc, 3, level);
  483. put_bits(&pbc, 1, 0); /* reserved */
  484. /* VC1AdvDecSpecStruc */
  485. put_bits(&pbc, 3, level);
  486. put_bits(&pbc, 1, 0); /* cbr */
  487. put_bits(&pbc, 6, 0); /* reserved */
  488. put_bits(&pbc, 1, !interlace); /* no interlace */
  489. put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
  490. put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
  491. put_bits(&pbc, 1, !slices); /* no slice code */
  492. put_bits(&pbc, 1, 0); /* no bframe */
  493. put_bits(&pbc, 1, 0); /* reserved */
  494. put_bits32(&pbc, track->enc->time_base.den); /* framerate */
  495. flush_put_bits(&pbc);
  496. av_free(unescaped);
  497. return 0;
  498. }
  499. static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
  500. {
  501. uint8_t buf[7] = { 0 };
  502. int ret;
  503. if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
  504. return ret;
  505. avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
  506. ffio_wfourcc(pb, "dvc1");
  507. track->vc1_info.struct_offset = avio_tell(pb);
  508. avio_write(pb, buf, sizeof(buf));
  509. avio_write(pb, track->vos_data, track->vos_len);
  510. return 0;
  511. }
  512. static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
  513. {
  514. avio_wb32(pb, track->vos_len + 8);
  515. ffio_wfourcc(pb, "glbl");
  516. avio_write(pb, track->vos_data, track->vos_len);
  517. return 8 + track->vos_len;
  518. }
  519. /**
  520. * Compute flags for 'lpcm' tag.
  521. * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
  522. */
  523. static int mov_get_lpcm_flags(enum AVCodecID codec_id)
  524. {
  525. switch (codec_id) {
  526. case AV_CODEC_ID_PCM_F32BE:
  527. case AV_CODEC_ID_PCM_F64BE:
  528. return 11;
  529. case AV_CODEC_ID_PCM_F32LE:
  530. case AV_CODEC_ID_PCM_F64LE:
  531. return 9;
  532. case AV_CODEC_ID_PCM_U8:
  533. return 10;
  534. case AV_CODEC_ID_PCM_S16BE:
  535. case AV_CODEC_ID_PCM_S24BE:
  536. case AV_CODEC_ID_PCM_S32BE:
  537. return 14;
  538. case AV_CODEC_ID_PCM_S8:
  539. case AV_CODEC_ID_PCM_S16LE:
  540. case AV_CODEC_ID_PCM_S24LE:
  541. case AV_CODEC_ID_PCM_S32LE:
  542. return 12;
  543. default:
  544. return 0;
  545. }
  546. }
  547. static int get_cluster_duration(MOVTrack *track, int cluster_idx)
  548. {
  549. int64_t next_dts;
  550. if (cluster_idx >= track->entry)
  551. return 0;
  552. if (cluster_idx + 1 == track->entry)
  553. next_dts = track->track_duration + track->start_dts;
  554. else
  555. next_dts = track->cluster[cluster_idx + 1].dts;
  556. next_dts -= track->cluster[cluster_idx].dts;
  557. av_assert0(next_dts >= 0);
  558. av_assert0(next_dts <= INT_MAX);
  559. return next_dts;
  560. }
  561. static int get_samples_per_packet(MOVTrack *track)
  562. {
  563. int i, first_duration;
  564. // return track->enc->frame_size;
  565. /* use 1 for raw PCM */
  566. if (!track->audio_vbr)
  567. return 1;
  568. /* check to see if duration is constant for all clusters */
  569. if (!track->entry)
  570. return 0;
  571. first_duration = get_cluster_duration(track, 0);
  572. for (i = 1; i < track->entry; i++) {
  573. if (get_cluster_duration(track, i) != first_duration)
  574. return 0;
  575. }
  576. return first_duration;
  577. }
  578. static int mov_write_audio_tag(AVIOContext *pb, MOVTrack *track)
  579. {
  580. int64_t pos = avio_tell(pb);
  581. int version = 0;
  582. uint32_t tag = track->tag;
  583. if (track->mode == MODE_MOV) {
  584. if (track->timescale > UINT16_MAX) {
  585. if (mov_get_lpcm_flags(track->enc->codec_id))
  586. tag = AV_RL32("lpcm");
  587. version = 2;
  588. } else if (track->audio_vbr || mov_pcm_le_gt16(track->enc->codec_id) ||
  589. mov_pcm_be_gt16(track->enc->codec_id) ||
  590. track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
  591. track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
  592. track->enc->codec_id == AV_CODEC_ID_QDM2) {
  593. version = 1;
  594. }
  595. }
  596. avio_wb32(pb, 0); /* size */
  597. avio_wl32(pb, tag); // store it byteswapped
  598. avio_wb32(pb, 0); /* Reserved */
  599. avio_wb16(pb, 0); /* Reserved */
  600. avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
  601. /* SoundDescription */
  602. avio_wb16(pb, version); /* Version */
  603. avio_wb16(pb, 0); /* Revision level */
  604. avio_wb32(pb, 0); /* Reserved */
  605. if (version == 2) {
  606. avio_wb16(pb, 3);
  607. avio_wb16(pb, 16);
  608. avio_wb16(pb, 0xfffe);
  609. avio_wb16(pb, 0);
  610. avio_wb32(pb, 0x00010000);
  611. avio_wb32(pb, 72);
  612. avio_wb64(pb, av_double2int(track->enc->sample_rate));
  613. avio_wb32(pb, track->enc->channels);
  614. avio_wb32(pb, 0x7F000000);
  615. avio_wb32(pb, av_get_bits_per_sample(track->enc->codec_id));
  616. avio_wb32(pb, mov_get_lpcm_flags(track->enc->codec_id));
  617. avio_wb32(pb, track->sample_size);
  618. avio_wb32(pb, get_samples_per_packet(track));
  619. } else {
  620. if (track->mode == MODE_MOV) {
  621. avio_wb16(pb, track->enc->channels);
  622. if (track->enc->codec_id == AV_CODEC_ID_PCM_U8 ||
  623. track->enc->codec_id == AV_CODEC_ID_PCM_S8)
  624. avio_wb16(pb, 8); /* bits per sample */
  625. else
  626. avio_wb16(pb, 16);
  627. avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
  628. } else { /* reserved for mp4/3gp */
  629. avio_wb16(pb, 2);
  630. avio_wb16(pb, 16);
  631. avio_wb16(pb, 0);
  632. }
  633. avio_wb16(pb, 0); /* packet size (= 0) */
  634. avio_wb16(pb, track->enc->sample_rate <= UINT16_MAX ?
  635. track->enc->sample_rate : 0);
  636. avio_wb16(pb, 0); /* Reserved */
  637. }
  638. if (version == 1) { /* SoundDescription V1 extended info */
  639. if (mov_pcm_le_gt16(track->enc->codec_id) ||
  640. mov_pcm_be_gt16(track->enc->codec_id))
  641. avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
  642. else
  643. avio_wb32(pb, track->enc->frame_size); /* Samples per packet */
  644. avio_wb32(pb, track->sample_size / track->enc->channels); /* Bytes per packet */
  645. avio_wb32(pb, track->sample_size); /* Bytes per frame */
  646. avio_wb32(pb, 2); /* Bytes per sample */
  647. }
  648. if (track->mode == MODE_MOV &&
  649. (track->enc->codec_id == AV_CODEC_ID_AAC ||
  650. track->enc->codec_id == AV_CODEC_ID_AC3 ||
  651. track->enc->codec_id == AV_CODEC_ID_AMR_NB ||
  652. track->enc->codec_id == AV_CODEC_ID_ALAC ||
  653. track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
  654. track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
  655. track->enc->codec_id == AV_CODEC_ID_QDM2 ||
  656. (mov_pcm_le_gt16(track->enc->codec_id) && version==1) ||
  657. (mov_pcm_be_gt16(track->enc->codec_id) && version==1)))
  658. mov_write_wave_tag(pb, track);
  659. else if (track->tag == MKTAG('m','p','4','a'))
  660. mov_write_esds_tag(pb, track);
  661. else if (track->enc->codec_id == AV_CODEC_ID_AMR_NB)
  662. mov_write_amr_tag(pb, track);
  663. else if (track->enc->codec_id == AV_CODEC_ID_AC3)
  664. mov_write_ac3_tag(pb, track);
  665. else if (track->enc->codec_id == AV_CODEC_ID_ALAC)
  666. mov_write_extradata_tag(pb, track);
  667. else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO)
  668. mov_write_wfex_tag(pb, track);
  669. else if (track->vos_len > 0)
  670. mov_write_glbl_tag(pb, track);
  671. if (track->mode == MODE_MOV && track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
  672. mov_write_chan_tag(pb, track);
  673. return update_size(pb, pos);
  674. }
  675. static int mov_write_d263_tag(AVIOContext *pb)
  676. {
  677. avio_wb32(pb, 0xf); /* size */
  678. ffio_wfourcc(pb, "d263");
  679. ffio_wfourcc(pb, "FFMP");
  680. avio_w8(pb, 0); /* decoder version */
  681. /* FIXME use AVCodecContext level/profile, when encoder will set values */
  682. avio_w8(pb, 0xa); /* level */
  683. avio_w8(pb, 0); /* profile */
  684. return 0xf;
  685. }
  686. static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
  687. {
  688. int64_t pos = avio_tell(pb);
  689. avio_wb32(pb, 0);
  690. ffio_wfourcc(pb, "avcC");
  691. ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
  692. return update_size(pb, pos);
  693. }
  694. static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
  695. {
  696. int64_t pos = avio_tell(pb);
  697. avio_wb32(pb, 0);
  698. ffio_wfourcc(pb, "hvcC");
  699. ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
  700. return update_size(pb, pos);
  701. }
  702. /* also used by all avid codecs (dv, imx, meridien) and their variants */
  703. static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
  704. {
  705. int i;
  706. avio_wb32(pb, 24); /* size */
  707. ffio_wfourcc(pb, "ACLR");
  708. ffio_wfourcc(pb, "ACLR");
  709. ffio_wfourcc(pb, "0001");
  710. avio_wb32(pb, 2); /* yuv range: full 1 / normal 2 */
  711. avio_wb32(pb, 0); /* unknown */
  712. avio_wb32(pb, 24); /* size */
  713. ffio_wfourcc(pb, "APRG");
  714. ffio_wfourcc(pb, "APRG");
  715. ffio_wfourcc(pb, "0001");
  716. avio_wb32(pb, 1); /* unknown */
  717. avio_wb32(pb, 0); /* unknown */
  718. avio_wb32(pb, 120); /* size */
  719. ffio_wfourcc(pb, "ARES");
  720. ffio_wfourcc(pb, "ARES");
  721. ffio_wfourcc(pb, "0001");
  722. avio_wb32(pb, AV_RB32(track->vos_data + 0x28)); /* dnxhd cid, some id ? */
  723. avio_wb32(pb, track->enc->width);
  724. /* values below are based on samples created with quicktime and avid codecs */
  725. if (track->vos_data[5] & 2) { // interlaced
  726. avio_wb32(pb, track->enc->height / 2);
  727. avio_wb32(pb, 2); /* unknown */
  728. avio_wb32(pb, 0); /* unknown */
  729. avio_wb32(pb, 4); /* unknown */
  730. } else {
  731. avio_wb32(pb, track->enc->height);
  732. avio_wb32(pb, 1); /* unknown */
  733. avio_wb32(pb, 0); /* unknown */
  734. if (track->enc->height == 1080)
  735. avio_wb32(pb, 5); /* unknown */
  736. else
  737. avio_wb32(pb, 6); /* unknown */
  738. }
  739. /* padding */
  740. for (i = 0; i < 10; i++)
  741. avio_wb64(pb, 0);
  742. /* extra padding for stsd needed */
  743. avio_wb32(pb, 0);
  744. return 0;
  745. }
  746. static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
  747. {
  748. int tag = track->enc->codec_tag;
  749. if (!ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id))
  750. return 0;
  751. if (track->enc->codec_id == AV_CODEC_ID_H264) tag = MKTAG('a','v','c','1');
  752. else if (track->enc->codec_id == AV_CODEC_ID_HEVC) tag = MKTAG('h','e','v','1');
  753. else if (track->enc->codec_id == AV_CODEC_ID_AC3) tag = MKTAG('a','c','-','3');
  754. else if (track->enc->codec_id == AV_CODEC_ID_DIRAC) tag = MKTAG('d','r','a','c');
  755. else if (track->enc->codec_id == AV_CODEC_ID_MOV_TEXT) tag = MKTAG('t','x','3','g');
  756. else if (track->enc->codec_id == AV_CODEC_ID_VC1) tag = MKTAG('v','c','-','1');
  757. else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
  758. else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
  759. else if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE) tag = MKTAG('m','p','4','s');
  760. return tag;
  761. }
  762. static const AVCodecTag codec_ipod_tags[] = {
  763. { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
  764. { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
  765. { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
  766. { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
  767. { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
  768. { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
  769. { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
  770. { AV_CODEC_ID_NONE, 0 },
  771. };
  772. static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
  773. {
  774. int tag = track->enc->codec_tag;
  775. // keep original tag for subs, ipod supports both formats
  776. if (!(track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE &&
  777. (tag == MKTAG('t', 'x', '3', 'g') ||
  778. tag == MKTAG('t', 'e', 'x', 't'))))
  779. tag = ff_codec_get_tag(codec_ipod_tags, track->enc->codec_id);
  780. if (!av_match_ext(s->filename, "m4a") && !av_match_ext(s->filename, "m4v"))
  781. av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
  782. "Quicktime/Ipod might not play the file\n");
  783. return tag;
  784. }
  785. static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
  786. {
  787. int tag;
  788. if (track->enc->width == 720) { /* SD */
  789. if (track->enc->height == 480) { /* NTSC */
  790. if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
  791. else tag = MKTAG('d','v','c',' ');
  792. }else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
  793. else if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
  794. else tag = MKTAG('d','v','p','p');
  795. } else if (track->enc->height == 720) { /* HD 720 line */
  796. if (track->enc->time_base.den == 50) tag = MKTAG('d','v','h','q');
  797. else tag = MKTAG('d','v','h','p');
  798. } else if (track->enc->height == 1080) { /* HD 1080 line */
  799. if (track->enc->time_base.den == 25) tag = MKTAG('d','v','h','5');
  800. else tag = MKTAG('d','v','h','6');
  801. } else {
  802. av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
  803. return 0;
  804. }
  805. return tag;
  806. }
  807. static AVRational find_fps(AVFormatContext *s, AVStream *st)
  808. {
  809. AVRational rate = {st->codec->time_base.den, st->codec->time_base.num};
  810. /* if the codec time base makes no sense, try to fallback on stream frame rate */
  811. if (av_timecode_check_frame_rate(rate) < 0) {
  812. av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
  813. rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
  814. rate = st->avg_frame_rate;
  815. }
  816. return rate;
  817. }
  818. static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
  819. {
  820. int tag = track->enc->codec_tag;
  821. int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
  822. AVStream *st = track->st;
  823. int rate = av_q2d(find_fps(s, st));
  824. if (!tag)
  825. tag = MKTAG('m', '2', 'v', '1'); //fallback tag
  826. if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P) {
  827. if (track->enc->width == 1280 && track->enc->height == 720) {
  828. if (!interlaced) {
  829. if (rate == 24) tag = MKTAG('x','d','v','4');
  830. else if (rate == 25) tag = MKTAG('x','d','v','5');
  831. else if (rate == 30) tag = MKTAG('x','d','v','1');
  832. else if (rate == 50) tag = MKTAG('x','d','v','a');
  833. else if (rate == 60) tag = MKTAG('x','d','v','9');
  834. }
  835. } else if (track->enc->width == 1440 && track->enc->height == 1080) {
  836. if (!interlaced) {
  837. if (rate == 24) tag = MKTAG('x','d','v','6');
  838. else if (rate == 25) tag = MKTAG('x','d','v','7');
  839. else if (rate == 30) tag = MKTAG('x','d','v','8');
  840. } else {
  841. if (rate == 25) tag = MKTAG('x','d','v','3');
  842. else if (rate == 30) tag = MKTAG('x','d','v','2');
  843. }
  844. } else if (track->enc->width == 1920 && track->enc->height == 1080) {
  845. if (!interlaced) {
  846. if (rate == 24) tag = MKTAG('x','d','v','d');
  847. else if (rate == 25) tag = MKTAG('x','d','v','e');
  848. else if (rate == 30) tag = MKTAG('x','d','v','f');
  849. } else {
  850. if (rate == 25) tag = MKTAG('x','d','v','c');
  851. else if (rate == 30) tag = MKTAG('x','d','v','b');
  852. }
  853. }
  854. } else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) {
  855. if (track->enc->width == 1280 && track->enc->height == 720) {
  856. if (!interlaced) {
  857. if (rate == 24) tag = MKTAG('x','d','5','4');
  858. else if (rate == 25) tag = MKTAG('x','d','5','5');
  859. else if (rate == 30) tag = MKTAG('x','d','5','1');
  860. else if (rate == 50) tag = MKTAG('x','d','5','a');
  861. else if (rate == 60) tag = MKTAG('x','d','5','9');
  862. }
  863. } else if (track->enc->width == 1920 && track->enc->height == 1080) {
  864. if (!interlaced) {
  865. if (rate == 24) tag = MKTAG('x','d','5','d');
  866. else if (rate == 25) tag = MKTAG('x','d','5','e');
  867. else if (rate == 30) tag = MKTAG('x','d','5','f');
  868. } else {
  869. if (rate == 25) tag = MKTAG('x','d','5','c');
  870. else if (rate == 30) tag = MKTAG('x','d','5','b');
  871. }
  872. }
  873. }
  874. return tag;
  875. }
  876. static const struct {
  877. enum AVPixelFormat pix_fmt;
  878. uint32_t tag;
  879. unsigned bps;
  880. } mov_pix_fmt_tags[] = {
  881. { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
  882. { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
  883. { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
  884. { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
  885. { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
  886. { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
  887. { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
  888. { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
  889. { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
  890. { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
  891. { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
  892. { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
  893. { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
  894. { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
  895. { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
  896. };
  897. static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
  898. {
  899. int tag = track->enc->codec_tag;
  900. int i;
  901. enum AVPixelFormat pix_fmt;
  902. for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
  903. if (track->enc->pix_fmt == mov_pix_fmt_tags[i].pix_fmt) {
  904. tag = mov_pix_fmt_tags[i].tag;
  905. track->enc->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
  906. if (track->enc->codec_tag == mov_pix_fmt_tags[i].tag)
  907. break;
  908. }
  909. }
  910. pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
  911. track->enc->bits_per_coded_sample);
  912. if (tag == MKTAG('r','a','w',' ') &&
  913. track->enc->pix_fmt != pix_fmt &&
  914. track->enc->pix_fmt != AV_PIX_FMT_NONE)
  915. av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
  916. av_get_pix_fmt_name(track->enc->pix_fmt));
  917. return tag;
  918. }
  919. static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
  920. {
  921. int tag = track->enc->codec_tag;
  922. if (!tag || (track->enc->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
  923. (track->enc->codec_id == AV_CODEC_ID_DVVIDEO ||
  924. track->enc->codec_id == AV_CODEC_ID_RAWVIDEO ||
  925. track->enc->codec_id == AV_CODEC_ID_H263 ||
  926. track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
  927. av_get_bits_per_sample(track->enc->codec_id)))) { // pcm audio
  928. if (track->enc->codec_id == AV_CODEC_ID_DVVIDEO)
  929. tag = mov_get_dv_codec_tag(s, track);
  930. else if (track->enc->codec_id == AV_CODEC_ID_RAWVIDEO)
  931. tag = mov_get_rawvideo_codec_tag(s, track);
  932. else if (track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO)
  933. tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
  934. else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  935. tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->enc->codec_id);
  936. if (!tag) { // if no mac fcc found, try with Microsoft tags
  937. tag = ff_codec_get_tag(ff_codec_bmp_tags, track->enc->codec_id);
  938. if (tag)
  939. av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
  940. "the file may be unplayable!\n");
  941. }
  942. } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
  943. tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->enc->codec_id);
  944. if (!tag) { // if no mac fcc found, try with Microsoft tags
  945. int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->enc->codec_id);
  946. if (ms_tag) {
  947. tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
  948. av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
  949. "the file may be unplayable!\n");
  950. }
  951. }
  952. } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
  953. tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->enc->codec_id);
  954. }
  955. return tag;
  956. }
  957. static const AVCodecTag codec_3gp_tags[] = {
  958. { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
  959. { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
  960. { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
  961. { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
  962. { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
  963. { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
  964. { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
  965. { AV_CODEC_ID_NONE, 0 },
  966. };
  967. static const AVCodecTag codec_f4v_tags[] = { // XXX: add GIF/PNG/JPEG?
  968. { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
  969. { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
  970. { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
  971. { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
  972. { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
  973. { AV_CODEC_ID_NONE, 0 },
  974. };
  975. static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
  976. {
  977. int tag;
  978. if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
  979. tag = mp4_get_codec_tag(s, track);
  980. else if (track->mode == MODE_ISM) {
  981. tag = mp4_get_codec_tag(s, track);
  982. if (!tag && track->enc->codec_id == AV_CODEC_ID_WMAPRO)
  983. tag = MKTAG('w', 'm', 'a', ' ');
  984. } else if (track->mode == MODE_IPOD)
  985. tag = ipod_get_codec_tag(s, track);
  986. else if (track->mode & MODE_3GP)
  987. tag = ff_codec_get_tag(codec_3gp_tags, track->enc->codec_id);
  988. else if (track->mode == MODE_F4V)
  989. tag = ff_codec_get_tag(codec_f4v_tags, track->enc->codec_id);
  990. else
  991. tag = mov_get_codec_tag(s, track);
  992. return tag;
  993. }
  994. /** Write uuid atom.
  995. * Needed to make file play in iPods running newest firmware
  996. * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
  997. */
  998. static int mov_write_uuid_tag_ipod(AVIOContext *pb)
  999. {
  1000. avio_wb32(pb, 28);
  1001. ffio_wfourcc(pb, "uuid");
  1002. avio_wb32(pb, 0x6b6840f2);
  1003. avio_wb32(pb, 0x5f244fc5);
  1004. avio_wb32(pb, 0xba39a51b);
  1005. avio_wb32(pb, 0xcf0323f3);
  1006. avio_wb32(pb, 0x0);
  1007. return 28;
  1008. }
  1009. static const uint16_t fiel_data[] = {
  1010. 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
  1011. };
  1012. static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track)
  1013. {
  1014. unsigned mov_field_order = 0;
  1015. if (track->enc->field_order < FF_ARRAY_ELEMS(fiel_data))
  1016. mov_field_order = fiel_data[track->enc->field_order];
  1017. else
  1018. return 0;
  1019. avio_wb32(pb, 10);
  1020. ffio_wfourcc(pb, "fiel");
  1021. avio_wb16(pb, mov_field_order);
  1022. return 10;
  1023. }
  1024. static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
  1025. {
  1026. int64_t pos = avio_tell(pb);
  1027. avio_wb32(pb, 0); /* size */
  1028. avio_wl32(pb, track->tag); // store it byteswapped
  1029. avio_wb32(pb, 0); /* Reserved */
  1030. avio_wb16(pb, 0); /* Reserved */
  1031. avio_wb16(pb, 1); /* Data-reference index */
  1032. if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
  1033. mov_write_esds_tag(pb, track);
  1034. else if (track->enc->extradata_size)
  1035. avio_write(pb, track->enc->extradata, track->enc->extradata_size);
  1036. return update_size(pb, pos);
  1037. }
  1038. static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
  1039. {
  1040. AVRational sar;
  1041. av_reduce(&sar.num, &sar.den, track->enc->sample_aspect_ratio.num,
  1042. track->enc->sample_aspect_ratio.den, INT_MAX);
  1043. avio_wb32(pb, 16);
  1044. ffio_wfourcc(pb, "pasp");
  1045. avio_wb32(pb, sar.num);
  1046. avio_wb32(pb, sar.den);
  1047. return 16;
  1048. }
  1049. static void find_compressor(char * compressor_name, int len, MOVTrack *track)
  1050. {
  1051. AVDictionaryEntry *encoder;
  1052. int xdcam_res = (track->enc->width == 1280 && track->enc->height == 720)
  1053. || (track->enc->width == 1440 && track->enc->height == 1080)
  1054. || (track->enc->width == 1920 && track->enc->height == 1080);
  1055. if (track->mode == MODE_MOV &&
  1056. (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
  1057. av_strlcpy(compressor_name, encoder->value, 32);
  1058. } else if (track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
  1059. int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
  1060. AVStream *st = track->st;
  1061. int rate = av_q2d(find_fps(NULL, st));
  1062. av_strlcatf(compressor_name, len, "XDCAM");
  1063. if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) {
  1064. av_strlcatf(compressor_name, len, " HD422");
  1065. } else if(track->enc->width == 1440) {
  1066. av_strlcatf(compressor_name, len, " HD");
  1067. } else
  1068. av_strlcatf(compressor_name, len, " EX");
  1069. av_strlcatf(compressor_name, len, " %d%c", track->enc->height, interlaced ? 'i' : 'p');
  1070. av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
  1071. }
  1072. }
  1073. static int mov_write_video_tag(AVIOContext *pb, MOVTrack *track)
  1074. {
  1075. int64_t pos = avio_tell(pb);
  1076. char compressor_name[32] = { 0 };
  1077. avio_wb32(pb, 0); /* size */
  1078. avio_wl32(pb, track->tag); // store it byteswapped
  1079. avio_wb32(pb, 0); /* Reserved */
  1080. avio_wb16(pb, 0); /* Reserved */
  1081. avio_wb16(pb, 1); /* Data-reference index */
  1082. avio_wb16(pb, 0); /* Codec stream version */
  1083. avio_wb16(pb, 0); /* Codec stream revision (=0) */
  1084. if (track->mode == MODE_MOV) {
  1085. ffio_wfourcc(pb, "FFMP"); /* Vendor */
  1086. if (track->enc->codec_id == AV_CODEC_ID_RAWVIDEO) {
  1087. avio_wb32(pb, 0); /* Temporal Quality */
  1088. avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
  1089. } else {
  1090. avio_wb32(pb, 0x200); /* Temporal Quality = normal */
  1091. avio_wb32(pb, 0x200); /* Spatial Quality = normal */
  1092. }
  1093. } else {
  1094. avio_wb32(pb, 0); /* Reserved */
  1095. avio_wb32(pb, 0); /* Reserved */
  1096. avio_wb32(pb, 0); /* Reserved */
  1097. }
  1098. avio_wb16(pb, track->enc->width); /* Video width */
  1099. avio_wb16(pb, track->height); /* Video height */
  1100. avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
  1101. avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
  1102. avio_wb32(pb, 0); /* Data size (= 0) */
  1103. avio_wb16(pb, 1); /* Frame count (= 1) */
  1104. /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
  1105. find_compressor(compressor_name, 32, track);
  1106. avio_w8(pb, strlen(compressor_name));
  1107. avio_write(pb, compressor_name, 31);
  1108. if (track->mode == MODE_MOV && track->enc->bits_per_coded_sample)
  1109. avio_wb16(pb, track->enc->bits_per_coded_sample);
  1110. else
  1111. avio_wb16(pb, 0x18); /* Reserved */
  1112. avio_wb16(pb, 0xffff); /* Reserved */
  1113. if (track->tag == MKTAG('m','p','4','v'))
  1114. mov_write_esds_tag(pb, track);
  1115. else if (track->enc->codec_id == AV_CODEC_ID_H263)
  1116. mov_write_d263_tag(pb);
  1117. else if (track->enc->codec_id == AV_CODEC_ID_AVUI ||
  1118. track->enc->codec_id == AV_CODEC_ID_SVQ3) {
  1119. mov_write_extradata_tag(pb, track);
  1120. avio_wb32(pb, 0);
  1121. } else if (track->enc->codec_id == AV_CODEC_ID_DNXHD)
  1122. mov_write_avid_tag(pb, track);
  1123. else if (track->enc->codec_id == AV_CODEC_ID_HEVC)
  1124. mov_write_hvcc_tag(pb, track);
  1125. else if (track->enc->codec_id == AV_CODEC_ID_H264) {
  1126. mov_write_avcc_tag(pb, track);
  1127. if (track->mode == MODE_IPOD)
  1128. mov_write_uuid_tag_ipod(pb);
  1129. } else if (track->enc->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
  1130. mov_write_dvc1_tag(pb, track);
  1131. else if (track->enc->codec_id == AV_CODEC_ID_VP6F ||
  1132. track->enc->codec_id == AV_CODEC_ID_VP6A) {
  1133. /* Don't write any potential extradata here - the cropping
  1134. * is signalled via the normal width/height fields. */
  1135. } else if (track->vos_len > 0)
  1136. mov_write_glbl_tag(pb, track);
  1137. if (track->enc->codec_id != AV_CODEC_ID_H264 &&
  1138. track->enc->codec_id != AV_CODEC_ID_MPEG4 &&
  1139. track->enc->codec_id != AV_CODEC_ID_DNXHD)
  1140. if (track->enc->field_order != AV_FIELD_UNKNOWN)
  1141. mov_write_fiel_tag(pb, track);
  1142. if (track->enc->sample_aspect_ratio.den && track->enc->sample_aspect_ratio.num &&
  1143. track->enc->sample_aspect_ratio.den != track->enc->sample_aspect_ratio.num) {
  1144. mov_write_pasp_tag(pb, track);
  1145. }
  1146. return update_size(pb, pos);
  1147. }
  1148. static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
  1149. {
  1150. int64_t pos = avio_tell(pb);
  1151. avio_wb32(pb, 0); /* size */
  1152. ffio_wfourcc(pb, "rtp ");
  1153. avio_wb32(pb, 0); /* Reserved */
  1154. avio_wb16(pb, 0); /* Reserved */
  1155. avio_wb16(pb, 1); /* Data-reference index */
  1156. avio_wb16(pb, 1); /* Hint track version */
  1157. avio_wb16(pb, 1); /* Highest compatible version */
  1158. avio_wb32(pb, track->max_packet_size); /* Max packet size */
  1159. avio_wb32(pb, 12); /* size */
  1160. ffio_wfourcc(pb, "tims");
  1161. avio_wb32(pb, track->timescale);
  1162. return update_size(pb, pos);
  1163. }
  1164. static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
  1165. {
  1166. int64_t pos = avio_tell(pb);
  1167. #if 1
  1168. int frame_duration = av_rescale(track->timescale, track->enc->time_base.num, track->enc->time_base.den);
  1169. int nb_frames = 1.0/av_q2d(track->enc->time_base) + 0.5;
  1170. if (nb_frames > 255) {
  1171. av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
  1172. return AVERROR(EINVAL);
  1173. }
  1174. avio_wb32(pb, 0); /* size */
  1175. ffio_wfourcc(pb, "tmcd"); /* Data format */
  1176. avio_wb32(pb, 0); /* Reserved */
  1177. avio_wb32(pb, 1); /* Data reference index */
  1178. avio_wb32(pb, 0); /* Flags */
  1179. avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
  1180. avio_wb32(pb, track->timescale); /* Timescale */
  1181. avio_wb32(pb, frame_duration); /* Frame duration */
  1182. avio_w8(pb, nb_frames); /* Number of frames */
  1183. avio_wb24(pb, 0); /* Reserved */
  1184. /* TODO: source reference string */
  1185. #else
  1186. avio_wb32(pb, 0); /* size */
  1187. ffio_wfourcc(pb, "tmcd"); /* Data format */
  1188. avio_wb32(pb, 0); /* Reserved */
  1189. avio_wb32(pb, 1); /* Data reference index */
  1190. if (track->enc->extradata_size)
  1191. avio_write(pb, track->enc->extradata, track->enc->extradata_size);
  1192. #endif
  1193. return update_size(pb, pos);
  1194. }
  1195. static int mov_write_stsd_tag(AVIOContext *pb, MOVTrack *track)
  1196. {
  1197. int64_t pos = avio_tell(pb);
  1198. avio_wb32(pb, 0); /* size */
  1199. ffio_wfourcc(pb, "stsd");
  1200. avio_wb32(pb, 0); /* version & flags */
  1201. avio_wb32(pb, 1); /* entry count */
  1202. if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
  1203. mov_write_video_tag(pb, track);
  1204. else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
  1205. mov_write_audio_tag(pb, track);
  1206. else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
  1207. mov_write_subtitle_tag(pb, track);
  1208. else if (track->enc->codec_tag == MKTAG('r','t','p',' '))
  1209. mov_write_rtp_tag(pb, track);
  1210. else if (track->enc->codec_tag == MKTAG('t','m','c','d'))
  1211. mov_write_tmcd_tag(pb, track);
  1212. return update_size(pb, pos);
  1213. }
  1214. static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
  1215. {
  1216. MOVStts *ctts_entries;
  1217. uint32_t entries = 0;
  1218. uint32_t atom_size;
  1219. int i;
  1220. ctts_entries = av_malloc((track->entry + 1) * sizeof(*ctts_entries)); /* worst case */
  1221. ctts_entries[0].count = 1;
  1222. ctts_entries[0].duration = track->cluster[0].cts;
  1223. for (i = 1; i < track->entry; i++) {
  1224. if (track->cluster[i].cts == ctts_entries[entries].duration) {
  1225. ctts_entries[entries].count++; /* compress */
  1226. } else {
  1227. entries++;
  1228. ctts_entries[entries].duration = track->cluster[i].cts;
  1229. ctts_entries[entries].count = 1;
  1230. }
  1231. }
  1232. entries++; /* last one */
  1233. atom_size = 16 + (entries * 8);
  1234. avio_wb32(pb, atom_size); /* size */
  1235. ffio_wfourcc(pb, "ctts");
  1236. avio_wb32(pb, 0); /* version & flags */
  1237. avio_wb32(pb, entries); /* entry count */
  1238. for (i = 0; i < entries; i++) {
  1239. avio_wb32(pb, ctts_entries[i].count);
  1240. avio_wb32(pb, ctts_entries[i].duration);
  1241. }
  1242. av_free(ctts_entries);
  1243. return atom_size;
  1244. }
  1245. /* Time to sample atom */
  1246. static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
  1247. {
  1248. MOVStts *stts_entries;
  1249. uint32_t entries = -1;
  1250. uint32_t atom_size;
  1251. int i;
  1252. if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
  1253. stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
  1254. stts_entries[0].count = track->sample_count;
  1255. stts_entries[0].duration = 1;
  1256. entries = 1;
  1257. } else {
  1258. stts_entries = track->entry ?
  1259. av_malloc(track->entry * sizeof(*stts_entries)) : /* worst case */
  1260. NULL;
  1261. for (i = 0; i < track->entry; i++) {
  1262. int duration = get_cluster_duration(track, i);
  1263. if (i && duration == stts_entries[entries].duration) {
  1264. stts_entries[entries].count++; /* compress */
  1265. } else {
  1266. entries++;
  1267. stts_entries[entries].duration = duration;
  1268. stts_entries[entries].count = 1;
  1269. }
  1270. }
  1271. entries++; /* last one */
  1272. }
  1273. atom_size = 16 + (entries * 8);
  1274. avio_wb32(pb, atom_size); /* size */
  1275. ffio_wfourcc(pb, "stts");
  1276. avio_wb32(pb, 0); /* version & flags */
  1277. avio_wb32(pb, entries); /* entry count */
  1278. for (i = 0; i < entries; i++) {
  1279. avio_wb32(pb, stts_entries[i].count);
  1280. avio_wb32(pb, stts_entries[i].duration);
  1281. }
  1282. av_free(stts_entries);
  1283. return atom_size;
  1284. }
  1285. static int mov_write_dref_tag(AVIOContext *pb)
  1286. {
  1287. avio_wb32(pb, 28); /* size */
  1288. ffio_wfourcc(pb, "dref");
  1289. avio_wb32(pb, 0); /* version & flags */
  1290. avio_wb32(pb, 1); /* entry count */
  1291. avio_wb32(pb, 0xc); /* size */
  1292. //FIXME add the alis and rsrc atom
  1293. ffio_wfourcc(pb, "url ");
  1294. avio_wb32(pb, 1); /* version & flags */
  1295. return 28;
  1296. }
  1297. static int mov_write_stbl_tag(AVIOContext *pb, MOVTrack *track)
  1298. {
  1299. int64_t pos = avio_tell(pb);
  1300. avio_wb32(pb, 0); /* size */
  1301. ffio_wfourcc(pb, "stbl");
  1302. mov_write_stsd_tag(pb, track);
  1303. mov_write_stts_tag(pb, track);
  1304. if ((track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
  1305. track->enc->codec_tag == MKTAG('r','t','p',' ')) &&
  1306. track->has_keyframes && track->has_keyframes < track->entry)
  1307. mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
  1308. if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
  1309. mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
  1310. if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO &&
  1311. track->flags & MOV_TRACK_CTTS)
  1312. mov_write_ctts_tag(pb, track);
  1313. mov_write_stsc_tag(pb, track);
  1314. mov_write_stsz_tag(pb, track);
  1315. mov_write_stco_tag(pb, track);
  1316. return update_size(pb, pos);
  1317. }
  1318. static int mov_write_dinf_tag(AVIOContext *pb)
  1319. {
  1320. int64_t pos = avio_tell(pb);
  1321. avio_wb32(pb, 0); /* size */
  1322. ffio_wfourcc(pb, "dinf");
  1323. mov_write_dref_tag(pb);
  1324. return update_size(pb, pos);
  1325. }
  1326. static int mov_write_nmhd_tag(AVIOContext *pb)
  1327. {
  1328. avio_wb32(pb, 12);
  1329. ffio_wfourcc(pb, "nmhd");
  1330. avio_wb32(pb, 0);
  1331. return 12;
  1332. }
  1333. static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
  1334. {
  1335. int64_t pos = avio_tell(pb);
  1336. const char *font = "Lucida Grande";
  1337. avio_wb32(pb, 0); /* size */
  1338. ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
  1339. avio_wb32(pb, 0); /* version & flags */
  1340. avio_wb16(pb, 0); /* text font */
  1341. avio_wb16(pb, 0); /* text face */
  1342. avio_wb16(pb, 12); /* text size */
  1343. avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
  1344. avio_wb16(pb, 0x0000); /* text color (red) */
  1345. avio_wb16(pb, 0x0000); /* text color (green) */
  1346. avio_wb16(pb, 0x0000); /* text color (blue) */
  1347. avio_wb16(pb, 0xffff); /* background color (red) */
  1348. avio_wb16(pb, 0xffff); /* background color (green) */
  1349. avio_wb16(pb, 0xffff); /* background color (blue) */
  1350. avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
  1351. avio_write(pb, font, strlen(font)); /* font name */
  1352. return update_size(pb, pos);
  1353. }
  1354. static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
  1355. {
  1356. int64_t pos = avio_tell(pb);
  1357. avio_wb32(pb, 0); /* size */
  1358. ffio_wfourcc(pb, "gmhd");
  1359. avio_wb32(pb, 0x18); /* gmin size */
  1360. ffio_wfourcc(pb, "gmin");/* generic media info */
  1361. avio_wb32(pb, 0); /* version & flags */
  1362. avio_wb16(pb, 0x40); /* graphics mode = */
  1363. avio_wb16(pb, 0x8000); /* opColor (r?) */
  1364. avio_wb16(pb, 0x8000); /* opColor (g?) */
  1365. avio_wb16(pb, 0x8000); /* opColor (b?) */
  1366. avio_wb16(pb, 0); /* balance */
  1367. avio_wb16(pb, 0); /* reserved */
  1368. /*
  1369. * This special text atom is required for
  1370. * Apple Quicktime chapters. The contents
  1371. * don't appear to be documented, so the
  1372. * bytes are copied verbatim.
  1373. */
  1374. if (track->tag != MKTAG('c','6','0','8')) {
  1375. avio_wb32(pb, 0x2C); /* size */
  1376. ffio_wfourcc(pb, "text");
  1377. avio_wb16(pb, 0x01);
  1378. avio_wb32(pb, 0x00);
  1379. avio_wb32(pb, 0x00);
  1380. avio_wb32(pb, 0x00);
  1381. avio_wb32(pb, 0x01);
  1382. avio_wb32(pb, 0x00);
  1383. avio_wb32(pb, 0x00);
  1384. avio_wb32(pb, 0x00);
  1385. avio_wb32(pb, 0x00004000);
  1386. avio_wb16(pb, 0x0000);
  1387. }
  1388. if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
  1389. int64_t tmcd_pos = avio_tell(pb);
  1390. avio_wb32(pb, 0); /* size */
  1391. ffio_wfourcc(pb, "tmcd");
  1392. mov_write_tcmi_tag(pb, track);
  1393. update_size(pb, tmcd_pos);
  1394. }
  1395. return update_size(pb, pos);
  1396. }
  1397. static int mov_write_smhd_tag(AVIOContext *pb)
  1398. {
  1399. avio_wb32(pb, 16); /* size */
  1400. ffio_wfourcc(pb, "smhd");
  1401. avio_wb32(pb, 0); /* version & flags */
  1402. avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
  1403. avio_wb16(pb, 0); /* reserved */
  1404. return 16;
  1405. }
  1406. static int mov_write_vmhd_tag(AVIOContext *pb)
  1407. {
  1408. avio_wb32(pb, 0x14); /* size (always 0x14) */
  1409. ffio_wfourcc(pb, "vmhd");
  1410. avio_wb32(pb, 0x01); /* version & flags */
  1411. avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
  1412. return 0x14;
  1413. }
  1414. static int is_clcp_track(MOVTrack *track)
  1415. {
  1416. return track->tag == MKTAG('c','7','0','8') ||
  1417. track->tag == MKTAG('c','6','0','8');
  1418. }
  1419. static int mov_write_hdlr_tag(AVIOContext *pb, MOVTrack *track)
  1420. {
  1421. const char *hdlr, *descr = NULL, *hdlr_type = NULL;
  1422. int64_t pos = avio_tell(pb);
  1423. hdlr = "dhlr";
  1424. hdlr_type = "url ";
  1425. descr = "DataHandler";
  1426. if (track) {
  1427. hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
  1428. if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  1429. hdlr_type = "vide";
  1430. descr = "VideoHandler";
  1431. } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
  1432. hdlr_type = "soun";
  1433. descr = "SoundHandler";
  1434. } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  1435. if (is_clcp_track(track)) {
  1436. hdlr_type = "clcp";
  1437. descr = "ClosedCaptionHandler";
  1438. } else {
  1439. if (track->tag == MKTAG('t','x','3','g')) {
  1440. hdlr_type = "sbtl";
  1441. } else if (track->tag == MKTAG('m','p','4','s')) {
  1442. hdlr_type = "subp";
  1443. } else {
  1444. hdlr_type = "text";
  1445. }
  1446. descr = "SubtitleHandler";
  1447. }
  1448. } else if (track->enc->codec_tag == MKTAG('r','t','p',' ')) {
  1449. hdlr_type = "hint";
  1450. descr = "HintHandler";
  1451. } else if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
  1452. hdlr_type = "tmcd";
  1453. descr = "TimeCodeHandler";
  1454. } else {
  1455. char tag_buf[32];
  1456. av_get_codec_tag_string(tag_buf, sizeof(tag_buf),
  1457. track->enc->codec_tag);
  1458. av_log(track->enc, AV_LOG_WARNING,
  1459. "Unknown hldr_type for %s / 0x%04X, writing dummy values\n",
  1460. tag_buf, track->enc->codec_tag);
  1461. }
  1462. }
  1463. avio_wb32(pb, 0); /* size */
  1464. ffio_wfourcc(pb, "hdlr");
  1465. avio_wb32(pb, 0); /* Version & flags */
  1466. avio_write(pb, hdlr, 4); /* handler */
  1467. ffio_wfourcc(pb, hdlr_type); /* handler type */
  1468. avio_wb32(pb, 0); /* reserved */
  1469. avio_wb32(pb, 0); /* reserved */
  1470. avio_wb32(pb, 0); /* reserved */
  1471. if (!track || track->mode == MODE_MOV)
  1472. avio_w8(pb, strlen(descr)); /* pascal string */
  1473. avio_write(pb, descr, strlen(descr)); /* handler description */
  1474. if (track && track->mode != MODE_MOV)
  1475. avio_w8(pb, 0); /* c string */
  1476. return update_size(pb, pos);
  1477. }
  1478. static int mov_write_hmhd_tag(AVIOContext *pb)
  1479. {
  1480. /* This atom must be present, but leaving the values at zero
  1481. * seems harmless. */
  1482. avio_wb32(pb, 28); /* size */
  1483. ffio_wfourcc(pb, "hmhd");
  1484. avio_wb32(pb, 0); /* version, flags */
  1485. avio_wb16(pb, 0); /* maxPDUsize */
  1486. avio_wb16(pb, 0); /* avgPDUsize */
  1487. avio_wb32(pb, 0); /* maxbitrate */
  1488. avio_wb32(pb, 0); /* avgbitrate */
  1489. avio_wb32(pb, 0); /* reserved */
  1490. return 28;
  1491. }
  1492. static int mov_write_minf_tag(AVIOContext *pb, MOVTrack *track)
  1493. {
  1494. int64_t pos = avio_tell(pb);
  1495. avio_wb32(pb, 0); /* size */
  1496. ffio_wfourcc(pb, "minf");
  1497. if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
  1498. mov_write_vmhd_tag(pb);
  1499. else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
  1500. mov_write_smhd_tag(pb);
  1501. else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  1502. if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
  1503. mov_write_gmhd_tag(pb, track);
  1504. } else {
  1505. mov_write_nmhd_tag(pb);
  1506. }
  1507. } else if (track->tag == MKTAG('r','t','p',' ')) {
  1508. mov_write_hmhd_tag(pb);
  1509. } else if (track->tag == MKTAG('t','m','c','d')) {
  1510. mov_write_gmhd_tag(pb, track);
  1511. }
  1512. if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
  1513. mov_write_hdlr_tag(pb, NULL);
  1514. mov_write_dinf_tag(pb);
  1515. mov_write_stbl_tag(pb, track);
  1516. return update_size(pb, pos);
  1517. }
  1518. static int mov_write_mdhd_tag(AVIOContext *pb, MOVTrack *track)
  1519. {
  1520. int version = track->track_duration < INT32_MAX ? 0 : 1;
  1521. if (track->mode == MODE_ISM)
  1522. version = 1;
  1523. (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
  1524. ffio_wfourcc(pb, "mdhd");
  1525. avio_w8(pb, version);
  1526. avio_wb24(pb, 0); /* flags */
  1527. if (version == 1) {
  1528. avio_wb64(pb, track->time);
  1529. avio_wb64(pb, track->time);
  1530. } else {
  1531. avio_wb32(pb, track->time); /* creation time */
  1532. avio_wb32(pb, track->time); /* modification time */
  1533. }
  1534. avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
  1535. if (!track->entry)
  1536. (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
  1537. else
  1538. (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
  1539. avio_wb16(pb, track->language); /* language */
  1540. avio_wb16(pb, 0); /* reserved (quality) */
  1541. if (version != 0 && track->mode == MODE_MOV) {
  1542. av_log(NULL, AV_LOG_ERROR,
  1543. "FATAL error, file duration too long for timebase, this file will not be\n"
  1544. "playable with quicktime. Choose a different timebase or a different\n"
  1545. "container format\n");
  1546. }
  1547. return 32;
  1548. }
  1549. static int mov_write_mdia_tag(AVIOContext *pb, MOVTrack *track)
  1550. {
  1551. int64_t pos = avio_tell(pb);
  1552. avio_wb32(pb, 0); /* size */
  1553. ffio_wfourcc(pb, "mdia");
  1554. mov_write_mdhd_tag(pb, track);
  1555. mov_write_hdlr_tag(pb, track);
  1556. mov_write_minf_tag(pb, track);
  1557. return update_size(pb, pos);
  1558. }
  1559. /* transformation matrix
  1560. |a b u|
  1561. |c d v|
  1562. |tx ty w| */
  1563. static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
  1564. int16_t d, int16_t tx, int16_t ty)
  1565. {
  1566. avio_wb32(pb, a << 16); /* 16.16 format */
  1567. avio_wb32(pb, b << 16); /* 16.16 format */
  1568. avio_wb32(pb, 0); /* u in 2.30 format */
  1569. avio_wb32(pb, c << 16); /* 16.16 format */
  1570. avio_wb32(pb, d << 16); /* 16.16 format */
  1571. avio_wb32(pb, 0); /* v in 2.30 format */
  1572. avio_wb32(pb, tx << 16); /* 16.16 format */
  1573. avio_wb32(pb, ty << 16); /* 16.16 format */
  1574. avio_wb32(pb, 1 << 30); /* w in 2.30 format */
  1575. }
  1576. static int mov_write_tkhd_tag(AVIOContext *pb, MOVTrack *track, AVStream *st)
  1577. {
  1578. int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
  1579. track->timescale, AV_ROUND_UP);
  1580. int version = duration < INT32_MAX ? 0 : 1;
  1581. int rotation = 0;
  1582. if (track->mode == MODE_ISM)
  1583. version = 1;
  1584. (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
  1585. ffio_wfourcc(pb, "tkhd");
  1586. avio_w8(pb, version);
  1587. avio_wb24(pb, (track->flags & MOV_TRACK_ENABLED) ?
  1588. MOV_TKHD_FLAG_ENABLED | MOV_TKHD_FLAG_IN_MOVIE :
  1589. MOV_TKHD_FLAG_IN_MOVIE);
  1590. if (version == 1) {
  1591. avio_wb64(pb, track->time);
  1592. avio_wb64(pb, track->time);
  1593. } else {
  1594. avio_wb32(pb, track->time); /* creation time */
  1595. avio_wb32(pb, track->time); /* modification time */
  1596. }
  1597. avio_wb32(pb, track->track_id); /* track-id */
  1598. avio_wb32(pb, 0); /* reserved */
  1599. if (!track->entry)
  1600. (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
  1601. else
  1602. (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
  1603. avio_wb32(pb, 0); /* reserved */
  1604. avio_wb32(pb, 0); /* reserved */
  1605. avio_wb16(pb, 0); /* layer */
  1606. avio_wb16(pb, st ? st->codec->codec_type : 0); /* alternate group) */
  1607. /* Volume, only for audio */
  1608. if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
  1609. avio_wb16(pb, 0x0100);
  1610. else
  1611. avio_wb16(pb, 0);
  1612. avio_wb16(pb, 0); /* reserved */
  1613. /* Matrix structure */
  1614. if (st && st->metadata) {
  1615. AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
  1616. rotation = (rot && rot->value) ? atoi(rot->value) : 0;
  1617. }
  1618. if (rotation == 90) {
  1619. write_matrix(pb, 0, 1, -1, 0, track->enc->height, 0);
  1620. } else if (rotation == 180) {
  1621. write_matrix(pb, -1, 0, 0, -1, track->enc->width, track->enc->height);
  1622. } else if (rotation == 270) {
  1623. write_matrix(pb, 0, -1, 1, 0, 0, track->enc->width);
  1624. } else {
  1625. write_matrix(pb, 1, 0, 0, 1, 0, 0);
  1626. }
  1627. /* Track width and height, for visual only */
  1628. if (st && (track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
  1629. track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
  1630. if (track->mode == MODE_MOV) {
  1631. avio_wb32(pb, track->enc->width << 16);
  1632. avio_wb32(pb, track->height << 16);
  1633. } else {
  1634. double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
  1635. if (!sample_aspect_ratio || track->height != track->enc->height)
  1636. sample_aspect_ratio = 1;
  1637. avio_wb32(pb, sample_aspect_ratio * track->enc->width * 0x10000);
  1638. avio_wb32(pb, track->height * 0x10000);
  1639. }
  1640. } else {
  1641. avio_wb32(pb, 0);
  1642. avio_wb32(pb, 0);
  1643. }
  1644. return 0x5c;
  1645. }
  1646. static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
  1647. {
  1648. int32_t width = av_rescale(track->enc->sample_aspect_ratio.num, track->enc->width,
  1649. track->enc->sample_aspect_ratio.den);
  1650. int64_t pos = avio_tell(pb);
  1651. avio_wb32(pb, 0); /* size */
  1652. ffio_wfourcc(pb, "tapt");
  1653. avio_wb32(pb, 20);
  1654. ffio_wfourcc(pb, "clef");
  1655. avio_wb32(pb, 0);
  1656. avio_wb32(pb, width << 16);
  1657. avio_wb32(pb, track->enc->height << 16);
  1658. avio_wb32(pb, 20);
  1659. ffio_wfourcc(pb, "prof");
  1660. avio_wb32(pb, 0);
  1661. avio_wb32(pb, width << 16);
  1662. avio_wb32(pb, track->enc->height << 16);
  1663. avio_wb32(pb, 20);
  1664. ffio_wfourcc(pb, "enof");
  1665. avio_wb32(pb, 0);
  1666. avio_wb32(pb, track->enc->width << 16);
  1667. avio_wb32(pb, track->enc->height << 16);
  1668. return update_size(pb, pos);
  1669. }
  1670. // This box seems important for the psp playback ... without it the movie seems to hang
  1671. static int mov_write_edts_tag(AVIOContext *pb, MOVTrack *track)
  1672. {
  1673. int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
  1674. track->timescale, AV_ROUND_UP);
  1675. int version = duration < INT32_MAX ? 0 : 1;
  1676. int entry_size, entry_count, size;
  1677. int64_t delay, start_ct = track->cluster[0].cts;
  1678. delay = av_rescale_rnd(track->cluster[0].dts + start_ct, MOV_TIMESCALE,
  1679. track->timescale, AV_ROUND_DOWN);
  1680. version |= delay < INT32_MAX ? 0 : 1;
  1681. entry_size = (version == 1) ? 20 : 12;
  1682. entry_count = 1 + (delay > 0);
  1683. size = 24 + entry_count * entry_size;
  1684. /* write the atom data */
  1685. avio_wb32(pb, size);
  1686. ffio_wfourcc(pb, "edts");
  1687. avio_wb32(pb, size - 8);
  1688. ffio_wfourcc(pb, "elst");
  1689. avio_w8(pb, version);
  1690. avio_wb24(pb, 0); /* flags */
  1691. avio_wb32(pb, entry_count);
  1692. if (delay > 0) { /* add an empty edit to delay presentation */
  1693. if (version == 1) {
  1694. avio_wb64(pb, delay);
  1695. avio_wb64(pb, -1);
  1696. } else {
  1697. avio_wb32(pb, delay);
  1698. avio_wb32(pb, -1);
  1699. }
  1700. avio_wb32(pb, 0x00010000);
  1701. } else {
  1702. av_assert0(av_rescale_rnd(track->cluster[0].dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
  1703. start_ct = -FFMIN(track->cluster[0].dts, 0); //FFMIN needed due to rounding
  1704. duration += delay;
  1705. }
  1706. /* duration */
  1707. if (version == 1) {
  1708. avio_wb64(pb, duration);
  1709. avio_wb64(pb, start_ct);
  1710. } else {
  1711. avio_wb32(pb, duration);
  1712. avio_wb32(pb, start_ct);
  1713. }
  1714. avio_wb32(pb, 0x00010000);
  1715. return size;
  1716. }
  1717. static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
  1718. {
  1719. avio_wb32(pb, 20); // size
  1720. ffio_wfourcc(pb, "tref");
  1721. avio_wb32(pb, 12); // size (subatom)
  1722. avio_wl32(pb, track->tref_tag);
  1723. avio_wb32(pb, track->tref_id);
  1724. return 20;
  1725. }
  1726. // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
  1727. static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
  1728. {
  1729. avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
  1730. ffio_wfourcc(pb, "uuid");
  1731. ffio_wfourcc(pb, "USMT");
  1732. avio_wb32(pb, 0x21d24fce);
  1733. avio_wb32(pb, 0xbb88695c);
  1734. avio_wb32(pb, 0xfac9c740);
  1735. avio_wb32(pb, 0x1c); // another size here!
  1736. ffio_wfourcc(pb, "MTDT");
  1737. avio_wb32(pb, 0x00010012);
  1738. avio_wb32(pb, 0x0a);
  1739. avio_wb32(pb, 0x55c40000);
  1740. avio_wb32(pb, 0x1);
  1741. avio_wb32(pb, 0x0);
  1742. return 0x34;
  1743. }
  1744. static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
  1745. {
  1746. AVFormatContext *ctx = track->rtp_ctx;
  1747. char buf[1000] = "";
  1748. int len;
  1749. ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
  1750. NULL, NULL, 0, 0, ctx);
  1751. av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
  1752. len = strlen(buf);
  1753. avio_wb32(pb, len + 24);
  1754. ffio_wfourcc(pb, "udta");
  1755. avio_wb32(pb, len + 16);
  1756. ffio_wfourcc(pb, "hnti");
  1757. avio_wb32(pb, len + 8);
  1758. ffio_wfourcc(pb, "sdp ");
  1759. avio_write(pb, buf, len);
  1760. return len + 24;
  1761. }
  1762. static int mov_write_trak_tag(AVIOContext *pb, MOVMuxContext *mov,
  1763. MOVTrack *track, AVStream *st)
  1764. {
  1765. int64_t pos = avio_tell(pb);
  1766. avio_wb32(pb, 0); /* size */
  1767. ffio_wfourcc(pb, "trak");
  1768. mov_write_tkhd_tag(pb, track, st);
  1769. if (supports_edts(mov))
  1770. mov_write_edts_tag(pb, track); // PSP Movies and several other cases require edts box
  1771. if (track->tref_tag)
  1772. mov_write_tref_tag(pb, track);
  1773. mov_write_mdia_tag(pb, track);
  1774. if (track->mode == MODE_PSP)
  1775. mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
  1776. if (track->tag == MKTAG('r','t','p',' '))
  1777. mov_write_udta_sdp(pb, track);
  1778. if (track->mode == MODE_MOV) {
  1779. if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  1780. double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
  1781. if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
  1782. mov_write_tapt_tag(pb, track);
  1783. }
  1784. }
  1785. if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
  1786. mov_write_tapt_tag(pb, track);
  1787. }
  1788. }
  1789. return update_size(pb, pos);
  1790. }
  1791. static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
  1792. {
  1793. int i, has_audio = 0, has_video = 0;
  1794. int64_t pos = avio_tell(pb);
  1795. int audio_profile = mov->iods_audio_profile;
  1796. int video_profile = mov->iods_video_profile;
  1797. for (i = 0; i < mov->nb_streams; i++) {
  1798. if (mov->tracks[i].entry > 0) {
  1799. has_audio |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_AUDIO;
  1800. has_video |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_VIDEO;
  1801. }
  1802. }
  1803. if (audio_profile < 0)
  1804. audio_profile = 0xFF - has_audio;
  1805. if (video_profile < 0)
  1806. video_profile = 0xFF - has_video;
  1807. avio_wb32(pb, 0x0); /* size */
  1808. ffio_wfourcc(pb, "iods");
  1809. avio_wb32(pb, 0); /* version & flags */
  1810. put_descr(pb, 0x10, 7);
  1811. avio_wb16(pb, 0x004f);
  1812. avio_w8(pb, 0xff);
  1813. avio_w8(pb, 0xff);
  1814. avio_w8(pb, audio_profile);
  1815. avio_w8(pb, video_profile);
  1816. avio_w8(pb, 0xff);
  1817. return update_size(pb, pos);
  1818. }
  1819. static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
  1820. {
  1821. avio_wb32(pb, 0x20); /* size */
  1822. ffio_wfourcc(pb, "trex");
  1823. avio_wb32(pb, 0); /* version & flags */
  1824. avio_wb32(pb, track->track_id); /* track ID */
  1825. avio_wb32(pb, 1); /* default sample description index */
  1826. avio_wb32(pb, 0); /* default sample duration */
  1827. avio_wb32(pb, 0); /* default sample size */
  1828. avio_wb32(pb, 0); /* default sample flags */
  1829. return 0;
  1830. }
  1831. static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
  1832. {
  1833. int64_t pos = avio_tell(pb);
  1834. int i;
  1835. avio_wb32(pb, 0x0); /* size */
  1836. ffio_wfourcc(pb, "mvex");
  1837. for (i = 0; i < mov->nb_streams; i++)
  1838. mov_write_trex_tag(pb, &mov->tracks[i]);
  1839. return update_size(pb, pos);
  1840. }
  1841. static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
  1842. {
  1843. int max_track_id = 1, i;
  1844. int64_t max_track_len_temp, max_track_len = 0;
  1845. int version;
  1846. for (i = 0; i < mov->nb_streams; i++) {
  1847. if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
  1848. max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
  1849. MOV_TIMESCALE,
  1850. mov->tracks[i].timescale,
  1851. AV_ROUND_UP);
  1852. if (max_track_len < max_track_len_temp)
  1853. max_track_len = max_track_len_temp;
  1854. if (max_track_id < mov->tracks[i].track_id)
  1855. max_track_id = mov->tracks[i].track_id;
  1856. }
  1857. }
  1858. version = max_track_len < UINT32_MAX ? 0 : 1;
  1859. (version == 1) ? avio_wb32(pb, 120) : avio_wb32(pb, 108); /* size */
  1860. ffio_wfourcc(pb, "mvhd");
  1861. avio_w8(pb, version);
  1862. avio_wb24(pb, 0); /* flags */
  1863. if (version == 1) {
  1864. avio_wb64(pb, mov->time);
  1865. avio_wb64(pb, mov->time);
  1866. } else {
  1867. avio_wb32(pb, mov->time); /* creation time */
  1868. avio_wb32(pb, mov->time); /* modification time */
  1869. }
  1870. avio_wb32(pb, MOV_TIMESCALE);
  1871. (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
  1872. avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
  1873. avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
  1874. avio_wb16(pb, 0); /* reserved */
  1875. avio_wb32(pb, 0); /* reserved */
  1876. avio_wb32(pb, 0); /* reserved */
  1877. /* Matrix structure */
  1878. write_matrix(pb, 1, 0, 0, 1, 0, 0);
  1879. avio_wb32(pb, 0); /* reserved (preview time) */
  1880. avio_wb32(pb, 0); /* reserved (preview duration) */
  1881. avio_wb32(pb, 0); /* reserved (poster time) */
  1882. avio_wb32(pb, 0); /* reserved (selection time) */
  1883. avio_wb32(pb, 0); /* reserved (selection duration) */
  1884. avio_wb32(pb, 0); /* reserved (current time) */
  1885. avio_wb32(pb, max_track_id + 1); /* Next track id */
  1886. return 0x6c;
  1887. }
  1888. static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
  1889. AVFormatContext *s)
  1890. {
  1891. avio_wb32(pb, 33); /* size */
  1892. ffio_wfourcc(pb, "hdlr");
  1893. avio_wb32(pb, 0);
  1894. avio_wb32(pb, 0);
  1895. ffio_wfourcc(pb, "mdir");
  1896. ffio_wfourcc(pb, "appl");
  1897. avio_wb32(pb, 0);
  1898. avio_wb32(pb, 0);
  1899. avio_w8(pb, 0);
  1900. return 33;
  1901. }
  1902. /* helper function to write a data tag with the specified string as data */
  1903. static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
  1904. {
  1905. if (long_style) {
  1906. int size = 16 + strlen(data);
  1907. avio_wb32(pb, size); /* size */
  1908. ffio_wfourcc(pb, "data");
  1909. avio_wb32(pb, 1);
  1910. avio_wb32(pb, 0);
  1911. avio_write(pb, data, strlen(data));
  1912. return size;
  1913. } else {
  1914. if (!lang)
  1915. lang = ff_mov_iso639_to_lang("und", 1);
  1916. avio_wb16(pb, strlen(data)); /* string length */
  1917. avio_wb16(pb, lang);
  1918. avio_write(pb, data, strlen(data));
  1919. return strlen(data) + 4;
  1920. }
  1921. }
  1922. static int mov_write_string_tag(AVIOContext *pb, const char *name,
  1923. const char *value, int lang, int long_style)
  1924. {
  1925. int size = 0;
  1926. if (value && value[0]) {
  1927. int64_t pos = avio_tell(pb);
  1928. avio_wb32(pb, 0); /* size */
  1929. ffio_wfourcc(pb, name);
  1930. mov_write_string_data_tag(pb, value, lang, long_style);
  1931. size = update_size(pb, pos);
  1932. }
  1933. return size;
  1934. }
  1935. static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
  1936. const char *name, const char *tag,
  1937. int long_style)
  1938. {
  1939. int l, lang = 0, len, len2;
  1940. AVDictionaryEntry *t, *t2 = NULL;
  1941. char tag2[16];
  1942. if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
  1943. return 0;
  1944. len = strlen(t->key);
  1945. snprintf(tag2, sizeof(tag2), "%s-", tag);
  1946. while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
  1947. len2 = strlen(t2->key);
  1948. if (len2 == len + 4 && !strcmp(t->value, t2->value)
  1949. && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
  1950. lang = l;
  1951. break;
  1952. }
  1953. }
  1954. return mov_write_string_tag(pb, name, t->value, lang, long_style);
  1955. }
  1956. /* iTunes bpm number */
  1957. static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
  1958. {
  1959. AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
  1960. int size = 0, tmpo = t ? atoi(t->value) : 0;
  1961. if (tmpo) {
  1962. size = 26;
  1963. avio_wb32(pb, size);
  1964. ffio_wfourcc(pb, "tmpo");
  1965. avio_wb32(pb, size-8); /* size */
  1966. ffio_wfourcc(pb, "data");
  1967. avio_wb32(pb, 0x15); //type specifier
  1968. avio_wb32(pb, 0);
  1969. avio_wb16(pb, tmpo); // data
  1970. }
  1971. return size;
  1972. }
  1973. /* iTunes track or disc number */
  1974. static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
  1975. AVFormatContext *s, int disc)
  1976. {
  1977. AVDictionaryEntry *t = av_dict_get(s->metadata,
  1978. disc ? "disc" : "track",
  1979. NULL, 0);
  1980. int size = 0, track = t ? atoi(t->value) : 0;
  1981. if (track) {
  1982. int tracks = 0;
  1983. char *slash = strchr(t->value, '/');
  1984. if (slash)
  1985. tracks = atoi(slash + 1);
  1986. avio_wb32(pb, 32); /* size */
  1987. ffio_wfourcc(pb, disc ? "disk" : "trkn");
  1988. avio_wb32(pb, 24); /* size */
  1989. ffio_wfourcc(pb, "data");
  1990. avio_wb32(pb, 0); // 8 bytes empty
  1991. avio_wb32(pb, 0);
  1992. avio_wb16(pb, 0); // empty
  1993. avio_wb16(pb, track); // track / disc number
  1994. avio_wb16(pb, tracks); // total track / disc number
  1995. avio_wb16(pb, 0); // empty
  1996. size = 32;
  1997. }
  1998. return size;
  1999. }
  2000. static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
  2001. const char *name, const char *tag,
  2002. int len)
  2003. {
  2004. AVDictionaryEntry *t = NULL;
  2005. uint8_t num;
  2006. int size = 24 + len;
  2007. if (len != 1 && len != 4)
  2008. return -1;
  2009. if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
  2010. return 0;
  2011. num = atoi(t->value);
  2012. avio_wb32(pb, size);
  2013. ffio_wfourcc(pb, name);
  2014. avio_wb32(pb, size - 8);
  2015. ffio_wfourcc(pb, "data");
  2016. avio_wb32(pb, 0x15);
  2017. avio_wb32(pb, 0);
  2018. if (len==4) avio_wb32(pb, num);
  2019. else avio_w8 (pb, num);
  2020. return size;
  2021. }
  2022. /* iTunes meta data list */
  2023. static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
  2024. AVFormatContext *s)
  2025. {
  2026. int64_t pos = avio_tell(pb);
  2027. avio_wb32(pb, 0); /* size */
  2028. ffio_wfourcc(pb, "ilst");
  2029. mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
  2030. mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
  2031. mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
  2032. mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
  2033. mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
  2034. mov_write_string_metadata(s, pb, "\251day", "date" , 1);
  2035. if (!mov->exact &&
  2036. !mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1))
  2037. mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
  2038. mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
  2039. mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
  2040. mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
  2041. mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
  2042. mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
  2043. mov_write_string_metadata(s, pb, "desc", "description",1);
  2044. mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
  2045. mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
  2046. mov_write_string_metadata(s, pb, "tven", "episode_id",1);
  2047. mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
  2048. mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
  2049. mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
  2050. mov_write_int8_metadata (s, pb, "stik", "media_type",1);
  2051. mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
  2052. mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
  2053. mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
  2054. mov_write_trkn_tag(pb, mov, s, 0); // track number
  2055. mov_write_trkn_tag(pb, mov, s, 1); // disc number
  2056. mov_write_tmpo_tag(pb, s);
  2057. return update_size(pb, pos);
  2058. }
  2059. /* iTunes meta data tag */
  2060. static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
  2061. AVFormatContext *s)
  2062. {
  2063. int size = 0;
  2064. int64_t pos = avio_tell(pb);
  2065. avio_wb32(pb, 0); /* size */
  2066. ffio_wfourcc(pb, "meta");
  2067. avio_wb32(pb, 0);
  2068. mov_write_itunes_hdlr_tag(pb, mov, s);
  2069. mov_write_ilst_tag(pb, mov, s);
  2070. size = update_size(pb, pos);
  2071. return size;
  2072. }
  2073. static int utf8len(const uint8_t *b)
  2074. {
  2075. int len = 0;
  2076. int val;
  2077. while (*b) {
  2078. GET_UTF8(val, *b++, return -1;)
  2079. len++;
  2080. }
  2081. return len;
  2082. }
  2083. static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
  2084. {
  2085. int val;
  2086. while (*b) {
  2087. GET_UTF8(val, *b++, return -1;)
  2088. avio_wb16(pb, val);
  2089. }
  2090. avio_wb16(pb, 0x00);
  2091. return 0;
  2092. }
  2093. static uint16_t language_code(const char *str)
  2094. {
  2095. return (((str[0] - 0x60) & 0x1F) << 10) +
  2096. (((str[1] - 0x60) & 0x1F) << 5) +
  2097. (( str[2] - 0x60) & 0x1F);
  2098. }
  2099. static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
  2100. const char *tag, const char *str)
  2101. {
  2102. int64_t pos = avio_tell(pb);
  2103. AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
  2104. if (!t || !utf8len(t->value))
  2105. return 0;
  2106. avio_wb32(pb, 0); /* size */
  2107. ffio_wfourcc(pb, tag); /* type */
  2108. avio_wb32(pb, 0); /* version + flags */
  2109. if (!strcmp(tag, "yrrc"))
  2110. avio_wb16(pb, atoi(t->value));
  2111. else {
  2112. avio_wb16(pb, language_code("eng")); /* language */
  2113. avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
  2114. if (!strcmp(tag, "albm") &&
  2115. (t = av_dict_get(s->metadata, "track", NULL, 0)))
  2116. avio_w8(pb, atoi(t->value));
  2117. }
  2118. return update_size(pb, pos);
  2119. }
  2120. static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
  2121. {
  2122. int64_t pos = avio_tell(pb);
  2123. int i, nb_chapters = FFMIN(s->nb_chapters, 255);
  2124. avio_wb32(pb, 0); // size
  2125. ffio_wfourcc(pb, "chpl");
  2126. avio_wb32(pb, 0x01000000); // version + flags
  2127. avio_wb32(pb, 0); // unknown
  2128. avio_w8(pb, nb_chapters);
  2129. for (i = 0; i < nb_chapters; i++) {
  2130. AVChapter *c = s->chapters[i];
  2131. AVDictionaryEntry *t;
  2132. avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
  2133. if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
  2134. int len = FFMIN(strlen(t->value), 255);
  2135. avio_w8(pb, len);
  2136. avio_write(pb, t->value, len);
  2137. } else
  2138. avio_w8(pb, 0);
  2139. }
  2140. return update_size(pb, pos);
  2141. }
  2142. static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
  2143. AVFormatContext *s)
  2144. {
  2145. AVIOContext *pb_buf;
  2146. int ret, size;
  2147. uint8_t *buf;
  2148. ret = avio_open_dyn_buf(&pb_buf);
  2149. if (ret < 0)
  2150. return ret;
  2151. if (mov->mode & MODE_3GP) {
  2152. mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
  2153. mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
  2154. mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
  2155. mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
  2156. mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
  2157. mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
  2158. mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
  2159. mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
  2160. } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
  2161. mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
  2162. mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
  2163. mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
  2164. mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
  2165. mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
  2166. mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
  2167. // currently ignored by mov.c
  2168. mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
  2169. // add support for libquicktime, this atom is also actually read by mov.c
  2170. mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
  2171. mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
  2172. mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
  2173. } else {
  2174. /* iTunes meta data */
  2175. mov_write_meta_tag(pb_buf, mov, s);
  2176. }
  2177. if (s->nb_chapters)
  2178. mov_write_chpl_tag(pb_buf, s);
  2179. if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
  2180. avio_wb32(pb, size + 8);
  2181. ffio_wfourcc(pb, "udta");
  2182. avio_write(pb, buf, size);
  2183. }
  2184. av_free(buf);
  2185. return 0;
  2186. }
  2187. static void mov_write_psp_udta_tag(AVIOContext *pb,
  2188. const char *str, const char *lang, int type)
  2189. {
  2190. int len = utf8len(str) + 1;
  2191. if (len <= 0)
  2192. return;
  2193. avio_wb16(pb, len * 2 + 10); /* size */
  2194. avio_wb32(pb, type); /* type */
  2195. avio_wb16(pb, language_code(lang)); /* language */
  2196. avio_wb16(pb, 0x01); /* ? */
  2197. ascii_to_wc(pb, str);
  2198. }
  2199. static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
  2200. {
  2201. MOVMuxContext *mov = s->priv_data;
  2202. AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
  2203. int64_t pos, pos2;
  2204. if (title) {
  2205. pos = avio_tell(pb);
  2206. avio_wb32(pb, 0); /* size placeholder*/
  2207. ffio_wfourcc(pb, "uuid");
  2208. ffio_wfourcc(pb, "USMT");
  2209. avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
  2210. avio_wb32(pb, 0xbb88695c);
  2211. avio_wb32(pb, 0xfac9c740);
  2212. pos2 = avio_tell(pb);
  2213. avio_wb32(pb, 0); /* size placeholder*/
  2214. ffio_wfourcc(pb, "MTDT");
  2215. avio_wb16(pb, 4);
  2216. // ?
  2217. avio_wb16(pb, 0x0C); /* size */
  2218. avio_wb32(pb, 0x0B); /* type */
  2219. avio_wb16(pb, language_code("und")); /* language */
  2220. avio_wb16(pb, 0x0); /* ? */
  2221. avio_wb16(pb, 0x021C); /* data */
  2222. if (!mov->exact)
  2223. mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
  2224. mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
  2225. mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
  2226. update_size(pb, pos2);
  2227. return update_size(pb, pos);
  2228. }
  2229. return 0;
  2230. }
  2231. static void build_chunks(MOVTrack *trk)
  2232. {
  2233. int i;
  2234. MOVIentry *chunk = &trk->cluster[0];
  2235. uint64_t chunkSize = chunk->size;
  2236. chunk->chunkNum = 1;
  2237. if (trk->chunkCount)
  2238. return;
  2239. trk->chunkCount = 1;
  2240. for (i = 1; i<trk->entry; i++){
  2241. if (chunk->pos + chunkSize == trk->cluster[i].pos &&
  2242. chunkSize + trk->cluster[i].size < (1<<20)){
  2243. chunkSize += trk->cluster[i].size;
  2244. chunk->samples_in_chunk += trk->cluster[i].entries;
  2245. } else {
  2246. trk->cluster[i].chunkNum = chunk->chunkNum+1;
  2247. chunk=&trk->cluster[i];
  2248. chunkSize = chunk->size;
  2249. trk->chunkCount++;
  2250. }
  2251. }
  2252. }
  2253. static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
  2254. AVFormatContext *s)
  2255. {
  2256. int i;
  2257. int64_t pos = avio_tell(pb);
  2258. avio_wb32(pb, 0); /* size placeholder*/
  2259. ffio_wfourcc(pb, "moov");
  2260. for (i = 0; i < mov->nb_streams; i++) {
  2261. if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
  2262. continue;
  2263. mov->tracks[i].time = mov->time;
  2264. mov->tracks[i].track_id = i + 1;
  2265. if (mov->tracks[i].entry)
  2266. build_chunks(&mov->tracks[i]);
  2267. }
  2268. if (mov->chapter_track)
  2269. for (i = 0; i < s->nb_streams; i++) {
  2270. mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
  2271. mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
  2272. }
  2273. for (i = 0; i < mov->nb_streams; i++) {
  2274. if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) {
  2275. mov->tracks[i].tref_tag = MKTAG('h','i','n','t');
  2276. mov->tracks[i].tref_id =
  2277. mov->tracks[mov->tracks[i].src_track].track_id;
  2278. }
  2279. }
  2280. for (i = 0; i < mov->nb_streams; i++) {
  2281. if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
  2282. int src_trk = mov->tracks[i].src_track;
  2283. mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
  2284. mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
  2285. //src_trk may have a different timescale than the tmcd track
  2286. mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
  2287. mov->tracks[i].timescale,
  2288. mov->tracks[src_trk].timescale);
  2289. }
  2290. }
  2291. mov_write_mvhd_tag(pb, mov);
  2292. if (mov->mode != MODE_MOV && !mov->iods_skip)
  2293. mov_write_iods_tag(pb, mov);
  2294. for (i = 0; i < mov->nb_streams; i++) {
  2295. if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
  2296. mov_write_trak_tag(pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
  2297. }
  2298. }
  2299. if (mov->flags & FF_MOV_FLAG_FRAGMENT)
  2300. mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
  2301. if (mov->mode == MODE_PSP)
  2302. mov_write_uuidusmt_tag(pb, s);
  2303. else
  2304. mov_write_udta_tag(pb, mov, s);
  2305. return update_size(pb, pos);
  2306. }
  2307. static void param_write_int(AVIOContext *pb, const char *name, int value)
  2308. {
  2309. avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
  2310. }
  2311. static void param_write_string(AVIOContext *pb, const char *name, const char *value)
  2312. {
  2313. avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
  2314. }
  2315. static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
  2316. {
  2317. char buf[150];
  2318. len = FFMIN(sizeof(buf) / 2 - 1, len);
  2319. ff_data_to_hex(buf, value, len, 0);
  2320. buf[2 * len] = '\0';
  2321. avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
  2322. }
  2323. static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov)
  2324. {
  2325. int64_t pos = avio_tell(pb);
  2326. int i;
  2327. static const uint8_t uuid[] = {
  2328. 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
  2329. 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
  2330. };
  2331. avio_wb32(pb, 0);
  2332. ffio_wfourcc(pb, "uuid");
  2333. avio_write(pb, uuid, sizeof(uuid));
  2334. avio_wb32(pb, 0);
  2335. avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
  2336. avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
  2337. avio_printf(pb, "<head>\n");
  2338. if (!mov->exact)
  2339. avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
  2340. LIBAVFORMAT_IDENT);
  2341. avio_printf(pb, "</head>\n");
  2342. avio_printf(pb, "<body>\n");
  2343. avio_printf(pb, "<switch>\n");
  2344. for (i = 0; i < mov->nb_streams; i++) {
  2345. MOVTrack *track = &mov->tracks[i];
  2346. const char *type;
  2347. /* track->track_id is initialized in write_moov, and thus isn't known
  2348. * here yet */
  2349. int track_id = i + 1;
  2350. if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  2351. type = "video";
  2352. } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
  2353. type = "audio";
  2354. } else {
  2355. continue;
  2356. }
  2357. avio_printf(pb, "<%s systemBitrate=\"%d\">\n", type,
  2358. track->enc->bit_rate);
  2359. param_write_int(pb, "systemBitrate", track->enc->bit_rate);
  2360. param_write_int(pb, "trackID", track_id);
  2361. if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  2362. if (track->enc->codec_id == AV_CODEC_ID_H264) {
  2363. uint8_t *ptr;
  2364. int size = track->enc->extradata_size;
  2365. if (!ff_avc_write_annexb_extradata(track->enc->extradata, &ptr,
  2366. &size)) {
  2367. param_write_hex(pb, "CodecPrivateData",
  2368. ptr ? ptr : track->enc->extradata,
  2369. size);
  2370. av_free(ptr);
  2371. }
  2372. param_write_string(pb, "FourCC", "H264");
  2373. } else if (track->enc->codec_id == AV_CODEC_ID_VC1) {
  2374. param_write_string(pb, "FourCC", "WVC1");
  2375. param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
  2376. track->enc->extradata_size);
  2377. }
  2378. param_write_int(pb, "MaxWidth", track->enc->width);
  2379. param_write_int(pb, "MaxHeight", track->enc->height);
  2380. param_write_int(pb, "DisplayWidth", track->enc->width);
  2381. param_write_int(pb, "DisplayHeight", track->enc->height);
  2382. } else {
  2383. if (track->enc->codec_id == AV_CODEC_ID_AAC) {
  2384. param_write_string(pb, "FourCC", "AACL");
  2385. } else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO) {
  2386. param_write_string(pb, "FourCC", "WMAP");
  2387. }
  2388. param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
  2389. track->enc->extradata_size);
  2390. param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
  2391. track->enc->codec_id));
  2392. param_write_int(pb, "Channels", track->enc->channels);
  2393. param_write_int(pb, "SamplingRate", track->enc->sample_rate);
  2394. param_write_int(pb, "BitsPerSample", 16);
  2395. param_write_int(pb, "PacketSize", track->enc->block_align ?
  2396. track->enc->block_align : 4);
  2397. }
  2398. avio_printf(pb, "</%s>\n", type);
  2399. }
  2400. avio_printf(pb, "</switch>\n");
  2401. avio_printf(pb, "</body>\n");
  2402. avio_printf(pb, "</smil>\n");
  2403. return update_size(pb, pos);
  2404. }
  2405. static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
  2406. {
  2407. avio_wb32(pb, 16);
  2408. ffio_wfourcc(pb, "mfhd");
  2409. avio_wb32(pb, 0);
  2410. avio_wb32(pb, mov->fragments);
  2411. return 0;
  2412. }
  2413. static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
  2414. MOVTrack *track, int64_t moof_offset)
  2415. {
  2416. int64_t pos = avio_tell(pb);
  2417. uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
  2418. MOV_TFHD_BASE_DATA_OFFSET;
  2419. if (!track->entry) {
  2420. flags |= MOV_TFHD_DURATION_IS_EMPTY;
  2421. } else {
  2422. flags |= MOV_TFHD_DEFAULT_FLAGS;
  2423. }
  2424. if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
  2425. flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
  2426. /* Don't set a default sample size, the silverlight player refuses
  2427. * to play files with that set. Don't set a default sample duration,
  2428. * WMP freaks out if it is set. Don't set a base data offset, PIFF
  2429. * file format says it MUST NOT be set. */
  2430. if (track->mode == MODE_ISM)
  2431. flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
  2432. MOV_TFHD_BASE_DATA_OFFSET);
  2433. avio_wb32(pb, 0); /* size placeholder */
  2434. ffio_wfourcc(pb, "tfhd");
  2435. avio_w8(pb, 0); /* version */
  2436. avio_wb24(pb, flags);
  2437. avio_wb32(pb, track->track_id); /* track-id */
  2438. if (flags & MOV_TFHD_BASE_DATA_OFFSET)
  2439. avio_wb64(pb, moof_offset);
  2440. if (flags & MOV_TFHD_DEFAULT_DURATION) {
  2441. track->default_duration = get_cluster_duration(track, 0);
  2442. avio_wb32(pb, track->default_duration);
  2443. }
  2444. if (flags & MOV_TFHD_DEFAULT_SIZE) {
  2445. track->default_size = track->entry ? track->cluster[0].size : 1;
  2446. avio_wb32(pb, track->default_size);
  2447. } else
  2448. track->default_size = -1;
  2449. if (flags & MOV_TFHD_DEFAULT_FLAGS) {
  2450. track->default_sample_flags =
  2451. track->enc->codec_type == AVMEDIA_TYPE_VIDEO ?
  2452. (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
  2453. MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
  2454. avio_wb32(pb, track->default_sample_flags);
  2455. }
  2456. return update_size(pb, pos);
  2457. }
  2458. static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
  2459. {
  2460. return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
  2461. (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
  2462. }
  2463. static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
  2464. MOVTrack *track, int moof_size)
  2465. {
  2466. int64_t pos = avio_tell(pb);
  2467. uint32_t flags = MOV_TRUN_DATA_OFFSET;
  2468. int i;
  2469. for (i = 0; i < track->entry; i++) {
  2470. if (get_cluster_duration(track, i) != track->default_duration)
  2471. flags |= MOV_TRUN_SAMPLE_DURATION;
  2472. if (track->cluster[i].size != track->default_size)
  2473. flags |= MOV_TRUN_SAMPLE_SIZE;
  2474. if (i > 0 && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
  2475. flags |= MOV_TRUN_SAMPLE_FLAGS;
  2476. }
  2477. if (!(flags & MOV_TRUN_SAMPLE_FLAGS))
  2478. flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
  2479. if (track->flags & MOV_TRACK_CTTS)
  2480. flags |= MOV_TRUN_SAMPLE_CTS;
  2481. avio_wb32(pb, 0); /* size placeholder */
  2482. ffio_wfourcc(pb, "trun");
  2483. avio_w8(pb, 0); /* version */
  2484. avio_wb24(pb, flags);
  2485. avio_wb32(pb, track->entry); /* sample count */
  2486. if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
  2487. !(mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) &&
  2488. track->track_id != 1)
  2489. avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
  2490. else
  2491. avio_wb32(pb, moof_size + 8 + track->data_offset +
  2492. track->cluster[0].pos); /* data offset */
  2493. if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
  2494. avio_wb32(pb, get_sample_flags(track, &track->cluster[0]));
  2495. for (i = 0; i < track->entry; i++) {
  2496. if (flags & MOV_TRUN_SAMPLE_DURATION)
  2497. avio_wb32(pb, get_cluster_duration(track, i));
  2498. if (flags & MOV_TRUN_SAMPLE_SIZE)
  2499. avio_wb32(pb, track->cluster[i].size);
  2500. if (flags & MOV_TRUN_SAMPLE_FLAGS)
  2501. avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
  2502. if (flags & MOV_TRUN_SAMPLE_CTS)
  2503. avio_wb32(pb, track->cluster[i].cts);
  2504. }
  2505. return update_size(pb, pos);
  2506. }
  2507. static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
  2508. {
  2509. int64_t pos = avio_tell(pb);
  2510. static const uint8_t uuid[] = {
  2511. 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
  2512. 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
  2513. };
  2514. avio_wb32(pb, 0); /* size placeholder */
  2515. ffio_wfourcc(pb, "uuid");
  2516. avio_write(pb, uuid, sizeof(uuid));
  2517. avio_w8(pb, 1);
  2518. avio_wb24(pb, 0);
  2519. avio_wb64(pb, track->frag_start);
  2520. avio_wb64(pb, track->start_dts + track->track_duration -
  2521. track->cluster[0].dts);
  2522. return update_size(pb, pos);
  2523. }
  2524. static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
  2525. MOVTrack *track, int entry)
  2526. {
  2527. int n = track->nb_frag_info - 1 - entry, i;
  2528. int size = 8 + 16 + 4 + 1 + 16*n;
  2529. static const uint8_t uuid[] = {
  2530. 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
  2531. 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
  2532. };
  2533. if (entry < 0)
  2534. return 0;
  2535. avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
  2536. avio_wb32(pb, size);
  2537. ffio_wfourcc(pb, "uuid");
  2538. avio_write(pb, uuid, sizeof(uuid));
  2539. avio_w8(pb, 1);
  2540. avio_wb24(pb, 0);
  2541. avio_w8(pb, n);
  2542. for (i = 0; i < n; i++) {
  2543. int index = entry + 1 + i;
  2544. avio_wb64(pb, track->frag_info[index].time);
  2545. avio_wb64(pb, track->frag_info[index].duration);
  2546. }
  2547. if (n < mov->ism_lookahead) {
  2548. int free_size = 16 * (mov->ism_lookahead - n);
  2549. avio_wb32(pb, free_size);
  2550. ffio_wfourcc(pb, "free");
  2551. ffio_fill(pb, 0, free_size - 8);
  2552. }
  2553. return 0;
  2554. }
  2555. static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
  2556. MOVTrack *track)
  2557. {
  2558. int64_t pos = avio_tell(pb);
  2559. int i;
  2560. for (i = 0; i < mov->ism_lookahead; i++) {
  2561. /* Update the tfrf tag for the last ism_lookahead fragments,
  2562. * nb_frag_info - 1 is the next fragment to be written. */
  2563. mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
  2564. }
  2565. avio_seek(pb, pos, SEEK_SET);
  2566. return 0;
  2567. }
  2568. static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
  2569. MOVTrack *track, int64_t moof_offset,
  2570. int moof_size)
  2571. {
  2572. int64_t pos = avio_tell(pb);
  2573. avio_wb32(pb, 0); /* size placeholder */
  2574. ffio_wfourcc(pb, "traf");
  2575. mov_write_tfhd_tag(pb, mov, track, moof_offset);
  2576. mov_write_trun_tag(pb, mov, track, moof_size);
  2577. if (mov->mode == MODE_ISM) {
  2578. mov_write_tfxd_tag(pb, track);
  2579. if (mov->ism_lookahead) {
  2580. int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
  2581. track->tfrf_offset = avio_tell(pb);
  2582. avio_wb32(pb, 8 + size);
  2583. ffio_wfourcc(pb, "free");
  2584. for (i = 0; i < size; i++)
  2585. avio_w8(pb, 0);
  2586. }
  2587. }
  2588. return update_size(pb, pos);
  2589. }
  2590. static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
  2591. int tracks, int moof_size)
  2592. {
  2593. int64_t pos = avio_tell(pb);
  2594. int i;
  2595. avio_wb32(pb, 0); /* size placeholder */
  2596. ffio_wfourcc(pb, "moof");
  2597. mov_write_mfhd_tag(pb, mov);
  2598. for (i = 0; i < mov->nb_streams; i++) {
  2599. MOVTrack *track = &mov->tracks[i];
  2600. if (tracks >= 0 && i != tracks)
  2601. continue;
  2602. if (!track->entry)
  2603. continue;
  2604. mov_write_traf_tag(pb, mov, track, pos, moof_size);
  2605. }
  2606. return update_size(pb, pos);
  2607. }
  2608. static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
  2609. {
  2610. AVIOContext *avio_buf;
  2611. int ret, moof_size;
  2612. if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
  2613. return ret;
  2614. mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
  2615. moof_size = ffio_close_null_buf(avio_buf);
  2616. return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
  2617. }
  2618. static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
  2619. {
  2620. int64_t pos = avio_tell(pb);
  2621. int i;
  2622. avio_wb32(pb, 0); /* size placeholder */
  2623. ffio_wfourcc(pb, "tfra");
  2624. avio_w8(pb, 1); /* version */
  2625. avio_wb24(pb, 0);
  2626. avio_wb32(pb, track->track_id);
  2627. avio_wb32(pb, 0); /* length of traf/trun/sample num */
  2628. avio_wb32(pb, track->nb_frag_info);
  2629. for (i = 0; i < track->nb_frag_info; i++) {
  2630. avio_wb64(pb, track->frag_info[i].time);
  2631. avio_wb64(pb, track->frag_info[i].offset);
  2632. avio_w8(pb, 1); /* traf number */
  2633. avio_w8(pb, 1); /* trun number */
  2634. avio_w8(pb, 1); /* sample number */
  2635. }
  2636. return update_size(pb, pos);
  2637. }
  2638. static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
  2639. {
  2640. int64_t pos = avio_tell(pb);
  2641. int i;
  2642. avio_wb32(pb, 0); /* size placeholder */
  2643. ffio_wfourcc(pb, "mfra");
  2644. /* An empty mfra atom is enough to indicate to the publishing point that
  2645. * the stream has ended. */
  2646. if (mov->flags & FF_MOV_FLAG_ISML)
  2647. return update_size(pb, pos);
  2648. for (i = 0; i < mov->nb_streams; i++) {
  2649. MOVTrack *track = &mov->tracks[i];
  2650. if (track->nb_frag_info)
  2651. mov_write_tfra_tag(pb, track);
  2652. }
  2653. avio_wb32(pb, 16);
  2654. ffio_wfourcc(pb, "mfro");
  2655. avio_wb32(pb, 0); /* version + flags */
  2656. avio_wb32(pb, avio_tell(pb) + 4 - pos);
  2657. return update_size(pb, pos);
  2658. }
  2659. static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
  2660. {
  2661. avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
  2662. ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
  2663. mov->mdat_pos = avio_tell(pb);
  2664. avio_wb32(pb, 0); /* size placeholder*/
  2665. ffio_wfourcc(pb, "mdat");
  2666. return 0;
  2667. }
  2668. /* TODO: This needs to be more general */
  2669. static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
  2670. {
  2671. MOVMuxContext *mov = s->priv_data;
  2672. int64_t pos = avio_tell(pb);
  2673. int has_h264 = 0, has_video = 0;
  2674. int minor = 0x200;
  2675. int i;
  2676. for (i = 0; i < s->nb_streams; i++) {
  2677. AVStream *st = s->streams[i];
  2678. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  2679. has_video = 1;
  2680. if (st->codec->codec_id == AV_CODEC_ID_H264)
  2681. has_h264 = 1;
  2682. }
  2683. avio_wb32(pb, 0); /* size */
  2684. ffio_wfourcc(pb, "ftyp");
  2685. if (mov->major_brand && strlen(mov->major_brand) >= 4)
  2686. ffio_wfourcc(pb, mov->major_brand);
  2687. else if (mov->mode == MODE_3GP) {
  2688. ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
  2689. minor = has_h264 ? 0x100 : 0x200;
  2690. } else if (mov->mode & MODE_3G2) {
  2691. ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
  2692. minor = has_h264 ? 0x20000 : 0x10000;
  2693. } else if (mov->mode == MODE_PSP)
  2694. ffio_wfourcc(pb, "MSNV");
  2695. else if (mov->mode == MODE_MP4)
  2696. ffio_wfourcc(pb, "isom");
  2697. else if (mov->mode == MODE_IPOD)
  2698. ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
  2699. else if (mov->mode == MODE_ISM)
  2700. ffio_wfourcc(pb, "isml");
  2701. else if (mov->mode == MODE_F4V)
  2702. ffio_wfourcc(pb, "f4v ");
  2703. else
  2704. ffio_wfourcc(pb, "qt ");
  2705. avio_wb32(pb, minor);
  2706. if (mov->mode == MODE_MOV)
  2707. ffio_wfourcc(pb, "qt ");
  2708. else if (mov->mode == MODE_ISM) {
  2709. ffio_wfourcc(pb, "piff");
  2710. ffio_wfourcc(pb, "iso2");
  2711. } else {
  2712. ffio_wfourcc(pb, "isom");
  2713. ffio_wfourcc(pb, "iso2");
  2714. if (has_h264)
  2715. ffio_wfourcc(pb, "avc1");
  2716. }
  2717. if (mov->mode == MODE_3GP)
  2718. ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
  2719. else if (mov->mode & MODE_3G2)
  2720. ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
  2721. else if (mov->mode == MODE_PSP)
  2722. ffio_wfourcc(pb, "MSNV");
  2723. else if (mov->mode == MODE_MP4)
  2724. ffio_wfourcc(pb, "mp41");
  2725. return update_size(pb, pos);
  2726. }
  2727. static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
  2728. {
  2729. AVCodecContext *video_codec = s->streams[0]->codec;
  2730. AVCodecContext *audio_codec = s->streams[1]->codec;
  2731. int audio_rate = audio_codec->sample_rate;
  2732. int frame_rate = ((video_codec->time_base.den) * (0x10000)) / (video_codec->time_base.num);
  2733. int audio_kbitrate = audio_codec->bit_rate / 1000;
  2734. int video_kbitrate = FFMIN(video_codec->bit_rate / 1000, 800 - audio_kbitrate);
  2735. avio_wb32(pb, 0x94); /* size */
  2736. ffio_wfourcc(pb, "uuid");
  2737. ffio_wfourcc(pb, "PROF");
  2738. avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
  2739. avio_wb32(pb, 0xbb88695c);
  2740. avio_wb32(pb, 0xfac9c740);
  2741. avio_wb32(pb, 0x0); /* ? */
  2742. avio_wb32(pb, 0x3); /* 3 sections ? */
  2743. avio_wb32(pb, 0x14); /* size */
  2744. ffio_wfourcc(pb, "FPRF");
  2745. avio_wb32(pb, 0x0); /* ? */
  2746. avio_wb32(pb, 0x0); /* ? */
  2747. avio_wb32(pb, 0x0); /* ? */
  2748. avio_wb32(pb, 0x2c); /* size */
  2749. ffio_wfourcc(pb, "APRF"); /* audio */
  2750. avio_wb32(pb, 0x0);
  2751. avio_wb32(pb, 0x2); /* TrackID */
  2752. ffio_wfourcc(pb, "mp4a");
  2753. avio_wb32(pb, 0x20f);
  2754. avio_wb32(pb, 0x0);
  2755. avio_wb32(pb, audio_kbitrate);
  2756. avio_wb32(pb, audio_kbitrate);
  2757. avio_wb32(pb, audio_rate);
  2758. avio_wb32(pb, audio_codec->channels);
  2759. avio_wb32(pb, 0x34); /* size */
  2760. ffio_wfourcc(pb, "VPRF"); /* video */
  2761. avio_wb32(pb, 0x0);
  2762. avio_wb32(pb, 0x1); /* TrackID */
  2763. if (video_codec->codec_id == AV_CODEC_ID_H264) {
  2764. ffio_wfourcc(pb, "avc1");
  2765. avio_wb16(pb, 0x014D);
  2766. avio_wb16(pb, 0x0015);
  2767. } else {
  2768. ffio_wfourcc(pb, "mp4v");
  2769. avio_wb16(pb, 0x0000);
  2770. avio_wb16(pb, 0x0103);
  2771. }
  2772. avio_wb32(pb, 0x0);
  2773. avio_wb32(pb, video_kbitrate);
  2774. avio_wb32(pb, video_kbitrate);
  2775. avio_wb32(pb, frame_rate);
  2776. avio_wb32(pb, frame_rate);
  2777. avio_wb16(pb, video_codec->width);
  2778. avio_wb16(pb, video_codec->height);
  2779. avio_wb32(pb, 0x010001); /* ? */
  2780. }
  2781. static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
  2782. {
  2783. uint32_t c = -1;
  2784. int i, closed_gop = 0;
  2785. for (i = 0; i < pkt->size - 4; i++) {
  2786. c = (c << 8) + pkt->data[i];
  2787. if (c == 0x1b8) { // gop
  2788. closed_gop = pkt->data[i + 4] >> 6 & 0x01;
  2789. } else if (c == 0x100) { // pic
  2790. int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
  2791. if (!temp_ref || closed_gop) // I picture is not reordered
  2792. *flags = MOV_SYNC_SAMPLE;
  2793. else
  2794. *flags = MOV_PARTIAL_SYNC_SAMPLE;
  2795. break;
  2796. }
  2797. }
  2798. return 0;
  2799. }
  2800. static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk, int fragment)
  2801. {
  2802. const uint8_t *start, *next, *end = pkt->data + pkt->size;
  2803. int seq = 0, entry = 0;
  2804. int key = pkt->flags & AV_PKT_FLAG_KEY;
  2805. start = find_next_marker(pkt->data, end);
  2806. for (next = start; next < end; start = next) {
  2807. next = find_next_marker(start + 4, end);
  2808. switch (AV_RB32(start)) {
  2809. case VC1_CODE_SEQHDR:
  2810. seq = 1;
  2811. break;
  2812. case VC1_CODE_ENTRYPOINT:
  2813. entry = 1;
  2814. break;
  2815. case VC1_CODE_SLICE:
  2816. trk->vc1_info.slices = 1;
  2817. break;
  2818. }
  2819. }
  2820. if (!trk->entry && !fragment) {
  2821. /* First packet in first fragment */
  2822. trk->vc1_info.first_packet_seq = seq;
  2823. trk->vc1_info.first_packet_entry = entry;
  2824. } else if ((seq && !trk->vc1_info.packet_seq) ||
  2825. (entry && !trk->vc1_info.packet_entry)) {
  2826. int i;
  2827. for (i = 0; i < trk->entry; i++)
  2828. trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
  2829. trk->has_keyframes = 0;
  2830. if (seq)
  2831. trk->vc1_info.packet_seq = 1;
  2832. if (entry)
  2833. trk->vc1_info.packet_entry = 1;
  2834. if (!fragment) {
  2835. /* First fragment */
  2836. if ((!seq || trk->vc1_info.first_packet_seq) &&
  2837. (!entry || trk->vc1_info.first_packet_entry)) {
  2838. /* First packet had the same headers as this one, readd the
  2839. * sync sample flag. */
  2840. trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
  2841. trk->has_keyframes = 1;
  2842. }
  2843. }
  2844. }
  2845. if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
  2846. key = seq && entry;
  2847. else if (trk->vc1_info.packet_seq)
  2848. key = seq;
  2849. else if (trk->vc1_info.packet_entry)
  2850. key = entry;
  2851. if (key) {
  2852. trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
  2853. trk->has_keyframes++;
  2854. }
  2855. }
  2856. static int mov_flush_fragment(AVFormatContext *s)
  2857. {
  2858. MOVMuxContext *mov = s->priv_data;
  2859. int i, first_track = -1;
  2860. int64_t mdat_size = 0;
  2861. if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
  2862. return 0;
  2863. if (!(mov->flags & FF_MOV_FLAG_EMPTY_MOOV) && mov->fragments == 0) {
  2864. int64_t pos = avio_tell(s->pb);
  2865. uint8_t *buf;
  2866. int buf_size, moov_size;
  2867. for (i = 0; i < mov->nb_streams; i++)
  2868. if (!mov->tracks[i].entry)
  2869. break;
  2870. /* Don't write the initial moov unless all tracks have data */
  2871. if (i < mov->nb_streams)
  2872. return 0;
  2873. moov_size = get_moov_size(s);
  2874. for (i = 0; i < mov->nb_streams; i++)
  2875. mov->tracks[i].data_offset = pos + moov_size + 8;
  2876. mov_write_moov_tag(s->pb, mov, s);
  2877. buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
  2878. mov->mdat_buf = NULL;
  2879. avio_wb32(s->pb, buf_size + 8);
  2880. ffio_wfourcc(s->pb, "mdat");
  2881. avio_write(s->pb, buf, buf_size);
  2882. av_free(buf);
  2883. mov->fragments++;
  2884. mov->mdat_size = 0;
  2885. for (i = 0; i < mov->nb_streams; i++) {
  2886. if (mov->tracks[i].entry)
  2887. mov->tracks[i].frag_start += mov->tracks[i].start_dts +
  2888. mov->tracks[i].track_duration -
  2889. mov->tracks[i].cluster[0].dts;
  2890. mov->tracks[i].entry = 0;
  2891. }
  2892. avio_flush(s->pb);
  2893. return 0;
  2894. }
  2895. for (i = 0; i < mov->nb_streams; i++) {
  2896. MOVTrack *track = &mov->tracks[i];
  2897. if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF)
  2898. track->data_offset = 0;
  2899. else
  2900. track->data_offset = mdat_size;
  2901. if (!track->mdat_buf)
  2902. continue;
  2903. mdat_size += avio_tell(track->mdat_buf);
  2904. if (first_track < 0)
  2905. first_track = i;
  2906. }
  2907. if (!mdat_size)
  2908. return 0;
  2909. for (i = 0; i < mov->nb_streams; i++) {
  2910. MOVTrack *track = &mov->tracks[i];
  2911. int buf_size, write_moof = 1, moof_tracks = -1;
  2912. uint8_t *buf;
  2913. int64_t duration = 0;
  2914. if (track->entry)
  2915. duration = track->start_dts + track->track_duration -
  2916. track->cluster[0].dts;
  2917. if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
  2918. if (!track->mdat_buf)
  2919. continue;
  2920. mdat_size = avio_tell(track->mdat_buf);
  2921. moof_tracks = i;
  2922. } else {
  2923. write_moof = i == first_track;
  2924. }
  2925. if (write_moof) {
  2926. MOVFragmentInfo *info;
  2927. avio_flush(s->pb);
  2928. track->nb_frag_info++;
  2929. if (track->nb_frag_info >= track->frag_info_capacity) {
  2930. unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
  2931. if (av_reallocp_array(&track->frag_info,
  2932. new_capacity,
  2933. sizeof(*track->frag_info)))
  2934. return AVERROR(ENOMEM);
  2935. track->frag_info_capacity = new_capacity;
  2936. }
  2937. info = &track->frag_info[track->nb_frag_info - 1];
  2938. info->offset = avio_tell(s->pb);
  2939. info->time = mov->tracks[i].frag_start;
  2940. info->duration = duration;
  2941. mov_write_tfrf_tags(s->pb, mov, track);
  2942. mov_write_moof_tag(s->pb, mov, moof_tracks);
  2943. info->tfrf_offset = track->tfrf_offset;
  2944. mov->fragments++;
  2945. avio_wb32(s->pb, mdat_size + 8);
  2946. ffio_wfourcc(s->pb, "mdat");
  2947. }
  2948. if (track->entry)
  2949. track->frag_start += duration;
  2950. track->entry = 0;
  2951. if (!track->mdat_buf)
  2952. continue;
  2953. buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
  2954. track->mdat_buf = NULL;
  2955. avio_write(s->pb, buf, buf_size);
  2956. av_free(buf);
  2957. }
  2958. mov->mdat_size = 0;
  2959. avio_flush(s->pb);
  2960. return 0;
  2961. }
  2962. int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
  2963. {
  2964. MOVMuxContext *mov = s->priv_data;
  2965. AVIOContext *pb = s->pb;
  2966. MOVTrack *trk = &mov->tracks[pkt->stream_index];
  2967. AVCodecContext *enc = trk->enc;
  2968. unsigned int samples_in_chunk = 0;
  2969. int size = pkt->size;
  2970. uint8_t *reformatted_data = NULL;
  2971. if (trk->entry) {
  2972. int64_t duration = pkt->dts - trk->cluster[trk->entry - 1].dts;
  2973. if (duration < 0 || duration > INT_MAX) {
  2974. av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
  2975. duration, pkt->dts
  2976. );
  2977. pkt->dts = trk->cluster[trk->entry - 1].dts + 1;
  2978. pkt->pts = AV_NOPTS_VALUE;
  2979. }
  2980. if (pkt->duration < 0) {
  2981. av_log(s, AV_LOG_ERROR, "Application provided duration: %d is invalid\n", pkt->duration);
  2982. return AVERROR(EINVAL);
  2983. }
  2984. }
  2985. if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
  2986. int ret;
  2987. if (mov->fragments > 0) {
  2988. if (!trk->mdat_buf) {
  2989. if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
  2990. return ret;
  2991. }
  2992. pb = trk->mdat_buf;
  2993. } else {
  2994. if (!mov->mdat_buf) {
  2995. if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
  2996. return ret;
  2997. }
  2998. pb = mov->mdat_buf;
  2999. }
  3000. }
  3001. if (enc->codec_id == AV_CODEC_ID_AMR_NB) {
  3002. /* We must find out how many AMR blocks there are in one packet */
  3003. static uint16_t packed_size[16] =
  3004. {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
  3005. int len = 0;
  3006. while (len < size && samples_in_chunk < 100) {
  3007. len += packed_size[(pkt->data[len] >> 3) & 0x0F];
  3008. samples_in_chunk++;
  3009. }
  3010. if (samples_in_chunk > 1) {
  3011. av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
  3012. return -1;
  3013. }
  3014. } else if (enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
  3015. enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
  3016. samples_in_chunk = enc->frame_size;
  3017. } else if (trk->sample_size)
  3018. samples_in_chunk = size / trk->sample_size;
  3019. else
  3020. samples_in_chunk = 1;
  3021. /* copy extradata if it exists */
  3022. if (trk->vos_len == 0 && enc->extradata_size > 0) {
  3023. trk->vos_len = enc->extradata_size;
  3024. trk->vos_data = av_malloc(trk->vos_len);
  3025. memcpy(trk->vos_data, enc->extradata, trk->vos_len);
  3026. }
  3027. if (enc->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
  3028. (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
  3029. if (!s->streams[pkt->stream_index]->nb_frames) {
  3030. av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
  3031. "use audio bitstream filter 'aac_adtstoasc' to fix it "
  3032. "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
  3033. return -1;
  3034. }
  3035. av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
  3036. }
  3037. if (enc->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1) {
  3038. /* from x264 or from bytestream h264 */
  3039. /* nal reformating needed */
  3040. if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
  3041. ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
  3042. &size);
  3043. avio_write(pb, reformatted_data, size);
  3044. } else {
  3045. size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
  3046. }
  3047. } else if (enc->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
  3048. (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
  3049. /* extradata is Annex B, assume the bitstream is too and convert it */
  3050. if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
  3051. ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
  3052. avio_write(pb, reformatted_data, size);
  3053. } else {
  3054. size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
  3055. }
  3056. } else {
  3057. avio_write(pb, pkt->data, size);
  3058. }
  3059. if ((enc->codec_id == AV_CODEC_ID_DNXHD ||
  3060. enc->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
  3061. /* copy frame to create needed atoms */
  3062. trk->vos_len = size;
  3063. trk->vos_data = av_malloc(size);
  3064. if (!trk->vos_data)
  3065. return AVERROR(ENOMEM);
  3066. memcpy(trk->vos_data, pkt->data, size);
  3067. }
  3068. if (trk->entry >= trk->cluster_capacity) {
  3069. unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
  3070. if (av_reallocp_array(&trk->cluster, new_capacity,
  3071. sizeof(*trk->cluster)))
  3072. return AVERROR(ENOMEM);
  3073. trk->cluster_capacity = new_capacity;
  3074. }
  3075. trk->cluster[trk->entry].pos = avio_tell(pb) - size;
  3076. trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
  3077. trk->cluster[trk->entry].chunkNum = 0;
  3078. trk->cluster[trk->entry].size = size;
  3079. trk->cluster[trk->entry].entries = samples_in_chunk;
  3080. trk->cluster[trk->entry].dts = pkt->dts;
  3081. if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
  3082. /* First packet of a new fragment. We already wrote the duration
  3083. * of the last packet of the previous fragment based on track_duration,
  3084. * which might not exactly match our dts. Therefore adjust the dts
  3085. * of this packet to be what the previous packets duration implies. */
  3086. trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
  3087. }
  3088. if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !supports_edts(mov)) {
  3089. trk->cluster[trk->entry].dts = trk->start_dts = 0;
  3090. }
  3091. if (trk->start_dts == AV_NOPTS_VALUE)
  3092. trk->start_dts = pkt->dts;
  3093. trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
  3094. trk->last_sample_is_subtitle_end = 0;
  3095. if (pkt->pts == AV_NOPTS_VALUE) {
  3096. av_log(s, AV_LOG_WARNING, "pts has no value\n");
  3097. pkt->pts = pkt->dts;
  3098. }
  3099. if (pkt->dts != pkt->pts)
  3100. trk->flags |= MOV_TRACK_CTTS;
  3101. trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
  3102. trk->cluster[trk->entry].flags = 0;
  3103. if (enc->codec_id == AV_CODEC_ID_VC1) {
  3104. mov_parse_vc1_frame(pkt, trk, mov->fragments);
  3105. } else if (pkt->flags & AV_PKT_FLAG_KEY) {
  3106. if (mov->mode == MODE_MOV && enc->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
  3107. trk->entry > 0) { // force sync sample for the first key frame
  3108. mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
  3109. if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
  3110. trk->flags |= MOV_TRACK_STPS;
  3111. } else {
  3112. trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
  3113. }
  3114. if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
  3115. trk->has_keyframes++;
  3116. }
  3117. trk->entry++;
  3118. trk->sample_count += samples_in_chunk;
  3119. mov->mdat_size += size;
  3120. if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
  3121. ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
  3122. reformatted_data, size);
  3123. av_free(reformatted_data);
  3124. return 0;
  3125. }
  3126. static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
  3127. {
  3128. MOVMuxContext *mov = s->priv_data;
  3129. MOVTrack *trk = &mov->tracks[pkt->stream_index];
  3130. AVCodecContext *enc = trk->enc;
  3131. int64_t frag_duration = 0;
  3132. int size = pkt->size;
  3133. if (!pkt->size)
  3134. return 0; /* Discard 0 sized packets */
  3135. if (trk->entry && pkt->stream_index < s->nb_streams)
  3136. frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
  3137. s->streams[pkt->stream_index]->time_base,
  3138. AV_TIME_BASE_Q);
  3139. if ((mov->max_fragment_duration &&
  3140. frag_duration >= mov->max_fragment_duration) ||
  3141. (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
  3142. (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
  3143. enc->codec_type == AVMEDIA_TYPE_VIDEO &&
  3144. trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
  3145. if (frag_duration >= mov->min_fragment_duration)
  3146. mov_flush_fragment(s);
  3147. }
  3148. return ff_mov_write_packet(s, pkt);
  3149. }
  3150. static int mov_write_subtitle_end_packet(AVFormatContext *s,
  3151. int stream_index,
  3152. int64_t dts) {
  3153. AVPacket end;
  3154. uint8_t data[2] = {0};
  3155. int ret;
  3156. av_init_packet(&end);
  3157. end.size = sizeof(data);
  3158. end.data = data;
  3159. end.pts = dts;
  3160. end.dts = dts;
  3161. end.duration = 0;
  3162. end.stream_index = stream_index;
  3163. ret = mov_write_single_packet(s, &end);
  3164. av_free_packet(&end);
  3165. return ret;
  3166. }
  3167. static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
  3168. {
  3169. if (!pkt) {
  3170. mov_flush_fragment(s);
  3171. return 1;
  3172. } else {
  3173. int i;
  3174. MOVMuxContext *mov = s->priv_data;
  3175. if (!pkt->size) return 0; /* Discard 0 sized packets */
  3176. /*
  3177. * Subtitles require special handling.
  3178. *
  3179. * 1) For full complaince, every track must have a sample at
  3180. * dts == 0, which is rarely true for subtitles. So, as soon
  3181. * as we see any packet with dts > 0, write an empty subtitle
  3182. * at dts == 0 for any subtitle track with no samples in it.
  3183. *
  3184. * 2) For each subtitle track, check if the current packet's
  3185. * dts is past the duration of the last subtitle sample. If
  3186. * so, we now need to write an end sample for that subtitle.
  3187. *
  3188. * This must be done conditionally to allow for subtitles that
  3189. * immediately replace each other, in which case an end sample
  3190. * is not needed, and is, in fact, actively harmful.
  3191. *
  3192. * 3) See mov_write_trailer for how the final end sample is
  3193. * handled.
  3194. */
  3195. for (i = 0; i < mov->nb_streams; i++) {
  3196. MOVTrack *trk = &mov->tracks[i];
  3197. int ret;
  3198. if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
  3199. trk->track_duration < pkt->dts &&
  3200. (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
  3201. ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
  3202. if (ret < 0) return ret;
  3203. trk->last_sample_is_subtitle_end = 1;
  3204. }
  3205. }
  3206. return mov_write_single_packet(s, pkt);
  3207. }
  3208. }
  3209. // QuickTime chapters involve an additional text track with the chapter names
  3210. // as samples, and a tref pointing from the other tracks to the chapter one.
  3211. static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
  3212. {
  3213. AVIOContext *pb;
  3214. MOVMuxContext *mov = s->priv_data;
  3215. MOVTrack *track = &mov->tracks[tracknum];
  3216. AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
  3217. int i, len;
  3218. track->mode = mov->mode;
  3219. track->tag = MKTAG('t','e','x','t');
  3220. track->timescale = MOV_TIMESCALE;
  3221. track->enc = avcodec_alloc_context3(NULL);
  3222. if (!track->enc)
  3223. return AVERROR(ENOMEM);
  3224. track->enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
  3225. #if 0
  3226. // These properties are required to make QT recognize the chapter track
  3227. uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
  3228. if (ff_alloc_extradata(track->enc, sizeof(chapter_properties)))
  3229. return AVERROR(ENOMEM);
  3230. memcpy(track->enc->extradata, chapter_properties, sizeof(chapter_properties));
  3231. #else
  3232. if (avio_open_dyn_buf(&pb) >= 0) {
  3233. int size;
  3234. uint8_t *buf;
  3235. /* Stub header (usually for Quicktime chapter track) */
  3236. // TextSampleEntry
  3237. avio_wb32(pb, 0x01); // displayFlags
  3238. avio_w8(pb, 0x00); // horizontal justification
  3239. avio_w8(pb, 0x00); // vertical justification
  3240. avio_w8(pb, 0x00); // bgColourRed
  3241. avio_w8(pb, 0x00); // bgColourGreen
  3242. avio_w8(pb, 0x00); // bgColourBlue
  3243. avio_w8(pb, 0x00); // bgColourAlpha
  3244. // BoxRecord
  3245. avio_wb16(pb, 0x00); // defTextBoxTop
  3246. avio_wb16(pb, 0x00); // defTextBoxLeft
  3247. avio_wb16(pb, 0x00); // defTextBoxBottom
  3248. avio_wb16(pb, 0x00); // defTextBoxRight
  3249. // StyleRecord
  3250. avio_wb16(pb, 0x00); // startChar
  3251. avio_wb16(pb, 0x00); // endChar
  3252. avio_wb16(pb, 0x01); // fontID
  3253. avio_w8(pb, 0x00); // fontStyleFlags
  3254. avio_w8(pb, 0x00); // fontSize
  3255. avio_w8(pb, 0x00); // fgColourRed
  3256. avio_w8(pb, 0x00); // fgColourGreen
  3257. avio_w8(pb, 0x00); // fgColourBlue
  3258. avio_w8(pb, 0x00); // fgColourAlpha
  3259. // FontTableBox
  3260. avio_wb32(pb, 0x0D); // box size
  3261. ffio_wfourcc(pb, "ftab"); // box atom name
  3262. avio_wb16(pb, 0x01); // entry count
  3263. // FontRecord
  3264. avio_wb16(pb, 0x01); // font ID
  3265. avio_w8(pb, 0x00); // font name length
  3266. if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
  3267. track->enc->extradata = buf;
  3268. track->enc->extradata_size = size;
  3269. } else {
  3270. av_freep(&buf);
  3271. }
  3272. }
  3273. #endif
  3274. for (i = 0; i < s->nb_chapters; i++) {
  3275. AVChapter *c = s->chapters[i];
  3276. AVDictionaryEntry *t;
  3277. int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
  3278. pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
  3279. pkt.duration = end - pkt.dts;
  3280. if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
  3281. len = strlen(t->value);
  3282. pkt.size = len + 2;
  3283. pkt.data = av_malloc(pkt.size);
  3284. if (!pkt.data)
  3285. return AVERROR(ENOMEM);
  3286. AV_WB16(pkt.data, len);
  3287. memcpy(pkt.data + 2, t->value, len);
  3288. ff_mov_write_packet(s, &pkt);
  3289. av_freep(&pkt.data);
  3290. }
  3291. }
  3292. return 0;
  3293. }
  3294. static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, const char *tcstr)
  3295. {
  3296. int ret;
  3297. MOVMuxContext *mov = s->priv_data;
  3298. MOVTrack *track = &mov->tracks[index];
  3299. AVStream *src_st = s->streams[src_index];
  3300. AVTimecode tc;
  3301. AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
  3302. AVRational rate = find_fps(s, src_st);
  3303. /* compute the frame number */
  3304. ret = av_timecode_init_from_string(&tc, rate, tcstr, s);
  3305. if (ret < 0)
  3306. return ret;
  3307. /* tmcd track based on video stream */
  3308. track->mode = mov->mode;
  3309. track->tag = MKTAG('t','m','c','d');
  3310. track->src_track = src_index;
  3311. track->timescale = mov->tracks[src_index].timescale;
  3312. if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
  3313. track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
  3314. /* encode context: tmcd data stream */
  3315. track->enc = avcodec_alloc_context3(NULL);
  3316. track->enc->codec_type = AVMEDIA_TYPE_DATA;
  3317. track->enc->codec_tag = track->tag;
  3318. track->enc->time_base = av_inv_q(rate);
  3319. /* the tmcd track just contains one packet with the frame number */
  3320. pkt.data = av_malloc(pkt.size);
  3321. AV_WB32(pkt.data, tc.start);
  3322. ret = ff_mov_write_packet(s, &pkt);
  3323. av_free(pkt.data);
  3324. return ret;
  3325. }
  3326. /*
  3327. * st->disposition controls the "enabled" flag in the tkhd tag.
  3328. * QuickTime will not play a track if it is not enabled. So make sure
  3329. * that one track of each type (audio, video, subtitle) is enabled.
  3330. *
  3331. * Subtitles are special. For audio and video, setting "enabled" also
  3332. * makes the track "default" (i.e. it is rendered when played). For
  3333. * subtitles, an "enabled" subtitle is not rendered by default, but
  3334. * if no subtitle is enabled, the subtitle menu in QuickTime will be
  3335. * empty!
  3336. */
  3337. static void enable_tracks(AVFormatContext *s)
  3338. {
  3339. MOVMuxContext *mov = s->priv_data;
  3340. int i;
  3341. uint8_t enabled[AVMEDIA_TYPE_NB];
  3342. int first[AVMEDIA_TYPE_NB];
  3343. for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
  3344. enabled[i] = 0;
  3345. first[i] = -1;
  3346. }
  3347. for (i = 0; i < s->nb_streams; i++) {
  3348. AVStream *st = s->streams[i];
  3349. if (st->codec->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
  3350. st->codec->codec_type >= AVMEDIA_TYPE_NB)
  3351. continue;
  3352. if (first[st->codec->codec_type] < 0)
  3353. first[st->codec->codec_type] = i;
  3354. if (st->disposition & AV_DISPOSITION_DEFAULT) {
  3355. mov->tracks[i].flags |= MOV_TRACK_ENABLED;
  3356. enabled[st->codec->codec_type] = 1;
  3357. }
  3358. }
  3359. for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
  3360. switch (i) {
  3361. case AVMEDIA_TYPE_VIDEO:
  3362. case AVMEDIA_TYPE_AUDIO:
  3363. case AVMEDIA_TYPE_SUBTITLE:
  3364. if (!enabled[i] && first[i] >= 0)
  3365. mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
  3366. break;
  3367. }
  3368. }
  3369. }
  3370. static void mov_free(AVFormatContext *s)
  3371. {
  3372. MOVMuxContext *mov = s->priv_data;
  3373. int i;
  3374. if (mov->chapter_track) {
  3375. if (mov->tracks[mov->chapter_track].enc)
  3376. av_freep(&mov->tracks[mov->chapter_track].enc->extradata);
  3377. av_freep(&mov->tracks[mov->chapter_track].enc);
  3378. }
  3379. for (i = 0; i < mov->nb_streams; i++) {
  3380. if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
  3381. ff_mov_close_hinting(&mov->tracks[i]);
  3382. else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
  3383. av_freep(&mov->tracks[i].enc);
  3384. av_freep(&mov->tracks[i].cluster);
  3385. av_freep(&mov->tracks[i].frag_info);
  3386. if (mov->tracks[i].vos_len)
  3387. av_freep(&mov->tracks[i].vos_data);
  3388. }
  3389. av_freep(&mov->tracks);
  3390. }
  3391. static uint32_t rgb_to_yuv(uint32_t rgb)
  3392. {
  3393. uint8_t r, g, b;
  3394. int y, cb, cr;
  3395. r = (rgb >> 16) & 0xFF;
  3396. g = (rgb >> 8) & 0xFF;
  3397. b = (rgb ) & 0xFF;
  3398. y = av_clip_uint8( 16. + 0.257 * r + 0.504 * g + 0.098 * b);
  3399. cb = av_clip_uint8(128. - 0.148 * r - 0.291 * g + 0.439 * b);
  3400. cr = av_clip_uint8(128. + 0.439 * r - 0.368 * g - 0.071 * b);
  3401. return (y << 16) | (cr << 8) | cb;
  3402. }
  3403. static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
  3404. AVStream *st)
  3405. {
  3406. int i, width = 720, height = 480;
  3407. int have_palette = 0, have_size = 0;
  3408. uint32_t palette[16];
  3409. char *cur = st->codec->extradata;
  3410. while (cur && *cur) {
  3411. if (strncmp("palette:", cur, 8) == 0) {
  3412. int i, count;
  3413. count = sscanf(cur + 8,
  3414. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
  3415. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
  3416. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
  3417. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
  3418. &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
  3419. &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
  3420. &palette[ 8], &palette[ 9], &palette[10], &palette[11],
  3421. &palette[12], &palette[13], &palette[14], &palette[15]);
  3422. for (i = 0; i < count; i++) {
  3423. palette[i] = rgb_to_yuv(palette[i]);
  3424. }
  3425. have_palette = 1;
  3426. } else if (!strncmp("size:", cur, 5)) {
  3427. sscanf(cur + 5, "%dx%d", &width, &height);
  3428. have_size = 1;
  3429. }
  3430. if (have_palette && have_size)
  3431. break;
  3432. cur += strcspn(cur, "\n\r");
  3433. cur += strspn(cur, "\n\r");
  3434. }
  3435. if (have_palette) {
  3436. track->vos_data = av_malloc(16*4);
  3437. if (!track->vos_data)
  3438. return AVERROR(ENOMEM);
  3439. for (i = 0; i < 16; i++) {
  3440. AV_WB32(track->vos_data + i * 4, palette[i]);
  3441. }
  3442. track->vos_len = 16 * 4;
  3443. }
  3444. st->codec->width = width;
  3445. st->codec->height = track->height = height;
  3446. return 0;
  3447. }
  3448. static int mov_write_header(AVFormatContext *s)
  3449. {
  3450. AVIOContext *pb = s->pb;
  3451. MOVMuxContext *mov = s->priv_data;
  3452. AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
  3453. int i, ret, hint_track = 0, tmcd_track = 0;
  3454. /* Default mode == MP4 */
  3455. mov->mode = MODE_MP4;
  3456. if (s->oformat != NULL) {
  3457. if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
  3458. else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
  3459. else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
  3460. else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
  3461. else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
  3462. else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
  3463. else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
  3464. }
  3465. for (i = 0; i < s->nb_streams; i++)
  3466. if (s->flags & AVFMT_FLAG_BITEXACT)
  3467. mov->exact = 1;
  3468. /* Set the FRAGMENT flag if any of the fragmentation methods are
  3469. * enabled. */
  3470. if (mov->max_fragment_duration || mov->max_fragment_size ||
  3471. mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
  3472. FF_MOV_FLAG_FRAG_KEYFRAME |
  3473. FF_MOV_FLAG_FRAG_CUSTOM))
  3474. mov->flags |= FF_MOV_FLAG_FRAGMENT;
  3475. /* Set other implicit flags immediately */
  3476. if (mov->mode == MODE_ISM)
  3477. mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
  3478. FF_MOV_FLAG_FRAGMENT;
  3479. /* faststart: moov at the beginning of the file, if supported */
  3480. if (mov->flags & FF_MOV_FLAG_FASTSTART) {
  3481. if ((mov->flags & FF_MOV_FLAG_FRAGMENT) ||
  3482. (s->flags & AVFMT_FLAG_CUSTOM_IO)) {
  3483. av_log(s, AV_LOG_WARNING, "The faststart flag is incompatible "
  3484. "with fragmentation and custom IO, disabling faststart\n");
  3485. mov->flags &= ~FF_MOV_FLAG_FASTSTART;
  3486. } else
  3487. mov->reserved_moov_size = -1;
  3488. }
  3489. if (!supports_edts(mov) && s->avoid_negative_ts < 0) {
  3490. s->avoid_negative_ts = 2;
  3491. }
  3492. /* Non-seekable output is ok if using fragmentation. If ism_lookahead
  3493. * is enabled, we don't support non-seekable output at all. */
  3494. if (!s->pb->seekable &&
  3495. (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
  3496. av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
  3497. return AVERROR(EINVAL);
  3498. }
  3499. mov_write_ftyp_tag(pb,s);
  3500. if (mov->mode == MODE_PSP) {
  3501. int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
  3502. for (i = 0; i < s->nb_streams; i++) {
  3503. AVStream *st = s->streams[i];
  3504. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  3505. video_streams_nb++;
  3506. else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  3507. audio_streams_nb++;
  3508. else
  3509. other_streams_nb++;
  3510. }
  3511. if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
  3512. av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
  3513. return AVERROR(EINVAL);
  3514. }
  3515. mov_write_uuidprof_tag(pb, s);
  3516. }
  3517. mov->nb_streams = s->nb_streams;
  3518. if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
  3519. mov->chapter_track = mov->nb_streams++;
  3520. if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
  3521. /* Add hint tracks for each audio and video stream */
  3522. hint_track = mov->nb_streams;
  3523. for (i = 0; i < s->nb_streams; i++) {
  3524. AVStream *st = s->streams[i];
  3525. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
  3526. st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  3527. mov->nb_streams++;
  3528. }
  3529. }
  3530. }
  3531. if (mov->mode == MODE_MOV) {
  3532. tmcd_track = mov->nb_streams;
  3533. /* +1 tmcd track for each video stream with a timecode */
  3534. for (i = 0; i < s->nb_streams; i++) {
  3535. AVStream *st = s->streams[i];
  3536. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
  3537. (global_tcr || av_dict_get(st->metadata, "timecode", NULL, 0)))
  3538. mov->nb_meta_tmcd++;
  3539. }
  3540. /* check if there is already a tmcd track to remux */
  3541. if (mov->nb_meta_tmcd) {
  3542. for (i = 0; i < s->nb_streams; i++) {
  3543. AVStream *st = s->streams[i];
  3544. if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
  3545. av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
  3546. "so timecode metadata are now ignored\n");
  3547. mov->nb_meta_tmcd = 0;
  3548. }
  3549. }
  3550. }
  3551. mov->nb_streams += mov->nb_meta_tmcd;
  3552. }
  3553. // Reserve an extra stream for chapters for the case where chapters
  3554. // are written in the trailer
  3555. mov->tracks = av_mallocz((mov->nb_streams + 1) * sizeof(*mov->tracks));
  3556. if (!mov->tracks)
  3557. return AVERROR(ENOMEM);
  3558. for (i = 0; i < s->nb_streams; i++) {
  3559. AVStream *st= s->streams[i];
  3560. MOVTrack *track= &mov->tracks[i];
  3561. AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
  3562. track->st = st;
  3563. track->enc = st->codec;
  3564. track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
  3565. if (track->language < 0)
  3566. track->language = 0;
  3567. track->mode = mov->mode;
  3568. track->tag = mov_find_codec_tag(s, track);
  3569. if (!track->tag) {
  3570. av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
  3571. "codec not currently supported in container\n",
  3572. avcodec_get_name(st->codec->codec_id), i);
  3573. ret = AVERROR(EINVAL);
  3574. goto error;
  3575. }
  3576. /* If hinting of this track is enabled by a later hint track,
  3577. * this is updated. */
  3578. track->hint_track = -1;
  3579. track->start_dts = AV_NOPTS_VALUE;
  3580. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  3581. if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
  3582. track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
  3583. track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
  3584. if (st->codec->width != 720 || (st->codec->height != 608 && st->codec->height != 512)) {
  3585. av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
  3586. ret = AVERROR(EINVAL);
  3587. goto error;
  3588. }
  3589. track->height = track->tag >> 24 == 'n' ? 486 : 576;
  3590. }
  3591. if (mov->video_track_timescale) {
  3592. track->timescale = mov->video_track_timescale;
  3593. } else {
  3594. track->timescale = st->codec->time_base.den;
  3595. while(track->timescale < 10000)
  3596. track->timescale *= 2;
  3597. }
  3598. if (track->mode == MODE_MOV && track->timescale > 100000)
  3599. av_log(s, AV_LOG_WARNING,
  3600. "WARNING codec timebase is very high. If duration is too long,\n"
  3601. "file may not be playable by quicktime. Specify a shorter timebase\n"
  3602. "or choose different container.\n");
  3603. } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  3604. track->timescale = st->codec->sample_rate;
  3605. if (!st->codec->frame_size && !av_get_bits_per_sample(st->codec->codec_id)) {
  3606. av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
  3607. track->audio_vbr = 1;
  3608. }else if (st->codec->codec_id == AV_CODEC_ID_ADPCM_MS ||
  3609. st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
  3610. st->codec->codec_id == AV_CODEC_ID_ILBC){
  3611. if (!st->codec->block_align) {
  3612. av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
  3613. ret = AVERROR(EINVAL);
  3614. goto error;
  3615. }
  3616. track->sample_size = st->codec->block_align;
  3617. }else if (st->codec->frame_size > 1){ /* assume compressed audio */
  3618. track->audio_vbr = 1;
  3619. }else{
  3620. track->sample_size = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
  3621. }
  3622. if (st->codec->codec_id == AV_CODEC_ID_ILBC ||
  3623. st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
  3624. track->audio_vbr = 1;
  3625. }
  3626. if (track->mode != MODE_MOV &&
  3627. track->enc->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
  3628. av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not supported\n",
  3629. i, track->enc->sample_rate);
  3630. ret = AVERROR(EINVAL);
  3631. goto error;
  3632. }
  3633. } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  3634. track->timescale = st->codec->time_base.den;
  3635. } else if (st->codec->codec_type == AVMEDIA_TYPE_DATA) {
  3636. track->timescale = st->codec->time_base.den;
  3637. } else {
  3638. track->timescale = MOV_TIMESCALE;
  3639. }
  3640. if (!track->height)
  3641. track->height = st->codec->height;
  3642. /* The ism specific timescale isn't mandatory, but is assumed by
  3643. * some tools, such as mp4split. */
  3644. if (mov->mode == MODE_ISM)
  3645. track->timescale = 10000000;
  3646. avpriv_set_pts_info(st, 64, 1, track->timescale);
  3647. /* copy extradata if it exists */
  3648. if (st->codec->extradata_size) {
  3649. if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
  3650. mov_create_dvd_sub_decoder_specific_info(track, st);
  3651. else {
  3652. track->vos_len = st->codec->extradata_size;
  3653. track->vos_data = av_malloc(track->vos_len);
  3654. memcpy(track->vos_data, st->codec->extradata, track->vos_len);
  3655. }
  3656. }
  3657. }
  3658. enable_tracks(s);
  3659. if (mov->reserved_moov_size){
  3660. mov->reserved_moov_pos= avio_tell(pb);
  3661. if (mov->reserved_moov_size > 0)
  3662. avio_skip(pb, mov->reserved_moov_size);
  3663. }
  3664. if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
  3665. /* If no fragmentation options have been set, set a default. */
  3666. if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
  3667. FF_MOV_FLAG_FRAG_CUSTOM)) &&
  3668. !mov->max_fragment_duration && !mov->max_fragment_size)
  3669. mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
  3670. } else {
  3671. if (mov->flags & FF_MOV_FLAG_FASTSTART)
  3672. mov->reserved_moov_pos = avio_tell(pb);
  3673. mov_write_mdat_tag(pb, mov);
  3674. }
  3675. if (t = av_dict_get(s->metadata, "creation_time", NULL, 0))
  3676. mov->time = ff_iso8601_to_unix_time(t->value);
  3677. if (mov->time)
  3678. mov->time += 0x7C25B080; // 1970 based -> 1904 based
  3679. if (mov->chapter_track)
  3680. if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
  3681. goto error;
  3682. if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
  3683. /* Initialize the hint tracks for each audio and video stream */
  3684. for (i = 0; i < s->nb_streams; i++) {
  3685. AVStream *st = s->streams[i];
  3686. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
  3687. st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  3688. if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
  3689. goto error;
  3690. hint_track++;
  3691. }
  3692. }
  3693. }
  3694. if (mov->nb_meta_tmcd) {
  3695. /* Initialize the tmcd tracks */
  3696. for (i = 0; i < s->nb_streams; i++) {
  3697. AVStream *st = s->streams[i];
  3698. t = global_tcr;
  3699. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  3700. if (!t)
  3701. t = av_dict_get(st->metadata, "timecode", NULL, 0);
  3702. if (!t)
  3703. continue;
  3704. if ((ret = mov_create_timecode_track(s, tmcd_track, i, t->value)) < 0)
  3705. goto error;
  3706. tmcd_track++;
  3707. }
  3708. }
  3709. }
  3710. avio_flush(pb);
  3711. if (mov->flags & FF_MOV_FLAG_ISML)
  3712. mov_write_isml_manifest(pb, mov);
  3713. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
  3714. mov_write_moov_tag(pb, mov, s);
  3715. mov->fragments++;
  3716. }
  3717. return 0;
  3718. error:
  3719. mov_free(s);
  3720. return ret;
  3721. }
  3722. static int get_moov_size(AVFormatContext *s)
  3723. {
  3724. int ret;
  3725. AVIOContext *moov_buf;
  3726. MOVMuxContext *mov = s->priv_data;
  3727. if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
  3728. return ret;
  3729. mov_write_moov_tag(moov_buf, mov, s);
  3730. return ffio_close_null_buf(moov_buf);
  3731. }
  3732. /*
  3733. * This function gets the moov size if moved to the top of the file: the chunk
  3734. * offset table can switch between stco (32-bit entries) to co64 (64-bit
  3735. * entries) when the moov is moved to the beginning, so the size of the moov
  3736. * would change. It also updates the chunk offset tables.
  3737. */
  3738. static int compute_moov_size(AVFormatContext *s)
  3739. {
  3740. int i, moov_size, moov_size2;
  3741. MOVMuxContext *mov = s->priv_data;
  3742. moov_size = get_moov_size(s);
  3743. if (moov_size < 0)
  3744. return moov_size;
  3745. for (i = 0; i < mov->nb_streams; i++)
  3746. mov->tracks[i].data_offset += moov_size;
  3747. moov_size2 = get_moov_size(s);
  3748. if (moov_size2 < 0)
  3749. return moov_size2;
  3750. /* if the size changed, we just switched from stco to co64 and need to
  3751. * update the offsets */
  3752. if (moov_size2 != moov_size)
  3753. for (i = 0; i < mov->nb_streams; i++)
  3754. mov->tracks[i].data_offset += moov_size2 - moov_size;
  3755. return moov_size2;
  3756. }
  3757. static int shift_data(AVFormatContext *s)
  3758. {
  3759. int ret = 0, moov_size;
  3760. MOVMuxContext *mov = s->priv_data;
  3761. int64_t pos, pos_end = avio_tell(s->pb);
  3762. uint8_t *buf, *read_buf[2];
  3763. int read_buf_id = 0;
  3764. int read_size[2];
  3765. AVIOContext *read_pb;
  3766. moov_size = compute_moov_size(s);
  3767. if (moov_size < 0)
  3768. return moov_size;
  3769. buf = av_malloc(moov_size * 2);
  3770. if (!buf)
  3771. return AVERROR(ENOMEM);
  3772. read_buf[0] = buf;
  3773. read_buf[1] = buf + moov_size;
  3774. /* Shift the data: the AVIO context of the output can only be used for
  3775. * writing, so we re-open the same output, but for reading. It also avoids
  3776. * a read/seek/write/seek back and forth. */
  3777. avio_flush(s->pb);
  3778. ret = avio_open(&read_pb, s->filename, AVIO_FLAG_READ);
  3779. if (ret < 0) {
  3780. av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
  3781. "the second pass (faststart)\n", s->filename);
  3782. goto end;
  3783. }
  3784. /* mark the end of the shift to up to the last data we wrote, and get ready
  3785. * for writing */
  3786. pos_end = avio_tell(s->pb);
  3787. avio_seek(s->pb, mov->reserved_moov_pos + moov_size, SEEK_SET);
  3788. /* start reading at where the new moov will be placed */
  3789. avio_seek(read_pb, mov->reserved_moov_pos, SEEK_SET);
  3790. pos = avio_tell(read_pb);
  3791. #define READ_BLOCK do { \
  3792. read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
  3793. read_buf_id ^= 1; \
  3794. } while (0)
  3795. /* shift data by chunk of at most moov_size */
  3796. READ_BLOCK;
  3797. do {
  3798. int n;
  3799. READ_BLOCK;
  3800. n = read_size[read_buf_id];
  3801. if (n <= 0)
  3802. break;
  3803. avio_write(s->pb, read_buf[read_buf_id], n);
  3804. pos += n;
  3805. } while (pos < pos_end);
  3806. avio_close(read_pb);
  3807. end:
  3808. av_free(buf);
  3809. return ret;
  3810. }
  3811. static int mov_write_trailer(AVFormatContext *s)
  3812. {
  3813. MOVMuxContext *mov = s->priv_data;
  3814. AVIOContext *pb = s->pb;
  3815. int res = 0;
  3816. int i;
  3817. int64_t moov_pos;
  3818. /*
  3819. * Before actually writing the trailer, make sure that there are no
  3820. * dangling subtitles, that need a terminating sample.
  3821. */
  3822. for (i = 0; i < mov->nb_streams; i++) {
  3823. MOVTrack *trk = &mov->tracks[i];
  3824. if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
  3825. !trk->last_sample_is_subtitle_end) {
  3826. mov_write_subtitle_end_packet(s, i, trk->track_duration);
  3827. trk->last_sample_is_subtitle_end = 1;
  3828. }
  3829. }
  3830. // If there were no chapters when the header was written, but there
  3831. // are chapters now, write them in the trailer. This only works
  3832. // when we are not doing fragments.
  3833. if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
  3834. if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
  3835. mov->chapter_track = mov->nb_streams++;
  3836. if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
  3837. goto error;
  3838. }
  3839. }
  3840. if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
  3841. moov_pos = avio_tell(pb);
  3842. /* Write size of mdat tag */
  3843. if (mov->mdat_size + 8 <= UINT32_MAX) {
  3844. avio_seek(pb, mov->mdat_pos, SEEK_SET);
  3845. avio_wb32(pb, mov->mdat_size + 8);
  3846. } else {
  3847. /* overwrite 'wide' placeholder atom */
  3848. avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
  3849. /* special value: real atom size will be 64 bit value after
  3850. * tag field */
  3851. avio_wb32(pb, 1);
  3852. ffio_wfourcc(pb, "mdat");
  3853. avio_wb64(pb, mov->mdat_size + 16);
  3854. }
  3855. avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_moov_pos : moov_pos, SEEK_SET);
  3856. if (mov->flags & FF_MOV_FLAG_FASTSTART) {
  3857. av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
  3858. res = shift_data(s);
  3859. if (res == 0) {
  3860. avio_seek(s->pb, mov->reserved_moov_pos, SEEK_SET);
  3861. mov_write_moov_tag(pb, mov, s);
  3862. }
  3863. } else if (mov->reserved_moov_size > 0) {
  3864. int64_t size;
  3865. mov_write_moov_tag(pb, mov, s);
  3866. size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_moov_pos);
  3867. if (size < 8){
  3868. av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
  3869. return -1;
  3870. }
  3871. avio_wb32(pb, size);
  3872. ffio_wfourcc(pb, "free");
  3873. for (i = 0; i < size; i++)
  3874. avio_w8(pb, 0);
  3875. avio_seek(pb, moov_pos, SEEK_SET);
  3876. } else {
  3877. mov_write_moov_tag(pb, mov, s);
  3878. }
  3879. } else {
  3880. mov_flush_fragment(s);
  3881. mov_write_mfra_tag(pb, mov);
  3882. }
  3883. for (i = 0; i < mov->nb_streams; i++) {
  3884. if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
  3885. mov->tracks[i].vc1_info.struct_offset && s->pb->seekable) {
  3886. int64_t off = avio_tell(pb);
  3887. uint8_t buf[7];
  3888. if (mov_write_dvc1_structs(&mov->tracks[i], buf) >= 0) {
  3889. avio_seek(pb, mov->tracks[i].vc1_info.struct_offset, SEEK_SET);
  3890. avio_write(pb, buf, 7);
  3891. avio_seek(pb, off, SEEK_SET);
  3892. }
  3893. }
  3894. }
  3895. error:
  3896. mov_free(s);
  3897. return res;
  3898. }
  3899. #if CONFIG_MOV_MUXER
  3900. MOV_CLASS(mov)
  3901. AVOutputFormat ff_mov_muxer = {
  3902. .name = "mov",
  3903. .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
  3904. .extensions = "mov",
  3905. .priv_data_size = sizeof(MOVMuxContext),
  3906. .audio_codec = AV_CODEC_ID_AAC,
  3907. .video_codec = CONFIG_LIBX264_ENCODER ?
  3908. AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
  3909. .write_header = mov_write_header,
  3910. .write_packet = mov_write_packet,
  3911. .write_trailer = mov_write_trailer,
  3912. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  3913. .codec_tag = (const AVCodecTag* const []){
  3914. ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
  3915. },
  3916. .priv_class = &mov_muxer_class,
  3917. };
  3918. #endif
  3919. #if CONFIG_TGP_MUXER
  3920. MOV_CLASS(tgp)
  3921. AVOutputFormat ff_tgp_muxer = {
  3922. .name = "3gp",
  3923. .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
  3924. .extensions = "3gp",
  3925. .priv_data_size = sizeof(MOVMuxContext),
  3926. .audio_codec = AV_CODEC_ID_AMR_NB,
  3927. .video_codec = AV_CODEC_ID_H263,
  3928. .write_header = mov_write_header,
  3929. .write_packet = mov_write_packet,
  3930. .write_trailer = mov_write_trailer,
  3931. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  3932. .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
  3933. .priv_class = &tgp_muxer_class,
  3934. };
  3935. #endif
  3936. #if CONFIG_MP4_MUXER
  3937. MOV_CLASS(mp4)
  3938. AVOutputFormat ff_mp4_muxer = {
  3939. .name = "mp4",
  3940. .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
  3941. .mime_type = "application/mp4",
  3942. .extensions = "mp4",
  3943. .priv_data_size = sizeof(MOVMuxContext),
  3944. .audio_codec = AV_CODEC_ID_AAC,
  3945. .video_codec = CONFIG_LIBX264_ENCODER ?
  3946. AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
  3947. .write_header = mov_write_header,
  3948. .write_packet = mov_write_packet,
  3949. .write_trailer = mov_write_trailer,
  3950. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  3951. .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
  3952. .priv_class = &mp4_muxer_class,
  3953. };
  3954. #endif
  3955. #if CONFIG_PSP_MUXER
  3956. MOV_CLASS(psp)
  3957. AVOutputFormat ff_psp_muxer = {
  3958. .name = "psp",
  3959. .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
  3960. .extensions = "mp4,psp",
  3961. .priv_data_size = sizeof(MOVMuxContext),
  3962. .audio_codec = AV_CODEC_ID_AAC,
  3963. .video_codec = CONFIG_LIBX264_ENCODER ?
  3964. AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
  3965. .write_header = mov_write_header,
  3966. .write_packet = mov_write_packet,
  3967. .write_trailer = mov_write_trailer,
  3968. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  3969. .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
  3970. .priv_class = &psp_muxer_class,
  3971. };
  3972. #endif
  3973. #if CONFIG_TG2_MUXER
  3974. MOV_CLASS(tg2)
  3975. AVOutputFormat ff_tg2_muxer = {
  3976. .name = "3g2",
  3977. .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
  3978. .extensions = "3g2",
  3979. .priv_data_size = sizeof(MOVMuxContext),
  3980. .audio_codec = AV_CODEC_ID_AMR_NB,
  3981. .video_codec = AV_CODEC_ID_H263,
  3982. .write_header = mov_write_header,
  3983. .write_packet = mov_write_packet,
  3984. .write_trailer = mov_write_trailer,
  3985. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  3986. .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
  3987. .priv_class = &tg2_muxer_class,
  3988. };
  3989. #endif
  3990. #if CONFIG_IPOD_MUXER
  3991. MOV_CLASS(ipod)
  3992. AVOutputFormat ff_ipod_muxer = {
  3993. .name = "ipod",
  3994. .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
  3995. .mime_type = "application/mp4",
  3996. .extensions = "m4v,m4a",
  3997. .priv_data_size = sizeof(MOVMuxContext),
  3998. .audio_codec = AV_CODEC_ID_AAC,
  3999. .video_codec = AV_CODEC_ID_H264,
  4000. .write_header = mov_write_header,
  4001. .write_packet = mov_write_packet,
  4002. .write_trailer = mov_write_trailer,
  4003. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  4004. .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
  4005. .priv_class = &ipod_muxer_class,
  4006. };
  4007. #endif
  4008. #if CONFIG_ISMV_MUXER
  4009. MOV_CLASS(ismv)
  4010. AVOutputFormat ff_ismv_muxer = {
  4011. .name = "ismv",
  4012. .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
  4013. .mime_type = "application/mp4",
  4014. .extensions = "ismv,isma",
  4015. .priv_data_size = sizeof(MOVMuxContext),
  4016. .audio_codec = AV_CODEC_ID_AAC,
  4017. .video_codec = AV_CODEC_ID_H264,
  4018. .write_header = mov_write_header,
  4019. .write_packet = mov_write_packet,
  4020. .write_trailer = mov_write_trailer,
  4021. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  4022. .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
  4023. .priv_class = &ismv_muxer_class,
  4024. };
  4025. #endif
  4026. #if CONFIG_F4V_MUXER
  4027. MOV_CLASS(f4v)
  4028. AVOutputFormat ff_f4v_muxer = {
  4029. .name = "f4v",
  4030. .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
  4031. .mime_type = "application/f4v",
  4032. .extensions = "f4v",
  4033. .priv_data_size = sizeof(MOVMuxContext),
  4034. .audio_codec = AV_CODEC_ID_AAC,
  4035. .video_codec = AV_CODEC_ID_H264,
  4036. .write_header = mov_write_header,
  4037. .write_packet = mov_write_packet,
  4038. .write_trailer = mov_write_trailer,
  4039. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
  4040. .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
  4041. .priv_class = &f4v_muxer_class,
  4042. };
  4043. #endif