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.

4511 lines
159KB

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