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.

4485 lines
158KB

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