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.

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