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.

6936 lines
251KB

  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/ac3_parser_internal.h"
  33. #include "libavcodec/dnxhddata.h"
  34. #include "libavcodec/flac.h"
  35. #include "libavcodec/get_bits.h"
  36. #include "libavcodec/internal.h"
  37. #include "libavcodec/put_bits.h"
  38. #include "libavcodec/vc1_common.h"
  39. #include "libavcodec/raw.h"
  40. #include "internal.h"
  41. #include "libavutil/avstring.h"
  42. #include "libavutil/intfloat.h"
  43. #include "libavutil/mathematics.h"
  44. #include "libavutil/libm.h"
  45. #include "libavutil/opt.h"
  46. #include "libavutil/dict.h"
  47. #include "libavutil/pixdesc.h"
  48. #include "libavutil/stereo3d.h"
  49. #include "libavutil/timecode.h"
  50. #include "libavutil/color_utils.h"
  51. #include "hevc.h"
  52. #include "rtpenc.h"
  53. #include "mov_chan.h"
  54. #include "vpcc.h"
  55. static const AVOption options[] = {
  56. { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  57. { "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" },
  58. { "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 },
  59. { "empty_moov", "Make the initial moov atom empty", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  60. { "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" },
  61. { "frag_every_frame", "Fragment at every frame", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_EVERY_FRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  62. { "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" },
  63. { "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" },
  64. { "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" },
  65. { "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" },
  66. { "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" },
  67. { "disable_chpl", "Disable Nero chapter atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DISABLE_CHPL}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  68. { "default_base_moof", "Set the default-base-is-moof flag in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DEFAULT_BASE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  69. { "dash", "Write DASH compatible fragmented MP4", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DASH}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  70. { "frag_discont", "Signal that the next fragment is discontinuous from earlier ones", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_DISCONT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  71. { "delay_moov", "Delay writing the initial moov until the first fragment is cut, or until the first fragment flush", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DELAY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  72. { "global_sidx", "Write a global sidx index at the start of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_GLOBAL_SIDX}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  73. { "write_colr", "Write colr atom (Experimental, may be renamed or changed, do not use from scripts)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_COLR}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  74. { "write_gama", "Write deprecated gama atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_GAMA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  75. { "use_metadata_tags", "Use mdta atom for metadata.", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_USE_MDTA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  76. { "skip_trailer", "Skip writing the mfra/tfra/mfro trailer for fragmented files", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SKIP_TRAILER}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  77. { "negative_cts_offsets", "Use negative CTS offsets (reducing the need for edit lists)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  78. FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
  79. { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
  80. { "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},
  81. { "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},
  82. { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
  83. { "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},
  84. { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
  85. { "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},
  86. { "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},
  87. { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
  88. { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
  89. { "fragment_index", "Fragment number of the next fragment", offsetof(MOVMuxContext, fragments), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
  90. { "mov_gamma", "gamma value for gama atom", offsetof(MOVMuxContext, gamma), AV_OPT_TYPE_FLOAT, {.dbl = 0.0 }, 0.0, 10, AV_OPT_FLAG_ENCODING_PARAM},
  91. { "frag_interleave", "Interleave samples within fragments (max number of consecutive samples, lower is tighter interleaving, but with more overhead)", offsetof(MOVMuxContext, frag_interleave), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
  92. { "encryption_scheme", "Configures the encryption scheme, allowed values are none, cenc-aes-ctr", offsetof(MOVMuxContext, encryption_scheme_str), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
  93. { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
  94. { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
  95. { "use_stream_ids_as_track_ids", "use stream ids as track ids", offsetof(MOVMuxContext, use_stream_ids_as_track_ids), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
  96. { "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
  97. { "write_prft", "Write producer reference time box with specified time source", offsetof(MOVMuxContext, write_prft), AV_OPT_TYPE_INT, {.i64 = MOV_PRFT_NONE}, 0, MOV_PRFT_NB-1, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
  98. { "wallclock", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_WALLCLOCK}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
  99. { "pts", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_PTS}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
  100. { NULL },
  101. };
  102. #define MOV_CLASS(flavor)\
  103. static const AVClass flavor ## _muxer_class = {\
  104. .class_name = #flavor " muxer",\
  105. .item_name = av_default_item_name,\
  106. .option = options,\
  107. .version = LIBAVUTIL_VERSION_INT,\
  108. };
  109. static int get_moov_size(AVFormatContext *s);
  110. static int utf8len(const uint8_t *b)
  111. {
  112. int len = 0;
  113. int val;
  114. while (*b) {
  115. GET_UTF8(val, *b++, return -1;)
  116. len++;
  117. }
  118. return len;
  119. }
  120. //FIXME support 64 bit variant with wide placeholders
  121. static int64_t update_size(AVIOContext *pb, int64_t pos)
  122. {
  123. int64_t curpos = avio_tell(pb);
  124. avio_seek(pb, pos, SEEK_SET);
  125. avio_wb32(pb, curpos - pos); /* rewrite size */
  126. avio_seek(pb, curpos, SEEK_SET);
  127. return curpos - pos;
  128. }
  129. static int co64_required(const MOVTrack *track)
  130. {
  131. if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
  132. return 1;
  133. return 0;
  134. }
  135. static int is_cover_image(const AVStream *st)
  136. {
  137. /* Eg. AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS
  138. * is encoded as sparse video track */
  139. return st && st->disposition == AV_DISPOSITION_ATTACHED_PIC;
  140. }
  141. static int rtp_hinting_needed(const AVStream *st)
  142. {
  143. /* Add hint tracks for each real audio and video stream */
  144. if (is_cover_image(st))
  145. return 0;
  146. return st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
  147. st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
  148. }
  149. /* Chunk offset atom */
  150. static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
  151. {
  152. int i;
  153. int mode64 = co64_required(track); // use 32 bit size variant if possible
  154. int64_t pos = avio_tell(pb);
  155. avio_wb32(pb, 0); /* size */
  156. if (mode64)
  157. ffio_wfourcc(pb, "co64");
  158. else
  159. ffio_wfourcc(pb, "stco");
  160. avio_wb32(pb, 0); /* version & flags */
  161. avio_wb32(pb, track->chunkCount); /* entry count */
  162. for (i = 0; i < track->entry; i++) {
  163. if (!track->cluster[i].chunkNum)
  164. continue;
  165. if (mode64 == 1)
  166. avio_wb64(pb, track->cluster[i].pos + track->data_offset);
  167. else
  168. avio_wb32(pb, track->cluster[i].pos + track->data_offset);
  169. }
  170. return update_size(pb, pos);
  171. }
  172. /* Sample size atom */
  173. static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
  174. {
  175. int equalChunks = 1;
  176. int i, j, entries = 0, tst = -1, oldtst = -1;
  177. int64_t pos = avio_tell(pb);
  178. avio_wb32(pb, 0); /* size */
  179. ffio_wfourcc(pb, "stsz");
  180. avio_wb32(pb, 0); /* version & flags */
  181. for (i = 0; i < track->entry; i++) {
  182. tst = track->cluster[i].size / track->cluster[i].entries;
  183. if (oldtst != -1 && tst != oldtst)
  184. equalChunks = 0;
  185. oldtst = tst;
  186. entries += track->cluster[i].entries;
  187. }
  188. if (equalChunks && track->entry) {
  189. int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
  190. sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
  191. avio_wb32(pb, sSize); // sample size
  192. avio_wb32(pb, entries); // sample count
  193. } else {
  194. avio_wb32(pb, 0); // sample size
  195. avio_wb32(pb, entries); // sample count
  196. for (i = 0; i < track->entry; i++) {
  197. for (j = 0; j < track->cluster[i].entries; j++) {
  198. avio_wb32(pb, track->cluster[i].size /
  199. track->cluster[i].entries);
  200. }
  201. }
  202. }
  203. return update_size(pb, pos);
  204. }
  205. /* Sample to chunk atom */
  206. static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
  207. {
  208. int index = 0, oldval = -1, i;
  209. int64_t entryPos, curpos;
  210. int64_t pos = avio_tell(pb);
  211. avio_wb32(pb, 0); /* size */
  212. ffio_wfourcc(pb, "stsc");
  213. avio_wb32(pb, 0); // version & flags
  214. entryPos = avio_tell(pb);
  215. avio_wb32(pb, track->chunkCount); // entry count
  216. for (i = 0; i < track->entry; i++) {
  217. if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
  218. avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
  219. avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
  220. avio_wb32(pb, 0x1); // sample description index
  221. oldval = track->cluster[i].samples_in_chunk;
  222. index++;
  223. }
  224. }
  225. curpos = avio_tell(pb);
  226. avio_seek(pb, entryPos, SEEK_SET);
  227. avio_wb32(pb, index); // rewrite size
  228. avio_seek(pb, curpos, SEEK_SET);
  229. return update_size(pb, pos);
  230. }
  231. /* Sync sample atom */
  232. static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
  233. {
  234. int64_t curpos, entryPos;
  235. int i, index = 0;
  236. int64_t pos = avio_tell(pb);
  237. avio_wb32(pb, 0); // size
  238. ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
  239. avio_wb32(pb, 0); // version & flags
  240. entryPos = avio_tell(pb);
  241. avio_wb32(pb, track->entry); // entry count
  242. for (i = 0; i < track->entry; i++) {
  243. if (track->cluster[i].flags & flag) {
  244. avio_wb32(pb, i + 1);
  245. index++;
  246. }
  247. }
  248. curpos = avio_tell(pb);
  249. avio_seek(pb, entryPos, SEEK_SET);
  250. avio_wb32(pb, index); // rewrite size
  251. avio_seek(pb, curpos, SEEK_SET);
  252. return update_size(pb, pos);
  253. }
  254. /* Sample dependency atom */
  255. static int mov_write_sdtp_tag(AVIOContext *pb, MOVTrack *track)
  256. {
  257. int i;
  258. uint8_t leading, dependent, reference, redundancy;
  259. int64_t pos = avio_tell(pb);
  260. avio_wb32(pb, 0); // size
  261. ffio_wfourcc(pb, "sdtp");
  262. avio_wb32(pb, 0); // version & flags
  263. for (i = 0; i < track->entry; i++) {
  264. dependent = MOV_SAMPLE_DEPENDENCY_YES;
  265. leading = reference = redundancy = MOV_SAMPLE_DEPENDENCY_UNKNOWN;
  266. if (track->cluster[i].flags & MOV_DISPOSABLE_SAMPLE) {
  267. reference = MOV_SAMPLE_DEPENDENCY_NO;
  268. }
  269. if (track->cluster[i].flags & MOV_SYNC_SAMPLE) {
  270. dependent = MOV_SAMPLE_DEPENDENCY_NO;
  271. }
  272. avio_w8(pb, (leading << 6) | (dependent << 4) |
  273. (reference << 2) | redundancy);
  274. }
  275. return update_size(pb, pos);
  276. }
  277. static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
  278. {
  279. avio_wb32(pb, 0x11); /* size */
  280. if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
  281. else ffio_wfourcc(pb, "damr");
  282. ffio_wfourcc(pb, "FFMP");
  283. avio_w8(pb, 0); /* decoder version */
  284. avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
  285. avio_w8(pb, 0x00); /* Mode change period (no restriction) */
  286. avio_w8(pb, 0x01); /* Frames per sample */
  287. return 0x11;
  288. }
  289. static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
  290. {
  291. GetBitContext gbc;
  292. PutBitContext pbc;
  293. uint8_t buf[3];
  294. int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
  295. if (track->vos_len < 7)
  296. return -1;
  297. avio_wb32(pb, 11);
  298. ffio_wfourcc(pb, "dac3");
  299. init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
  300. fscod = get_bits(&gbc, 2);
  301. frmsizecod = get_bits(&gbc, 6);
  302. bsid = get_bits(&gbc, 5);
  303. bsmod = get_bits(&gbc, 3);
  304. acmod = get_bits(&gbc, 3);
  305. if (acmod == 2) {
  306. skip_bits(&gbc, 2); // dsurmod
  307. } else {
  308. if ((acmod & 1) && acmod != 1)
  309. skip_bits(&gbc, 2); // cmixlev
  310. if (acmod & 4)
  311. skip_bits(&gbc, 2); // surmixlev
  312. }
  313. lfeon = get_bits1(&gbc);
  314. init_put_bits(&pbc, buf, sizeof(buf));
  315. put_bits(&pbc, 2, fscod);
  316. put_bits(&pbc, 5, bsid);
  317. put_bits(&pbc, 3, bsmod);
  318. put_bits(&pbc, 3, acmod);
  319. put_bits(&pbc, 1, lfeon);
  320. put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
  321. put_bits(&pbc, 5, 0); // reserved
  322. flush_put_bits(&pbc);
  323. avio_write(pb, buf, sizeof(buf));
  324. return 11;
  325. }
  326. struct eac3_info {
  327. AVPacket pkt;
  328. uint8_t ec3_done;
  329. uint8_t num_blocks;
  330. /* Layout of the EC3SpecificBox */
  331. /* maximum bitrate */
  332. uint16_t data_rate;
  333. /* number of independent substreams */
  334. uint8_t num_ind_sub;
  335. struct {
  336. /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
  337. uint8_t fscod;
  338. /* bit stream identification 5 bits */
  339. uint8_t bsid;
  340. /* one bit reserved */
  341. /* audio service mixing (not supported yet) 1 bit */
  342. /* bit stream mode 3 bits */
  343. uint8_t bsmod;
  344. /* audio coding mode 3 bits */
  345. uint8_t acmod;
  346. /* sub woofer on 1 bit */
  347. uint8_t lfeon;
  348. /* 3 bits reserved */
  349. /* number of dependent substreams associated with this substream 4 bits */
  350. uint8_t num_dep_sub;
  351. /* channel locations of the dependent substream(s), if any, 9 bits */
  352. uint16_t chan_loc;
  353. /* if there is no dependent substream, then one bit reserved instead */
  354. } substream[1]; /* TODO: support 8 independent substreams */
  355. };
  356. #if CONFIG_AC3_PARSER
  357. static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
  358. {
  359. AC3HeaderInfo *hdr = NULL;
  360. struct eac3_info *info;
  361. int num_blocks, ret;
  362. if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
  363. return AVERROR(ENOMEM);
  364. info = track->eac3_priv;
  365. if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) {
  366. /* drop the packets until we see a good one */
  367. if (!track->entry) {
  368. av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
  369. ret = 0;
  370. } else
  371. ret = AVERROR_INVALIDDATA;
  372. goto end;
  373. }
  374. info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
  375. num_blocks = hdr->num_blocks;
  376. if (!info->ec3_done) {
  377. /* AC-3 substream must be the first one */
  378. if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) {
  379. ret = AVERROR(EINVAL);
  380. goto end;
  381. }
  382. /* this should always be the case, given that our AC-3 parser
  383. * concatenates dependent frames to their independent parent */
  384. if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
  385. /* substream ids must be incremental */
  386. if (hdr->substreamid > info->num_ind_sub + 1) {
  387. ret = AVERROR(EINVAL);
  388. goto end;
  389. }
  390. if (hdr->substreamid == info->num_ind_sub + 1) {
  391. //info->num_ind_sub++;
  392. avpriv_request_sample(track->par, "Multiple independent substreams");
  393. ret = AVERROR_PATCHWELCOME;
  394. goto end;
  395. } else if (hdr->substreamid < info->num_ind_sub ||
  396. hdr->substreamid == 0 && info->substream[0].bsid) {
  397. info->ec3_done = 1;
  398. goto concatenate;
  399. }
  400. }
  401. /* fill the info needed for the "dec3" atom */
  402. info->substream[hdr->substreamid].fscod = hdr->sr_code;
  403. info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
  404. info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
  405. info->substream[hdr->substreamid].acmod = hdr->channel_mode;
  406. info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
  407. /* Parse dependent substream(s), if any */
  408. if (pkt->size != hdr->frame_size) {
  409. int cumul_size = hdr->frame_size;
  410. int parent = hdr->substreamid;
  411. while (cumul_size != pkt->size) {
  412. GetBitContext gbc;
  413. int i;
  414. ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size);
  415. if (ret < 0)
  416. goto end;
  417. if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) {
  418. ret = AVERROR(EINVAL);
  419. goto end;
  420. }
  421. info->substream[parent].num_dep_sub++;
  422. ret /= 8;
  423. /* header is parsed up to lfeon, but custom channel map may be needed */
  424. init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret);
  425. /* skip bsid */
  426. skip_bits(&gbc, 5);
  427. /* skip volume control params */
  428. for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
  429. skip_bits(&gbc, 5); // skip dialog normalization
  430. if (get_bits1(&gbc)) {
  431. skip_bits(&gbc, 8); // skip compression gain word
  432. }
  433. }
  434. /* get the dependent stream channel map, if exists */
  435. if (get_bits1(&gbc))
  436. info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
  437. else
  438. info->substream[parent].chan_loc |= hdr->channel_mode;
  439. cumul_size += hdr->frame_size;
  440. }
  441. }
  442. }
  443. concatenate:
  444. if (!info->num_blocks && num_blocks == 6) {
  445. ret = pkt->size;
  446. goto end;
  447. }
  448. else if (info->num_blocks + num_blocks > 6) {
  449. ret = AVERROR_INVALIDDATA;
  450. goto end;
  451. }
  452. if (!info->num_blocks) {
  453. ret = av_packet_ref(&info->pkt, pkt);
  454. if (!ret)
  455. info->num_blocks = num_blocks;
  456. goto end;
  457. } else {
  458. if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
  459. goto end;
  460. memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
  461. info->num_blocks += num_blocks;
  462. info->pkt.duration += pkt->duration;
  463. if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
  464. goto end;
  465. if (info->num_blocks != 6)
  466. goto end;
  467. av_packet_unref(pkt);
  468. av_packet_move_ref(pkt, &info->pkt);
  469. info->num_blocks = 0;
  470. }
  471. ret = pkt->size;
  472. end:
  473. av_free(hdr);
  474. return ret;
  475. }
  476. #endif
  477. static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
  478. {
  479. PutBitContext pbc;
  480. uint8_t *buf;
  481. struct eac3_info *info;
  482. int size, i;
  483. if (!track->eac3_priv)
  484. return AVERROR(EINVAL);
  485. info = track->eac3_priv;
  486. size = 2 + 4 * (info->num_ind_sub + 1);
  487. buf = av_malloc(size);
  488. if (!buf) {
  489. size = AVERROR(ENOMEM);
  490. goto end;
  491. }
  492. init_put_bits(&pbc, buf, size);
  493. put_bits(&pbc, 13, info->data_rate);
  494. put_bits(&pbc, 3, info->num_ind_sub);
  495. for (i = 0; i <= info->num_ind_sub; i++) {
  496. put_bits(&pbc, 2, info->substream[i].fscod);
  497. put_bits(&pbc, 5, info->substream[i].bsid);
  498. put_bits(&pbc, 1, 0); /* reserved */
  499. put_bits(&pbc, 1, 0); /* asvc */
  500. put_bits(&pbc, 3, info->substream[i].bsmod);
  501. put_bits(&pbc, 3, info->substream[i].acmod);
  502. put_bits(&pbc, 1, info->substream[i].lfeon);
  503. put_bits(&pbc, 5, 0); /* reserved */
  504. put_bits(&pbc, 4, info->substream[i].num_dep_sub);
  505. if (!info->substream[i].num_dep_sub) {
  506. put_bits(&pbc, 1, 0); /* reserved */
  507. size--;
  508. } else {
  509. put_bits(&pbc, 9, info->substream[i].chan_loc);
  510. }
  511. }
  512. flush_put_bits(&pbc);
  513. avio_wb32(pb, size + 8);
  514. ffio_wfourcc(pb, "dec3");
  515. avio_write(pb, buf, size);
  516. av_free(buf);
  517. end:
  518. av_packet_unref(&info->pkt);
  519. av_freep(&track->eac3_priv);
  520. return size;
  521. }
  522. /**
  523. * This function writes extradata "as is".
  524. * Extradata must be formatted like a valid atom (with size and tag).
  525. */
  526. static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
  527. {
  528. avio_write(pb, track->par->extradata, track->par->extradata_size);
  529. return track->par->extradata_size;
  530. }
  531. static int mov_write_enda_tag(AVIOContext *pb)
  532. {
  533. avio_wb32(pb, 10);
  534. ffio_wfourcc(pb, "enda");
  535. avio_wb16(pb, 1); /* little endian */
  536. return 10;
  537. }
  538. static int mov_write_enda_tag_be(AVIOContext *pb)
  539. {
  540. avio_wb32(pb, 10);
  541. ffio_wfourcc(pb, "enda");
  542. avio_wb16(pb, 0); /* big endian */
  543. return 10;
  544. }
  545. static void put_descr(AVIOContext *pb, int tag, unsigned int size)
  546. {
  547. int i = 3;
  548. avio_w8(pb, tag);
  549. for (; i > 0; i--)
  550. avio_w8(pb, (size >> (7 * i)) | 0x80);
  551. avio_w8(pb, size & 0x7F);
  552. }
  553. static unsigned compute_avg_bitrate(MOVTrack *track)
  554. {
  555. uint64_t size = 0;
  556. int i;
  557. if (!track->track_duration)
  558. return 0;
  559. for (i = 0; i < track->entry; i++)
  560. size += track->cluster[i].size;
  561. return size * 8 * track->timescale / track->track_duration;
  562. }
  563. static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
  564. {
  565. AVCPBProperties *props;
  566. int64_t pos = avio_tell(pb);
  567. int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
  568. unsigned avg_bitrate;
  569. avio_wb32(pb, 0); // size
  570. ffio_wfourcc(pb, "esds");
  571. avio_wb32(pb, 0); // Version
  572. // ES descriptor
  573. put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
  574. avio_wb16(pb, track->track_id);
  575. avio_w8(pb, 0x00); // flags (= no flags)
  576. // DecoderConfig descriptor
  577. put_descr(pb, 0x04, 13 + decoder_specific_info_len);
  578. // Object type indication
  579. if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
  580. track->par->codec_id == AV_CODEC_ID_MP3) &&
  581. track->par->sample_rate > 24000)
  582. avio_w8(pb, 0x6B); // 11172-3
  583. else
  584. avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
  585. // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
  586. // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
  587. if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
  588. avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
  589. else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
  590. avio_w8(pb, 0x15); // flags (= Audiostream)
  591. else
  592. avio_w8(pb, 0x11); // flags (= Visualstream)
  593. props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
  594. NULL);
  595. avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
  596. avg_bitrate = compute_avg_bitrate(track);
  597. avio_wb32(pb, props ? FFMAX3(props->max_bitrate, props->avg_bitrate, avg_bitrate) : FFMAX(track->par->bit_rate, avg_bitrate)); // maxbitrate (FIXME should be max rate in any 1 sec window)
  598. avio_wb32(pb, avg_bitrate);
  599. if (track->vos_len) {
  600. // DecoderSpecific info descriptor
  601. put_descr(pb, 0x05, track->vos_len);
  602. avio_write(pb, track->vos_data, track->vos_len);
  603. }
  604. // SL descriptor
  605. put_descr(pb, 0x06, 1);
  606. avio_w8(pb, 0x02);
  607. return update_size(pb, pos);
  608. }
  609. static int mov_pcm_le_gt16(enum AVCodecID codec_id)
  610. {
  611. return codec_id == AV_CODEC_ID_PCM_S24LE ||
  612. codec_id == AV_CODEC_ID_PCM_S32LE ||
  613. codec_id == AV_CODEC_ID_PCM_F32LE ||
  614. codec_id == AV_CODEC_ID_PCM_F64LE;
  615. }
  616. static int mov_pcm_be_gt16(enum AVCodecID codec_id)
  617. {
  618. return codec_id == AV_CODEC_ID_PCM_S24BE ||
  619. codec_id == AV_CODEC_ID_PCM_S32BE ||
  620. codec_id == AV_CODEC_ID_PCM_F32BE ||
  621. codec_id == AV_CODEC_ID_PCM_F64BE;
  622. }
  623. static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
  624. {
  625. int ret;
  626. int64_t pos = avio_tell(pb);
  627. avio_wb32(pb, 0);
  628. avio_wl32(pb, track->tag); // store it byteswapped
  629. track->par->codec_tag = av_bswap16(track->tag >> 16);
  630. if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
  631. return ret;
  632. return update_size(pb, pos);
  633. }
  634. static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
  635. {
  636. int ret;
  637. int64_t pos = avio_tell(pb);
  638. avio_wb32(pb, 0);
  639. ffio_wfourcc(pb, "wfex");
  640. if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
  641. return ret;
  642. return update_size(pb, pos);
  643. }
  644. static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track)
  645. {
  646. int64_t pos = avio_tell(pb);
  647. avio_wb32(pb, 0);
  648. ffio_wfourcc(pb, "dfLa");
  649. avio_w8(pb, 0); /* version */
  650. avio_wb24(pb, 0); /* flags */
  651. /* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */
  652. if (track->par->extradata_size != FLAC_STREAMINFO_SIZE)
  653. return AVERROR_INVALIDDATA;
  654. /* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */
  655. avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */
  656. avio_wb24(pb, track->par->extradata_size); /* Length */
  657. avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */
  658. return update_size(pb, pos);
  659. }
  660. static int mov_write_dops_tag(AVIOContext *pb, MOVTrack *track)
  661. {
  662. int64_t pos = avio_tell(pb);
  663. avio_wb32(pb, 0);
  664. ffio_wfourcc(pb, "dOps");
  665. avio_w8(pb, 0); /* Version */
  666. if (track->par->extradata_size < 19) {
  667. av_log(pb, AV_LOG_ERROR, "invalid extradata size\n");
  668. return AVERROR_INVALIDDATA;
  669. }
  670. /* extradata contains an Ogg OpusHead, other than byte-ordering and
  671. OpusHead's preceeding magic/version, OpusSpecificBox is currently
  672. identical. */
  673. avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */
  674. avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */
  675. avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */
  676. avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */
  677. /* Write the rest of the header out without byte-swapping. */
  678. avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18);
  679. return update_size(pb, pos);
  680. }
  681. static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
  682. {
  683. uint32_t layout_tag, bitmap;
  684. int64_t pos = avio_tell(pb);
  685. layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
  686. track->par->channel_layout,
  687. &bitmap);
  688. if (!layout_tag) {
  689. av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
  690. "lack of channel information\n");
  691. return 0;
  692. }
  693. if (track->multichannel_as_mono)
  694. return 0;
  695. avio_wb32(pb, 0); // Size
  696. ffio_wfourcc(pb, "chan"); // Type
  697. avio_w8(pb, 0); // Version
  698. avio_wb24(pb, 0); // Flags
  699. avio_wb32(pb, layout_tag); // mChannelLayoutTag
  700. avio_wb32(pb, bitmap); // mChannelBitmap
  701. avio_wb32(pb, 0); // mNumberChannelDescriptions
  702. return update_size(pb, pos);
  703. }
  704. static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
  705. {
  706. int64_t pos = avio_tell(pb);
  707. avio_wb32(pb, 0); /* size */
  708. ffio_wfourcc(pb, "wave");
  709. if (track->par->codec_id != AV_CODEC_ID_QDM2) {
  710. avio_wb32(pb, 12); /* size */
  711. ffio_wfourcc(pb, "frma");
  712. avio_wl32(pb, track->tag);
  713. }
  714. if (track->par->codec_id == AV_CODEC_ID_AAC) {
  715. /* useless atom needed by mplayer, ipod, not needed by quicktime */
  716. avio_wb32(pb, 12); /* size */
  717. ffio_wfourcc(pb, "mp4a");
  718. avio_wb32(pb, 0);
  719. mov_write_esds_tag(pb, track);
  720. } else if (mov_pcm_le_gt16(track->par->codec_id)) {
  721. mov_write_enda_tag(pb);
  722. } else if (mov_pcm_be_gt16(track->par->codec_id)) {
  723. mov_write_enda_tag_be(pb);
  724. } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
  725. mov_write_amr_tag(pb, track);
  726. } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
  727. mov_write_ac3_tag(pb, track);
  728. } else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
  729. mov_write_eac3_tag(pb, track);
  730. } else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
  731. track->par->codec_id == AV_CODEC_ID_QDM2) {
  732. mov_write_extradata_tag(pb, track);
  733. } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
  734. track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
  735. mov_write_ms_tag(s, pb, track);
  736. }
  737. avio_wb32(pb, 8); /* size */
  738. avio_wb32(pb, 0); /* null tag */
  739. return update_size(pb, pos);
  740. }
  741. static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
  742. {
  743. uint8_t *unescaped;
  744. const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
  745. int unescaped_size, seq_found = 0;
  746. int level = 0, interlace = 0;
  747. int packet_seq = track->vc1_info.packet_seq;
  748. int packet_entry = track->vc1_info.packet_entry;
  749. int slices = track->vc1_info.slices;
  750. PutBitContext pbc;
  751. if (track->start_dts == AV_NOPTS_VALUE) {
  752. /* No packets written yet, vc1_info isn't authoritative yet. */
  753. /* Assume inline sequence and entry headers. */
  754. packet_seq = packet_entry = 1;
  755. av_log(NULL, AV_LOG_WARNING,
  756. "moov atom written before any packets, unable to write correct "
  757. "dvc1 atom. Set the delay_moov flag to fix this.\n");
  758. }
  759. unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
  760. if (!unescaped)
  761. return AVERROR(ENOMEM);
  762. start = find_next_marker(track->vos_data, end);
  763. for (next = start; next < end; start = next) {
  764. GetBitContext gb;
  765. int size;
  766. next = find_next_marker(start + 4, end);
  767. size = next - start - 4;
  768. if (size <= 0)
  769. continue;
  770. unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
  771. init_get_bits(&gb, unescaped, 8 * unescaped_size);
  772. if (AV_RB32(start) == VC1_CODE_SEQHDR) {
  773. int profile = get_bits(&gb, 2);
  774. if (profile != PROFILE_ADVANCED) {
  775. av_free(unescaped);
  776. return AVERROR(ENOSYS);
  777. }
  778. seq_found = 1;
  779. level = get_bits(&gb, 3);
  780. /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
  781. * width, height */
  782. skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
  783. skip_bits(&gb, 1); /* broadcast */
  784. interlace = get_bits1(&gb);
  785. skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
  786. }
  787. }
  788. if (!seq_found) {
  789. av_free(unescaped);
  790. return AVERROR(ENOSYS);
  791. }
  792. init_put_bits(&pbc, buf, 7);
  793. /* VC1DecSpecStruc */
  794. put_bits(&pbc, 4, 12); /* profile - advanced */
  795. put_bits(&pbc, 3, level);
  796. put_bits(&pbc, 1, 0); /* reserved */
  797. /* VC1AdvDecSpecStruc */
  798. put_bits(&pbc, 3, level);
  799. put_bits(&pbc, 1, 0); /* cbr */
  800. put_bits(&pbc, 6, 0); /* reserved */
  801. put_bits(&pbc, 1, !interlace); /* no interlace */
  802. put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
  803. put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
  804. put_bits(&pbc, 1, !slices); /* no slice code */
  805. put_bits(&pbc, 1, 0); /* no bframe */
  806. put_bits(&pbc, 1, 0); /* reserved */
  807. /* framerate */
  808. if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
  809. put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
  810. else
  811. put_bits32(&pbc, 0xffffffff);
  812. flush_put_bits(&pbc);
  813. av_free(unescaped);
  814. return 0;
  815. }
  816. static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
  817. {
  818. uint8_t buf[7] = { 0 };
  819. int ret;
  820. if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
  821. return ret;
  822. avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
  823. ffio_wfourcc(pb, "dvc1");
  824. avio_write(pb, buf, sizeof(buf));
  825. avio_write(pb, track->vos_data, track->vos_len);
  826. return 0;
  827. }
  828. static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
  829. {
  830. avio_wb32(pb, track->vos_len + 8);
  831. ffio_wfourcc(pb, "glbl");
  832. avio_write(pb, track->vos_data, track->vos_len);
  833. return 8 + track->vos_len;
  834. }
  835. /**
  836. * Compute flags for 'lpcm' tag.
  837. * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
  838. */
  839. static int mov_get_lpcm_flags(enum AVCodecID codec_id)
  840. {
  841. switch (codec_id) {
  842. case AV_CODEC_ID_PCM_F32BE:
  843. case AV_CODEC_ID_PCM_F64BE:
  844. return 11;
  845. case AV_CODEC_ID_PCM_F32LE:
  846. case AV_CODEC_ID_PCM_F64LE:
  847. return 9;
  848. case AV_CODEC_ID_PCM_U8:
  849. return 10;
  850. case AV_CODEC_ID_PCM_S16BE:
  851. case AV_CODEC_ID_PCM_S24BE:
  852. case AV_CODEC_ID_PCM_S32BE:
  853. return 14;
  854. case AV_CODEC_ID_PCM_S8:
  855. case AV_CODEC_ID_PCM_S16LE:
  856. case AV_CODEC_ID_PCM_S24LE:
  857. case AV_CODEC_ID_PCM_S32LE:
  858. return 12;
  859. default:
  860. return 0;
  861. }
  862. }
  863. static int get_cluster_duration(MOVTrack *track, int cluster_idx)
  864. {
  865. int64_t next_dts;
  866. if (cluster_idx >= track->entry)
  867. return 0;
  868. if (cluster_idx + 1 == track->entry)
  869. next_dts = track->track_duration + track->start_dts;
  870. else
  871. next_dts = track->cluster[cluster_idx + 1].dts;
  872. next_dts -= track->cluster[cluster_idx].dts;
  873. av_assert0(next_dts >= 0);
  874. av_assert0(next_dts <= INT_MAX);
  875. return next_dts;
  876. }
  877. static int get_samples_per_packet(MOVTrack *track)
  878. {
  879. int i, first_duration;
  880. // return track->par->frame_size;
  881. /* use 1 for raw PCM */
  882. if (!track->audio_vbr)
  883. return 1;
  884. /* check to see if duration is constant for all clusters */
  885. if (!track->entry)
  886. return 0;
  887. first_duration = get_cluster_duration(track, 0);
  888. for (i = 1; i < track->entry; i++) {
  889. if (get_cluster_duration(track, i) != first_duration)
  890. return 0;
  891. }
  892. return first_duration;
  893. }
  894. static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
  895. {
  896. int64_t pos = avio_tell(pb);
  897. int version = 0;
  898. uint32_t tag = track->tag;
  899. if (track->mode == MODE_MOV) {
  900. if (track->timescale > UINT16_MAX) {
  901. if (mov_get_lpcm_flags(track->par->codec_id))
  902. tag = AV_RL32("lpcm");
  903. version = 2;
  904. } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
  905. mov_pcm_be_gt16(track->par->codec_id) ||
  906. track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
  907. track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
  908. track->par->codec_id == AV_CODEC_ID_QDM2) {
  909. version = 1;
  910. }
  911. }
  912. avio_wb32(pb, 0); /* size */
  913. if (mov->encryption_scheme != MOV_ENC_NONE) {
  914. ffio_wfourcc(pb, "enca");
  915. } else {
  916. avio_wl32(pb, tag); // store it byteswapped
  917. }
  918. avio_wb32(pb, 0); /* Reserved */
  919. avio_wb16(pb, 0); /* Reserved */
  920. avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
  921. /* SoundDescription */
  922. avio_wb16(pb, version); /* Version */
  923. avio_wb16(pb, 0); /* Revision level */
  924. avio_wb32(pb, 0); /* Reserved */
  925. if (version == 2) {
  926. avio_wb16(pb, 3);
  927. avio_wb16(pb, 16);
  928. avio_wb16(pb, 0xfffe);
  929. avio_wb16(pb, 0);
  930. avio_wb32(pb, 0x00010000);
  931. avio_wb32(pb, 72);
  932. avio_wb64(pb, av_double2int(track->par->sample_rate));
  933. avio_wb32(pb, track->par->channels);
  934. avio_wb32(pb, 0x7F000000);
  935. avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
  936. avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
  937. avio_wb32(pb, track->sample_size);
  938. avio_wb32(pb, get_samples_per_packet(track));
  939. } else {
  940. if (track->mode == MODE_MOV) {
  941. avio_wb16(pb, track->par->channels);
  942. if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
  943. track->par->codec_id == AV_CODEC_ID_PCM_S8)
  944. avio_wb16(pb, 8); /* bits per sample */
  945. else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
  946. avio_wb16(pb, track->par->bits_per_coded_sample);
  947. else
  948. avio_wb16(pb, 16);
  949. avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
  950. } else { /* reserved for mp4/3gp */
  951. if (track->par->codec_id == AV_CODEC_ID_FLAC ||
  952. track->par->codec_id == AV_CODEC_ID_OPUS) {
  953. avio_wb16(pb, track->par->channels);
  954. } else {
  955. avio_wb16(pb, 2);
  956. }
  957. if (track->par->codec_id == AV_CODEC_ID_FLAC) {
  958. avio_wb16(pb, track->par->bits_per_raw_sample);
  959. } else {
  960. avio_wb16(pb, 16);
  961. }
  962. avio_wb16(pb, 0);
  963. }
  964. avio_wb16(pb, 0); /* packet size (= 0) */
  965. if (track->par->codec_id == AV_CODEC_ID_OPUS)
  966. avio_wb16(pb, 48000);
  967. else
  968. avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
  969. track->par->sample_rate : 0);
  970. avio_wb16(pb, 0); /* Reserved */
  971. }
  972. if (version == 1) { /* SoundDescription V1 extended info */
  973. if (mov_pcm_le_gt16(track->par->codec_id) ||
  974. mov_pcm_be_gt16(track->par->codec_id))
  975. avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
  976. else
  977. avio_wb32(pb, track->par->frame_size); /* Samples per packet */
  978. avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
  979. avio_wb32(pb, track->sample_size); /* Bytes per frame */
  980. avio_wb32(pb, 2); /* Bytes per sample */
  981. }
  982. if (track->mode == MODE_MOV &&
  983. (track->par->codec_id == AV_CODEC_ID_AAC ||
  984. track->par->codec_id == AV_CODEC_ID_AC3 ||
  985. track->par->codec_id == AV_CODEC_ID_EAC3 ||
  986. track->par->codec_id == AV_CODEC_ID_AMR_NB ||
  987. track->par->codec_id == AV_CODEC_ID_ALAC ||
  988. track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
  989. track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
  990. track->par->codec_id == AV_CODEC_ID_QDM2 ||
  991. (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
  992. (mov_pcm_be_gt16(track->par->codec_id) && version==1)))
  993. mov_write_wave_tag(s, pb, track);
  994. else if (track->tag == MKTAG('m','p','4','a'))
  995. mov_write_esds_tag(pb, track);
  996. else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
  997. mov_write_amr_tag(pb, track);
  998. else if (track->par->codec_id == AV_CODEC_ID_AC3)
  999. mov_write_ac3_tag(pb, track);
  1000. else if (track->par->codec_id == AV_CODEC_ID_EAC3)
  1001. mov_write_eac3_tag(pb, track);
  1002. else if (track->par->codec_id == AV_CODEC_ID_ALAC)
  1003. mov_write_extradata_tag(pb, track);
  1004. else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
  1005. mov_write_wfex_tag(s, pb, track);
  1006. else if (track->par->codec_id == AV_CODEC_ID_FLAC)
  1007. mov_write_dfla_tag(pb, track);
  1008. else if (track->par->codec_id == AV_CODEC_ID_OPUS)
  1009. mov_write_dops_tag(pb, track);
  1010. else if (track->vos_len > 0)
  1011. mov_write_glbl_tag(pb, track);
  1012. if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)
  1013. mov_write_chan_tag(s, pb, track);
  1014. if (mov->encryption_scheme != MOV_ENC_NONE) {
  1015. ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
  1016. }
  1017. return update_size(pb, pos);
  1018. }
  1019. static int mov_write_d263_tag(AVIOContext *pb)
  1020. {
  1021. avio_wb32(pb, 0xf); /* size */
  1022. ffio_wfourcc(pb, "d263");
  1023. ffio_wfourcc(pb, "FFMP");
  1024. avio_w8(pb, 0); /* decoder version */
  1025. /* FIXME use AVCodecContext level/profile, when encoder will set values */
  1026. avio_w8(pb, 0xa); /* level */
  1027. avio_w8(pb, 0); /* profile */
  1028. return 0xf;
  1029. }
  1030. static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
  1031. {
  1032. int64_t pos = avio_tell(pb);
  1033. avio_wb32(pb, 0);
  1034. ffio_wfourcc(pb, "avcC");
  1035. ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
  1036. return update_size(pb, pos);
  1037. }
  1038. static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
  1039. {
  1040. int64_t pos = avio_tell(pb);
  1041. avio_wb32(pb, 0);
  1042. ffio_wfourcc(pb, "vpcC");
  1043. avio_w8(pb, 1); /* version */
  1044. avio_wb24(pb, 0); /* flags */
  1045. ff_isom_write_vpcc(s, pb, track->par);
  1046. return update_size(pb, pos);
  1047. }
  1048. static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
  1049. {
  1050. int64_t pos = avio_tell(pb);
  1051. avio_wb32(pb, 0);
  1052. ffio_wfourcc(pb, "hvcC");
  1053. if (track->tag == MKTAG('h','v','c','1'))
  1054. ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1);
  1055. else
  1056. ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
  1057. return update_size(pb, pos);
  1058. }
  1059. /* also used by all avid codecs (dv, imx, meridien) and their variants */
  1060. static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
  1061. {
  1062. int i;
  1063. int interlaced;
  1064. int cid;
  1065. int display_width = track->par->width;
  1066. if (track->vos_data && track->vos_len > 0x29) {
  1067. if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
  1068. /* looks like a DNxHD bit stream */
  1069. interlaced = (track->vos_data[5] & 2);
  1070. cid = AV_RB32(track->vos_data + 0x28);
  1071. } else {
  1072. av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
  1073. return 0;
  1074. }
  1075. } else {
  1076. av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
  1077. return 0;
  1078. }
  1079. avio_wb32(pb, 24); /* size */
  1080. ffio_wfourcc(pb, "ACLR");
  1081. ffio_wfourcc(pb, "ACLR");
  1082. ffio_wfourcc(pb, "0001");
  1083. if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
  1084. track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
  1085. avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
  1086. } else { /* Full range (0-255) */
  1087. avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
  1088. }
  1089. avio_wb32(pb, 0); /* unknown */
  1090. if (track->tag == MKTAG('A','V','d','h')) {
  1091. avio_wb32(pb, 32);
  1092. ffio_wfourcc(pb, "ADHR");
  1093. ffio_wfourcc(pb, "0001");
  1094. avio_wb32(pb, cid);
  1095. avio_wb32(pb, 0); /* unknown */
  1096. avio_wb32(pb, 1); /* unknown */
  1097. avio_wb32(pb, 0); /* unknown */
  1098. avio_wb32(pb, 0); /* unknown */
  1099. return 0;
  1100. }
  1101. avio_wb32(pb, 24); /* size */
  1102. ffio_wfourcc(pb, "APRG");
  1103. ffio_wfourcc(pb, "APRG");
  1104. ffio_wfourcc(pb, "0001");
  1105. avio_wb32(pb, 1); /* unknown */
  1106. avio_wb32(pb, 0); /* unknown */
  1107. avio_wb32(pb, 120); /* size */
  1108. ffio_wfourcc(pb, "ARES");
  1109. ffio_wfourcc(pb, "ARES");
  1110. ffio_wfourcc(pb, "0001");
  1111. avio_wb32(pb, cid); /* dnxhd cid, some id ? */
  1112. if ( track->par->sample_aspect_ratio.num > 0
  1113. && track->par->sample_aspect_ratio.den > 0)
  1114. display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
  1115. avio_wb32(pb, display_width);
  1116. /* values below are based on samples created with quicktime and avid codecs */
  1117. if (interlaced) {
  1118. avio_wb32(pb, track->par->height / 2);
  1119. avio_wb32(pb, 2); /* unknown */
  1120. avio_wb32(pb, 0); /* unknown */
  1121. avio_wb32(pb, 4); /* unknown */
  1122. } else {
  1123. avio_wb32(pb, track->par->height);
  1124. avio_wb32(pb, 1); /* unknown */
  1125. avio_wb32(pb, 0); /* unknown */
  1126. if (track->par->height == 1080)
  1127. avio_wb32(pb, 5); /* unknown */
  1128. else
  1129. avio_wb32(pb, 6); /* unknown */
  1130. }
  1131. /* padding */
  1132. for (i = 0; i < 10; i++)
  1133. avio_wb64(pb, 0);
  1134. return 0;
  1135. }
  1136. static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
  1137. {
  1138. avio_wb32(pb, 12);
  1139. ffio_wfourcc(pb, "DpxE");
  1140. if (track->par->extradata_size >= 12 &&
  1141. !memcmp(&track->par->extradata[4], "DpxE", 4)) {
  1142. avio_wb32(pb, track->par->extradata[11]);
  1143. } else {
  1144. avio_wb32(pb, 1);
  1145. }
  1146. return 0;
  1147. }
  1148. static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
  1149. {
  1150. int tag;
  1151. if (track->par->width == 720) { /* SD */
  1152. if (track->par->height == 480) { /* NTSC */
  1153. if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
  1154. else tag = MKTAG('d','v','c',' ');
  1155. }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
  1156. else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
  1157. else tag = MKTAG('d','v','p','p');
  1158. } else if (track->par->height == 720) { /* HD 720 line */
  1159. if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
  1160. else tag = MKTAG('d','v','h','p');
  1161. } else if (track->par->height == 1080) { /* HD 1080 line */
  1162. if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
  1163. else tag = MKTAG('d','v','h','6');
  1164. } else {
  1165. av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
  1166. return 0;
  1167. }
  1168. return tag;
  1169. }
  1170. static AVRational find_fps(AVFormatContext *s, AVStream *st)
  1171. {
  1172. AVRational rate = st->avg_frame_rate;
  1173. #if FF_API_LAVF_AVCTX
  1174. FF_DISABLE_DEPRECATION_WARNINGS
  1175. rate = av_inv_q(st->codec->time_base);
  1176. if (av_timecode_check_frame_rate(rate) < 0) {
  1177. av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
  1178. rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
  1179. rate = st->avg_frame_rate;
  1180. }
  1181. FF_ENABLE_DEPRECATION_WARNINGS
  1182. #endif
  1183. return rate;
  1184. }
  1185. static int defined_frame_rate(AVFormatContext *s, AVStream *st)
  1186. {
  1187. AVRational rational_framerate = find_fps(s, st);
  1188. int rate = 0;
  1189. if (rational_framerate.den != 0)
  1190. rate = av_q2d(rational_framerate);
  1191. return rate;
  1192. }
  1193. static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
  1194. {
  1195. int tag = track->par->codec_tag;
  1196. int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
  1197. AVStream *st = track->st;
  1198. int rate = defined_frame_rate(s, st);
  1199. if (!tag)
  1200. tag = MKTAG('m', '2', 'v', '1'); //fallback tag
  1201. if (track->par->format == AV_PIX_FMT_YUV420P) {
  1202. if (track->par->width == 1280 && track->par->height == 720) {
  1203. if (!interlaced) {
  1204. if (rate == 24) tag = MKTAG('x','d','v','4');
  1205. else if (rate == 25) tag = MKTAG('x','d','v','5');
  1206. else if (rate == 30) tag = MKTAG('x','d','v','1');
  1207. else if (rate == 50) tag = MKTAG('x','d','v','a');
  1208. else if (rate == 60) tag = MKTAG('x','d','v','9');
  1209. }
  1210. } else if (track->par->width == 1440 && track->par->height == 1080) {
  1211. if (!interlaced) {
  1212. if (rate == 24) tag = MKTAG('x','d','v','6');
  1213. else if (rate == 25) tag = MKTAG('x','d','v','7');
  1214. else if (rate == 30) tag = MKTAG('x','d','v','8');
  1215. } else {
  1216. if (rate == 25) tag = MKTAG('x','d','v','3');
  1217. else if (rate == 30) tag = MKTAG('x','d','v','2');
  1218. }
  1219. } else if (track->par->width == 1920 && track->par->height == 1080) {
  1220. if (!interlaced) {
  1221. if (rate == 24) tag = MKTAG('x','d','v','d');
  1222. else if (rate == 25) tag = MKTAG('x','d','v','e');
  1223. else if (rate == 30) tag = MKTAG('x','d','v','f');
  1224. } else {
  1225. if (rate == 25) tag = MKTAG('x','d','v','c');
  1226. else if (rate == 30) tag = MKTAG('x','d','v','b');
  1227. }
  1228. }
  1229. } else if (track->par->format == AV_PIX_FMT_YUV422P) {
  1230. if (track->par->width == 1280 && track->par->height == 720) {
  1231. if (!interlaced) {
  1232. if (rate == 24) tag = MKTAG('x','d','5','4');
  1233. else if (rate == 25) tag = MKTAG('x','d','5','5');
  1234. else if (rate == 30) tag = MKTAG('x','d','5','1');
  1235. else if (rate == 50) tag = MKTAG('x','d','5','a');
  1236. else if (rate == 60) tag = MKTAG('x','d','5','9');
  1237. }
  1238. } else if (track->par->width == 1920 && track->par->height == 1080) {
  1239. if (!interlaced) {
  1240. if (rate == 24) tag = MKTAG('x','d','5','d');
  1241. else if (rate == 25) tag = MKTAG('x','d','5','e');
  1242. else if (rate == 30) tag = MKTAG('x','d','5','f');
  1243. } else {
  1244. if (rate == 25) tag = MKTAG('x','d','5','c');
  1245. else if (rate == 30) tag = MKTAG('x','d','5','b');
  1246. }
  1247. }
  1248. }
  1249. return tag;
  1250. }
  1251. static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
  1252. {
  1253. int tag = track->par->codec_tag;
  1254. int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
  1255. AVStream *st = track->st;
  1256. int rate = defined_frame_rate(s, st);
  1257. if (!tag)
  1258. tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
  1259. if (track->par->format == AV_PIX_FMT_YUV420P10) {
  1260. if (track->par->width == 960 && track->par->height == 720) {
  1261. if (!interlaced) {
  1262. if (rate == 24) tag = MKTAG('a','i','5','p');
  1263. else if (rate == 25) tag = MKTAG('a','i','5','q');
  1264. else if (rate == 30) tag = MKTAG('a','i','5','p');
  1265. else if (rate == 50) tag = MKTAG('a','i','5','q');
  1266. else if (rate == 60) tag = MKTAG('a','i','5','p');
  1267. }
  1268. } else if (track->par->width == 1440 && track->par->height == 1080) {
  1269. if (!interlaced) {
  1270. if (rate == 24) tag = MKTAG('a','i','5','3');
  1271. else if (rate == 25) tag = MKTAG('a','i','5','2');
  1272. else if (rate == 30) tag = MKTAG('a','i','5','3');
  1273. } else {
  1274. if (rate == 50) tag = MKTAG('a','i','5','5');
  1275. else if (rate == 60) tag = MKTAG('a','i','5','6');
  1276. }
  1277. }
  1278. } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
  1279. if (track->par->width == 1280 && track->par->height == 720) {
  1280. if (!interlaced) {
  1281. if (rate == 24) tag = MKTAG('a','i','1','p');
  1282. else if (rate == 25) tag = MKTAG('a','i','1','q');
  1283. else if (rate == 30) tag = MKTAG('a','i','1','p');
  1284. else if (rate == 50) tag = MKTAG('a','i','1','q');
  1285. else if (rate == 60) tag = MKTAG('a','i','1','p');
  1286. }
  1287. } else if (track->par->width == 1920 && track->par->height == 1080) {
  1288. if (!interlaced) {
  1289. if (rate == 24) tag = MKTAG('a','i','1','3');
  1290. else if (rate == 25) tag = MKTAG('a','i','1','2');
  1291. else if (rate == 30) tag = MKTAG('a','i','1','3');
  1292. } else {
  1293. if (rate == 25) tag = MKTAG('a','i','1','5');
  1294. else if (rate == 50) tag = MKTAG('a','i','1','5');
  1295. else if (rate == 60) tag = MKTAG('a','i','1','6');
  1296. }
  1297. } else if ( track->par->width == 4096 && track->par->height == 2160
  1298. || track->par->width == 3840 && track->par->height == 2160
  1299. || track->par->width == 2048 && track->par->height == 1080) {
  1300. tag = MKTAG('a','i','v','x');
  1301. }
  1302. }
  1303. return tag;
  1304. }
  1305. static const struct {
  1306. enum AVPixelFormat pix_fmt;
  1307. uint32_t tag;
  1308. unsigned bps;
  1309. } mov_pix_fmt_tags[] = {
  1310. { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
  1311. { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
  1312. { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
  1313. { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
  1314. { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
  1315. { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
  1316. { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
  1317. { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
  1318. { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
  1319. { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
  1320. { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
  1321. { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
  1322. { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
  1323. { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
  1324. { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
  1325. };
  1326. static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
  1327. {
  1328. int tag = MKTAG('A','V','d','n');
  1329. if (track->par->profile != FF_PROFILE_UNKNOWN &&
  1330. track->par->profile != FF_PROFILE_DNXHD)
  1331. tag = MKTAG('A','V','d','h');
  1332. return tag;
  1333. }
  1334. static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
  1335. {
  1336. int tag = track->par->codec_tag;
  1337. int i;
  1338. enum AVPixelFormat pix_fmt;
  1339. for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
  1340. if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
  1341. tag = mov_pix_fmt_tags[i].tag;
  1342. track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
  1343. if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
  1344. break;
  1345. }
  1346. }
  1347. pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
  1348. track->par->bits_per_coded_sample);
  1349. if (tag == MKTAG('r','a','w',' ') &&
  1350. track->par->format != pix_fmt &&
  1351. track->par->format != AV_PIX_FMT_GRAY8 &&
  1352. track->par->format != AV_PIX_FMT_NONE)
  1353. av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
  1354. av_get_pix_fmt_name(track->par->format));
  1355. return tag;
  1356. }
  1357. static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
  1358. {
  1359. int tag = track->par->codec_tag;
  1360. if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
  1361. (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
  1362. track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
  1363. track->par->codec_id == AV_CODEC_ID_H263 ||
  1364. track->par->codec_id == AV_CODEC_ID_H264 ||
  1365. track->par->codec_id == AV_CODEC_ID_DNXHD ||
  1366. track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
  1367. av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
  1368. if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
  1369. tag = mov_get_dv_codec_tag(s, track);
  1370. else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
  1371. tag = mov_get_rawvideo_codec_tag(s, track);
  1372. else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
  1373. tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
  1374. else if (track->par->codec_id == AV_CODEC_ID_H264)
  1375. tag = mov_get_h264_codec_tag(s, track);
  1376. else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
  1377. tag = mov_get_dnxhd_codec_tag(s, track);
  1378. else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  1379. tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
  1380. if (!tag) { // if no mac fcc found, try with Microsoft tags
  1381. tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
  1382. if (tag)
  1383. av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
  1384. "the file may be unplayable!\n");
  1385. }
  1386. } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
  1387. tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
  1388. if (!tag) { // if no mac fcc found, try with Microsoft tags
  1389. int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
  1390. if (ms_tag) {
  1391. tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
  1392. av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
  1393. "the file may be unplayable!\n");
  1394. }
  1395. }
  1396. } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
  1397. tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
  1398. }
  1399. return tag;
  1400. }
  1401. static const AVCodecTag codec_cover_image_tags[] = {
  1402. { AV_CODEC_ID_MJPEG, 0xD },
  1403. { AV_CODEC_ID_PNG, 0xE },
  1404. { AV_CODEC_ID_BMP, 0x1B },
  1405. { AV_CODEC_ID_NONE, 0 },
  1406. };
  1407. static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
  1408. {
  1409. int tag;
  1410. if (is_cover_image(track->st))
  1411. return ff_codec_get_tag(codec_cover_image_tags, track->par->codec_id);
  1412. if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
  1413. tag = track->par->codec_tag;
  1414. else if (track->mode == MODE_ISM)
  1415. tag = track->par->codec_tag;
  1416. else if (track->mode == MODE_IPOD) {
  1417. if (!av_match_ext(s->url, "m4a") &&
  1418. !av_match_ext(s->url, "m4v") &&
  1419. !av_match_ext(s->url, "m4b"))
  1420. av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
  1421. "Quicktime/Ipod might not play the file\n");
  1422. tag = track->par->codec_tag;
  1423. } else if (track->mode & MODE_3GP)
  1424. tag = track->par->codec_tag;
  1425. else if (track->mode == MODE_F4V)
  1426. tag = track->par->codec_tag;
  1427. else
  1428. tag = mov_get_codec_tag(s, track);
  1429. return tag;
  1430. }
  1431. /** Write uuid atom.
  1432. * Needed to make file play in iPods running newest firmware
  1433. * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
  1434. */
  1435. static int mov_write_uuid_tag_ipod(AVIOContext *pb)
  1436. {
  1437. avio_wb32(pb, 28);
  1438. ffio_wfourcc(pb, "uuid");
  1439. avio_wb32(pb, 0x6b6840f2);
  1440. avio_wb32(pb, 0x5f244fc5);
  1441. avio_wb32(pb, 0xba39a51b);
  1442. avio_wb32(pb, 0xcf0323f3);
  1443. avio_wb32(pb, 0x0);
  1444. return 28;
  1445. }
  1446. static const uint16_t fiel_data[] = {
  1447. 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
  1448. };
  1449. static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
  1450. {
  1451. unsigned mov_field_order = 0;
  1452. if (field_order < FF_ARRAY_ELEMS(fiel_data))
  1453. mov_field_order = fiel_data[field_order];
  1454. else
  1455. return 0;
  1456. avio_wb32(pb, 10);
  1457. ffio_wfourcc(pb, "fiel");
  1458. avio_wb16(pb, mov_field_order);
  1459. return 10;
  1460. }
  1461. static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
  1462. {
  1463. int64_t pos = avio_tell(pb);
  1464. avio_wb32(pb, 0); /* size */
  1465. avio_wl32(pb, track->tag); // store it byteswapped
  1466. avio_wb32(pb, 0); /* Reserved */
  1467. avio_wb16(pb, 0); /* Reserved */
  1468. avio_wb16(pb, 1); /* Data-reference index */
  1469. if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
  1470. mov_write_esds_tag(pb, track);
  1471. else if (track->par->extradata_size)
  1472. avio_write(pb, track->par->extradata, track->par->extradata_size);
  1473. return update_size(pb, pos);
  1474. }
  1475. static int mov_write_st3d_tag(AVIOContext *pb, AVStereo3D *stereo_3d)
  1476. {
  1477. int8_t stereo_mode;
  1478. if (stereo_3d->flags != 0) {
  1479. av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags);
  1480. return 0;
  1481. }
  1482. switch (stereo_3d->type) {
  1483. case AV_STEREO3D_2D:
  1484. stereo_mode = 0;
  1485. break;
  1486. case AV_STEREO3D_TOPBOTTOM:
  1487. stereo_mode = 1;
  1488. break;
  1489. case AV_STEREO3D_SIDEBYSIDE:
  1490. stereo_mode = 2;
  1491. break;
  1492. default:
  1493. av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type));
  1494. return 0;
  1495. }
  1496. avio_wb32(pb, 13); /* size */
  1497. ffio_wfourcc(pb, "st3d");
  1498. avio_wb32(pb, 0); /* version = 0 & flags = 0 */
  1499. avio_w8(pb, stereo_mode);
  1500. return 13;
  1501. }
  1502. static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping)
  1503. {
  1504. int64_t sv3d_pos, svhd_pos, proj_pos;
  1505. const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT;
  1506. if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
  1507. spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
  1508. spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) {
  1509. av_log(pb, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection);
  1510. return 0;
  1511. }
  1512. sv3d_pos = avio_tell(pb);
  1513. avio_wb32(pb, 0); /* size */
  1514. ffio_wfourcc(pb, "sv3d");
  1515. svhd_pos = avio_tell(pb);
  1516. avio_wb32(pb, 0); /* size */
  1517. ffio_wfourcc(pb, "svhd");
  1518. avio_wb32(pb, 0); /* version = 0 & flags = 0 */
  1519. avio_put_str(pb, metadata_source);
  1520. update_size(pb, svhd_pos);
  1521. proj_pos = avio_tell(pb);
  1522. avio_wb32(pb, 0); /* size */
  1523. ffio_wfourcc(pb, "proj");
  1524. avio_wb32(pb, 24); /* size */
  1525. ffio_wfourcc(pb, "prhd");
  1526. avio_wb32(pb, 0); /* version = 0 & flags = 0 */
  1527. avio_wb32(pb, spherical_mapping->yaw);
  1528. avio_wb32(pb, spherical_mapping->pitch);
  1529. avio_wb32(pb, spherical_mapping->roll);
  1530. switch (spherical_mapping->projection) {
  1531. case AV_SPHERICAL_EQUIRECTANGULAR:
  1532. case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
  1533. avio_wb32(pb, 28); /* size */
  1534. ffio_wfourcc(pb, "equi");
  1535. avio_wb32(pb, 0); /* version = 0 & flags = 0 */
  1536. avio_wb32(pb, spherical_mapping->bound_top);
  1537. avio_wb32(pb, spherical_mapping->bound_bottom);
  1538. avio_wb32(pb, spherical_mapping->bound_left);
  1539. avio_wb32(pb, spherical_mapping->bound_right);
  1540. break;
  1541. case AV_SPHERICAL_CUBEMAP:
  1542. avio_wb32(pb, 20); /* size */
  1543. ffio_wfourcc(pb, "cbmp");
  1544. avio_wb32(pb, 0); /* version = 0 & flags = 0 */
  1545. avio_wb32(pb, 0); /* layout */
  1546. avio_wb32(pb, spherical_mapping->padding); /* padding */
  1547. break;
  1548. }
  1549. update_size(pb, proj_pos);
  1550. return update_size(pb, sv3d_pos);
  1551. }
  1552. static int mov_write_clap_tag(AVIOContext *pb, MOVTrack *track)
  1553. {
  1554. avio_wb32(pb, 40);
  1555. ffio_wfourcc(pb, "clap");
  1556. avio_wb32(pb, track->par->width); /* apertureWidth_N */
  1557. avio_wb32(pb, 1); /* apertureWidth_D (= 1) */
  1558. avio_wb32(pb, track->height); /* apertureHeight_N */
  1559. avio_wb32(pb, 1); /* apertureHeight_D (= 1) */
  1560. avio_wb32(pb, 0); /* horizOff_N (= 0) */
  1561. avio_wb32(pb, 1); /* horizOff_D (= 1) */
  1562. avio_wb32(pb, 0); /* vertOff_N (= 0) */
  1563. avio_wb32(pb, 1); /* vertOff_D (= 1) */
  1564. return 40;
  1565. }
  1566. static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
  1567. {
  1568. AVRational sar;
  1569. av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
  1570. track->par->sample_aspect_ratio.den, INT_MAX);
  1571. avio_wb32(pb, 16);
  1572. ffio_wfourcc(pb, "pasp");
  1573. avio_wb32(pb, sar.num);
  1574. avio_wb32(pb, sar.den);
  1575. return 16;
  1576. }
  1577. static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
  1578. {
  1579. uint32_t gama = 0;
  1580. if (gamma <= 0.0)
  1581. {
  1582. gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
  1583. }
  1584. av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
  1585. if (gamma > 1e-6) {
  1586. gama = (uint32_t)lrint((double)(1<<16) * gamma);
  1587. av_log(pb, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama);
  1588. av_assert0(track->mode == MODE_MOV);
  1589. avio_wb32(pb, 12);
  1590. ffio_wfourcc(pb, "gama");
  1591. avio_wb32(pb, gama);
  1592. return 12;
  1593. }
  1594. else {
  1595. av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
  1596. }
  1597. return 0;
  1598. }
  1599. static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
  1600. {
  1601. // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
  1602. // Ref (MP4): ISO/IEC 14496-12:2012
  1603. if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
  1604. track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
  1605. track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
  1606. if ((track->par->width >= 1920 && track->par->height >= 1080)
  1607. || (track->par->width == 1280 && track->par->height == 720)) {
  1608. av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
  1609. track->par->color_primaries = AVCOL_PRI_BT709;
  1610. } else if (track->par->width == 720 && track->height == 576) {
  1611. av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
  1612. track->par->color_primaries = AVCOL_PRI_BT470BG;
  1613. } else if (track->par->width == 720 &&
  1614. (track->height == 486 || track->height == 480)) {
  1615. av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
  1616. track->par->color_primaries = AVCOL_PRI_SMPTE170M;
  1617. } else {
  1618. av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
  1619. }
  1620. switch (track->par->color_primaries) {
  1621. case AVCOL_PRI_BT709:
  1622. track->par->color_trc = AVCOL_TRC_BT709;
  1623. track->par->color_space = AVCOL_SPC_BT709;
  1624. break;
  1625. case AVCOL_PRI_SMPTE170M:
  1626. case AVCOL_PRI_BT470BG:
  1627. track->par->color_trc = AVCOL_TRC_BT709;
  1628. track->par->color_space = AVCOL_SPC_SMPTE170M;
  1629. break;
  1630. }
  1631. }
  1632. /* We should only ever be called by MOV or MP4. */
  1633. av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
  1634. avio_wb32(pb, 18 + (track->mode == MODE_MP4));
  1635. ffio_wfourcc(pb, "colr");
  1636. if (track->mode == MODE_MP4)
  1637. ffio_wfourcc(pb, "nclx");
  1638. else
  1639. ffio_wfourcc(pb, "nclc");
  1640. switch (track->par->color_primaries) {
  1641. case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
  1642. case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
  1643. case AVCOL_PRI_SMPTE170M:
  1644. case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
  1645. case AVCOL_PRI_BT2020: avio_wb16(pb, 9); break;
  1646. case AVCOL_PRI_SMPTE431: avio_wb16(pb, 11); break;
  1647. case AVCOL_PRI_SMPTE432: avio_wb16(pb, 12); break;
  1648. default: avio_wb16(pb, 2);
  1649. }
  1650. switch (track->par->color_trc) {
  1651. case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
  1652. case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
  1653. case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
  1654. case AVCOL_TRC_SMPTEST2084: avio_wb16(pb, 16); break;
  1655. case AVCOL_TRC_SMPTE428: avio_wb16(pb, 17); break;
  1656. case AVCOL_TRC_ARIB_STD_B67: avio_wb16(pb, 18); break;
  1657. default: avio_wb16(pb, 2);
  1658. }
  1659. switch (track->par->color_space) {
  1660. case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
  1661. case AVCOL_SPC_BT470BG:
  1662. case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
  1663. case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
  1664. case AVCOL_SPC_BT2020_NCL: avio_wb16(pb, 9); break;
  1665. default: avio_wb16(pb, 2);
  1666. }
  1667. if (track->mode == MODE_MP4) {
  1668. int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
  1669. avio_w8(pb, full_range << 7);
  1670. return 19;
  1671. } else {
  1672. return 18;
  1673. }
  1674. }
  1675. static void find_compressor(char * compressor_name, int len, MOVTrack *track)
  1676. {
  1677. AVDictionaryEntry *encoder;
  1678. int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
  1679. || (track->par->width == 1440 && track->par->height == 1080)
  1680. || (track->par->width == 1920 && track->par->height == 1080);
  1681. if (track->mode == MODE_MOV &&
  1682. (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
  1683. av_strlcpy(compressor_name, encoder->value, 32);
  1684. } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
  1685. int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
  1686. AVStream *st = track->st;
  1687. int rate = defined_frame_rate(NULL, st);
  1688. av_strlcatf(compressor_name, len, "XDCAM");
  1689. if (track->par->format == AV_PIX_FMT_YUV422P) {
  1690. av_strlcatf(compressor_name, len, " HD422");
  1691. } else if(track->par->width == 1440) {
  1692. av_strlcatf(compressor_name, len, " HD");
  1693. } else
  1694. av_strlcatf(compressor_name, len, " EX");
  1695. av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
  1696. av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
  1697. }
  1698. }
  1699. static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
  1700. {
  1701. int64_t pos = avio_tell(pb);
  1702. char compressor_name[32] = { 0 };
  1703. int avid = 0;
  1704. int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422)
  1705. || (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422)
  1706. || track->par->codec_id == AV_CODEC_ID_V308
  1707. || track->par->codec_id == AV_CODEC_ID_V408
  1708. || track->par->codec_id == AV_CODEC_ID_V410
  1709. || track->par->codec_id == AV_CODEC_ID_V210);
  1710. avio_wb32(pb, 0); /* size */
  1711. if (mov->encryption_scheme != MOV_ENC_NONE) {
  1712. ffio_wfourcc(pb, "encv");
  1713. } else {
  1714. avio_wl32(pb, track->tag); // store it byteswapped
  1715. }
  1716. avio_wb32(pb, 0); /* Reserved */
  1717. avio_wb16(pb, 0); /* Reserved */
  1718. avio_wb16(pb, 1); /* Data-reference index */
  1719. if (uncompressed_ycbcr) {
  1720. avio_wb16(pb, 2); /* Codec stream version */
  1721. } else {
  1722. avio_wb16(pb, 0); /* Codec stream version */
  1723. }
  1724. avio_wb16(pb, 0); /* Codec stream revision (=0) */
  1725. if (track->mode == MODE_MOV) {
  1726. ffio_wfourcc(pb, "FFMP"); /* Vendor */
  1727. if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) {
  1728. avio_wb32(pb, 0); /* Temporal Quality */
  1729. avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
  1730. } else {
  1731. avio_wb32(pb, 0x200); /* Temporal Quality = normal */
  1732. avio_wb32(pb, 0x200); /* Spatial Quality = normal */
  1733. }
  1734. } else {
  1735. avio_wb32(pb, 0); /* Reserved */
  1736. avio_wb32(pb, 0); /* Reserved */
  1737. avio_wb32(pb, 0); /* Reserved */
  1738. }
  1739. avio_wb16(pb, track->par->width); /* Video width */
  1740. avio_wb16(pb, track->height); /* Video height */
  1741. avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
  1742. avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
  1743. avio_wb32(pb, 0); /* Data size (= 0) */
  1744. avio_wb16(pb, 1); /* Frame count (= 1) */
  1745. /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
  1746. find_compressor(compressor_name, 32, track);
  1747. avio_w8(pb, strlen(compressor_name));
  1748. avio_write(pb, compressor_name, 31);
  1749. if (track->mode == MODE_MOV &&
  1750. (track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210))
  1751. avio_wb16(pb, 0x18);
  1752. else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
  1753. avio_wb16(pb, track->par->bits_per_coded_sample |
  1754. (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
  1755. else
  1756. avio_wb16(pb, 0x18); /* Reserved */
  1757. if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
  1758. int pal_size = 1 << track->par->bits_per_coded_sample;
  1759. int i;
  1760. avio_wb16(pb, 0); /* Color table ID */
  1761. avio_wb32(pb, 0); /* Color table seed */
  1762. avio_wb16(pb, 0x8000); /* Color table flags */
  1763. avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
  1764. for (i = 0; i < pal_size; i++) {
  1765. uint32_t rgb = track->palette[i];
  1766. uint16_t r = (rgb >> 16) & 0xff;
  1767. uint16_t g = (rgb >> 8) & 0xff;
  1768. uint16_t b = rgb & 0xff;
  1769. avio_wb16(pb, 0);
  1770. avio_wb16(pb, (r << 8) | r);
  1771. avio_wb16(pb, (g << 8) | g);
  1772. avio_wb16(pb, (b << 8) | b);
  1773. }
  1774. } else
  1775. avio_wb16(pb, 0xffff); /* Reserved */
  1776. if (track->tag == MKTAG('m','p','4','v'))
  1777. mov_write_esds_tag(pb, track);
  1778. else if (track->par->codec_id == AV_CODEC_ID_H263)
  1779. mov_write_d263_tag(pb);
  1780. else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
  1781. track->par->codec_id == AV_CODEC_ID_SVQ3) {
  1782. mov_write_extradata_tag(pb, track);
  1783. avio_wb32(pb, 0);
  1784. } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
  1785. mov_write_avid_tag(pb, track);
  1786. avid = 1;
  1787. } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
  1788. mov_write_hvcc_tag(pb, track);
  1789. else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
  1790. mov_write_avcc_tag(pb, track);
  1791. if (track->mode == MODE_IPOD)
  1792. mov_write_uuid_tag_ipod(pb);
  1793. } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
  1794. mov_write_vpcc_tag(mov->fc, pb, track);
  1795. } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
  1796. mov_write_dvc1_tag(pb, track);
  1797. else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
  1798. track->par->codec_id == AV_CODEC_ID_VP6A) {
  1799. /* Don't write any potential extradata here - the cropping
  1800. * is signalled via the normal width/height fields. */
  1801. } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
  1802. if (track->par->codec_tag == MKTAG('R','1','0','k'))
  1803. mov_write_dpxe_tag(pb, track);
  1804. } else if (track->vos_len > 0)
  1805. mov_write_glbl_tag(pb, track);
  1806. if (track->par->codec_id != AV_CODEC_ID_H264 &&
  1807. track->par->codec_id != AV_CODEC_ID_MPEG4 &&
  1808. track->par->codec_id != AV_CODEC_ID_DNXHD) {
  1809. int field_order = track->par->field_order;
  1810. #if FF_API_LAVF_AVCTX
  1811. FF_DISABLE_DEPRECATION_WARNINGS
  1812. if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
  1813. field_order = track->st->codec->field_order;
  1814. FF_ENABLE_DEPRECATION_WARNINGS
  1815. #endif
  1816. if (field_order != AV_FIELD_UNKNOWN)
  1817. mov_write_fiel_tag(pb, track, field_order);
  1818. }
  1819. if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
  1820. if (track->mode == MODE_MOV)
  1821. mov_write_gama_tag(pb, track, mov->gamma);
  1822. else
  1823. av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
  1824. }
  1825. if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
  1826. if (track->mode == MODE_MOV || track->mode == MODE_MP4)
  1827. mov_write_colr_tag(pb, track);
  1828. else
  1829. av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
  1830. }
  1831. if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
  1832. AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL);
  1833. AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL);
  1834. if (stereo_3d)
  1835. mov_write_st3d_tag(pb, stereo_3d);
  1836. if (spherical_mapping)
  1837. mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
  1838. }
  1839. if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
  1840. mov_write_pasp_tag(pb, track);
  1841. }
  1842. if (uncompressed_ycbcr){
  1843. mov_write_clap_tag(pb, track);
  1844. }
  1845. if (mov->encryption_scheme != MOV_ENC_NONE) {
  1846. ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
  1847. }
  1848. /* extra padding for avid stsd */
  1849. /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
  1850. if (avid)
  1851. avio_wb32(pb, 0);
  1852. return update_size(pb, pos);
  1853. }
  1854. static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
  1855. {
  1856. int64_t pos = avio_tell(pb);
  1857. avio_wb32(pb, 0); /* size */
  1858. ffio_wfourcc(pb, "rtp ");
  1859. avio_wb32(pb, 0); /* Reserved */
  1860. avio_wb16(pb, 0); /* Reserved */
  1861. avio_wb16(pb, 1); /* Data-reference index */
  1862. avio_wb16(pb, 1); /* Hint track version */
  1863. avio_wb16(pb, 1); /* Highest compatible version */
  1864. avio_wb32(pb, track->max_packet_size); /* Max packet size */
  1865. avio_wb32(pb, 12); /* size */
  1866. ffio_wfourcc(pb, "tims");
  1867. avio_wb32(pb, track->timescale);
  1868. return update_size(pb, pos);
  1869. }
  1870. static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
  1871. {
  1872. uint64_t str_size =strlen(reel_name);
  1873. int64_t pos = avio_tell(pb);
  1874. if (str_size >= UINT16_MAX){
  1875. av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
  1876. avio_wb16(pb, 0);
  1877. return AVERROR(EINVAL);
  1878. }
  1879. avio_wb32(pb, 0); /* size */
  1880. ffio_wfourcc(pb, "name"); /* Data format */
  1881. avio_wb16(pb, str_size); /* string size */
  1882. avio_wb16(pb, track->language); /* langcode */
  1883. avio_write(pb, reel_name, str_size); /* reel name */
  1884. return update_size(pb,pos);
  1885. }
  1886. static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
  1887. {
  1888. int64_t pos = avio_tell(pb);
  1889. #if 1
  1890. int frame_duration;
  1891. int nb_frames;
  1892. AVDictionaryEntry *t = NULL;
  1893. if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
  1894. #if FF_API_LAVF_AVCTX
  1895. FF_DISABLE_DEPRECATION_WARNINGS
  1896. frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
  1897. nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
  1898. FF_ENABLE_DEPRECATION_WARNINGS
  1899. #else
  1900. av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
  1901. return AVERROR(EINVAL);
  1902. #endif
  1903. } else {
  1904. frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
  1905. nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
  1906. }
  1907. if (nb_frames > 255) {
  1908. av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
  1909. return AVERROR(EINVAL);
  1910. }
  1911. avio_wb32(pb, 0); /* size */
  1912. ffio_wfourcc(pb, "tmcd"); /* Data format */
  1913. avio_wb32(pb, 0); /* Reserved */
  1914. avio_wb32(pb, 1); /* Data reference index */
  1915. avio_wb32(pb, 0); /* Flags */
  1916. avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
  1917. avio_wb32(pb, track->timescale); /* Timescale */
  1918. avio_wb32(pb, frame_duration); /* Frame duration */
  1919. avio_w8(pb, nb_frames); /* Number of frames */
  1920. avio_w8(pb, 0); /* Reserved */
  1921. t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
  1922. if (t && utf8len(t->value) && track->mode != MODE_MP4)
  1923. mov_write_source_reference_tag(pb, track, t->value);
  1924. else
  1925. avio_wb16(pb, 0); /* zero size */
  1926. #else
  1927. avio_wb32(pb, 0); /* size */
  1928. ffio_wfourcc(pb, "tmcd"); /* Data format */
  1929. avio_wb32(pb, 0); /* Reserved */
  1930. avio_wb32(pb, 1); /* Data reference index */
  1931. if (track->par->extradata_size)
  1932. avio_write(pb, track->par->extradata, track->par->extradata_size);
  1933. #endif
  1934. return update_size(pb, pos);
  1935. }
  1936. static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track)
  1937. {
  1938. int64_t pos = avio_tell(pb);
  1939. avio_wb32(pb, 0); /* size */
  1940. ffio_wfourcc(pb, "gpmd");
  1941. avio_wb32(pb, 0); /* Reserved */
  1942. avio_wb16(pb, 0); /* Reserved */
  1943. avio_wb16(pb, 1); /* Data-reference index */
  1944. avio_wb32(pb, 0); /* Reserved */
  1945. return update_size(pb, pos);
  1946. }
  1947. static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
  1948. {
  1949. int64_t pos = avio_tell(pb);
  1950. avio_wb32(pb, 0); /* size */
  1951. ffio_wfourcc(pb, "stsd");
  1952. avio_wb32(pb, 0); /* version & flags */
  1953. avio_wb32(pb, 1); /* entry count */
  1954. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
  1955. mov_write_video_tag(pb, mov, track);
  1956. else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
  1957. mov_write_audio_tag(s, pb, mov, track);
  1958. else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
  1959. mov_write_subtitle_tag(pb, track);
  1960. else if (track->par->codec_tag == MKTAG('r','t','p',' '))
  1961. mov_write_rtp_tag(pb, track);
  1962. else if (track->par->codec_tag == MKTAG('t','m','c','d'))
  1963. mov_write_tmcd_tag(pb, track);
  1964. else if (track->par->codec_tag == MKTAG('g','p','m','d'))
  1965. mov_write_gpmd_tag(pb, track);
  1966. return update_size(pb, pos);
  1967. }
  1968. static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
  1969. {
  1970. MOVMuxContext *mov = s->priv_data;
  1971. MOVStts *ctts_entries;
  1972. uint32_t entries = 0;
  1973. uint32_t atom_size;
  1974. int i;
  1975. ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
  1976. if (!ctts_entries)
  1977. return AVERROR(ENOMEM);
  1978. ctts_entries[0].count = 1;
  1979. ctts_entries[0].duration = track->cluster[0].cts;
  1980. for (i = 1; i < track->entry; i++) {
  1981. if (track->cluster[i].cts == ctts_entries[entries].duration) {
  1982. ctts_entries[entries].count++; /* compress */
  1983. } else {
  1984. entries++;
  1985. ctts_entries[entries].duration = track->cluster[i].cts;
  1986. ctts_entries[entries].count = 1;
  1987. }
  1988. }
  1989. entries++; /* last one */
  1990. atom_size = 16 + (entries * 8);
  1991. avio_wb32(pb, atom_size); /* size */
  1992. ffio_wfourcc(pb, "ctts");
  1993. if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
  1994. avio_w8(pb, 1); /* version */
  1995. else
  1996. avio_w8(pb, 0); /* version */
  1997. avio_wb24(pb, 0); /* flags */
  1998. avio_wb32(pb, entries); /* entry count */
  1999. for (i = 0; i < entries; i++) {
  2000. avio_wb32(pb, ctts_entries[i].count);
  2001. avio_wb32(pb, ctts_entries[i].duration);
  2002. }
  2003. av_free(ctts_entries);
  2004. return atom_size;
  2005. }
  2006. /* Time to sample atom */
  2007. static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
  2008. {
  2009. MOVStts *stts_entries = NULL;
  2010. uint32_t entries = -1;
  2011. uint32_t atom_size;
  2012. int i;
  2013. if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
  2014. stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
  2015. if (!stts_entries)
  2016. return AVERROR(ENOMEM);
  2017. stts_entries[0].count = track->sample_count;
  2018. stts_entries[0].duration = 1;
  2019. entries = 1;
  2020. } else {
  2021. if (track->entry) {
  2022. stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
  2023. if (!stts_entries)
  2024. return AVERROR(ENOMEM);
  2025. }
  2026. for (i = 0; i < track->entry; i++) {
  2027. int duration = get_cluster_duration(track, i);
  2028. if (i && duration == stts_entries[entries].duration) {
  2029. stts_entries[entries].count++; /* compress */
  2030. } else {
  2031. entries++;
  2032. stts_entries[entries].duration = duration;
  2033. stts_entries[entries].count = 1;
  2034. }
  2035. }
  2036. entries++; /* last one */
  2037. }
  2038. atom_size = 16 + (entries * 8);
  2039. avio_wb32(pb, atom_size); /* size */
  2040. ffio_wfourcc(pb, "stts");
  2041. avio_wb32(pb, 0); /* version & flags */
  2042. avio_wb32(pb, entries); /* entry count */
  2043. for (i = 0; i < entries; i++) {
  2044. avio_wb32(pb, stts_entries[i].count);
  2045. avio_wb32(pb, stts_entries[i].duration);
  2046. }
  2047. av_free(stts_entries);
  2048. return atom_size;
  2049. }
  2050. static int mov_write_dref_tag(AVIOContext *pb)
  2051. {
  2052. avio_wb32(pb, 28); /* size */
  2053. ffio_wfourcc(pb, "dref");
  2054. avio_wb32(pb, 0); /* version & flags */
  2055. avio_wb32(pb, 1); /* entry count */
  2056. avio_wb32(pb, 0xc); /* size */
  2057. //FIXME add the alis and rsrc atom
  2058. ffio_wfourcc(pb, "url ");
  2059. avio_wb32(pb, 1); /* version & flags */
  2060. return 28;
  2061. }
  2062. static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track)
  2063. {
  2064. struct sgpd_entry {
  2065. int count;
  2066. int16_t roll_distance;
  2067. int group_description_index;
  2068. };
  2069. struct sgpd_entry *sgpd_entries = NULL;
  2070. int entries = -1;
  2071. int group = 0;
  2072. int i, j;
  2073. const int OPUS_SEEK_PREROLL_MS = 80;
  2074. int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
  2075. (AVRational){1, 1000},
  2076. (AVRational){1, 48000});
  2077. if (!track->entry)
  2078. return 0;
  2079. sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
  2080. if (!sgpd_entries)
  2081. return AVERROR(ENOMEM);
  2082. av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC);
  2083. if (track->par->codec_id == AV_CODEC_ID_OPUS) {
  2084. for (i = 0; i < track->entry; i++) {
  2085. int roll_samples_remaining = roll_samples;
  2086. int distance = 0;
  2087. for (j = i - 1; j >= 0; j--) {
  2088. roll_samples_remaining -= get_cluster_duration(track, j);
  2089. distance++;
  2090. if (roll_samples_remaining <= 0)
  2091. break;
  2092. }
  2093. /* We don't have enough preceeding samples to compute a valid
  2094. roll_distance here, so this sample can't be independently
  2095. decoded. */
  2096. if (roll_samples_remaining > 0)
  2097. distance = 0;
  2098. /* Verify distance is a minimum of 2 (60ms) packets and a maximum of
  2099. 32 (2.5ms) packets. */
  2100. av_assert0(distance == 0 || (distance >= 2 && distance <= 32));
  2101. if (i && distance == sgpd_entries[entries].roll_distance) {
  2102. sgpd_entries[entries].count++;
  2103. } else {
  2104. entries++;
  2105. sgpd_entries[entries].count = 1;
  2106. sgpd_entries[entries].roll_distance = distance;
  2107. sgpd_entries[entries].group_description_index = distance ? ++group : 0;
  2108. }
  2109. }
  2110. } else {
  2111. entries++;
  2112. sgpd_entries[entries].count = track->sample_count;
  2113. sgpd_entries[entries].roll_distance = 1;
  2114. sgpd_entries[entries].group_description_index = ++group;
  2115. }
  2116. entries++;
  2117. if (!group) {
  2118. av_free(sgpd_entries);
  2119. return 0;
  2120. }
  2121. /* Write sgpd tag */
  2122. avio_wb32(pb, 24 + (group * 2)); /* size */
  2123. ffio_wfourcc(pb, "sgpd");
  2124. avio_wb32(pb, 1 << 24); /* fullbox */
  2125. ffio_wfourcc(pb, "roll");
  2126. avio_wb32(pb, 2); /* default_length */
  2127. avio_wb32(pb, group); /* entry_count */
  2128. for (i = 0; i < entries; i++) {
  2129. if (sgpd_entries[i].group_description_index) {
  2130. avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
  2131. }
  2132. }
  2133. /* Write sbgp tag */
  2134. avio_wb32(pb, 20 + (entries * 8)); /* size */
  2135. ffio_wfourcc(pb, "sbgp");
  2136. avio_wb32(pb, 0); /* fullbox */
  2137. ffio_wfourcc(pb, "roll");
  2138. avio_wb32(pb, entries); /* entry_count */
  2139. for (i = 0; i < entries; i++) {
  2140. avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
  2141. avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
  2142. }
  2143. av_free(sgpd_entries);
  2144. return 0;
  2145. }
  2146. static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
  2147. {
  2148. int64_t pos = avio_tell(pb);
  2149. int ret;
  2150. avio_wb32(pb, 0); /* size */
  2151. ffio_wfourcc(pb, "stbl");
  2152. mov_write_stsd_tag(s, pb, mov, track);
  2153. mov_write_stts_tag(pb, track);
  2154. if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
  2155. track->par->codec_tag == MKTAG('r','t','p',' ')) &&
  2156. track->has_keyframes && track->has_keyframes < track->entry)
  2157. mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
  2158. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->has_disposable)
  2159. mov_write_sdtp_tag(pb, track);
  2160. if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
  2161. mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
  2162. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
  2163. track->flags & MOV_TRACK_CTTS && track->entry) {
  2164. if ((ret = mov_write_ctts_tag(s, pb, track)) < 0)
  2165. return ret;
  2166. }
  2167. mov_write_stsc_tag(pb, track);
  2168. mov_write_stsz_tag(pb, track);
  2169. mov_write_stco_tag(pb, track);
  2170. if (track->cenc.aes_ctr) {
  2171. ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
  2172. }
  2173. if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) {
  2174. mov_preroll_write_stbl_atoms(pb, track);
  2175. }
  2176. return update_size(pb, pos);
  2177. }
  2178. static int mov_write_dinf_tag(AVIOContext *pb)
  2179. {
  2180. int64_t pos = avio_tell(pb);
  2181. avio_wb32(pb, 0); /* size */
  2182. ffio_wfourcc(pb, "dinf");
  2183. mov_write_dref_tag(pb);
  2184. return update_size(pb, pos);
  2185. }
  2186. static int mov_write_nmhd_tag(AVIOContext *pb)
  2187. {
  2188. avio_wb32(pb, 12);
  2189. ffio_wfourcc(pb, "nmhd");
  2190. avio_wb32(pb, 0);
  2191. return 12;
  2192. }
  2193. static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
  2194. {
  2195. int64_t pos = avio_tell(pb);
  2196. const char *font = "Lucida Grande";
  2197. avio_wb32(pb, 0); /* size */
  2198. ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
  2199. avio_wb32(pb, 0); /* version & flags */
  2200. avio_wb16(pb, 0); /* text font */
  2201. avio_wb16(pb, 0); /* text face */
  2202. avio_wb16(pb, 12); /* text size */
  2203. avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
  2204. avio_wb16(pb, 0x0000); /* text color (red) */
  2205. avio_wb16(pb, 0x0000); /* text color (green) */
  2206. avio_wb16(pb, 0x0000); /* text color (blue) */
  2207. avio_wb16(pb, 0xffff); /* background color (red) */
  2208. avio_wb16(pb, 0xffff); /* background color (green) */
  2209. avio_wb16(pb, 0xffff); /* background color (blue) */
  2210. avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
  2211. avio_write(pb, font, strlen(font)); /* font name */
  2212. return update_size(pb, pos);
  2213. }
  2214. static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
  2215. {
  2216. int64_t pos = avio_tell(pb);
  2217. avio_wb32(pb, 0); /* size */
  2218. ffio_wfourcc(pb, "gmhd");
  2219. avio_wb32(pb, 0x18); /* gmin size */
  2220. ffio_wfourcc(pb, "gmin");/* generic media info */
  2221. avio_wb32(pb, 0); /* version & flags */
  2222. avio_wb16(pb, 0x40); /* graphics mode = */
  2223. avio_wb16(pb, 0x8000); /* opColor (r?) */
  2224. avio_wb16(pb, 0x8000); /* opColor (g?) */
  2225. avio_wb16(pb, 0x8000); /* opColor (b?) */
  2226. avio_wb16(pb, 0); /* balance */
  2227. avio_wb16(pb, 0); /* reserved */
  2228. /*
  2229. * This special text atom is required for
  2230. * Apple Quicktime chapters. The contents
  2231. * don't appear to be documented, so the
  2232. * bytes are copied verbatim.
  2233. */
  2234. if (track->tag != MKTAG('c','6','0','8')) {
  2235. avio_wb32(pb, 0x2C); /* size */
  2236. ffio_wfourcc(pb, "text");
  2237. avio_wb16(pb, 0x01);
  2238. avio_wb32(pb, 0x00);
  2239. avio_wb32(pb, 0x00);
  2240. avio_wb32(pb, 0x00);
  2241. avio_wb32(pb, 0x01);
  2242. avio_wb32(pb, 0x00);
  2243. avio_wb32(pb, 0x00);
  2244. avio_wb32(pb, 0x00);
  2245. avio_wb32(pb, 0x00004000);
  2246. avio_wb16(pb, 0x0000);
  2247. }
  2248. if (track->par->codec_tag == MKTAG('t','m','c','d')) {
  2249. int64_t tmcd_pos = avio_tell(pb);
  2250. avio_wb32(pb, 0); /* size */
  2251. ffio_wfourcc(pb, "tmcd");
  2252. mov_write_tcmi_tag(pb, track);
  2253. update_size(pb, tmcd_pos);
  2254. } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
  2255. int64_t gpmd_pos = avio_tell(pb);
  2256. avio_wb32(pb, 0); /* size */
  2257. ffio_wfourcc(pb, "gpmd");
  2258. avio_wb32(pb, 0); /* version */
  2259. update_size(pb, gpmd_pos);
  2260. }
  2261. return update_size(pb, pos);
  2262. }
  2263. static int mov_write_smhd_tag(AVIOContext *pb)
  2264. {
  2265. avio_wb32(pb, 16); /* size */
  2266. ffio_wfourcc(pb, "smhd");
  2267. avio_wb32(pb, 0); /* version & flags */
  2268. avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
  2269. avio_wb16(pb, 0); /* reserved */
  2270. return 16;
  2271. }
  2272. static int mov_write_vmhd_tag(AVIOContext *pb)
  2273. {
  2274. avio_wb32(pb, 0x14); /* size (always 0x14) */
  2275. ffio_wfourcc(pb, "vmhd");
  2276. avio_wb32(pb, 0x01); /* version & flags */
  2277. avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
  2278. return 0x14;
  2279. }
  2280. static int is_clcp_track(MOVTrack *track)
  2281. {
  2282. return track->tag == MKTAG('c','7','0','8') ||
  2283. track->tag == MKTAG('c','6','0','8');
  2284. }
  2285. static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
  2286. {
  2287. const char *hdlr, *descr = NULL, *hdlr_type = NULL;
  2288. int64_t pos = avio_tell(pb);
  2289. hdlr = "dhlr";
  2290. hdlr_type = "url ";
  2291. descr = "DataHandler";
  2292. if (track) {
  2293. hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
  2294. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  2295. hdlr_type = "vide";
  2296. descr = "VideoHandler";
  2297. } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
  2298. hdlr_type = "soun";
  2299. descr = "SoundHandler";
  2300. } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  2301. if (is_clcp_track(track)) {
  2302. hdlr_type = "clcp";
  2303. descr = "ClosedCaptionHandler";
  2304. } else {
  2305. if (track->tag == MKTAG('t','x','3','g')) {
  2306. hdlr_type = "sbtl";
  2307. } else if (track->tag == MKTAG('m','p','4','s')) {
  2308. hdlr_type = "subp";
  2309. } else {
  2310. hdlr_type = "text";
  2311. }
  2312. descr = "SubtitleHandler";
  2313. }
  2314. } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
  2315. hdlr_type = "hint";
  2316. descr = "HintHandler";
  2317. } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
  2318. hdlr_type = "tmcd";
  2319. descr = "TimeCodeHandler";
  2320. } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
  2321. hdlr_type = "meta";
  2322. descr = "GoPro MET"; // GoPro Metadata
  2323. } else {
  2324. av_log(s, AV_LOG_WARNING,
  2325. "Unknown hldr_type for %s, writing dummy values\n",
  2326. av_fourcc2str(track->par->codec_tag));
  2327. }
  2328. if (track->st) {
  2329. // hdlr.name is used by some players to identify the content title
  2330. // of the track. So if an alternate handler description is
  2331. // specified, use it.
  2332. AVDictionaryEntry *t;
  2333. t = av_dict_get(track->st->metadata, "handler_name", NULL, 0);
  2334. if (t && utf8len(t->value))
  2335. descr = t->value;
  2336. }
  2337. }
  2338. avio_wb32(pb, 0); /* size */
  2339. ffio_wfourcc(pb, "hdlr");
  2340. avio_wb32(pb, 0); /* Version & flags */
  2341. avio_write(pb, hdlr, 4); /* handler */
  2342. ffio_wfourcc(pb, hdlr_type); /* handler type */
  2343. avio_wb32(pb, 0); /* reserved */
  2344. avio_wb32(pb, 0); /* reserved */
  2345. avio_wb32(pb, 0); /* reserved */
  2346. if (!track || track->mode == MODE_MOV)
  2347. avio_w8(pb, strlen(descr)); /* pascal string */
  2348. avio_write(pb, descr, strlen(descr)); /* handler description */
  2349. if (track && track->mode != MODE_MOV)
  2350. avio_w8(pb, 0); /* c string */
  2351. return update_size(pb, pos);
  2352. }
  2353. static int mov_write_hmhd_tag(AVIOContext *pb)
  2354. {
  2355. /* This atom must be present, but leaving the values at zero
  2356. * seems harmless. */
  2357. avio_wb32(pb, 28); /* size */
  2358. ffio_wfourcc(pb, "hmhd");
  2359. avio_wb32(pb, 0); /* version, flags */
  2360. avio_wb16(pb, 0); /* maxPDUsize */
  2361. avio_wb16(pb, 0); /* avgPDUsize */
  2362. avio_wb32(pb, 0); /* maxbitrate */
  2363. avio_wb32(pb, 0); /* avgbitrate */
  2364. avio_wb32(pb, 0); /* reserved */
  2365. return 28;
  2366. }
  2367. static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
  2368. {
  2369. int64_t pos = avio_tell(pb);
  2370. int ret;
  2371. avio_wb32(pb, 0); /* size */
  2372. ffio_wfourcc(pb, "minf");
  2373. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
  2374. mov_write_vmhd_tag(pb);
  2375. else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
  2376. mov_write_smhd_tag(pb);
  2377. else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  2378. if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
  2379. mov_write_gmhd_tag(pb, track);
  2380. } else {
  2381. mov_write_nmhd_tag(pb);
  2382. }
  2383. } else if (track->tag == MKTAG('r','t','p',' ')) {
  2384. mov_write_hmhd_tag(pb);
  2385. } else if (track->tag == MKTAG('t','m','c','d')) {
  2386. if (track->mode != MODE_MOV)
  2387. mov_write_nmhd_tag(pb);
  2388. else
  2389. mov_write_gmhd_tag(pb, track);
  2390. } else if (track->tag == MKTAG('g','p','m','d')) {
  2391. mov_write_gmhd_tag(pb, track);
  2392. }
  2393. if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
  2394. mov_write_hdlr_tag(s, pb, NULL);
  2395. mov_write_dinf_tag(pb);
  2396. if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
  2397. return ret;
  2398. return update_size(pb, pos);
  2399. }
  2400. static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
  2401. MOVTrack *track)
  2402. {
  2403. int version = track->track_duration < INT32_MAX ? 0 : 1;
  2404. if (track->mode == MODE_ISM)
  2405. version = 1;
  2406. (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
  2407. ffio_wfourcc(pb, "mdhd");
  2408. avio_w8(pb, version);
  2409. avio_wb24(pb, 0); /* flags */
  2410. if (version == 1) {
  2411. avio_wb64(pb, track->time);
  2412. avio_wb64(pb, track->time);
  2413. } else {
  2414. avio_wb32(pb, track->time); /* creation time */
  2415. avio_wb32(pb, track->time); /* modification time */
  2416. }
  2417. avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
  2418. if (!track->entry && mov->mode == MODE_ISM)
  2419. (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
  2420. else if (!track->entry)
  2421. (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
  2422. else
  2423. (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
  2424. avio_wb16(pb, track->language); /* language */
  2425. avio_wb16(pb, 0); /* reserved (quality) */
  2426. if (version != 0 && track->mode == MODE_MOV) {
  2427. av_log(NULL, AV_LOG_ERROR,
  2428. "FATAL error, file duration too long for timebase, this file will not be\n"
  2429. "playable with quicktime. Choose a different timebase or a different\n"
  2430. "container format\n");
  2431. }
  2432. return 32;
  2433. }
  2434. static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
  2435. MOVMuxContext *mov, MOVTrack *track)
  2436. {
  2437. int64_t pos = avio_tell(pb);
  2438. int ret;
  2439. avio_wb32(pb, 0); /* size */
  2440. ffio_wfourcc(pb, "mdia");
  2441. mov_write_mdhd_tag(pb, mov, track);
  2442. mov_write_hdlr_tag(s, pb, track);
  2443. if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
  2444. return ret;
  2445. return update_size(pb, pos);
  2446. }
  2447. /* transformation matrix
  2448. |a b u|
  2449. |c d v|
  2450. |tx ty w| */
  2451. static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
  2452. int16_t d, int16_t tx, int16_t ty)
  2453. {
  2454. avio_wb32(pb, a << 16); /* 16.16 format */
  2455. avio_wb32(pb, b << 16); /* 16.16 format */
  2456. avio_wb32(pb, 0); /* u in 2.30 format */
  2457. avio_wb32(pb, c << 16); /* 16.16 format */
  2458. avio_wb32(pb, d << 16); /* 16.16 format */
  2459. avio_wb32(pb, 0); /* v in 2.30 format */
  2460. avio_wb32(pb, tx << 16); /* 16.16 format */
  2461. avio_wb32(pb, ty << 16); /* 16.16 format */
  2462. avio_wb32(pb, 1 << 30); /* w in 2.30 format */
  2463. }
  2464. static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
  2465. MOVTrack *track, AVStream *st)
  2466. {
  2467. int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
  2468. track->timescale, AV_ROUND_UP);
  2469. int version = duration < INT32_MAX ? 0 : 1;
  2470. int flags = MOV_TKHD_FLAG_IN_MOVIE;
  2471. int rotation = 0;
  2472. int group = 0;
  2473. uint32_t *display_matrix = NULL;
  2474. int display_matrix_size, i;
  2475. if (st) {
  2476. if (mov->per_stream_grouping)
  2477. group = st->index;
  2478. else
  2479. group = st->codecpar->codec_type;
  2480. display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
  2481. &display_matrix_size);
  2482. if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
  2483. display_matrix = NULL;
  2484. }
  2485. if (track->flags & MOV_TRACK_ENABLED)
  2486. flags |= MOV_TKHD_FLAG_ENABLED;
  2487. if (track->mode == MODE_ISM)
  2488. version = 1;
  2489. (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
  2490. ffio_wfourcc(pb, "tkhd");
  2491. avio_w8(pb, version);
  2492. avio_wb24(pb, flags);
  2493. if (version == 1) {
  2494. avio_wb64(pb, track->time);
  2495. avio_wb64(pb, track->time);
  2496. } else {
  2497. avio_wb32(pb, track->time); /* creation time */
  2498. avio_wb32(pb, track->time); /* modification time */
  2499. }
  2500. avio_wb32(pb, track->track_id); /* track-id */
  2501. avio_wb32(pb, 0); /* reserved */
  2502. if (!track->entry && mov->mode == MODE_ISM)
  2503. (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
  2504. else if (!track->entry)
  2505. (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
  2506. else
  2507. (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
  2508. avio_wb32(pb, 0); /* reserved */
  2509. avio_wb32(pb, 0); /* reserved */
  2510. avio_wb16(pb, 0); /* layer */
  2511. avio_wb16(pb, group); /* alternate group) */
  2512. /* Volume, only for audio */
  2513. if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
  2514. avio_wb16(pb, 0x0100);
  2515. else
  2516. avio_wb16(pb, 0);
  2517. avio_wb16(pb, 0); /* reserved */
  2518. /* Matrix structure */
  2519. #if FF_API_OLD_ROTATE_API
  2520. if (st && st->metadata) {
  2521. AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
  2522. rotation = (rot && rot->value) ? atoi(rot->value) : 0;
  2523. }
  2524. #endif
  2525. if (display_matrix) {
  2526. for (i = 0; i < 9; i++)
  2527. avio_wb32(pb, display_matrix[i]);
  2528. #if FF_API_OLD_ROTATE_API
  2529. } else if (rotation == 90) {
  2530. write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
  2531. } else if (rotation == 180) {
  2532. write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
  2533. } else if (rotation == 270) {
  2534. write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
  2535. #endif
  2536. } else {
  2537. write_matrix(pb, 1, 0, 0, 1, 0, 0);
  2538. }
  2539. /* Track width and height, for visual only */
  2540. if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
  2541. track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
  2542. int64_t track_width_1616;
  2543. if (track->mode == MODE_MOV) {
  2544. track_width_1616 = track->par->width * 0x10000ULL;
  2545. } else {
  2546. track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
  2547. track->par->width * 0x10000LL,
  2548. st->sample_aspect_ratio.den);
  2549. if (!track_width_1616 ||
  2550. track->height != track->par->height ||
  2551. track_width_1616 > UINT32_MAX)
  2552. track_width_1616 = track->par->width * 0x10000ULL;
  2553. }
  2554. if (track_width_1616 > UINT32_MAX) {
  2555. av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
  2556. track_width_1616 = 0;
  2557. }
  2558. avio_wb32(pb, track_width_1616);
  2559. if (track->height > 0xFFFF) {
  2560. av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
  2561. avio_wb32(pb, 0);
  2562. } else
  2563. avio_wb32(pb, track->height * 0x10000U);
  2564. } else {
  2565. avio_wb32(pb, 0);
  2566. avio_wb32(pb, 0);
  2567. }
  2568. return 0x5c;
  2569. }
  2570. static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
  2571. {
  2572. int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
  2573. track->par->sample_aspect_ratio.den);
  2574. int64_t pos = avio_tell(pb);
  2575. avio_wb32(pb, 0); /* size */
  2576. ffio_wfourcc(pb, "tapt");
  2577. avio_wb32(pb, 20);
  2578. ffio_wfourcc(pb, "clef");
  2579. avio_wb32(pb, 0);
  2580. avio_wb32(pb, width << 16);
  2581. avio_wb32(pb, track->par->height << 16);
  2582. avio_wb32(pb, 20);
  2583. ffio_wfourcc(pb, "prof");
  2584. avio_wb32(pb, 0);
  2585. avio_wb32(pb, width << 16);
  2586. avio_wb32(pb, track->par->height << 16);
  2587. avio_wb32(pb, 20);
  2588. ffio_wfourcc(pb, "enof");
  2589. avio_wb32(pb, 0);
  2590. avio_wb32(pb, track->par->width << 16);
  2591. avio_wb32(pb, track->par->height << 16);
  2592. return update_size(pb, pos);
  2593. }
  2594. // This box seems important for the psp playback ... without it the movie seems to hang
  2595. static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
  2596. MOVTrack *track)
  2597. {
  2598. int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
  2599. track->timescale, AV_ROUND_UP);
  2600. int version = duration < INT32_MAX ? 0 : 1;
  2601. int entry_size, entry_count, size;
  2602. int64_t delay, start_ct = track->start_cts;
  2603. int64_t start_dts = track->start_dts;
  2604. if (track->entry) {
  2605. if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
  2606. av_log(mov->fc, AV_LOG_DEBUG,
  2607. "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
  2608. track->cluster[0].dts, track->cluster[0].cts,
  2609. start_dts, start_ct, track->track_id);
  2610. start_dts = track->cluster[0].dts;
  2611. start_ct = track->cluster[0].cts;
  2612. }
  2613. }
  2614. delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
  2615. track->timescale, AV_ROUND_DOWN);
  2616. version |= delay < INT32_MAX ? 0 : 1;
  2617. entry_size = (version == 1) ? 20 : 12;
  2618. entry_count = 1 + (delay > 0);
  2619. size = 24 + entry_count * entry_size;
  2620. /* write the atom data */
  2621. avio_wb32(pb, size);
  2622. ffio_wfourcc(pb, "edts");
  2623. avio_wb32(pb, size - 8);
  2624. ffio_wfourcc(pb, "elst");
  2625. avio_w8(pb, version);
  2626. avio_wb24(pb, 0); /* flags */
  2627. avio_wb32(pb, entry_count);
  2628. if (delay > 0) { /* add an empty edit to delay presentation */
  2629. /* In the positive delay case, the delay includes the cts
  2630. * offset, and the second edit list entry below trims out
  2631. * the same amount from the actual content. This makes sure
  2632. * that the offset last sample is included in the edit
  2633. * list duration as well. */
  2634. if (version == 1) {
  2635. avio_wb64(pb, delay);
  2636. avio_wb64(pb, -1);
  2637. } else {
  2638. avio_wb32(pb, delay);
  2639. avio_wb32(pb, -1);
  2640. }
  2641. avio_wb32(pb, 0x00010000);
  2642. } else {
  2643. /* Avoid accidentally ending up with start_ct = -1 which has got a
  2644. * special meaning. Normally start_ct should end up positive or zero
  2645. * here, but use FFMIN in case dts is a small positive integer
  2646. * rounded to 0 when represented in MOV_TIMESCALE units. */
  2647. av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
  2648. start_ct = -FFMIN(start_dts, 0);
  2649. /* Note, this delay is calculated from the pts of the first sample,
  2650. * ensuring that we don't reduce the duration for cases with
  2651. * dts<0 pts=0. */
  2652. duration += delay;
  2653. }
  2654. /* For fragmented files, we don't know the full length yet. Setting
  2655. * duration to 0 allows us to only specify the offset, including
  2656. * the rest of the content (from all future fragments) without specifying
  2657. * an explicit duration. */
  2658. if (mov->flags & FF_MOV_FLAG_FRAGMENT)
  2659. duration = 0;
  2660. /* duration */
  2661. if (version == 1) {
  2662. avio_wb64(pb, duration);
  2663. avio_wb64(pb, start_ct);
  2664. } else {
  2665. avio_wb32(pb, duration);
  2666. avio_wb32(pb, start_ct);
  2667. }
  2668. avio_wb32(pb, 0x00010000);
  2669. return size;
  2670. }
  2671. static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
  2672. {
  2673. avio_wb32(pb, 20); // size
  2674. ffio_wfourcc(pb, "tref");
  2675. avio_wb32(pb, 12); // size (subatom)
  2676. avio_wl32(pb, track->tref_tag);
  2677. avio_wb32(pb, track->tref_id);
  2678. return 20;
  2679. }
  2680. // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
  2681. static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
  2682. {
  2683. avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
  2684. ffio_wfourcc(pb, "uuid");
  2685. ffio_wfourcc(pb, "USMT");
  2686. avio_wb32(pb, 0x21d24fce);
  2687. avio_wb32(pb, 0xbb88695c);
  2688. avio_wb32(pb, 0xfac9c740);
  2689. avio_wb32(pb, 0x1c); // another size here!
  2690. ffio_wfourcc(pb, "MTDT");
  2691. avio_wb32(pb, 0x00010012);
  2692. avio_wb32(pb, 0x0a);
  2693. avio_wb32(pb, 0x55c40000);
  2694. avio_wb32(pb, 0x1);
  2695. avio_wb32(pb, 0x0);
  2696. return 0x34;
  2697. }
  2698. static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
  2699. {
  2700. AVFormatContext *ctx = track->rtp_ctx;
  2701. char buf[1000] = "";
  2702. int len;
  2703. ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
  2704. NULL, NULL, 0, 0, ctx);
  2705. av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
  2706. len = strlen(buf);
  2707. avio_wb32(pb, len + 24);
  2708. ffio_wfourcc(pb, "udta");
  2709. avio_wb32(pb, len + 16);
  2710. ffio_wfourcc(pb, "hnti");
  2711. avio_wb32(pb, len + 8);
  2712. ffio_wfourcc(pb, "sdp ");
  2713. avio_write(pb, buf, len);
  2714. return len + 24;
  2715. }
  2716. static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
  2717. const char *tag, const char *str)
  2718. {
  2719. int64_t pos = avio_tell(pb);
  2720. AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
  2721. if (!t || !utf8len(t->value))
  2722. return 0;
  2723. avio_wb32(pb, 0); /* size */
  2724. ffio_wfourcc(pb, tag); /* type */
  2725. avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
  2726. return update_size(pb, pos);
  2727. }
  2728. static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
  2729. AVStream *st)
  2730. {
  2731. AVIOContext *pb_buf;
  2732. int ret, size;
  2733. uint8_t *buf;
  2734. if (!st)
  2735. return 0;
  2736. ret = avio_open_dyn_buf(&pb_buf);
  2737. if (ret < 0)
  2738. return ret;
  2739. if (mov->mode & (MODE_MP4|MODE_MOV))
  2740. mov_write_track_metadata(pb_buf, st, "name", "title");
  2741. if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
  2742. avio_wb32(pb, size + 8);
  2743. ffio_wfourcc(pb, "udta");
  2744. avio_write(pb, buf, size);
  2745. }
  2746. av_free(buf);
  2747. return 0;
  2748. }
  2749. static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
  2750. MOVTrack *track, AVStream *st)
  2751. {
  2752. int64_t pos = avio_tell(pb);
  2753. int entry_backup = track->entry;
  2754. int chunk_backup = track->chunkCount;
  2755. int ret;
  2756. /* If we want to have an empty moov, but some samples already have been
  2757. * buffered (delay_moov), pretend that no samples have been written yet. */
  2758. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
  2759. track->chunkCount = track->entry = 0;
  2760. avio_wb32(pb, 0); /* size */
  2761. ffio_wfourcc(pb, "trak");
  2762. mov_write_tkhd_tag(pb, mov, track, st);
  2763. av_assert2(mov->use_editlist >= 0);
  2764. if (track->start_dts != AV_NOPTS_VALUE) {
  2765. if (mov->use_editlist)
  2766. mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
  2767. else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
  2768. av_log(mov->fc, AV_LOG_WARNING,
  2769. "Not writing any edit list even though one would have been required\n");
  2770. }
  2771. if (track->tref_tag)
  2772. mov_write_tref_tag(pb, track);
  2773. if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
  2774. return ret;
  2775. if (track->mode == MODE_PSP)
  2776. mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
  2777. if (track->tag == MKTAG('r','t','p',' '))
  2778. mov_write_udta_sdp(pb, track);
  2779. if (track->mode == MODE_MOV) {
  2780. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  2781. double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
  2782. if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
  2783. mov_write_tapt_tag(pb, track);
  2784. }
  2785. }
  2786. if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
  2787. mov_write_tapt_tag(pb, track);
  2788. }
  2789. }
  2790. mov_write_track_udta_tag(pb, mov, st);
  2791. track->entry = entry_backup;
  2792. track->chunkCount = chunk_backup;
  2793. return update_size(pb, pos);
  2794. }
  2795. static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
  2796. {
  2797. int i, has_audio = 0, has_video = 0;
  2798. int64_t pos = avio_tell(pb);
  2799. int audio_profile = mov->iods_audio_profile;
  2800. int video_profile = mov->iods_video_profile;
  2801. for (i = 0; i < mov->nb_streams; i++) {
  2802. if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
  2803. has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
  2804. has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
  2805. }
  2806. }
  2807. if (audio_profile < 0)
  2808. audio_profile = 0xFF - has_audio;
  2809. if (video_profile < 0)
  2810. video_profile = 0xFF - has_video;
  2811. avio_wb32(pb, 0x0); /* size */
  2812. ffio_wfourcc(pb, "iods");
  2813. avio_wb32(pb, 0); /* version & flags */
  2814. put_descr(pb, 0x10, 7);
  2815. avio_wb16(pb, 0x004f);
  2816. avio_w8(pb, 0xff);
  2817. avio_w8(pb, 0xff);
  2818. avio_w8(pb, audio_profile);
  2819. avio_w8(pb, video_profile);
  2820. avio_w8(pb, 0xff);
  2821. return update_size(pb, pos);
  2822. }
  2823. static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
  2824. {
  2825. avio_wb32(pb, 0x20); /* size */
  2826. ffio_wfourcc(pb, "trex");
  2827. avio_wb32(pb, 0); /* version & flags */
  2828. avio_wb32(pb, track->track_id); /* track ID */
  2829. avio_wb32(pb, 1); /* default sample description index */
  2830. avio_wb32(pb, 0); /* default sample duration */
  2831. avio_wb32(pb, 0); /* default sample size */
  2832. avio_wb32(pb, 0); /* default sample flags */
  2833. return 0;
  2834. }
  2835. static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
  2836. {
  2837. int64_t pos = avio_tell(pb);
  2838. int i;
  2839. avio_wb32(pb, 0x0); /* size */
  2840. ffio_wfourcc(pb, "mvex");
  2841. for (i = 0; i < mov->nb_streams; i++)
  2842. mov_write_trex_tag(pb, &mov->tracks[i]);
  2843. return update_size(pb, pos);
  2844. }
  2845. static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
  2846. {
  2847. int max_track_id = 1, i;
  2848. int64_t max_track_len = 0;
  2849. int version;
  2850. for (i = 0; i < mov->nb_streams; i++) {
  2851. if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
  2852. int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
  2853. MOV_TIMESCALE,
  2854. mov->tracks[i].timescale,
  2855. AV_ROUND_UP);
  2856. if (max_track_len < max_track_len_temp)
  2857. max_track_len = max_track_len_temp;
  2858. if (max_track_id < mov->tracks[i].track_id)
  2859. max_track_id = mov->tracks[i].track_id;
  2860. }
  2861. }
  2862. /* If using delay_moov, make sure the output is the same as if no
  2863. * samples had been written yet. */
  2864. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
  2865. max_track_len = 0;
  2866. max_track_id = 1;
  2867. }
  2868. version = max_track_len < UINT32_MAX ? 0 : 1;
  2869. avio_wb32(pb, version == 1 ? 120 : 108); /* size */
  2870. ffio_wfourcc(pb, "mvhd");
  2871. avio_w8(pb, version);
  2872. avio_wb24(pb, 0); /* flags */
  2873. if (version == 1) {
  2874. avio_wb64(pb, mov->time);
  2875. avio_wb64(pb, mov->time);
  2876. } else {
  2877. avio_wb32(pb, mov->time); /* creation time */
  2878. avio_wb32(pb, mov->time); /* modification time */
  2879. }
  2880. avio_wb32(pb, MOV_TIMESCALE);
  2881. (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
  2882. avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
  2883. avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
  2884. avio_wb16(pb, 0); /* reserved */
  2885. avio_wb32(pb, 0); /* reserved */
  2886. avio_wb32(pb, 0); /* reserved */
  2887. /* Matrix structure */
  2888. write_matrix(pb, 1, 0, 0, 1, 0, 0);
  2889. avio_wb32(pb, 0); /* reserved (preview time) */
  2890. avio_wb32(pb, 0); /* reserved (preview duration) */
  2891. avio_wb32(pb, 0); /* reserved (poster time) */
  2892. avio_wb32(pb, 0); /* reserved (selection time) */
  2893. avio_wb32(pb, 0); /* reserved (selection duration) */
  2894. avio_wb32(pb, 0); /* reserved (current time) */
  2895. avio_wb32(pb, max_track_id + 1); /* Next track id */
  2896. return 0x6c;
  2897. }
  2898. static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
  2899. AVFormatContext *s)
  2900. {
  2901. avio_wb32(pb, 33); /* size */
  2902. ffio_wfourcc(pb, "hdlr");
  2903. avio_wb32(pb, 0);
  2904. avio_wb32(pb, 0);
  2905. ffio_wfourcc(pb, "mdir");
  2906. ffio_wfourcc(pb, "appl");
  2907. avio_wb32(pb, 0);
  2908. avio_wb32(pb, 0);
  2909. avio_w8(pb, 0);
  2910. return 33;
  2911. }
  2912. /* helper function to write a data tag with the specified string as data */
  2913. static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
  2914. {
  2915. if (long_style) {
  2916. int size = 16 + strlen(data);
  2917. avio_wb32(pb, size); /* size */
  2918. ffio_wfourcc(pb, "data");
  2919. avio_wb32(pb, 1);
  2920. avio_wb32(pb, 0);
  2921. avio_write(pb, data, strlen(data));
  2922. return size;
  2923. } else {
  2924. if (!lang)
  2925. lang = ff_mov_iso639_to_lang("und", 1);
  2926. avio_wb16(pb, strlen(data)); /* string length */
  2927. avio_wb16(pb, lang);
  2928. avio_write(pb, data, strlen(data));
  2929. return strlen(data) + 4;
  2930. }
  2931. }
  2932. static int mov_write_string_tag(AVIOContext *pb, const char *name,
  2933. const char *value, int lang, int long_style)
  2934. {
  2935. int size = 0;
  2936. if (value && value[0]) {
  2937. int64_t pos = avio_tell(pb);
  2938. avio_wb32(pb, 0); /* size */
  2939. ffio_wfourcc(pb, name);
  2940. mov_write_string_data_tag(pb, value, lang, long_style);
  2941. size = update_size(pb, pos);
  2942. }
  2943. return size;
  2944. }
  2945. static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
  2946. const char *tag, int *lang)
  2947. {
  2948. int l, len, len2;
  2949. AVDictionaryEntry *t, *t2 = NULL;
  2950. char tag2[16];
  2951. *lang = 0;
  2952. if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
  2953. return NULL;
  2954. len = strlen(t->key);
  2955. snprintf(tag2, sizeof(tag2), "%s-", tag);
  2956. while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
  2957. len2 = strlen(t2->key);
  2958. if (len2 == len + 4 && !strcmp(t->value, t2->value)
  2959. && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
  2960. *lang = l;
  2961. return t;
  2962. }
  2963. }
  2964. return t;
  2965. }
  2966. static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
  2967. const char *name, const char *tag,
  2968. int long_style)
  2969. {
  2970. int lang;
  2971. AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
  2972. if (!t)
  2973. return 0;
  2974. return mov_write_string_tag(pb, name, t->value, lang, long_style);
  2975. }
  2976. /* iTunes bpm number */
  2977. static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
  2978. {
  2979. AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
  2980. int size = 0, tmpo = t ? atoi(t->value) : 0;
  2981. if (tmpo) {
  2982. size = 26;
  2983. avio_wb32(pb, size);
  2984. ffio_wfourcc(pb, "tmpo");
  2985. avio_wb32(pb, size-8); /* size */
  2986. ffio_wfourcc(pb, "data");
  2987. avio_wb32(pb, 0x15); //type specifier
  2988. avio_wb32(pb, 0);
  2989. avio_wb16(pb, tmpo); // data
  2990. }
  2991. return size;
  2992. }
  2993. /* 3GPP TS 26.244 */
  2994. static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
  2995. {
  2996. int lang;
  2997. int64_t pos = avio_tell(pb);
  2998. double latitude, longitude, altitude;
  2999. int32_t latitude_fix, longitude_fix, altitude_fix;
  3000. AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
  3001. const char *ptr, *place = "";
  3002. char *end;
  3003. static const char *astronomical_body = "earth";
  3004. if (!t)
  3005. return 0;
  3006. ptr = t->value;
  3007. longitude = strtod(ptr, &end);
  3008. if (end == ptr) {
  3009. av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
  3010. return 0;
  3011. }
  3012. ptr = end;
  3013. latitude = strtod(ptr, &end);
  3014. if (end == ptr) {
  3015. av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
  3016. return 0;
  3017. }
  3018. ptr = end;
  3019. altitude = strtod(ptr, &end);
  3020. /* If no altitude was present, the default 0 should be fine */
  3021. if (*end == '/')
  3022. place = end + 1;
  3023. latitude_fix = (int32_t) ((1 << 16) * latitude);
  3024. longitude_fix = (int32_t) ((1 << 16) * longitude);
  3025. altitude_fix = (int32_t) ((1 << 16) * altitude);
  3026. avio_wb32(pb, 0); /* size */
  3027. ffio_wfourcc(pb, "loci"); /* type */
  3028. avio_wb32(pb, 0); /* version + flags */
  3029. avio_wb16(pb, lang);
  3030. avio_write(pb, place, strlen(place) + 1);
  3031. avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
  3032. avio_wb32(pb, latitude_fix);
  3033. avio_wb32(pb, longitude_fix);
  3034. avio_wb32(pb, altitude_fix);
  3035. avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
  3036. avio_w8(pb, 0); /* additional notes, null terminated string */
  3037. return update_size(pb, pos);
  3038. }
  3039. /* iTunes track or disc number */
  3040. static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
  3041. AVFormatContext *s, int disc)
  3042. {
  3043. AVDictionaryEntry *t = av_dict_get(s->metadata,
  3044. disc ? "disc" : "track",
  3045. NULL, 0);
  3046. int size = 0, track = t ? atoi(t->value) : 0;
  3047. if (track) {
  3048. int tracks = 0;
  3049. char *slash = strchr(t->value, '/');
  3050. if (slash)
  3051. tracks = atoi(slash + 1);
  3052. avio_wb32(pb, 32); /* size */
  3053. ffio_wfourcc(pb, disc ? "disk" : "trkn");
  3054. avio_wb32(pb, 24); /* size */
  3055. ffio_wfourcc(pb, "data");
  3056. avio_wb32(pb, 0); // 8 bytes empty
  3057. avio_wb32(pb, 0);
  3058. avio_wb16(pb, 0); // empty
  3059. avio_wb16(pb, track); // track / disc number
  3060. avio_wb16(pb, tracks); // total track / disc number
  3061. avio_wb16(pb, 0); // empty
  3062. size = 32;
  3063. }
  3064. return size;
  3065. }
  3066. static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
  3067. const char *name, const char *tag,
  3068. int len)
  3069. {
  3070. AVDictionaryEntry *t = NULL;
  3071. uint8_t num;
  3072. int size = 24 + len;
  3073. if (len != 1 && len != 4)
  3074. return -1;
  3075. if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
  3076. return 0;
  3077. num = atoi(t->value);
  3078. avio_wb32(pb, size);
  3079. ffio_wfourcc(pb, name);
  3080. avio_wb32(pb, size - 8);
  3081. ffio_wfourcc(pb, "data");
  3082. avio_wb32(pb, 0x15);
  3083. avio_wb32(pb, 0);
  3084. if (len==4) avio_wb32(pb, num);
  3085. else avio_w8 (pb, num);
  3086. return size;
  3087. }
  3088. static int mov_write_covr(AVIOContext *pb, AVFormatContext *s)
  3089. {
  3090. MOVMuxContext *mov = s->priv_data;
  3091. int64_t pos = 0;
  3092. int i;
  3093. for (i = 0; i < s->nb_streams; i++) {
  3094. MOVTrack *trk = &mov->tracks[i];
  3095. if (!is_cover_image(trk->st) || trk->cover_image.size <= 0)
  3096. continue;
  3097. if (!pos) {
  3098. pos = avio_tell(pb);
  3099. avio_wb32(pb, 0);
  3100. ffio_wfourcc(pb, "covr");
  3101. }
  3102. avio_wb32(pb, 16 + trk->cover_image.size);
  3103. ffio_wfourcc(pb, "data");
  3104. avio_wb32(pb, trk->tag);
  3105. avio_wb32(pb , 0);
  3106. avio_write(pb, trk->cover_image.data, trk->cover_image.size);
  3107. }
  3108. return pos ? update_size(pb, pos) : 0;
  3109. }
  3110. /* iTunes meta data list */
  3111. static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
  3112. AVFormatContext *s)
  3113. {
  3114. int64_t pos = avio_tell(pb);
  3115. avio_wb32(pb, 0); /* size */
  3116. ffio_wfourcc(pb, "ilst");
  3117. mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
  3118. mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
  3119. mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
  3120. mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
  3121. mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
  3122. mov_write_string_metadata(s, pb, "\251day", "date" , 1);
  3123. if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
  3124. if (!(s->flags & AVFMT_FLAG_BITEXACT))
  3125. mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
  3126. }
  3127. mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
  3128. mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
  3129. mov_write_string_metadata(s, pb, "cprt", "copyright", 1);
  3130. mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
  3131. mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
  3132. mov_write_string_metadata(s, pb, "desc", "description",1);
  3133. mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
  3134. mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
  3135. mov_write_string_metadata(s, pb, "tven", "episode_id",1);
  3136. mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
  3137. mov_write_string_metadata(s, pb, "keyw", "keywords" , 1);
  3138. mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
  3139. mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
  3140. mov_write_int8_metadata (s, pb, "stik", "media_type",1);
  3141. mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
  3142. mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
  3143. mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
  3144. mov_write_covr(pb, s);
  3145. mov_write_trkn_tag(pb, mov, s, 0); // track number
  3146. mov_write_trkn_tag(pb, mov, s, 1); // disc number
  3147. mov_write_tmpo_tag(pb, s);
  3148. return update_size(pb, pos);
  3149. }
  3150. static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
  3151. AVFormatContext *s)
  3152. {
  3153. avio_wb32(pb, 33); /* size */
  3154. ffio_wfourcc(pb, "hdlr");
  3155. avio_wb32(pb, 0);
  3156. avio_wb32(pb, 0);
  3157. ffio_wfourcc(pb, "mdta");
  3158. avio_wb32(pb, 0);
  3159. avio_wb32(pb, 0);
  3160. avio_wb32(pb, 0);
  3161. avio_w8(pb, 0);
  3162. return 33;
  3163. }
  3164. static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
  3165. AVFormatContext *s)
  3166. {
  3167. AVDictionaryEntry *t = NULL;
  3168. int64_t pos = avio_tell(pb);
  3169. int64_t curpos, entry_pos;
  3170. int count = 0;
  3171. avio_wb32(pb, 0); /* size */
  3172. ffio_wfourcc(pb, "keys");
  3173. avio_wb32(pb, 0);
  3174. entry_pos = avio_tell(pb);
  3175. avio_wb32(pb, 0); /* entry count */
  3176. while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
  3177. avio_wb32(pb, strlen(t->key) + 8);
  3178. ffio_wfourcc(pb, "mdta");
  3179. avio_write(pb, t->key, strlen(t->key));
  3180. count += 1;
  3181. }
  3182. curpos = avio_tell(pb);
  3183. avio_seek(pb, entry_pos, SEEK_SET);
  3184. avio_wb32(pb, count); // rewrite entry count
  3185. avio_seek(pb, curpos, SEEK_SET);
  3186. return update_size(pb, pos);
  3187. }
  3188. static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
  3189. AVFormatContext *s)
  3190. {
  3191. AVDictionaryEntry *t = NULL;
  3192. int64_t pos = avio_tell(pb);
  3193. int count = 1; /* keys are 1-index based */
  3194. avio_wb32(pb, 0); /* size */
  3195. ffio_wfourcc(pb, "ilst");
  3196. while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
  3197. int64_t entry_pos = avio_tell(pb);
  3198. avio_wb32(pb, 0); /* size */
  3199. avio_wb32(pb, count); /* key */
  3200. mov_write_string_data_tag(pb, t->value, 0, 1);
  3201. update_size(pb, entry_pos);
  3202. count += 1;
  3203. }
  3204. return update_size(pb, pos);
  3205. }
  3206. /* meta data tags */
  3207. static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
  3208. AVFormatContext *s)
  3209. {
  3210. int size = 0;
  3211. int64_t pos = avio_tell(pb);
  3212. avio_wb32(pb, 0); /* size */
  3213. ffio_wfourcc(pb, "meta");
  3214. avio_wb32(pb, 0);
  3215. if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
  3216. mov_write_mdta_hdlr_tag(pb, mov, s);
  3217. mov_write_mdta_keys_tag(pb, mov, s);
  3218. mov_write_mdta_ilst_tag(pb, mov, s);
  3219. }
  3220. else {
  3221. /* iTunes metadata tag */
  3222. mov_write_itunes_hdlr_tag(pb, mov, s);
  3223. mov_write_ilst_tag(pb, mov, s);
  3224. }
  3225. size = update_size(pb, pos);
  3226. return size;
  3227. }
  3228. static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
  3229. const char *name, const char *key)
  3230. {
  3231. int len;
  3232. AVDictionaryEntry *t;
  3233. if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
  3234. return 0;
  3235. len = strlen(t->value);
  3236. if (len > 0) {
  3237. int size = len + 8;
  3238. avio_wb32(pb, size);
  3239. ffio_wfourcc(pb, name);
  3240. avio_write(pb, t->value, len);
  3241. return size;
  3242. }
  3243. return 0;
  3244. }
  3245. static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
  3246. {
  3247. int val;
  3248. while (*b) {
  3249. GET_UTF8(val, *b++, return -1;)
  3250. avio_wb16(pb, val);
  3251. }
  3252. avio_wb16(pb, 0x00);
  3253. return 0;
  3254. }
  3255. static uint16_t language_code(const char *str)
  3256. {
  3257. return (((str[0] - 0x60) & 0x1F) << 10) +
  3258. (((str[1] - 0x60) & 0x1F) << 5) +
  3259. (( str[2] - 0x60) & 0x1F);
  3260. }
  3261. static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
  3262. const char *tag, const char *str)
  3263. {
  3264. int64_t pos = avio_tell(pb);
  3265. AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
  3266. if (!t || !utf8len(t->value))
  3267. return 0;
  3268. avio_wb32(pb, 0); /* size */
  3269. ffio_wfourcc(pb, tag); /* type */
  3270. avio_wb32(pb, 0); /* version + flags */
  3271. if (!strcmp(tag, "yrrc"))
  3272. avio_wb16(pb, atoi(t->value));
  3273. else {
  3274. avio_wb16(pb, language_code("eng")); /* language */
  3275. avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
  3276. if (!strcmp(tag, "albm") &&
  3277. (t = av_dict_get(s->metadata, "track", NULL, 0)))
  3278. avio_w8(pb, atoi(t->value));
  3279. }
  3280. return update_size(pb, pos);
  3281. }
  3282. static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
  3283. {
  3284. int64_t pos = avio_tell(pb);
  3285. int i, nb_chapters = FFMIN(s->nb_chapters, 255);
  3286. avio_wb32(pb, 0); // size
  3287. ffio_wfourcc(pb, "chpl");
  3288. avio_wb32(pb, 0x01000000); // version + flags
  3289. avio_wb32(pb, 0); // unknown
  3290. avio_w8(pb, nb_chapters);
  3291. for (i = 0; i < nb_chapters; i++) {
  3292. AVChapter *c = s->chapters[i];
  3293. AVDictionaryEntry *t;
  3294. avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
  3295. if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
  3296. int len = FFMIN(strlen(t->value), 255);
  3297. avio_w8(pb, len);
  3298. avio_write(pb, t->value, len);
  3299. } else
  3300. avio_w8(pb, 0);
  3301. }
  3302. return update_size(pb, pos);
  3303. }
  3304. static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
  3305. AVFormatContext *s)
  3306. {
  3307. AVIOContext *pb_buf;
  3308. int ret, size;
  3309. uint8_t *buf;
  3310. ret = avio_open_dyn_buf(&pb_buf);
  3311. if (ret < 0)
  3312. return ret;
  3313. if (mov->mode & MODE_3GP) {
  3314. mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
  3315. mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
  3316. mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
  3317. mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
  3318. mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
  3319. mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
  3320. mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
  3321. mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
  3322. mov_write_loci_tag(s, pb_buf);
  3323. } else if (mov->mode == MODE_MOV && !(mov->flags & FF_MOV_FLAG_USE_MDTA)) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
  3324. mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
  3325. mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
  3326. mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
  3327. mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
  3328. mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
  3329. mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
  3330. // currently ignored by mov.c
  3331. mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
  3332. // add support for libquicktime, this atom is also actually read by mov.c
  3333. mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
  3334. mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
  3335. mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
  3336. mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
  3337. mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
  3338. mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
  3339. mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0);
  3340. mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
  3341. } else {
  3342. /* iTunes meta data */
  3343. mov_write_meta_tag(pb_buf, mov, s);
  3344. mov_write_loci_tag(s, pb_buf);
  3345. }
  3346. if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
  3347. mov_write_chpl_tag(pb_buf, s);
  3348. if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
  3349. avio_wb32(pb, size + 8);
  3350. ffio_wfourcc(pb, "udta");
  3351. avio_write(pb, buf, size);
  3352. }
  3353. av_free(buf);
  3354. return 0;
  3355. }
  3356. static void mov_write_psp_udta_tag(AVIOContext *pb,
  3357. const char *str, const char *lang, int type)
  3358. {
  3359. int len = utf8len(str) + 1;
  3360. if (len <= 0)
  3361. return;
  3362. avio_wb16(pb, len * 2 + 10); /* size */
  3363. avio_wb32(pb, type); /* type */
  3364. avio_wb16(pb, language_code(lang)); /* language */
  3365. avio_wb16(pb, 0x01); /* ? */
  3366. ascii_to_wc(pb, str);
  3367. }
  3368. static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
  3369. {
  3370. AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
  3371. int64_t pos, pos2;
  3372. if (title) {
  3373. pos = avio_tell(pb);
  3374. avio_wb32(pb, 0); /* size placeholder*/
  3375. ffio_wfourcc(pb, "uuid");
  3376. ffio_wfourcc(pb, "USMT");
  3377. avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
  3378. avio_wb32(pb, 0xbb88695c);
  3379. avio_wb32(pb, 0xfac9c740);
  3380. pos2 = avio_tell(pb);
  3381. avio_wb32(pb, 0); /* size placeholder*/
  3382. ffio_wfourcc(pb, "MTDT");
  3383. avio_wb16(pb, 4);
  3384. // ?
  3385. avio_wb16(pb, 0x0C); /* size */
  3386. avio_wb32(pb, 0x0B); /* type */
  3387. avio_wb16(pb, language_code("und")); /* language */
  3388. avio_wb16(pb, 0x0); /* ? */
  3389. avio_wb16(pb, 0x021C); /* data */
  3390. if (!(s->flags & AVFMT_FLAG_BITEXACT))
  3391. mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
  3392. mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
  3393. mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
  3394. update_size(pb, pos2);
  3395. return update_size(pb, pos);
  3396. }
  3397. return 0;
  3398. }
  3399. static void build_chunks(MOVTrack *trk)
  3400. {
  3401. int i;
  3402. MOVIentry *chunk = &trk->cluster[0];
  3403. uint64_t chunkSize = chunk->size;
  3404. chunk->chunkNum = 1;
  3405. if (trk->chunkCount)
  3406. return;
  3407. trk->chunkCount = 1;
  3408. for (i = 1; i<trk->entry; i++){
  3409. if (chunk->pos + chunkSize == trk->cluster[i].pos &&
  3410. chunkSize + trk->cluster[i].size < (1<<20)){
  3411. chunkSize += trk->cluster[i].size;
  3412. chunk->samples_in_chunk += trk->cluster[i].entries;
  3413. } else {
  3414. trk->cluster[i].chunkNum = chunk->chunkNum+1;
  3415. chunk=&trk->cluster[i];
  3416. chunkSize = chunk->size;
  3417. trk->chunkCount++;
  3418. }
  3419. }
  3420. }
  3421. /**
  3422. * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
  3423. * the stream ids are used as track ids.
  3424. *
  3425. * This assumes mov->tracks and s->streams are in the same order and
  3426. * there are no gaps in either of them (so mov->tracks[n] refers to
  3427. * s->streams[n]).
  3428. *
  3429. * As an exception, there can be more entries in
  3430. * s->streams than in mov->tracks, in which case new track ids are
  3431. * generated (starting after the largest found stream id).
  3432. */
  3433. static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
  3434. {
  3435. int i;
  3436. if (mov->track_ids_ok)
  3437. return 0;
  3438. if (mov->use_stream_ids_as_track_ids) {
  3439. int next_generated_track_id = 0;
  3440. for (i = 0; i < s->nb_streams; i++) {
  3441. if (s->streams[i]->id > next_generated_track_id)
  3442. next_generated_track_id = s->streams[i]->id;
  3443. }
  3444. for (i = 0; i < mov->nb_streams; i++) {
  3445. if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
  3446. continue;
  3447. mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
  3448. }
  3449. } else {
  3450. for (i = 0; i < mov->nb_streams; i++) {
  3451. if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
  3452. continue;
  3453. mov->tracks[i].track_id = i + 1;
  3454. }
  3455. }
  3456. mov->track_ids_ok = 1;
  3457. return 0;
  3458. }
  3459. static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
  3460. AVFormatContext *s)
  3461. {
  3462. int i;
  3463. int64_t pos = avio_tell(pb);
  3464. avio_wb32(pb, 0); /* size placeholder*/
  3465. ffio_wfourcc(pb, "moov");
  3466. mov_setup_track_ids(mov, s);
  3467. for (i = 0; i < mov->nb_streams; i++) {
  3468. if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
  3469. continue;
  3470. mov->tracks[i].time = mov->time;
  3471. if (mov->tracks[i].entry)
  3472. build_chunks(&mov->tracks[i]);
  3473. }
  3474. if (mov->chapter_track)
  3475. for (i = 0; i < s->nb_streams; i++) {
  3476. mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
  3477. mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
  3478. }
  3479. for (i = 0; i < mov->nb_streams; i++) {
  3480. MOVTrack *track = &mov->tracks[i];
  3481. if (track->tag == MKTAG('r','t','p',' ')) {
  3482. track->tref_tag = MKTAG('h','i','n','t');
  3483. track->tref_id = mov->tracks[track->src_track].track_id;
  3484. } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
  3485. int * fallback, size;
  3486. fallback = (int*)av_stream_get_side_data(track->st,
  3487. AV_PKT_DATA_FALLBACK_TRACK,
  3488. &size);
  3489. if (fallback != NULL && size == sizeof(int)) {
  3490. if (*fallback >= 0 && *fallback < mov->nb_streams) {
  3491. track->tref_tag = MKTAG('f','a','l','l');
  3492. track->tref_id = mov->tracks[*fallback].track_id;
  3493. }
  3494. }
  3495. }
  3496. }
  3497. for (i = 0; i < mov->nb_streams; i++) {
  3498. if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
  3499. int src_trk = mov->tracks[i].src_track;
  3500. mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
  3501. mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
  3502. //src_trk may have a different timescale than the tmcd track
  3503. mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
  3504. mov->tracks[i].timescale,
  3505. mov->tracks[src_trk].timescale);
  3506. }
  3507. }
  3508. mov_write_mvhd_tag(pb, mov);
  3509. if (mov->mode != MODE_MOV && !mov->iods_skip)
  3510. mov_write_iods_tag(pb, mov);
  3511. for (i = 0; i < mov->nb_streams; i++) {
  3512. if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
  3513. int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
  3514. if (ret < 0)
  3515. return ret;
  3516. }
  3517. }
  3518. if (mov->flags & FF_MOV_FLAG_FRAGMENT)
  3519. mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
  3520. if (mov->mode == MODE_PSP)
  3521. mov_write_uuidusmt_tag(pb, s);
  3522. else
  3523. mov_write_udta_tag(pb, mov, s);
  3524. return update_size(pb, pos);
  3525. }
  3526. static void param_write_int(AVIOContext *pb, const char *name, int value)
  3527. {
  3528. avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
  3529. }
  3530. static void param_write_string(AVIOContext *pb, const char *name, const char *value)
  3531. {
  3532. avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
  3533. }
  3534. static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
  3535. {
  3536. char buf[150];
  3537. len = FFMIN(sizeof(buf) / 2 - 1, len);
  3538. ff_data_to_hex(buf, value, len, 0);
  3539. buf[2 * len] = '\0';
  3540. avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
  3541. }
  3542. static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
  3543. {
  3544. int64_t pos = avio_tell(pb);
  3545. int i;
  3546. int64_t manifest_bit_rate = 0;
  3547. AVCPBProperties *props = NULL;
  3548. static const uint8_t uuid[] = {
  3549. 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
  3550. 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
  3551. };
  3552. avio_wb32(pb, 0);
  3553. ffio_wfourcc(pb, "uuid");
  3554. avio_write(pb, uuid, sizeof(uuid));
  3555. avio_wb32(pb, 0);
  3556. avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
  3557. avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
  3558. avio_printf(pb, "<head>\n");
  3559. if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
  3560. avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
  3561. LIBAVFORMAT_IDENT);
  3562. avio_printf(pb, "</head>\n");
  3563. avio_printf(pb, "<body>\n");
  3564. avio_printf(pb, "<switch>\n");
  3565. mov_setup_track_ids(mov, s);
  3566. for (i = 0; i < mov->nb_streams; i++) {
  3567. MOVTrack *track = &mov->tracks[i];
  3568. const char *type;
  3569. int track_id = track->track_id;
  3570. char track_name_buf[32] = { 0 };
  3571. AVStream *st = track->st;
  3572. AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
  3573. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && !is_cover_image(st)) {
  3574. type = "video";
  3575. } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
  3576. type = "audio";
  3577. } else {
  3578. continue;
  3579. }
  3580. props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
  3581. if (track->par->bit_rate) {
  3582. manifest_bit_rate = track->par->bit_rate;
  3583. } else if (props) {
  3584. manifest_bit_rate = props->max_bitrate;
  3585. }
  3586. avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
  3587. manifest_bit_rate);
  3588. param_write_int(pb, "systemBitrate", manifest_bit_rate);
  3589. param_write_int(pb, "trackID", track_id);
  3590. param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
  3591. /* Build track name piece by piece: */
  3592. /* 1. track type */
  3593. av_strlcat(track_name_buf, type, sizeof(track_name_buf));
  3594. /* 2. track language, if available */
  3595. if (lang)
  3596. av_strlcatf(track_name_buf, sizeof(track_name_buf),
  3597. "_%s", lang->value);
  3598. /* 3. special type suffix */
  3599. /* "_cc" = closed captions, "_ad" = audio_description */
  3600. if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
  3601. av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
  3602. else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
  3603. av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
  3604. param_write_string(pb, "trackName", track_name_buf);
  3605. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  3606. if (track->par->codec_id == AV_CODEC_ID_H264) {
  3607. uint8_t *ptr;
  3608. int size = track->par->extradata_size;
  3609. if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
  3610. &size)) {
  3611. param_write_hex(pb, "CodecPrivateData",
  3612. ptr ? ptr : track->par->extradata,
  3613. size);
  3614. av_free(ptr);
  3615. }
  3616. param_write_string(pb, "FourCC", "H264");
  3617. } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
  3618. param_write_string(pb, "FourCC", "WVC1");
  3619. param_write_hex(pb, "CodecPrivateData", track->par->extradata,
  3620. track->par->extradata_size);
  3621. }
  3622. param_write_int(pb, "MaxWidth", track->par->width);
  3623. param_write_int(pb, "MaxHeight", track->par->height);
  3624. param_write_int(pb, "DisplayWidth", track->par->width);
  3625. param_write_int(pb, "DisplayHeight", track->par->height);
  3626. } else {
  3627. if (track->par->codec_id == AV_CODEC_ID_AAC) {
  3628. switch (track->par->profile)
  3629. {
  3630. case FF_PROFILE_AAC_HE_V2:
  3631. param_write_string(pb, "FourCC", "AACP");
  3632. break;
  3633. case FF_PROFILE_AAC_HE:
  3634. param_write_string(pb, "FourCC", "AACH");
  3635. break;
  3636. default:
  3637. param_write_string(pb, "FourCC", "AACL");
  3638. }
  3639. } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
  3640. param_write_string(pb, "FourCC", "WMAP");
  3641. }
  3642. param_write_hex(pb, "CodecPrivateData", track->par->extradata,
  3643. track->par->extradata_size);
  3644. param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
  3645. track->par->codec_id));
  3646. param_write_int(pb, "Channels", track->par->channels);
  3647. param_write_int(pb, "SamplingRate", track->par->sample_rate);
  3648. param_write_int(pb, "BitsPerSample", 16);
  3649. param_write_int(pb, "PacketSize", track->par->block_align ?
  3650. track->par->block_align : 4);
  3651. }
  3652. avio_printf(pb, "</%s>\n", type);
  3653. }
  3654. avio_printf(pb, "</switch>\n");
  3655. avio_printf(pb, "</body>\n");
  3656. avio_printf(pb, "</smil>\n");
  3657. return update_size(pb, pos);
  3658. }
  3659. static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
  3660. {
  3661. avio_wb32(pb, 16);
  3662. ffio_wfourcc(pb, "mfhd");
  3663. avio_wb32(pb, 0);
  3664. avio_wb32(pb, mov->fragments);
  3665. return 0;
  3666. }
  3667. static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
  3668. {
  3669. return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
  3670. (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
  3671. }
  3672. static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
  3673. MOVTrack *track, int64_t moof_offset)
  3674. {
  3675. int64_t pos = avio_tell(pb);
  3676. uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
  3677. MOV_TFHD_BASE_DATA_OFFSET;
  3678. if (!track->entry) {
  3679. flags |= MOV_TFHD_DURATION_IS_EMPTY;
  3680. } else {
  3681. flags |= MOV_TFHD_DEFAULT_FLAGS;
  3682. }
  3683. if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
  3684. flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
  3685. if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
  3686. flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
  3687. flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
  3688. }
  3689. /* Don't set a default sample size, the silverlight player refuses
  3690. * to play files with that set. Don't set a default sample duration,
  3691. * WMP freaks out if it is set. Don't set a base data offset, PIFF
  3692. * file format says it MUST NOT be set. */
  3693. if (track->mode == MODE_ISM)
  3694. flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
  3695. MOV_TFHD_BASE_DATA_OFFSET);
  3696. avio_wb32(pb, 0); /* size placeholder */
  3697. ffio_wfourcc(pb, "tfhd");
  3698. avio_w8(pb, 0); /* version */
  3699. avio_wb24(pb, flags);
  3700. avio_wb32(pb, track->track_id); /* track-id */
  3701. if (flags & MOV_TFHD_BASE_DATA_OFFSET)
  3702. avio_wb64(pb, moof_offset);
  3703. if (flags & MOV_TFHD_DEFAULT_DURATION) {
  3704. track->default_duration = get_cluster_duration(track, 0);
  3705. avio_wb32(pb, track->default_duration);
  3706. }
  3707. if (flags & MOV_TFHD_DEFAULT_SIZE) {
  3708. track->default_size = track->entry ? track->cluster[0].size : 1;
  3709. avio_wb32(pb, track->default_size);
  3710. } else
  3711. track->default_size = -1;
  3712. if (flags & MOV_TFHD_DEFAULT_FLAGS) {
  3713. /* Set the default flags based on the second sample, if available.
  3714. * If the first sample is different, that can be signaled via a separate field. */
  3715. if (track->entry > 1)
  3716. track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
  3717. else
  3718. track->default_sample_flags =
  3719. track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
  3720. (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
  3721. MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
  3722. avio_wb32(pb, track->default_sample_flags);
  3723. }
  3724. return update_size(pb, pos);
  3725. }
  3726. static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
  3727. MOVTrack *track, int moof_size,
  3728. int first, int end)
  3729. {
  3730. int64_t pos = avio_tell(pb);
  3731. uint32_t flags = MOV_TRUN_DATA_OFFSET;
  3732. int i;
  3733. for (i = first; i < end; i++) {
  3734. if (get_cluster_duration(track, i) != track->default_duration)
  3735. flags |= MOV_TRUN_SAMPLE_DURATION;
  3736. if (track->cluster[i].size != track->default_size)
  3737. flags |= MOV_TRUN_SAMPLE_SIZE;
  3738. if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
  3739. flags |= MOV_TRUN_SAMPLE_FLAGS;
  3740. }
  3741. if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
  3742. get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
  3743. flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
  3744. if (track->flags & MOV_TRACK_CTTS)
  3745. flags |= MOV_TRUN_SAMPLE_CTS;
  3746. avio_wb32(pb, 0); /* size placeholder */
  3747. ffio_wfourcc(pb, "trun");
  3748. if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
  3749. avio_w8(pb, 1); /* version */
  3750. else
  3751. avio_w8(pb, 0); /* version */
  3752. avio_wb24(pb, flags);
  3753. avio_wb32(pb, end - first); /* sample count */
  3754. if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
  3755. !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
  3756. !mov->first_trun)
  3757. avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
  3758. else
  3759. avio_wb32(pb, moof_size + 8 + track->data_offset +
  3760. track->cluster[first].pos); /* data offset */
  3761. if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
  3762. avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
  3763. for (i = first; i < end; i++) {
  3764. if (flags & MOV_TRUN_SAMPLE_DURATION)
  3765. avio_wb32(pb, get_cluster_duration(track, i));
  3766. if (flags & MOV_TRUN_SAMPLE_SIZE)
  3767. avio_wb32(pb, track->cluster[i].size);
  3768. if (flags & MOV_TRUN_SAMPLE_FLAGS)
  3769. avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
  3770. if (flags & MOV_TRUN_SAMPLE_CTS)
  3771. avio_wb32(pb, track->cluster[i].cts);
  3772. }
  3773. mov->first_trun = 0;
  3774. return update_size(pb, pos);
  3775. }
  3776. static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
  3777. {
  3778. int64_t pos = avio_tell(pb);
  3779. static const uint8_t uuid[] = {
  3780. 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
  3781. 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
  3782. };
  3783. avio_wb32(pb, 0); /* size placeholder */
  3784. ffio_wfourcc(pb, "uuid");
  3785. avio_write(pb, uuid, sizeof(uuid));
  3786. avio_w8(pb, 1);
  3787. avio_wb24(pb, 0);
  3788. avio_wb64(pb, track->start_dts + track->frag_start +
  3789. track->cluster[0].cts);
  3790. avio_wb64(pb, track->end_pts -
  3791. (track->cluster[0].dts + track->cluster[0].cts));
  3792. return update_size(pb, pos);
  3793. }
  3794. static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
  3795. MOVTrack *track, int entry)
  3796. {
  3797. int n = track->nb_frag_info - 1 - entry, i;
  3798. int size = 8 + 16 + 4 + 1 + 16*n;
  3799. static const uint8_t uuid[] = {
  3800. 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
  3801. 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
  3802. };
  3803. if (entry < 0)
  3804. return 0;
  3805. avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
  3806. avio_wb32(pb, size);
  3807. ffio_wfourcc(pb, "uuid");
  3808. avio_write(pb, uuid, sizeof(uuid));
  3809. avio_w8(pb, 1);
  3810. avio_wb24(pb, 0);
  3811. avio_w8(pb, n);
  3812. for (i = 0; i < n; i++) {
  3813. int index = entry + 1 + i;
  3814. avio_wb64(pb, track->frag_info[index].time);
  3815. avio_wb64(pb, track->frag_info[index].duration);
  3816. }
  3817. if (n < mov->ism_lookahead) {
  3818. int free_size = 16 * (mov->ism_lookahead - n);
  3819. avio_wb32(pb, free_size);
  3820. ffio_wfourcc(pb, "free");
  3821. ffio_fill(pb, 0, free_size - 8);
  3822. }
  3823. return 0;
  3824. }
  3825. static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
  3826. MOVTrack *track)
  3827. {
  3828. int64_t pos = avio_tell(pb);
  3829. int i;
  3830. for (i = 0; i < mov->ism_lookahead; i++) {
  3831. /* Update the tfrf tag for the last ism_lookahead fragments,
  3832. * nb_frag_info - 1 is the next fragment to be written. */
  3833. mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
  3834. }
  3835. avio_seek(pb, pos, SEEK_SET);
  3836. return 0;
  3837. }
  3838. static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
  3839. int size)
  3840. {
  3841. int i;
  3842. for (i = 0; i < mov->nb_streams; i++) {
  3843. MOVTrack *track = &mov->tracks[i];
  3844. MOVFragmentInfo *info;
  3845. if ((tracks >= 0 && i != tracks) || !track->entry)
  3846. continue;
  3847. track->nb_frag_info++;
  3848. if (track->nb_frag_info >= track->frag_info_capacity) {
  3849. unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
  3850. if (av_reallocp_array(&track->frag_info,
  3851. new_capacity,
  3852. sizeof(*track->frag_info)))
  3853. return AVERROR(ENOMEM);
  3854. track->frag_info_capacity = new_capacity;
  3855. }
  3856. info = &track->frag_info[track->nb_frag_info - 1];
  3857. info->offset = avio_tell(pb);
  3858. info->size = size;
  3859. // Try to recreate the original pts for the first packet
  3860. // from the fields we have stored
  3861. info->time = track->start_dts + track->frag_start +
  3862. track->cluster[0].cts;
  3863. info->duration = track->end_pts -
  3864. (track->cluster[0].dts + track->cluster[0].cts);
  3865. // If the pts is less than zero, we will have trimmed
  3866. // away parts of the media track using an edit list,
  3867. // and the corresponding start presentation time is zero.
  3868. if (info->time < 0) {
  3869. info->duration += info->time;
  3870. info->time = 0;
  3871. }
  3872. info->tfrf_offset = 0;
  3873. mov_write_tfrf_tags(pb, mov, track);
  3874. }
  3875. return 0;
  3876. }
  3877. static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
  3878. {
  3879. int i;
  3880. for (i = 0; i < mov->nb_streams; i++) {
  3881. MOVTrack *track = &mov->tracks[i];
  3882. if ((tracks >= 0 && i != tracks) || !track->entry)
  3883. continue;
  3884. if (track->nb_frag_info > max) {
  3885. memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
  3886. track->nb_frag_info = max;
  3887. }
  3888. }
  3889. }
  3890. static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
  3891. {
  3892. int64_t pos = avio_tell(pb);
  3893. avio_wb32(pb, 0); /* size */
  3894. ffio_wfourcc(pb, "tfdt");
  3895. avio_w8(pb, 1); /* version */
  3896. avio_wb24(pb, 0);
  3897. avio_wb64(pb, track->frag_start);
  3898. return update_size(pb, pos);
  3899. }
  3900. static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
  3901. MOVTrack *track, int64_t moof_offset,
  3902. int moof_size)
  3903. {
  3904. int64_t pos = avio_tell(pb);
  3905. int i, start = 0;
  3906. avio_wb32(pb, 0); /* size placeholder */
  3907. ffio_wfourcc(pb, "traf");
  3908. mov_write_tfhd_tag(pb, mov, track, moof_offset);
  3909. if (mov->mode != MODE_ISM)
  3910. mov_write_tfdt_tag(pb, track);
  3911. for (i = 1; i < track->entry; i++) {
  3912. if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
  3913. mov_write_trun_tag(pb, mov, track, moof_size, start, i);
  3914. start = i;
  3915. }
  3916. }
  3917. mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
  3918. if (mov->mode == MODE_ISM) {
  3919. mov_write_tfxd_tag(pb, track);
  3920. if (mov->ism_lookahead) {
  3921. int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
  3922. if (track->nb_frag_info > 0) {
  3923. MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
  3924. if (!info->tfrf_offset)
  3925. info->tfrf_offset = avio_tell(pb);
  3926. }
  3927. avio_wb32(pb, 8 + size);
  3928. ffio_wfourcc(pb, "free");
  3929. for (i = 0; i < size; i++)
  3930. avio_w8(pb, 0);
  3931. }
  3932. }
  3933. return update_size(pb, pos);
  3934. }
  3935. static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
  3936. int tracks, int moof_size)
  3937. {
  3938. int64_t pos = avio_tell(pb);
  3939. int i;
  3940. avio_wb32(pb, 0); /* size placeholder */
  3941. ffio_wfourcc(pb, "moof");
  3942. mov->first_trun = 1;
  3943. mov_write_mfhd_tag(pb, mov);
  3944. for (i = 0; i < mov->nb_streams; i++) {
  3945. MOVTrack *track = &mov->tracks[i];
  3946. if (tracks >= 0 && i != tracks)
  3947. continue;
  3948. if (!track->entry)
  3949. continue;
  3950. mov_write_traf_tag(pb, mov, track, pos, moof_size);
  3951. }
  3952. return update_size(pb, pos);
  3953. }
  3954. static int mov_write_sidx_tag(AVIOContext *pb,
  3955. MOVTrack *track, int ref_size, int total_sidx_size)
  3956. {
  3957. int64_t pos = avio_tell(pb), offset_pos, end_pos;
  3958. int64_t presentation_time, duration, offset;
  3959. int starts_with_SAP, i, entries;
  3960. if (track->entry) {
  3961. entries = 1;
  3962. presentation_time = track->start_dts + track->frag_start +
  3963. track->cluster[0].cts;
  3964. duration = track->end_pts -
  3965. (track->cluster[0].dts + track->cluster[0].cts);
  3966. starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
  3967. // pts<0 should be cut away using edts
  3968. if (presentation_time < 0) {
  3969. duration += presentation_time;
  3970. presentation_time = 0;
  3971. }
  3972. } else {
  3973. entries = track->nb_frag_info;
  3974. if (entries <= 0)
  3975. return 0;
  3976. presentation_time = track->frag_info[0].time;
  3977. }
  3978. avio_wb32(pb, 0); /* size */
  3979. ffio_wfourcc(pb, "sidx");
  3980. avio_w8(pb, 1); /* version */
  3981. avio_wb24(pb, 0);
  3982. avio_wb32(pb, track->track_id); /* reference_ID */
  3983. avio_wb32(pb, track->timescale); /* timescale */
  3984. avio_wb64(pb, presentation_time); /* earliest_presentation_time */
  3985. offset_pos = avio_tell(pb);
  3986. avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
  3987. avio_wb16(pb, 0); /* reserved */
  3988. avio_wb16(pb, entries); /* reference_count */
  3989. for (i = 0; i < entries; i++) {
  3990. if (!track->entry) {
  3991. if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
  3992. av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
  3993. }
  3994. duration = track->frag_info[i].duration;
  3995. ref_size = track->frag_info[i].size;
  3996. starts_with_SAP = 1;
  3997. }
  3998. avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
  3999. avio_wb32(pb, duration); /* subsegment_duration */
  4000. avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
  4001. }
  4002. end_pos = avio_tell(pb);
  4003. offset = pos + total_sidx_size - end_pos;
  4004. avio_seek(pb, offset_pos, SEEK_SET);
  4005. avio_wb64(pb, offset);
  4006. avio_seek(pb, end_pos, SEEK_SET);
  4007. return update_size(pb, pos);
  4008. }
  4009. static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
  4010. int tracks, int ref_size)
  4011. {
  4012. int i, round, ret;
  4013. AVIOContext *avio_buf;
  4014. int total_size = 0;
  4015. for (round = 0; round < 2; round++) {
  4016. // First run one round to calculate the total size of all
  4017. // sidx atoms.
  4018. // This would be much simpler if we'd only write one sidx
  4019. // atom, for the first track in the moof.
  4020. if (round == 0) {
  4021. if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
  4022. return ret;
  4023. } else {
  4024. avio_buf = pb;
  4025. }
  4026. for (i = 0; i < mov->nb_streams; i++) {
  4027. MOVTrack *track = &mov->tracks[i];
  4028. if (tracks >= 0 && i != tracks)
  4029. continue;
  4030. // When writing a sidx for the full file, entry is 0, but
  4031. // we want to include all tracks. ref_size is 0 in this case,
  4032. // since we read it from frag_info instead.
  4033. if (!track->entry && ref_size > 0)
  4034. continue;
  4035. total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
  4036. total_size);
  4037. }
  4038. if (round == 0)
  4039. total_size = ffio_close_null_buf(avio_buf);
  4040. }
  4041. return 0;
  4042. }
  4043. static int mov_write_prft_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
  4044. {
  4045. int64_t pos = avio_tell(pb), pts_us, ntp_ts;
  4046. MOVTrack *first_track;
  4047. /* PRFT should be associated with at most one track. So, choosing only the
  4048. * first track. */
  4049. if (tracks > 0)
  4050. return 0;
  4051. first_track = &(mov->tracks[0]);
  4052. if (!first_track->entry) {
  4053. av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, no entries in the track\n");
  4054. return 0;
  4055. }
  4056. if (first_track->cluster[0].pts == AV_NOPTS_VALUE) {
  4057. av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, first PTS is invalid\n");
  4058. return 0;
  4059. }
  4060. if (mov->write_prft == MOV_PRFT_SRC_WALLCLOCK) {
  4061. ntp_ts = ff_get_formatted_ntp_time(ff_ntp_time());
  4062. } else if (mov->write_prft == MOV_PRFT_SRC_PTS) {
  4063. pts_us = av_rescale_q(first_track->cluster[0].pts,
  4064. first_track->st->time_base, AV_TIME_BASE_Q);
  4065. ntp_ts = ff_get_formatted_ntp_time(pts_us + NTP_OFFSET_US);
  4066. } else {
  4067. av_log(mov->fc, AV_LOG_WARNING, "Unsupported PRFT box configuration: %d\n",
  4068. mov->write_prft);
  4069. return 0;
  4070. }
  4071. avio_wb32(pb, 0); // Size place holder
  4072. ffio_wfourcc(pb, "prft"); // Type
  4073. avio_w8(pb, 1); // Version
  4074. avio_wb24(pb, 0); // Flags
  4075. avio_wb32(pb, first_track->track_id); // reference track ID
  4076. avio_wb64(pb, ntp_ts); // NTP time stamp
  4077. avio_wb64(pb, first_track->cluster[0].pts); //media time
  4078. return update_size(pb, pos);
  4079. }
  4080. static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
  4081. int64_t mdat_size)
  4082. {
  4083. AVIOContext *avio_buf;
  4084. int ret, moof_size;
  4085. if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
  4086. return ret;
  4087. mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
  4088. moof_size = ffio_close_null_buf(avio_buf);
  4089. if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
  4090. mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
  4091. if (mov->write_prft > MOV_PRFT_NONE && mov->write_prft < MOV_PRFT_NB)
  4092. mov_write_prft_tag(pb, mov, tracks);
  4093. if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
  4094. !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
  4095. mov->ism_lookahead) {
  4096. if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
  4097. return ret;
  4098. if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
  4099. mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
  4100. mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
  4101. }
  4102. }
  4103. return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
  4104. }
  4105. static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
  4106. {
  4107. int64_t pos = avio_tell(pb);
  4108. int i;
  4109. avio_wb32(pb, 0); /* size placeholder */
  4110. ffio_wfourcc(pb, "tfra");
  4111. avio_w8(pb, 1); /* version */
  4112. avio_wb24(pb, 0);
  4113. avio_wb32(pb, track->track_id);
  4114. avio_wb32(pb, 0); /* length of traf/trun/sample num */
  4115. avio_wb32(pb, track->nb_frag_info);
  4116. for (i = 0; i < track->nb_frag_info; i++) {
  4117. avio_wb64(pb, track->frag_info[i].time);
  4118. avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
  4119. avio_w8(pb, 1); /* traf number */
  4120. avio_w8(pb, 1); /* trun number */
  4121. avio_w8(pb, 1); /* sample number */
  4122. }
  4123. return update_size(pb, pos);
  4124. }
  4125. static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
  4126. {
  4127. int64_t pos = avio_tell(pb);
  4128. int i;
  4129. avio_wb32(pb, 0); /* size placeholder */
  4130. ffio_wfourcc(pb, "mfra");
  4131. /* An empty mfra atom is enough to indicate to the publishing point that
  4132. * the stream has ended. */
  4133. if (mov->flags & FF_MOV_FLAG_ISML)
  4134. return update_size(pb, pos);
  4135. for (i = 0; i < mov->nb_streams; i++) {
  4136. MOVTrack *track = &mov->tracks[i];
  4137. if (track->nb_frag_info)
  4138. mov_write_tfra_tag(pb, track);
  4139. }
  4140. avio_wb32(pb, 16);
  4141. ffio_wfourcc(pb, "mfro");
  4142. avio_wb32(pb, 0); /* version + flags */
  4143. avio_wb32(pb, avio_tell(pb) + 4 - pos);
  4144. return update_size(pb, pos);
  4145. }
  4146. static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
  4147. {
  4148. avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
  4149. ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
  4150. mov->mdat_pos = avio_tell(pb);
  4151. avio_wb32(pb, 0); /* size placeholder*/
  4152. ffio_wfourcc(pb, "mdat");
  4153. return 0;
  4154. }
  4155. /* TODO: This needs to be more general */
  4156. static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
  4157. {
  4158. MOVMuxContext *mov = s->priv_data;
  4159. int64_t pos = avio_tell(pb);
  4160. int has_h264 = 0, has_video = 0;
  4161. int minor = 0x200;
  4162. int i;
  4163. for (i = 0; i < s->nb_streams; i++) {
  4164. AVStream *st = s->streams[i];
  4165. if (is_cover_image(st))
  4166. continue;
  4167. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  4168. has_video = 1;
  4169. if (st->codecpar->codec_id == AV_CODEC_ID_H264)
  4170. has_h264 = 1;
  4171. }
  4172. avio_wb32(pb, 0); /* size */
  4173. ffio_wfourcc(pb, "ftyp");
  4174. if (mov->major_brand && strlen(mov->major_brand) >= 4)
  4175. ffio_wfourcc(pb, mov->major_brand);
  4176. else if (mov->mode == MODE_3GP) {
  4177. ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
  4178. minor = has_h264 ? 0x100 : 0x200;
  4179. } else if (mov->mode & MODE_3G2) {
  4180. ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
  4181. minor = has_h264 ? 0x20000 : 0x10000;
  4182. } else if (mov->mode == MODE_PSP)
  4183. ffio_wfourcc(pb, "MSNV");
  4184. else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
  4185. ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
  4186. else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
  4187. ffio_wfourcc(pb, "iso4");
  4188. else if (mov->mode == MODE_MP4)
  4189. ffio_wfourcc(pb, "isom");
  4190. else if (mov->mode == MODE_IPOD)
  4191. ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
  4192. else if (mov->mode == MODE_ISM)
  4193. ffio_wfourcc(pb, "isml");
  4194. else if (mov->mode == MODE_F4V)
  4195. ffio_wfourcc(pb, "f4v ");
  4196. else
  4197. ffio_wfourcc(pb, "qt ");
  4198. avio_wb32(pb, minor);
  4199. if (mov->mode == MODE_MOV)
  4200. ffio_wfourcc(pb, "qt ");
  4201. else if (mov->mode == MODE_ISM) {
  4202. ffio_wfourcc(pb, "piff");
  4203. } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
  4204. ffio_wfourcc(pb, "isom");
  4205. ffio_wfourcc(pb, "iso2");
  4206. if (has_h264)
  4207. ffio_wfourcc(pb, "avc1");
  4208. }
  4209. // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
  4210. // brand. This is compatible with users that don't understand tfdt.
  4211. if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
  4212. ffio_wfourcc(pb, "iso6");
  4213. if (mov->mode == MODE_3GP)
  4214. ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
  4215. else if (mov->mode & MODE_3G2)
  4216. ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
  4217. else if (mov->mode == MODE_PSP)
  4218. ffio_wfourcc(pb, "MSNV");
  4219. else if (mov->mode == MODE_MP4)
  4220. ffio_wfourcc(pb, "mp41");
  4221. if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
  4222. ffio_wfourcc(pb, "dash");
  4223. return update_size(pb, pos);
  4224. }
  4225. static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
  4226. {
  4227. AVStream *video_st = s->streams[0];
  4228. AVCodecParameters *video_par = s->streams[0]->codecpar;
  4229. AVCodecParameters *audio_par = s->streams[1]->codecpar;
  4230. int audio_rate = audio_par->sample_rate;
  4231. int64_t frame_rate = video_st->avg_frame_rate.den ?
  4232. (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
  4233. 0;
  4234. int audio_kbitrate = audio_par->bit_rate / 1000;
  4235. int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
  4236. if (frame_rate < 0 || frame_rate > INT32_MAX) {
  4237. av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
  4238. return AVERROR(EINVAL);
  4239. }
  4240. avio_wb32(pb, 0x94); /* size */
  4241. ffio_wfourcc(pb, "uuid");
  4242. ffio_wfourcc(pb, "PROF");
  4243. avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
  4244. avio_wb32(pb, 0xbb88695c);
  4245. avio_wb32(pb, 0xfac9c740);
  4246. avio_wb32(pb, 0x0); /* ? */
  4247. avio_wb32(pb, 0x3); /* 3 sections ? */
  4248. avio_wb32(pb, 0x14); /* size */
  4249. ffio_wfourcc(pb, "FPRF");
  4250. avio_wb32(pb, 0x0); /* ? */
  4251. avio_wb32(pb, 0x0); /* ? */
  4252. avio_wb32(pb, 0x0); /* ? */
  4253. avio_wb32(pb, 0x2c); /* size */
  4254. ffio_wfourcc(pb, "APRF"); /* audio */
  4255. avio_wb32(pb, 0x0);
  4256. avio_wb32(pb, 0x2); /* TrackID */
  4257. ffio_wfourcc(pb, "mp4a");
  4258. avio_wb32(pb, 0x20f);
  4259. avio_wb32(pb, 0x0);
  4260. avio_wb32(pb, audio_kbitrate);
  4261. avio_wb32(pb, audio_kbitrate);
  4262. avio_wb32(pb, audio_rate);
  4263. avio_wb32(pb, audio_par->channels);
  4264. avio_wb32(pb, 0x34); /* size */
  4265. ffio_wfourcc(pb, "VPRF"); /* video */
  4266. avio_wb32(pb, 0x0);
  4267. avio_wb32(pb, 0x1); /* TrackID */
  4268. if (video_par->codec_id == AV_CODEC_ID_H264) {
  4269. ffio_wfourcc(pb, "avc1");
  4270. avio_wb16(pb, 0x014D);
  4271. avio_wb16(pb, 0x0015);
  4272. } else {
  4273. ffio_wfourcc(pb, "mp4v");
  4274. avio_wb16(pb, 0x0000);
  4275. avio_wb16(pb, 0x0103);
  4276. }
  4277. avio_wb32(pb, 0x0);
  4278. avio_wb32(pb, video_kbitrate);
  4279. avio_wb32(pb, video_kbitrate);
  4280. avio_wb32(pb, frame_rate);
  4281. avio_wb32(pb, frame_rate);
  4282. avio_wb16(pb, video_par->width);
  4283. avio_wb16(pb, video_par->height);
  4284. avio_wb32(pb, 0x010001); /* ? */
  4285. return 0;
  4286. }
  4287. static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
  4288. {
  4289. MOVMuxContext *mov = s->priv_data;
  4290. int i;
  4291. mov_write_ftyp_tag(pb,s);
  4292. if (mov->mode == MODE_PSP) {
  4293. int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
  4294. for (i = 0; i < s->nb_streams; i++) {
  4295. AVStream *st = s->streams[i];
  4296. if (is_cover_image(st))
  4297. continue;
  4298. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  4299. video_streams_nb++;
  4300. else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
  4301. audio_streams_nb++;
  4302. else
  4303. other_streams_nb++;
  4304. }
  4305. if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
  4306. av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
  4307. return AVERROR(EINVAL);
  4308. }
  4309. return mov_write_uuidprof_tag(pb, s);
  4310. }
  4311. return 0;
  4312. }
  4313. static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
  4314. {
  4315. uint32_t c = -1;
  4316. int i, closed_gop = 0;
  4317. for (i = 0; i < pkt->size - 4; i++) {
  4318. c = (c << 8) + pkt->data[i];
  4319. if (c == 0x1b8) { // gop
  4320. closed_gop = pkt->data[i + 4] >> 6 & 0x01;
  4321. } else if (c == 0x100) { // pic
  4322. int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
  4323. if (!temp_ref || closed_gop) // I picture is not reordered
  4324. *flags = MOV_SYNC_SAMPLE;
  4325. else
  4326. *flags = MOV_PARTIAL_SYNC_SAMPLE;
  4327. break;
  4328. }
  4329. }
  4330. return 0;
  4331. }
  4332. static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
  4333. {
  4334. const uint8_t *start, *next, *end = pkt->data + pkt->size;
  4335. int seq = 0, entry = 0;
  4336. int key = pkt->flags & AV_PKT_FLAG_KEY;
  4337. start = find_next_marker(pkt->data, end);
  4338. for (next = start; next < end; start = next) {
  4339. next = find_next_marker(start + 4, end);
  4340. switch (AV_RB32(start)) {
  4341. case VC1_CODE_SEQHDR:
  4342. seq = 1;
  4343. break;
  4344. case VC1_CODE_ENTRYPOINT:
  4345. entry = 1;
  4346. break;
  4347. case VC1_CODE_SLICE:
  4348. trk->vc1_info.slices = 1;
  4349. break;
  4350. }
  4351. }
  4352. if (!trk->entry && trk->vc1_info.first_packet_seen)
  4353. trk->vc1_info.first_frag_written = 1;
  4354. if (!trk->entry && !trk->vc1_info.first_frag_written) {
  4355. /* First packet in first fragment */
  4356. trk->vc1_info.first_packet_seq = seq;
  4357. trk->vc1_info.first_packet_entry = entry;
  4358. trk->vc1_info.first_packet_seen = 1;
  4359. } else if ((seq && !trk->vc1_info.packet_seq) ||
  4360. (entry && !trk->vc1_info.packet_entry)) {
  4361. int i;
  4362. for (i = 0; i < trk->entry; i++)
  4363. trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
  4364. trk->has_keyframes = 0;
  4365. if (seq)
  4366. trk->vc1_info.packet_seq = 1;
  4367. if (entry)
  4368. trk->vc1_info.packet_entry = 1;
  4369. if (!trk->vc1_info.first_frag_written) {
  4370. /* First fragment */
  4371. if ((!seq || trk->vc1_info.first_packet_seq) &&
  4372. (!entry || trk->vc1_info.first_packet_entry)) {
  4373. /* First packet had the same headers as this one, readd the
  4374. * sync sample flag. */
  4375. trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
  4376. trk->has_keyframes = 1;
  4377. }
  4378. }
  4379. }
  4380. if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
  4381. key = seq && entry;
  4382. else if (trk->vc1_info.packet_seq)
  4383. key = seq;
  4384. else if (trk->vc1_info.packet_entry)
  4385. key = entry;
  4386. if (key) {
  4387. trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
  4388. trk->has_keyframes++;
  4389. }
  4390. }
  4391. static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
  4392. {
  4393. MOVMuxContext *mov = s->priv_data;
  4394. int ret, buf_size;
  4395. uint8_t *buf;
  4396. int i, offset;
  4397. if (!track->mdat_buf)
  4398. return 0;
  4399. if (!mov->mdat_buf) {
  4400. if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
  4401. return ret;
  4402. }
  4403. buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
  4404. track->mdat_buf = NULL;
  4405. offset = avio_tell(mov->mdat_buf);
  4406. avio_write(mov->mdat_buf, buf, buf_size);
  4407. av_free(buf);
  4408. for (i = track->entries_flushed; i < track->entry; i++)
  4409. track->cluster[i].pos += offset;
  4410. track->entries_flushed = track->entry;
  4411. return 0;
  4412. }
  4413. static int mov_flush_fragment(AVFormatContext *s, int force)
  4414. {
  4415. MOVMuxContext *mov = s->priv_data;
  4416. int i, first_track = -1;
  4417. int64_t mdat_size = 0;
  4418. int ret;
  4419. int has_video = 0, starts_with_key = 0, first_video_track = 1;
  4420. if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
  4421. return 0;
  4422. // Try to fill in the duration of the last packet in each stream
  4423. // from queued packets in the interleave queues. If the flushing
  4424. // of fragments was triggered automatically by an AVPacket, we
  4425. // already have reliable info for the end of that track, but other
  4426. // tracks may need to be filled in.
  4427. for (i = 0; i < s->nb_streams; i++) {
  4428. MOVTrack *track = &mov->tracks[i];
  4429. if (!track->end_reliable) {
  4430. AVPacket pkt;
  4431. if (!ff_interleaved_peek(s, i, &pkt, 1)) {
  4432. if (track->dts_shift != AV_NOPTS_VALUE)
  4433. pkt.dts += track->dts_shift;
  4434. track->track_duration = pkt.dts - track->start_dts;
  4435. if (pkt.pts != AV_NOPTS_VALUE)
  4436. track->end_pts = pkt.pts;
  4437. else
  4438. track->end_pts = pkt.dts;
  4439. }
  4440. }
  4441. }
  4442. for (i = 0; i < mov->nb_streams; i++) {
  4443. MOVTrack *track = &mov->tracks[i];
  4444. if (track->entry <= 1)
  4445. continue;
  4446. // Sample durations are calculated as the diff of dts values,
  4447. // but for the last sample in a fragment, we don't know the dts
  4448. // of the first sample in the next fragment, so we have to rely
  4449. // on what was set as duration in the AVPacket. Not all callers
  4450. // set this though, so we might want to replace it with an
  4451. // estimate if it currently is zero.
  4452. if (get_cluster_duration(track, track->entry - 1) != 0)
  4453. continue;
  4454. // Use the duration (i.e. dts diff) of the second last sample for
  4455. // the last one. This is a wild guess (and fatal if it turns out
  4456. // to be too long), but probably the best we can do - having a zero
  4457. // duration is bad as well.
  4458. track->track_duration += get_cluster_duration(track, track->entry - 2);
  4459. track->end_pts += get_cluster_duration(track, track->entry - 2);
  4460. if (!mov->missing_duration_warned) {
  4461. av_log(s, AV_LOG_WARNING,
  4462. "Estimating the duration of the last packet in a "
  4463. "fragment, consider setting the duration field in "
  4464. "AVPacket instead.\n");
  4465. mov->missing_duration_warned = 1;
  4466. }
  4467. }
  4468. if (!mov->moov_written) {
  4469. int64_t pos = avio_tell(s->pb);
  4470. uint8_t *buf;
  4471. int buf_size, moov_size;
  4472. for (i = 0; i < mov->nb_streams; i++)
  4473. if (!mov->tracks[i].entry && !is_cover_image(mov->tracks[i].st))
  4474. break;
  4475. /* Don't write the initial moov unless all tracks have data */
  4476. if (i < mov->nb_streams && !force)
  4477. return 0;
  4478. moov_size = get_moov_size(s);
  4479. for (i = 0; i < mov->nb_streams; i++)
  4480. mov->tracks[i].data_offset = pos + moov_size + 8;
  4481. avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
  4482. if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
  4483. mov_write_identification(s->pb, s);
  4484. if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
  4485. return ret;
  4486. if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
  4487. if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
  4488. mov->reserved_header_pos = avio_tell(s->pb);
  4489. avio_flush(s->pb);
  4490. mov->moov_written = 1;
  4491. return 0;
  4492. }
  4493. buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
  4494. mov->mdat_buf = NULL;
  4495. avio_wb32(s->pb, buf_size + 8);
  4496. ffio_wfourcc(s->pb, "mdat");
  4497. avio_write(s->pb, buf, buf_size);
  4498. av_free(buf);
  4499. if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
  4500. mov->reserved_header_pos = avio_tell(s->pb);
  4501. mov->moov_written = 1;
  4502. mov->mdat_size = 0;
  4503. for (i = 0; i < mov->nb_streams; i++) {
  4504. if (mov->tracks[i].entry)
  4505. mov->tracks[i].frag_start += mov->tracks[i].start_dts +
  4506. mov->tracks[i].track_duration -
  4507. mov->tracks[i].cluster[0].dts;
  4508. mov->tracks[i].entry = 0;
  4509. mov->tracks[i].end_reliable = 0;
  4510. }
  4511. avio_flush(s->pb);
  4512. return 0;
  4513. }
  4514. if (mov->frag_interleave) {
  4515. for (i = 0; i < mov->nb_streams; i++) {
  4516. MOVTrack *track = &mov->tracks[i];
  4517. int ret;
  4518. if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
  4519. return ret;
  4520. }
  4521. if (!mov->mdat_buf)
  4522. return 0;
  4523. mdat_size = avio_tell(mov->mdat_buf);
  4524. }
  4525. for (i = 0; i < mov->nb_streams; i++) {
  4526. MOVTrack *track = &mov->tracks[i];
  4527. if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
  4528. track->data_offset = 0;
  4529. else
  4530. track->data_offset = mdat_size;
  4531. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  4532. has_video = 1;
  4533. if (first_video_track) {
  4534. if (track->entry)
  4535. starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
  4536. first_video_track = 0;
  4537. }
  4538. }
  4539. if (!track->entry)
  4540. continue;
  4541. if (track->mdat_buf)
  4542. mdat_size += avio_tell(track->mdat_buf);
  4543. if (first_track < 0)
  4544. first_track = i;
  4545. }
  4546. if (!mdat_size)
  4547. return 0;
  4548. avio_write_marker(s->pb,
  4549. av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
  4550. (has_video ? starts_with_key : mov->tracks[first_track].cluster[0].flags & MOV_SYNC_SAMPLE) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT);
  4551. for (i = 0; i < mov->nb_streams; i++) {
  4552. MOVTrack *track = &mov->tracks[i];
  4553. int buf_size, write_moof = 1, moof_tracks = -1;
  4554. uint8_t *buf;
  4555. int64_t duration = 0;
  4556. if (track->entry)
  4557. duration = track->start_dts + track->track_duration -
  4558. track->cluster[0].dts;
  4559. if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
  4560. if (!track->mdat_buf)
  4561. continue;
  4562. mdat_size = avio_tell(track->mdat_buf);
  4563. moof_tracks = i;
  4564. } else {
  4565. write_moof = i == first_track;
  4566. }
  4567. if (write_moof) {
  4568. avio_flush(s->pb);
  4569. mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
  4570. mov->fragments++;
  4571. avio_wb32(s->pb, mdat_size + 8);
  4572. ffio_wfourcc(s->pb, "mdat");
  4573. }
  4574. if (track->entry)
  4575. track->frag_start += duration;
  4576. track->entry = 0;
  4577. track->entries_flushed = 0;
  4578. track->end_reliable = 0;
  4579. if (!mov->frag_interleave) {
  4580. if (!track->mdat_buf)
  4581. continue;
  4582. buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
  4583. track->mdat_buf = NULL;
  4584. } else {
  4585. if (!mov->mdat_buf)
  4586. continue;
  4587. buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
  4588. mov->mdat_buf = NULL;
  4589. }
  4590. avio_write(s->pb, buf, buf_size);
  4591. av_free(buf);
  4592. }
  4593. mov->mdat_size = 0;
  4594. avio_flush(s->pb);
  4595. return 0;
  4596. }
  4597. static int mov_auto_flush_fragment(AVFormatContext *s, int force)
  4598. {
  4599. MOVMuxContext *mov = s->priv_data;
  4600. int had_moov = mov->moov_written;
  4601. int ret = mov_flush_fragment(s, force);
  4602. if (ret < 0)
  4603. return ret;
  4604. // If using delay_moov, the first flush only wrote the moov,
  4605. // not the actual moof+mdat pair, thus flush once again.
  4606. if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
  4607. ret = mov_flush_fragment(s, force);
  4608. return ret;
  4609. }
  4610. static int check_pkt(AVFormatContext *s, AVPacket *pkt)
  4611. {
  4612. MOVMuxContext *mov = s->priv_data;
  4613. MOVTrack *trk = &mov->tracks[pkt->stream_index];
  4614. int64_t ref;
  4615. uint64_t duration;
  4616. if (trk->entry) {
  4617. ref = trk->cluster[trk->entry - 1].dts;
  4618. } else if ( trk->start_dts != AV_NOPTS_VALUE
  4619. && !trk->frag_discont) {
  4620. ref = trk->start_dts + trk->track_duration;
  4621. } else
  4622. ref = pkt->dts; // Skip tests for the first packet
  4623. if (trk->dts_shift != AV_NOPTS_VALUE) {
  4624. /* With negative CTS offsets we have set an offset to the DTS,
  4625. * reverse this for the check. */
  4626. ref -= trk->dts_shift;
  4627. }
  4628. duration = pkt->dts - ref;
  4629. if (pkt->dts < ref || duration >= INT_MAX) {
  4630. av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
  4631. duration, pkt->dts
  4632. );
  4633. pkt->dts = ref + 1;
  4634. pkt->pts = AV_NOPTS_VALUE;
  4635. }
  4636. if (pkt->duration < 0 || pkt->duration > INT_MAX) {
  4637. av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
  4638. return AVERROR(EINVAL);
  4639. }
  4640. return 0;
  4641. }
  4642. int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
  4643. {
  4644. MOVMuxContext *mov = s->priv_data;
  4645. AVIOContext *pb = s->pb;
  4646. MOVTrack *trk = &mov->tracks[pkt->stream_index];
  4647. AVCodecParameters *par = trk->par;
  4648. unsigned int samples_in_chunk = 0;
  4649. int size = pkt->size, ret = 0;
  4650. uint8_t *reformatted_data = NULL;
  4651. ret = check_pkt(s, pkt);
  4652. if (ret < 0)
  4653. return ret;
  4654. if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
  4655. int ret;
  4656. if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
  4657. if (mov->frag_interleave && mov->fragments > 0) {
  4658. if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
  4659. if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
  4660. return ret;
  4661. }
  4662. }
  4663. if (!trk->mdat_buf) {
  4664. if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
  4665. return ret;
  4666. }
  4667. pb = trk->mdat_buf;
  4668. } else {
  4669. if (!mov->mdat_buf) {
  4670. if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
  4671. return ret;
  4672. }
  4673. pb = mov->mdat_buf;
  4674. }
  4675. }
  4676. if (par->codec_id == AV_CODEC_ID_AMR_NB) {
  4677. /* We must find out how many AMR blocks there are in one packet */
  4678. static const uint16_t packed_size[16] =
  4679. {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
  4680. int len = 0;
  4681. while (len < size && samples_in_chunk < 100) {
  4682. len += packed_size[(pkt->data[len] >> 3) & 0x0F];
  4683. samples_in_chunk++;
  4684. }
  4685. if (samples_in_chunk > 1) {
  4686. av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
  4687. return -1;
  4688. }
  4689. } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
  4690. par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
  4691. samples_in_chunk = trk->par->frame_size;
  4692. } else if (trk->sample_size)
  4693. samples_in_chunk = size / trk->sample_size;
  4694. else
  4695. samples_in_chunk = 1;
  4696. /* copy extradata if it exists */
  4697. if (trk->vos_len == 0 && par->extradata_size > 0 &&
  4698. !TAG_IS_AVCI(trk->tag) &&
  4699. (par->codec_id != AV_CODEC_ID_DNXHD)) {
  4700. trk->vos_len = par->extradata_size;
  4701. trk->vos_data = av_malloc(trk->vos_len);
  4702. if (!trk->vos_data) {
  4703. ret = AVERROR(ENOMEM);
  4704. goto err;
  4705. }
  4706. memcpy(trk->vos_data, par->extradata, trk->vos_len);
  4707. }
  4708. if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
  4709. (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
  4710. if (!s->streams[pkt->stream_index]->nb_frames) {
  4711. av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
  4712. "use the audio bitstream filter 'aac_adtstoasc' to fix it "
  4713. "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
  4714. return -1;
  4715. }
  4716. av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
  4717. }
  4718. if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
  4719. /* from x264 or from bytestream H.264 */
  4720. /* NAL reformatting needed */
  4721. if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
  4722. ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
  4723. &size);
  4724. avio_write(pb, reformatted_data, size);
  4725. } else {
  4726. if (trk->cenc.aes_ctr) {
  4727. size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
  4728. if (size < 0) {
  4729. ret = size;
  4730. goto err;
  4731. }
  4732. } else {
  4733. size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
  4734. }
  4735. }
  4736. } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
  4737. (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
  4738. /* extradata is Annex B, assume the bitstream is too and convert it */
  4739. if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
  4740. ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
  4741. avio_write(pb, reformatted_data, size);
  4742. } else {
  4743. size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
  4744. }
  4745. #if CONFIG_AC3_PARSER
  4746. } else if (par->codec_id == AV_CODEC_ID_EAC3) {
  4747. size = handle_eac3(mov, pkt, trk);
  4748. if (size < 0)
  4749. return size;
  4750. else if (!size)
  4751. goto end;
  4752. avio_write(pb, pkt->data, size);
  4753. #endif
  4754. } else {
  4755. if (trk->cenc.aes_ctr) {
  4756. if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
  4757. int nal_size_length = (par->extradata[4] & 0x3) + 1;
  4758. ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
  4759. } else {
  4760. ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
  4761. }
  4762. if (ret) {
  4763. goto err;
  4764. }
  4765. } else {
  4766. avio_write(pb, pkt->data, size);
  4767. }
  4768. }
  4769. if ((par->codec_id == AV_CODEC_ID_DNXHD ||
  4770. par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
  4771. /* copy frame to create needed atoms */
  4772. trk->vos_len = size;
  4773. trk->vos_data = av_malloc(size);
  4774. if (!trk->vos_data) {
  4775. ret = AVERROR(ENOMEM);
  4776. goto err;
  4777. }
  4778. memcpy(trk->vos_data, pkt->data, size);
  4779. }
  4780. if (trk->entry >= trk->cluster_capacity) {
  4781. unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
  4782. if (av_reallocp_array(&trk->cluster, new_capacity,
  4783. sizeof(*trk->cluster))) {
  4784. ret = AVERROR(ENOMEM);
  4785. goto err;
  4786. }
  4787. trk->cluster_capacity = new_capacity;
  4788. }
  4789. trk->cluster[trk->entry].pos = avio_tell(pb) - size;
  4790. trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
  4791. trk->cluster[trk->entry].chunkNum = 0;
  4792. trk->cluster[trk->entry].size = size;
  4793. trk->cluster[trk->entry].entries = samples_in_chunk;
  4794. trk->cluster[trk->entry].dts = pkt->dts;
  4795. trk->cluster[trk->entry].pts = pkt->pts;
  4796. if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
  4797. if (!trk->frag_discont) {
  4798. /* First packet of a new fragment. We already wrote the duration
  4799. * of the last packet of the previous fragment based on track_duration,
  4800. * which might not exactly match our dts. Therefore adjust the dts
  4801. * of this packet to be what the previous packets duration implies. */
  4802. trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
  4803. /* We also may have written the pts and the corresponding duration
  4804. * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
  4805. * the next fragment. This means the cts of the first sample must
  4806. * be the same in all fragments, unless end_pts was updated by
  4807. * the packet causing the fragment to be written. */
  4808. if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
  4809. mov->mode == MODE_ISM)
  4810. pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
  4811. } else {
  4812. /* New fragment, but discontinuous from previous fragments.
  4813. * Pretend the duration sum of the earlier fragments is
  4814. * pkt->dts - trk->start_dts. */
  4815. trk->frag_start = pkt->dts - trk->start_dts;
  4816. trk->end_pts = AV_NOPTS_VALUE;
  4817. trk->frag_discont = 0;
  4818. }
  4819. }
  4820. if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
  4821. s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
  4822. /* Not using edit lists and shifting the first track to start from zero.
  4823. * If the other streams start from a later timestamp, we won't be able
  4824. * to signal the difference in starting time without an edit list.
  4825. * Thus move the timestamp for this first sample to 0, increasing
  4826. * its duration instead. */
  4827. trk->cluster[trk->entry].dts = trk->start_dts = 0;
  4828. }
  4829. if (trk->start_dts == AV_NOPTS_VALUE) {
  4830. trk->start_dts = pkt->dts;
  4831. if (trk->frag_discont) {
  4832. if (mov->use_editlist) {
  4833. /* Pretend the whole stream started at pts=0, with earlier fragments
  4834. * already written. If the stream started at pts=0, the duration sum
  4835. * of earlier fragments would have been pkt->pts. */
  4836. trk->frag_start = pkt->pts;
  4837. trk->start_dts = pkt->dts - pkt->pts;
  4838. } else {
  4839. /* Pretend the whole stream started at dts=0, with earlier fragments
  4840. * already written, with a duration summing up to pkt->dts. */
  4841. trk->frag_start = pkt->dts;
  4842. trk->start_dts = 0;
  4843. }
  4844. trk->frag_discont = 0;
  4845. } else if (pkt->dts && mov->moov_written)
  4846. av_log(s, AV_LOG_WARNING,
  4847. "Track %d starts with a nonzero dts %"PRId64", while the moov "
  4848. "already has been written. Set the delay_moov flag to handle "
  4849. "this case.\n",
  4850. pkt->stream_index, pkt->dts);
  4851. }
  4852. trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
  4853. trk->last_sample_is_subtitle_end = 0;
  4854. if (pkt->pts == AV_NOPTS_VALUE) {
  4855. av_log(s, AV_LOG_WARNING, "pts has no value\n");
  4856. pkt->pts = pkt->dts;
  4857. }
  4858. if (pkt->dts != pkt->pts)
  4859. trk->flags |= MOV_TRACK_CTTS;
  4860. trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
  4861. trk->cluster[trk->entry].flags = 0;
  4862. if (trk->start_cts == AV_NOPTS_VALUE)
  4863. trk->start_cts = pkt->pts - pkt->dts;
  4864. if (trk->end_pts == AV_NOPTS_VALUE)
  4865. trk->end_pts = trk->cluster[trk->entry].dts +
  4866. trk->cluster[trk->entry].cts + pkt->duration;
  4867. else
  4868. trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
  4869. trk->cluster[trk->entry].cts +
  4870. pkt->duration);
  4871. if (par->codec_id == AV_CODEC_ID_VC1) {
  4872. mov_parse_vc1_frame(pkt, trk);
  4873. } else if (pkt->flags & AV_PKT_FLAG_KEY) {
  4874. if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
  4875. trk->entry > 0) { // force sync sample for the first key frame
  4876. mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
  4877. if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
  4878. trk->flags |= MOV_TRACK_STPS;
  4879. } else {
  4880. trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
  4881. }
  4882. if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
  4883. trk->has_keyframes++;
  4884. }
  4885. if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) {
  4886. trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE;
  4887. trk->has_disposable++;
  4888. }
  4889. trk->entry++;
  4890. trk->sample_count += samples_in_chunk;
  4891. mov->mdat_size += size;
  4892. if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
  4893. ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
  4894. reformatted_data, size);
  4895. end:
  4896. err:
  4897. av_free(reformatted_data);
  4898. return ret;
  4899. }
  4900. static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
  4901. {
  4902. MOVMuxContext *mov = s->priv_data;
  4903. MOVTrack *trk = &mov->tracks[pkt->stream_index];
  4904. AVCodecParameters *par = trk->par;
  4905. int64_t frag_duration = 0;
  4906. int size = pkt->size;
  4907. int ret = check_pkt(s, pkt);
  4908. if (ret < 0)
  4909. return ret;
  4910. if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
  4911. int i;
  4912. for (i = 0; i < s->nb_streams; i++)
  4913. mov->tracks[i].frag_discont = 1;
  4914. mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
  4915. }
  4916. if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) {
  4917. if (trk->dts_shift == AV_NOPTS_VALUE)
  4918. trk->dts_shift = pkt->pts - pkt->dts;
  4919. pkt->dts += trk->dts_shift;
  4920. }
  4921. if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
  4922. trk->par->codec_id == AV_CODEC_ID_AAC ||
  4923. trk->par->codec_id == AV_CODEC_ID_FLAC) {
  4924. int side_size = 0;
  4925. uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
  4926. if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
  4927. void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
  4928. if (!newextra)
  4929. return AVERROR(ENOMEM);
  4930. av_free(par->extradata);
  4931. par->extradata = newextra;
  4932. memcpy(par->extradata, side, side_size);
  4933. par->extradata_size = side_size;
  4934. if (!pkt->size) // Flush packet
  4935. mov->need_rewrite_extradata = 1;
  4936. }
  4937. }
  4938. if (!pkt->size) {
  4939. if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
  4940. trk->start_dts = pkt->dts;
  4941. if (pkt->pts != AV_NOPTS_VALUE)
  4942. trk->start_cts = pkt->pts - pkt->dts;
  4943. else
  4944. trk->start_cts = 0;
  4945. }
  4946. return 0; /* Discard 0 sized packets */
  4947. }
  4948. if (trk->entry && pkt->stream_index < s->nb_streams)
  4949. frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
  4950. s->streams[pkt->stream_index]->time_base,
  4951. AV_TIME_BASE_Q);
  4952. if ((mov->max_fragment_duration &&
  4953. frag_duration >= mov->max_fragment_duration) ||
  4954. (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
  4955. (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
  4956. par->codec_type == AVMEDIA_TYPE_VIDEO &&
  4957. trk->entry && pkt->flags & AV_PKT_FLAG_KEY) ||
  4958. (mov->flags & FF_MOV_FLAG_FRAG_EVERY_FRAME)) {
  4959. if (frag_duration >= mov->min_fragment_duration) {
  4960. // Set the duration of this track to line up with the next
  4961. // sample in this track. This avoids relying on AVPacket
  4962. // duration, but only helps for this particular track, not
  4963. // for the other ones that are flushed at the same time.
  4964. trk->track_duration = pkt->dts - trk->start_dts;
  4965. if (pkt->pts != AV_NOPTS_VALUE)
  4966. trk->end_pts = pkt->pts;
  4967. else
  4968. trk->end_pts = pkt->dts;
  4969. trk->end_reliable = 1;
  4970. mov_auto_flush_fragment(s, 0);
  4971. }
  4972. }
  4973. return ff_mov_write_packet(s, pkt);
  4974. }
  4975. static int mov_write_subtitle_end_packet(AVFormatContext *s,
  4976. int stream_index,
  4977. int64_t dts) {
  4978. AVPacket end;
  4979. uint8_t data[2] = {0};
  4980. int ret;
  4981. av_init_packet(&end);
  4982. end.size = sizeof(data);
  4983. end.data = data;
  4984. end.pts = dts;
  4985. end.dts = dts;
  4986. end.duration = 0;
  4987. end.stream_index = stream_index;
  4988. ret = mov_write_single_packet(s, &end);
  4989. av_packet_unref(&end);
  4990. return ret;
  4991. }
  4992. static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
  4993. {
  4994. MOVMuxContext *mov = s->priv_data;
  4995. MOVTrack *trk;
  4996. if (!pkt) {
  4997. mov_flush_fragment(s, 1);
  4998. return 1;
  4999. }
  5000. trk = &mov->tracks[pkt->stream_index];
  5001. if (is_cover_image(trk->st)) {
  5002. int ret;
  5003. if (trk->st->nb_frames >= 1) {
  5004. if (trk->st->nb_frames == 1)
  5005. av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
  5006. " ignoring.\n", pkt->stream_index);
  5007. return 0;
  5008. }
  5009. if ((ret = av_packet_ref(&trk->cover_image, pkt)) < 0)
  5010. return ret;
  5011. return 0;
  5012. } else {
  5013. int i;
  5014. if (!pkt->size)
  5015. return mov_write_single_packet(s, pkt); /* Passthrough. */
  5016. /*
  5017. * Subtitles require special handling.
  5018. *
  5019. * 1) For full complaince, every track must have a sample at
  5020. * dts == 0, which is rarely true for subtitles. So, as soon
  5021. * as we see any packet with dts > 0, write an empty subtitle
  5022. * at dts == 0 for any subtitle track with no samples in it.
  5023. *
  5024. * 2) For each subtitle track, check if the current packet's
  5025. * dts is past the duration of the last subtitle sample. If
  5026. * so, we now need to write an end sample for that subtitle.
  5027. *
  5028. * This must be done conditionally to allow for subtitles that
  5029. * immediately replace each other, in which case an end sample
  5030. * is not needed, and is, in fact, actively harmful.
  5031. *
  5032. * 3) See mov_write_trailer for how the final end sample is
  5033. * handled.
  5034. */
  5035. for (i = 0; i < mov->nb_streams; i++) {
  5036. MOVTrack *trk = &mov->tracks[i];
  5037. int ret;
  5038. if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
  5039. trk->track_duration < pkt->dts &&
  5040. (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
  5041. ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
  5042. if (ret < 0) return ret;
  5043. trk->last_sample_is_subtitle_end = 1;
  5044. }
  5045. }
  5046. if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  5047. AVPacket *opkt = pkt;
  5048. int reshuffle_ret, ret;
  5049. if (trk->is_unaligned_qt_rgb) {
  5050. int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
  5051. int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
  5052. reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
  5053. if (reshuffle_ret < 0)
  5054. return reshuffle_ret;
  5055. } else
  5056. reshuffle_ret = 0;
  5057. if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
  5058. ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
  5059. if (ret < 0)
  5060. goto fail;
  5061. if (ret)
  5062. trk->pal_done++;
  5063. } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
  5064. (trk->par->format == AV_PIX_FMT_GRAY8 ||
  5065. trk->par->format == AV_PIX_FMT_MONOBLACK)) {
  5066. for (i = 0; i < pkt->size; i++)
  5067. pkt->data[i] = ~pkt->data[i];
  5068. }
  5069. if (reshuffle_ret) {
  5070. ret = mov_write_single_packet(s, pkt);
  5071. fail:
  5072. if (reshuffle_ret)
  5073. av_packet_free(&pkt);
  5074. return ret;
  5075. }
  5076. }
  5077. return mov_write_single_packet(s, pkt);
  5078. }
  5079. }
  5080. // QuickTime chapters involve an additional text track with the chapter names
  5081. // as samples, and a tref pointing from the other tracks to the chapter one.
  5082. static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
  5083. {
  5084. AVIOContext *pb;
  5085. MOVMuxContext *mov = s->priv_data;
  5086. MOVTrack *track = &mov->tracks[tracknum];
  5087. AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
  5088. int i, len;
  5089. track->mode = mov->mode;
  5090. track->tag = MKTAG('t','e','x','t');
  5091. track->timescale = MOV_TIMESCALE;
  5092. track->par = avcodec_parameters_alloc();
  5093. if (!track->par)
  5094. return AVERROR(ENOMEM);
  5095. track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
  5096. #if 0
  5097. // These properties are required to make QT recognize the chapter track
  5098. uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
  5099. if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
  5100. return AVERROR(ENOMEM);
  5101. memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
  5102. #else
  5103. if (avio_open_dyn_buf(&pb) >= 0) {
  5104. int size;
  5105. uint8_t *buf;
  5106. /* Stub header (usually for Quicktime chapter track) */
  5107. // TextSampleEntry
  5108. avio_wb32(pb, 0x01); // displayFlags
  5109. avio_w8(pb, 0x00); // horizontal justification
  5110. avio_w8(pb, 0x00); // vertical justification
  5111. avio_w8(pb, 0x00); // bgColourRed
  5112. avio_w8(pb, 0x00); // bgColourGreen
  5113. avio_w8(pb, 0x00); // bgColourBlue
  5114. avio_w8(pb, 0x00); // bgColourAlpha
  5115. // BoxRecord
  5116. avio_wb16(pb, 0x00); // defTextBoxTop
  5117. avio_wb16(pb, 0x00); // defTextBoxLeft
  5118. avio_wb16(pb, 0x00); // defTextBoxBottom
  5119. avio_wb16(pb, 0x00); // defTextBoxRight
  5120. // StyleRecord
  5121. avio_wb16(pb, 0x00); // startChar
  5122. avio_wb16(pb, 0x00); // endChar
  5123. avio_wb16(pb, 0x01); // fontID
  5124. avio_w8(pb, 0x00); // fontStyleFlags
  5125. avio_w8(pb, 0x00); // fontSize
  5126. avio_w8(pb, 0x00); // fgColourRed
  5127. avio_w8(pb, 0x00); // fgColourGreen
  5128. avio_w8(pb, 0x00); // fgColourBlue
  5129. avio_w8(pb, 0x00); // fgColourAlpha
  5130. // FontTableBox
  5131. avio_wb32(pb, 0x0D); // box size
  5132. ffio_wfourcc(pb, "ftab"); // box atom name
  5133. avio_wb16(pb, 0x01); // entry count
  5134. // FontRecord
  5135. avio_wb16(pb, 0x01); // font ID
  5136. avio_w8(pb, 0x00); // font name length
  5137. if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
  5138. track->par->extradata = buf;
  5139. track->par->extradata_size = size;
  5140. } else {
  5141. av_freep(&buf);
  5142. }
  5143. }
  5144. #endif
  5145. for (i = 0; i < s->nb_chapters; i++) {
  5146. AVChapter *c = s->chapters[i];
  5147. AVDictionaryEntry *t;
  5148. int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
  5149. pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
  5150. pkt.duration = end - pkt.dts;
  5151. if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
  5152. static const char encd[12] = {
  5153. 0x00, 0x00, 0x00, 0x0C,
  5154. 'e', 'n', 'c', 'd',
  5155. 0x00, 0x00, 0x01, 0x00 };
  5156. len = strlen(t->value);
  5157. pkt.size = len + 2 + 12;
  5158. pkt.data = av_malloc(pkt.size);
  5159. if (!pkt.data)
  5160. return AVERROR(ENOMEM);
  5161. AV_WB16(pkt.data, len);
  5162. memcpy(pkt.data + 2, t->value, len);
  5163. memcpy(pkt.data + len + 2, encd, sizeof(encd));
  5164. ff_mov_write_packet(s, &pkt);
  5165. av_freep(&pkt.data);
  5166. }
  5167. }
  5168. return 0;
  5169. }
  5170. static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
  5171. {
  5172. int ret;
  5173. /* compute the frame number */
  5174. ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
  5175. return ret;
  5176. }
  5177. static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
  5178. {
  5179. int ret;
  5180. MOVMuxContext *mov = s->priv_data;
  5181. MOVTrack *track = &mov->tracks[index];
  5182. AVStream *src_st = s->streams[src_index];
  5183. AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
  5184. AVRational rate = find_fps(s, src_st);
  5185. /* tmcd track based on video stream */
  5186. track->mode = mov->mode;
  5187. track->tag = MKTAG('t','m','c','d');
  5188. track->src_track = src_index;
  5189. track->timescale = mov->tracks[src_index].timescale;
  5190. if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
  5191. track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
  5192. /* set st to src_st for metadata access*/
  5193. track->st = src_st;
  5194. /* encode context: tmcd data stream */
  5195. track->par = avcodec_parameters_alloc();
  5196. if (!track->par)
  5197. return AVERROR(ENOMEM);
  5198. track->par->codec_type = AVMEDIA_TYPE_DATA;
  5199. track->par->codec_tag = track->tag;
  5200. track->st->avg_frame_rate = av_inv_q(rate);
  5201. /* the tmcd track just contains one packet with the frame number */
  5202. pkt.data = av_malloc(pkt.size);
  5203. if (!pkt.data)
  5204. return AVERROR(ENOMEM);
  5205. AV_WB32(pkt.data, tc.start);
  5206. ret = ff_mov_write_packet(s, &pkt);
  5207. av_free(pkt.data);
  5208. return ret;
  5209. }
  5210. /*
  5211. * st->disposition controls the "enabled" flag in the tkhd tag.
  5212. * QuickTime will not play a track if it is not enabled. So make sure
  5213. * that one track of each type (audio, video, subtitle) is enabled.
  5214. *
  5215. * Subtitles are special. For audio and video, setting "enabled" also
  5216. * makes the track "default" (i.e. it is rendered when played). For
  5217. * subtitles, an "enabled" subtitle is not rendered by default, but
  5218. * if no subtitle is enabled, the subtitle menu in QuickTime will be
  5219. * empty!
  5220. */
  5221. static void enable_tracks(AVFormatContext *s)
  5222. {
  5223. MOVMuxContext *mov = s->priv_data;
  5224. int i;
  5225. int enabled[AVMEDIA_TYPE_NB];
  5226. int first[AVMEDIA_TYPE_NB];
  5227. for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
  5228. enabled[i] = 0;
  5229. first[i] = -1;
  5230. }
  5231. for (i = 0; i < s->nb_streams; i++) {
  5232. AVStream *st = s->streams[i];
  5233. if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
  5234. st->codecpar->codec_type >= AVMEDIA_TYPE_NB ||
  5235. is_cover_image(st))
  5236. continue;
  5237. if (first[st->codecpar->codec_type] < 0)
  5238. first[st->codecpar->codec_type] = i;
  5239. if (st->disposition & AV_DISPOSITION_DEFAULT) {
  5240. mov->tracks[i].flags |= MOV_TRACK_ENABLED;
  5241. enabled[st->codecpar->codec_type]++;
  5242. }
  5243. }
  5244. for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
  5245. switch (i) {
  5246. case AVMEDIA_TYPE_VIDEO:
  5247. case AVMEDIA_TYPE_AUDIO:
  5248. case AVMEDIA_TYPE_SUBTITLE:
  5249. if (enabled[i] > 1)
  5250. mov->per_stream_grouping = 1;
  5251. if (!enabled[i] && first[i] >= 0)
  5252. mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
  5253. break;
  5254. }
  5255. }
  5256. }
  5257. static void mov_free(AVFormatContext *s)
  5258. {
  5259. MOVMuxContext *mov = s->priv_data;
  5260. int i;
  5261. if (mov->chapter_track) {
  5262. if (mov->tracks[mov->chapter_track].par)
  5263. av_freep(&mov->tracks[mov->chapter_track].par->extradata);
  5264. av_freep(&mov->tracks[mov->chapter_track].par);
  5265. }
  5266. for (i = 0; i < mov->nb_streams; i++) {
  5267. if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
  5268. ff_mov_close_hinting(&mov->tracks[i]);
  5269. else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
  5270. av_freep(&mov->tracks[i].par);
  5271. av_freep(&mov->tracks[i].cluster);
  5272. av_freep(&mov->tracks[i].frag_info);
  5273. av_packet_unref(&mov->tracks[i].cover_image);
  5274. if (mov->tracks[i].vos_len)
  5275. av_freep(&mov->tracks[i].vos_data);
  5276. ff_mov_cenc_free(&mov->tracks[i].cenc);
  5277. }
  5278. av_freep(&mov->tracks);
  5279. }
  5280. static uint32_t rgb_to_yuv(uint32_t rgb)
  5281. {
  5282. uint8_t r, g, b;
  5283. int y, cb, cr;
  5284. r = (rgb >> 16) & 0xFF;
  5285. g = (rgb >> 8) & 0xFF;
  5286. b = (rgb ) & 0xFF;
  5287. y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
  5288. cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
  5289. cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
  5290. return (y << 16) | (cr << 8) | cb;
  5291. }
  5292. static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
  5293. AVStream *st)
  5294. {
  5295. int i, width = 720, height = 480;
  5296. int have_palette = 0, have_size = 0;
  5297. uint32_t palette[16];
  5298. char *cur = st->codecpar->extradata;
  5299. while (cur && *cur) {
  5300. if (strncmp("palette:", cur, 8) == 0) {
  5301. int i, count;
  5302. count = sscanf(cur + 8,
  5303. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
  5304. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
  5305. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
  5306. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
  5307. &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
  5308. &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
  5309. &palette[ 8], &palette[ 9], &palette[10], &palette[11],
  5310. &palette[12], &palette[13], &palette[14], &palette[15]);
  5311. for (i = 0; i < count; i++) {
  5312. palette[i] = rgb_to_yuv(palette[i]);
  5313. }
  5314. have_palette = 1;
  5315. } else if (!strncmp("size:", cur, 5)) {
  5316. sscanf(cur + 5, "%dx%d", &width, &height);
  5317. have_size = 1;
  5318. }
  5319. if (have_palette && have_size)
  5320. break;
  5321. cur += strcspn(cur, "\n\r");
  5322. cur += strspn(cur, "\n\r");
  5323. }
  5324. if (have_palette) {
  5325. track->vos_data = av_malloc(16*4);
  5326. if (!track->vos_data)
  5327. return AVERROR(ENOMEM);
  5328. for (i = 0; i < 16; i++) {
  5329. AV_WB32(track->vos_data + i * 4, palette[i]);
  5330. }
  5331. track->vos_len = 16 * 4;
  5332. }
  5333. st->codecpar->width = width;
  5334. st->codecpar->height = track->height = height;
  5335. return 0;
  5336. }
  5337. static int mov_init(AVFormatContext *s)
  5338. {
  5339. MOVMuxContext *mov = s->priv_data;
  5340. AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
  5341. int i, ret;
  5342. mov->fc = s;
  5343. /* Default mode == MP4 */
  5344. mov->mode = MODE_MP4;
  5345. if (s->oformat) {
  5346. if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
  5347. else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
  5348. else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
  5349. else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
  5350. else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
  5351. else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
  5352. else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
  5353. }
  5354. if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
  5355. mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
  5356. /* Set the FRAGMENT flag if any of the fragmentation methods are
  5357. * enabled. */
  5358. if (mov->max_fragment_duration || mov->max_fragment_size ||
  5359. mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
  5360. FF_MOV_FLAG_FRAG_KEYFRAME |
  5361. FF_MOV_FLAG_FRAG_CUSTOM |
  5362. FF_MOV_FLAG_FRAG_EVERY_FRAME))
  5363. mov->flags |= FF_MOV_FLAG_FRAGMENT;
  5364. /* Set other implicit flags immediately */
  5365. if (mov->mode == MODE_ISM)
  5366. mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
  5367. FF_MOV_FLAG_FRAGMENT;
  5368. if (mov->flags & FF_MOV_FLAG_DASH)
  5369. mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
  5370. FF_MOV_FLAG_DEFAULT_BASE_MOOF;
  5371. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
  5372. av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
  5373. s->flags &= ~AVFMT_FLAG_AUTO_BSF;
  5374. }
  5375. if (mov->flags & FF_MOV_FLAG_FASTSTART) {
  5376. mov->reserved_moov_size = -1;
  5377. }
  5378. if (mov->use_editlist < 0) {
  5379. mov->use_editlist = 1;
  5380. if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
  5381. !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
  5382. // If we can avoid needing an edit list by shifting the
  5383. // tracks, prefer that over (trying to) write edit lists
  5384. // in fragmented output.
  5385. if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
  5386. s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
  5387. mov->use_editlist = 0;
  5388. }
  5389. }
  5390. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
  5391. !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
  5392. av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
  5393. if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
  5394. s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
  5395. /* Clear the omit_tfhd_offset flag if default_base_moof is set;
  5396. * if the latter is set that's enough and omit_tfhd_offset doesn't
  5397. * add anything extra on top of that. */
  5398. if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
  5399. mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
  5400. mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
  5401. if (mov->frag_interleave &&
  5402. mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
  5403. av_log(s, AV_LOG_ERROR,
  5404. "Sample interleaving in fragments is mutually exclusive with "
  5405. "omit_tfhd_offset and separate_moof\n");
  5406. return AVERROR(EINVAL);
  5407. }
  5408. /* Non-seekable output is ok if using fragmentation. If ism_lookahead
  5409. * is enabled, we don't support non-seekable output at all. */
  5410. if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
  5411. (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
  5412. av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
  5413. return AVERROR(EINVAL);
  5414. }
  5415. mov->nb_streams = s->nb_streams;
  5416. if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
  5417. mov->chapter_track = mov->nb_streams++;
  5418. if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
  5419. for (i = 0; i < s->nb_streams; i++)
  5420. if (rtp_hinting_needed(s->streams[i]))
  5421. mov->nb_streams++;
  5422. }
  5423. if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
  5424. || mov->write_tmcd == 1) {
  5425. /* +1 tmcd track for each video stream with a timecode */
  5426. for (i = 0; i < s->nb_streams; i++) {
  5427. AVStream *st = s->streams[i];
  5428. AVDictionaryEntry *t = global_tcr;
  5429. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
  5430. (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
  5431. AVTimecode tc;
  5432. ret = mov_check_timecode_track(s, &tc, i, t->value);
  5433. if (ret >= 0)
  5434. mov->nb_meta_tmcd++;
  5435. }
  5436. }
  5437. /* check if there is already a tmcd track to remux */
  5438. if (mov->nb_meta_tmcd) {
  5439. for (i = 0; i < s->nb_streams; i++) {
  5440. AVStream *st = s->streams[i];
  5441. if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
  5442. av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
  5443. "so timecode metadata are now ignored\n");
  5444. mov->nb_meta_tmcd = 0;
  5445. }
  5446. }
  5447. }
  5448. mov->nb_streams += mov->nb_meta_tmcd;
  5449. }
  5450. // Reserve an extra stream for chapters for the case where chapters
  5451. // are written in the trailer
  5452. mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
  5453. if (!mov->tracks)
  5454. return AVERROR(ENOMEM);
  5455. if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
  5456. if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
  5457. mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
  5458. if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
  5459. av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
  5460. mov->encryption_key_len, AES_CTR_KEY_SIZE);
  5461. return AVERROR(EINVAL);
  5462. }
  5463. if (mov->encryption_kid_len != CENC_KID_SIZE) {
  5464. av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
  5465. mov->encryption_kid_len, CENC_KID_SIZE);
  5466. return AVERROR(EINVAL);
  5467. }
  5468. } else {
  5469. av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
  5470. mov->encryption_scheme_str);
  5471. return AVERROR(EINVAL);
  5472. }
  5473. }
  5474. for (i = 0; i < s->nb_streams; i++) {
  5475. AVStream *st= s->streams[i];
  5476. MOVTrack *track= &mov->tracks[i];
  5477. AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
  5478. track->st = st;
  5479. track->par = st->codecpar;
  5480. track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
  5481. if (track->language < 0)
  5482. track->language = 0;
  5483. track->mode = mov->mode;
  5484. track->tag = mov_find_codec_tag(s, track);
  5485. if (!track->tag) {
  5486. av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
  5487. "codec not currently supported in container\n",
  5488. avcodec_get_name(st->codecpar->codec_id), i);
  5489. return AVERROR(EINVAL);
  5490. }
  5491. /* If hinting of this track is enabled by a later hint track,
  5492. * this is updated. */
  5493. track->hint_track = -1;
  5494. track->start_dts = AV_NOPTS_VALUE;
  5495. track->start_cts = AV_NOPTS_VALUE;
  5496. track->end_pts = AV_NOPTS_VALUE;
  5497. track->dts_shift = AV_NOPTS_VALUE;
  5498. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  5499. if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
  5500. track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
  5501. track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
  5502. if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
  5503. av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
  5504. return AVERROR(EINVAL);
  5505. }
  5506. track->height = track->tag >> 24 == 'n' ? 486 : 576;
  5507. }
  5508. if (mov->video_track_timescale) {
  5509. track->timescale = mov->video_track_timescale;
  5510. } else {
  5511. track->timescale = st->time_base.den;
  5512. while(track->timescale < 10000)
  5513. track->timescale *= 2;
  5514. }
  5515. if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
  5516. av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
  5517. return AVERROR(EINVAL);
  5518. }
  5519. if (track->mode == MODE_MOV && track->timescale > 100000)
  5520. av_log(s, AV_LOG_WARNING,
  5521. "WARNING codec timebase is very high. If duration is too long,\n"
  5522. "file may not be playable by quicktime. Specify a shorter timebase\n"
  5523. "or choose different container.\n");
  5524. if (track->mode == MODE_MOV &&
  5525. track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
  5526. track->tag == MKTAG('r','a','w',' ')) {
  5527. enum AVPixelFormat pix_fmt = track->par->format;
  5528. if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
  5529. pix_fmt = AV_PIX_FMT_MONOWHITE;
  5530. track->is_unaligned_qt_rgb =
  5531. pix_fmt == AV_PIX_FMT_RGB24 ||
  5532. pix_fmt == AV_PIX_FMT_BGR24 ||
  5533. pix_fmt == AV_PIX_FMT_PAL8 ||
  5534. pix_fmt == AV_PIX_FMT_GRAY8 ||
  5535. pix_fmt == AV_PIX_FMT_MONOWHITE ||
  5536. pix_fmt == AV_PIX_FMT_MONOBLACK;
  5537. }
  5538. if (track->par->codec_id == AV_CODEC_ID_VP9) {
  5539. if (track->mode != MODE_MP4) {
  5540. av_log(s, AV_LOG_ERROR, "VP9 only supported in MP4.\n");
  5541. return AVERROR(EINVAL);
  5542. }
  5543. } else if (track->par->codec_id == AV_CODEC_ID_AV1) {
  5544. /* spec is not finished, so forbid for now */
  5545. av_log(s, AV_LOG_ERROR, "AV1 muxing is currently not supported.\n");
  5546. return AVERROR_PATCHWELCOME;
  5547. } else if (track->par->codec_id == AV_CODEC_ID_VP8) {
  5548. /* altref frames handling is not defined in the spec as of version v1.0,
  5549. * so just forbid muxing VP8 streams altogether until a new version does */
  5550. av_log(s, AV_LOG_ERROR, "VP8 muxing is currently not supported.\n");
  5551. return AVERROR_PATCHWELCOME;
  5552. }
  5553. } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  5554. track->timescale = st->codecpar->sample_rate;
  5555. if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
  5556. av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
  5557. track->audio_vbr = 1;
  5558. }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
  5559. st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
  5560. st->codecpar->codec_id == AV_CODEC_ID_ILBC){
  5561. if (!st->codecpar->block_align) {
  5562. av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
  5563. return AVERROR(EINVAL);
  5564. }
  5565. track->sample_size = st->codecpar->block_align;
  5566. }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
  5567. track->audio_vbr = 1;
  5568. }else{
  5569. track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
  5570. }
  5571. if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
  5572. st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
  5573. track->audio_vbr = 1;
  5574. }
  5575. if (track->mode != MODE_MOV &&
  5576. track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
  5577. if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
  5578. av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
  5579. i, track->par->sample_rate);
  5580. return AVERROR(EINVAL);
  5581. } else {
  5582. av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
  5583. i, track->par->sample_rate);
  5584. }
  5585. }
  5586. if (track->par->codec_id == AV_CODEC_ID_FLAC ||
  5587. track->par->codec_id == AV_CODEC_ID_OPUS) {
  5588. if (track->mode != MODE_MP4) {
  5589. av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
  5590. return AVERROR(EINVAL);
  5591. }
  5592. if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
  5593. av_log(s, AV_LOG_ERROR,
  5594. "%s in MP4 support is experimental, add "
  5595. "'-strict %d' if you want to use it.\n",
  5596. avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL);
  5597. return AVERROR_EXPERIMENTAL;
  5598. }
  5599. }
  5600. } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  5601. track->timescale = st->time_base.den;
  5602. } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
  5603. track->timescale = st->time_base.den;
  5604. } else {
  5605. track->timescale = MOV_TIMESCALE;
  5606. }
  5607. if (!track->height)
  5608. track->height = st->codecpar->height;
  5609. /* The ism specific timescale isn't mandatory, but is assumed by
  5610. * some tools, such as mp4split. */
  5611. if (mov->mode == MODE_ISM)
  5612. track->timescale = 10000000;
  5613. avpriv_set_pts_info(st, 64, 1, track->timescale);
  5614. if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
  5615. ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
  5616. track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
  5617. if (ret)
  5618. return ret;
  5619. }
  5620. }
  5621. enable_tracks(s);
  5622. return 0;
  5623. }
  5624. static int mov_write_header(AVFormatContext *s)
  5625. {
  5626. AVIOContext *pb = s->pb;
  5627. MOVMuxContext *mov = s->priv_data;
  5628. AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
  5629. int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
  5630. if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
  5631. nb_tracks++;
  5632. if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
  5633. hint_track = nb_tracks;
  5634. for (i = 0; i < s->nb_streams; i++)
  5635. if (rtp_hinting_needed(s->streams[i]))
  5636. nb_tracks++;
  5637. }
  5638. if (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
  5639. tmcd_track = nb_tracks;
  5640. for (i = 0; i < s->nb_streams; i++) {
  5641. int j;
  5642. AVStream *st= s->streams[i];
  5643. MOVTrack *track= &mov->tracks[i];
  5644. /* copy extradata if it exists */
  5645. if (st->codecpar->extradata_size) {
  5646. if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
  5647. mov_create_dvd_sub_decoder_specific_info(track, st);
  5648. else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
  5649. track->vos_len = st->codecpar->extradata_size;
  5650. track->vos_data = av_malloc(track->vos_len);
  5651. if (!track->vos_data) {
  5652. return AVERROR(ENOMEM);
  5653. }
  5654. memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
  5655. }
  5656. }
  5657. if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
  5658. track->par->channel_layout != AV_CH_LAYOUT_MONO)
  5659. continue;
  5660. for (j = 0; j < s->nb_streams; j++) {
  5661. AVStream *stj= s->streams[j];
  5662. MOVTrack *trackj= &mov->tracks[j];
  5663. if (j == i)
  5664. continue;
  5665. if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
  5666. trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
  5667. trackj->language != track->language ||
  5668. trackj->tag != track->tag
  5669. )
  5670. continue;
  5671. track->multichannel_as_mono++;
  5672. }
  5673. }
  5674. if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
  5675. if ((ret = mov_write_identification(pb, s)) < 0)
  5676. return ret;
  5677. }
  5678. if (mov->reserved_moov_size){
  5679. mov->reserved_header_pos = avio_tell(pb);
  5680. if (mov->reserved_moov_size > 0)
  5681. avio_skip(pb, mov->reserved_moov_size);
  5682. }
  5683. if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
  5684. /* If no fragmentation options have been set, set a default. */
  5685. if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
  5686. FF_MOV_FLAG_FRAG_CUSTOM |
  5687. FF_MOV_FLAG_FRAG_EVERY_FRAME)) &&
  5688. !mov->max_fragment_duration && !mov->max_fragment_size)
  5689. mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
  5690. } else {
  5691. if (mov->flags & FF_MOV_FLAG_FASTSTART)
  5692. mov->reserved_header_pos = avio_tell(pb);
  5693. mov_write_mdat_tag(pb, mov);
  5694. }
  5695. ff_parse_creation_time_metadata(s, &mov->time, 1);
  5696. if (mov->time)
  5697. mov->time += 0x7C25B080; // 1970 based -> 1904 based
  5698. if (mov->chapter_track)
  5699. if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
  5700. return ret;
  5701. if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
  5702. for (i = 0; i < s->nb_streams; i++) {
  5703. if (rtp_hinting_needed(s->streams[i])) {
  5704. if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
  5705. return ret;
  5706. hint_track++;
  5707. }
  5708. }
  5709. }
  5710. if (mov->nb_meta_tmcd) {
  5711. /* Initialize the tmcd tracks */
  5712. for (i = 0; i < s->nb_streams; i++) {
  5713. AVStream *st = s->streams[i];
  5714. t = global_tcr;
  5715. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  5716. AVTimecode tc;
  5717. if (!t)
  5718. t = av_dict_get(st->metadata, "timecode", NULL, 0);
  5719. if (!t)
  5720. continue;
  5721. if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
  5722. continue;
  5723. if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
  5724. return ret;
  5725. tmcd_track++;
  5726. }
  5727. }
  5728. }
  5729. avio_flush(pb);
  5730. if (mov->flags & FF_MOV_FLAG_ISML)
  5731. mov_write_isml_manifest(pb, mov, s);
  5732. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
  5733. !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
  5734. if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
  5735. return ret;
  5736. avio_flush(pb);
  5737. mov->moov_written = 1;
  5738. if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
  5739. mov->reserved_header_pos = avio_tell(pb);
  5740. }
  5741. return 0;
  5742. }
  5743. static int get_moov_size(AVFormatContext *s)
  5744. {
  5745. int ret;
  5746. AVIOContext *moov_buf;
  5747. MOVMuxContext *mov = s->priv_data;
  5748. if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
  5749. return ret;
  5750. if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
  5751. return ret;
  5752. return ffio_close_null_buf(moov_buf);
  5753. }
  5754. static int get_sidx_size(AVFormatContext *s)
  5755. {
  5756. int ret;
  5757. AVIOContext *buf;
  5758. MOVMuxContext *mov = s->priv_data;
  5759. if ((ret = ffio_open_null_buf(&buf)) < 0)
  5760. return ret;
  5761. mov_write_sidx_tags(buf, mov, -1, 0);
  5762. return ffio_close_null_buf(buf);
  5763. }
  5764. /*
  5765. * This function gets the moov size if moved to the top of the file: the chunk
  5766. * offset table can switch between stco (32-bit entries) to co64 (64-bit
  5767. * entries) when the moov is moved to the beginning, so the size of the moov
  5768. * would change. It also updates the chunk offset tables.
  5769. */
  5770. static int compute_moov_size(AVFormatContext *s)
  5771. {
  5772. int i, moov_size, moov_size2;
  5773. MOVMuxContext *mov = s->priv_data;
  5774. moov_size = get_moov_size(s);
  5775. if (moov_size < 0)
  5776. return moov_size;
  5777. for (i = 0; i < mov->nb_streams; i++)
  5778. mov->tracks[i].data_offset += moov_size;
  5779. moov_size2 = get_moov_size(s);
  5780. if (moov_size2 < 0)
  5781. return moov_size2;
  5782. /* if the size changed, we just switched from stco to co64 and need to
  5783. * update the offsets */
  5784. if (moov_size2 != moov_size)
  5785. for (i = 0; i < mov->nb_streams; i++)
  5786. mov->tracks[i].data_offset += moov_size2 - moov_size;
  5787. return moov_size2;
  5788. }
  5789. static int compute_sidx_size(AVFormatContext *s)
  5790. {
  5791. int i, sidx_size;
  5792. MOVMuxContext *mov = s->priv_data;
  5793. sidx_size = get_sidx_size(s);
  5794. if (sidx_size < 0)
  5795. return sidx_size;
  5796. for (i = 0; i < mov->nb_streams; i++)
  5797. mov->tracks[i].data_offset += sidx_size;
  5798. return sidx_size;
  5799. }
  5800. static int shift_data(AVFormatContext *s)
  5801. {
  5802. int ret = 0, moov_size;
  5803. MOVMuxContext *mov = s->priv_data;
  5804. int64_t pos, pos_end = avio_tell(s->pb);
  5805. uint8_t *buf, *read_buf[2];
  5806. int read_buf_id = 0;
  5807. int read_size[2];
  5808. AVIOContext *read_pb;
  5809. if (mov->flags & FF_MOV_FLAG_FRAGMENT)
  5810. moov_size = compute_sidx_size(s);
  5811. else
  5812. moov_size = compute_moov_size(s);
  5813. if (moov_size < 0)
  5814. return moov_size;
  5815. buf = av_malloc(moov_size * 2);
  5816. if (!buf)
  5817. return AVERROR(ENOMEM);
  5818. read_buf[0] = buf;
  5819. read_buf[1] = buf + moov_size;
  5820. /* Shift the data: the AVIO context of the output can only be used for
  5821. * writing, so we re-open the same output, but for reading. It also avoids
  5822. * a read/seek/write/seek back and forth. */
  5823. avio_flush(s->pb);
  5824. ret = s->io_open(s, &read_pb, s->url, AVIO_FLAG_READ, NULL);
  5825. if (ret < 0) {
  5826. av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
  5827. "the second pass (faststart)\n", s->url);
  5828. goto end;
  5829. }
  5830. /* mark the end of the shift to up to the last data we wrote, and get ready
  5831. * for writing */
  5832. pos_end = avio_tell(s->pb);
  5833. avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
  5834. /* start reading at where the new moov will be placed */
  5835. avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
  5836. pos = avio_tell(read_pb);
  5837. #define READ_BLOCK do { \
  5838. read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
  5839. read_buf_id ^= 1; \
  5840. } while (0)
  5841. /* shift data by chunk of at most moov_size */
  5842. READ_BLOCK;
  5843. do {
  5844. int n;
  5845. READ_BLOCK;
  5846. n = read_size[read_buf_id];
  5847. if (n <= 0)
  5848. break;
  5849. avio_write(s->pb, read_buf[read_buf_id], n);
  5850. pos += n;
  5851. } while (pos < pos_end);
  5852. ff_format_io_close(s, &read_pb);
  5853. end:
  5854. av_free(buf);
  5855. return ret;
  5856. }
  5857. static int mov_write_trailer(AVFormatContext *s)
  5858. {
  5859. MOVMuxContext *mov = s->priv_data;
  5860. AVIOContext *pb = s->pb;
  5861. int res = 0;
  5862. int i;
  5863. int64_t moov_pos;
  5864. if (mov->need_rewrite_extradata) {
  5865. for (i = 0; i < s->nb_streams; i++) {
  5866. MOVTrack *track = &mov->tracks[i];
  5867. AVCodecParameters *par = track->par;
  5868. track->vos_len = par->extradata_size;
  5869. track->vos_data = av_malloc(track->vos_len);
  5870. if (!track->vos_data)
  5871. return AVERROR(ENOMEM);
  5872. memcpy(track->vos_data, par->extradata, track->vos_len);
  5873. }
  5874. mov->need_rewrite_extradata = 0;
  5875. }
  5876. /*
  5877. * Before actually writing the trailer, make sure that there are no
  5878. * dangling subtitles, that need a terminating sample.
  5879. */
  5880. for (i = 0; i < mov->nb_streams; i++) {
  5881. MOVTrack *trk = &mov->tracks[i];
  5882. if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
  5883. !trk->last_sample_is_subtitle_end) {
  5884. mov_write_subtitle_end_packet(s, i, trk->track_duration);
  5885. trk->last_sample_is_subtitle_end = 1;
  5886. }
  5887. }
  5888. // If there were no chapters when the header was written, but there
  5889. // are chapters now, write them in the trailer. This only works
  5890. // when we are not doing fragments.
  5891. if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
  5892. if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
  5893. mov->chapter_track = mov->nb_streams++;
  5894. if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
  5895. return res;
  5896. }
  5897. }
  5898. if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
  5899. moov_pos = avio_tell(pb);
  5900. /* Write size of mdat tag */
  5901. if (mov->mdat_size + 8 <= UINT32_MAX) {
  5902. avio_seek(pb, mov->mdat_pos, SEEK_SET);
  5903. avio_wb32(pb, mov->mdat_size + 8);
  5904. } else {
  5905. /* overwrite 'wide' placeholder atom */
  5906. avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
  5907. /* special value: real atom size will be 64 bit value after
  5908. * tag field */
  5909. avio_wb32(pb, 1);
  5910. ffio_wfourcc(pb, "mdat");
  5911. avio_wb64(pb, mov->mdat_size + 16);
  5912. }
  5913. avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
  5914. if (mov->flags & FF_MOV_FLAG_FASTSTART) {
  5915. av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
  5916. res = shift_data(s);
  5917. if (res < 0)
  5918. return res;
  5919. avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
  5920. if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
  5921. return res;
  5922. } else if (mov->reserved_moov_size > 0) {
  5923. int64_t size;
  5924. if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
  5925. return res;
  5926. size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
  5927. if (size < 8){
  5928. av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
  5929. return AVERROR(EINVAL);
  5930. }
  5931. avio_wb32(pb, size);
  5932. ffio_wfourcc(pb, "free");
  5933. ffio_fill(pb, 0, size - 8);
  5934. avio_seek(pb, moov_pos, SEEK_SET);
  5935. } else {
  5936. if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
  5937. return res;
  5938. }
  5939. res = 0;
  5940. } else {
  5941. mov_auto_flush_fragment(s, 1);
  5942. for (i = 0; i < mov->nb_streams; i++)
  5943. mov->tracks[i].data_offset = 0;
  5944. if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
  5945. int64_t end;
  5946. av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
  5947. res = shift_data(s);
  5948. if (res < 0)
  5949. return res;
  5950. end = avio_tell(pb);
  5951. avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
  5952. mov_write_sidx_tags(pb, mov, -1, 0);
  5953. avio_seek(pb, end, SEEK_SET);
  5954. avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
  5955. mov_write_mfra_tag(pb, mov);
  5956. } else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
  5957. avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
  5958. mov_write_mfra_tag(pb, mov);
  5959. }
  5960. }
  5961. return res;
  5962. }
  5963. static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
  5964. {
  5965. int ret = 1;
  5966. AVStream *st = s->streams[pkt->stream_index];
  5967. if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
  5968. if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
  5969. ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
  5970. } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
  5971. ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
  5972. }
  5973. return ret;
  5974. }
  5975. static const AVCodecTag codec_3gp_tags[] = {
  5976. { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
  5977. { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
  5978. { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
  5979. { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
  5980. { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
  5981. { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
  5982. { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
  5983. { AV_CODEC_ID_NONE, 0 },
  5984. };
  5985. const AVCodecTag codec_mp4_tags[] = {
  5986. { AV_CODEC_ID_MPEG4 , MKTAG('m', 'p', '4', 'v') },
  5987. { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '1') },
  5988. { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '3') },
  5989. { AV_CODEC_ID_HEVC , MKTAG('h', 'e', 'v', '1') },
  5990. { AV_CODEC_ID_HEVC , MKTAG('h', 'v', 'c', '1') },
  5991. { AV_CODEC_ID_MPEG2VIDEO , MKTAG('m', 'p', '4', 'v') },
  5992. { AV_CODEC_ID_MPEG1VIDEO , MKTAG('m', 'p', '4', 'v') },
  5993. { AV_CODEC_ID_MJPEG , MKTAG('m', 'p', '4', 'v') },
  5994. { AV_CODEC_ID_PNG , MKTAG('m', 'p', '4', 'v') },
  5995. { AV_CODEC_ID_JPEG2000 , MKTAG('m', 'p', '4', 'v') },
  5996. { AV_CODEC_ID_VC1 , MKTAG('v', 'c', '-', '1') },
  5997. { AV_CODEC_ID_DIRAC , MKTAG('d', 'r', 'a', 'c') },
  5998. { AV_CODEC_ID_TSCC2 , MKTAG('m', 'p', '4', 'v') },
  5999. { AV_CODEC_ID_VP9 , MKTAG('v', 'p', '0', '9') },
  6000. { AV_CODEC_ID_AAC , MKTAG('m', 'p', '4', 'a') },
  6001. { AV_CODEC_ID_MP4ALS , MKTAG('m', 'p', '4', 'a') },
  6002. { AV_CODEC_ID_MP3 , MKTAG('m', 'p', '4', 'a') },
  6003. { AV_CODEC_ID_MP2 , MKTAG('m', 'p', '4', 'a') },
  6004. { AV_CODEC_ID_AC3 , MKTAG('a', 'c', '-', '3') },
  6005. { AV_CODEC_ID_EAC3 , MKTAG('e', 'c', '-', '3') },
  6006. { AV_CODEC_ID_DTS , MKTAG('m', 'p', '4', 'a') },
  6007. { AV_CODEC_ID_FLAC , MKTAG('f', 'L', 'a', 'C') },
  6008. { AV_CODEC_ID_OPUS , MKTAG('O', 'p', 'u', 's') },
  6009. { AV_CODEC_ID_VORBIS , MKTAG('m', 'p', '4', 'a') },
  6010. { AV_CODEC_ID_QCELP , MKTAG('m', 'p', '4', 'a') },
  6011. { AV_CODEC_ID_EVRC , MKTAG('m', 'p', '4', 'a') },
  6012. { AV_CODEC_ID_DVD_SUBTITLE, MKTAG('m', 'p', '4', 's') },
  6013. { AV_CODEC_ID_MOV_TEXT , MKTAG('t', 'x', '3', 'g') },
  6014. { AV_CODEC_ID_NONE , 0 },
  6015. };
  6016. const AVCodecTag codec_ism_tags[] = {
  6017. { AV_CODEC_ID_WMAPRO , MKTAG('w', 'm', 'a', ' ') },
  6018. { AV_CODEC_ID_NONE , 0 },
  6019. };
  6020. static const AVCodecTag codec_ipod_tags[] = {
  6021. { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
  6022. { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
  6023. { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
  6024. { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
  6025. { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
  6026. { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
  6027. { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
  6028. { AV_CODEC_ID_NONE, 0 },
  6029. };
  6030. static const AVCodecTag codec_f4v_tags[] = {
  6031. { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
  6032. { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
  6033. { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
  6034. { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
  6035. { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
  6036. { AV_CODEC_ID_NONE, 0 },
  6037. };
  6038. #if CONFIG_MOV_MUXER
  6039. MOV_CLASS(mov)
  6040. AVOutputFormat ff_mov_muxer = {
  6041. .name = "mov",
  6042. .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
  6043. .extensions = "mov",
  6044. .priv_data_size = sizeof(MOVMuxContext),
  6045. .audio_codec = AV_CODEC_ID_AAC,
  6046. .video_codec = CONFIG_LIBX264_ENCODER ?
  6047. AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
  6048. .init = mov_init,
  6049. .write_header = mov_write_header,
  6050. .write_packet = mov_write_packet,
  6051. .write_trailer = mov_write_trailer,
  6052. .deinit = mov_free,
  6053. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  6054. .codec_tag = (const AVCodecTag* const []){
  6055. ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
  6056. },
  6057. .check_bitstream = mov_check_bitstream,
  6058. .priv_class = &mov_muxer_class,
  6059. };
  6060. #endif
  6061. #if CONFIG_TGP_MUXER
  6062. MOV_CLASS(tgp)
  6063. AVOutputFormat ff_tgp_muxer = {
  6064. .name = "3gp",
  6065. .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
  6066. .extensions = "3gp",
  6067. .priv_data_size = sizeof(MOVMuxContext),
  6068. .audio_codec = AV_CODEC_ID_AMR_NB,
  6069. .video_codec = AV_CODEC_ID_H263,
  6070. .init = mov_init,
  6071. .write_header = mov_write_header,
  6072. .write_packet = mov_write_packet,
  6073. .write_trailer = mov_write_trailer,
  6074. .deinit = mov_free,
  6075. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  6076. .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
  6077. .check_bitstream = mov_check_bitstream,
  6078. .priv_class = &tgp_muxer_class,
  6079. };
  6080. #endif
  6081. #if CONFIG_MP4_MUXER
  6082. MOV_CLASS(mp4)
  6083. AVOutputFormat ff_mp4_muxer = {
  6084. .name = "mp4",
  6085. .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
  6086. .mime_type = "video/mp4",
  6087. .extensions = "mp4",
  6088. .priv_data_size = sizeof(MOVMuxContext),
  6089. .audio_codec = AV_CODEC_ID_AAC,
  6090. .video_codec = CONFIG_LIBX264_ENCODER ?
  6091. AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
  6092. .init = mov_init,
  6093. .write_header = mov_write_header,
  6094. .write_packet = mov_write_packet,
  6095. .write_trailer = mov_write_trailer,
  6096. .deinit = mov_free,
  6097. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  6098. .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
  6099. .check_bitstream = mov_check_bitstream,
  6100. .priv_class = &mp4_muxer_class,
  6101. };
  6102. #endif
  6103. #if CONFIG_PSP_MUXER
  6104. MOV_CLASS(psp)
  6105. AVOutputFormat ff_psp_muxer = {
  6106. .name = "psp",
  6107. .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
  6108. .extensions = "mp4,psp",
  6109. .priv_data_size = sizeof(MOVMuxContext),
  6110. .audio_codec = AV_CODEC_ID_AAC,
  6111. .video_codec = CONFIG_LIBX264_ENCODER ?
  6112. AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
  6113. .init = mov_init,
  6114. .write_header = mov_write_header,
  6115. .write_packet = mov_write_packet,
  6116. .write_trailer = mov_write_trailer,
  6117. .deinit = mov_free,
  6118. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  6119. .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
  6120. .check_bitstream = mov_check_bitstream,
  6121. .priv_class = &psp_muxer_class,
  6122. };
  6123. #endif
  6124. #if CONFIG_TG2_MUXER
  6125. MOV_CLASS(tg2)
  6126. AVOutputFormat ff_tg2_muxer = {
  6127. .name = "3g2",
  6128. .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
  6129. .extensions = "3g2",
  6130. .priv_data_size = sizeof(MOVMuxContext),
  6131. .audio_codec = AV_CODEC_ID_AMR_NB,
  6132. .video_codec = AV_CODEC_ID_H263,
  6133. .init = mov_init,
  6134. .write_header = mov_write_header,
  6135. .write_packet = mov_write_packet,
  6136. .write_trailer = mov_write_trailer,
  6137. .deinit = mov_free,
  6138. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  6139. .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
  6140. .check_bitstream = mov_check_bitstream,
  6141. .priv_class = &tg2_muxer_class,
  6142. };
  6143. #endif
  6144. #if CONFIG_IPOD_MUXER
  6145. MOV_CLASS(ipod)
  6146. AVOutputFormat ff_ipod_muxer = {
  6147. .name = "ipod",
  6148. .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
  6149. .mime_type = "video/mp4",
  6150. .extensions = "m4v,m4a,m4b",
  6151. .priv_data_size = sizeof(MOVMuxContext),
  6152. .audio_codec = AV_CODEC_ID_AAC,
  6153. .video_codec = AV_CODEC_ID_H264,
  6154. .init = mov_init,
  6155. .write_header = mov_write_header,
  6156. .write_packet = mov_write_packet,
  6157. .write_trailer = mov_write_trailer,
  6158. .deinit = mov_free,
  6159. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  6160. .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
  6161. .check_bitstream = mov_check_bitstream,
  6162. .priv_class = &ipod_muxer_class,
  6163. };
  6164. #endif
  6165. #if CONFIG_ISMV_MUXER
  6166. MOV_CLASS(ismv)
  6167. AVOutputFormat ff_ismv_muxer = {
  6168. .name = "ismv",
  6169. .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
  6170. .mime_type = "video/mp4",
  6171. .extensions = "ismv,isma",
  6172. .priv_data_size = sizeof(MOVMuxContext),
  6173. .audio_codec = AV_CODEC_ID_AAC,
  6174. .video_codec = AV_CODEC_ID_H264,
  6175. .init = mov_init,
  6176. .write_header = mov_write_header,
  6177. .write_packet = mov_write_packet,
  6178. .write_trailer = mov_write_trailer,
  6179. .deinit = mov_free,
  6180. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  6181. .codec_tag = (const AVCodecTag* const []){
  6182. codec_mp4_tags, codec_ism_tags, 0 },
  6183. .check_bitstream = mov_check_bitstream,
  6184. .priv_class = &ismv_muxer_class,
  6185. };
  6186. #endif
  6187. #if CONFIG_F4V_MUXER
  6188. MOV_CLASS(f4v)
  6189. AVOutputFormat ff_f4v_muxer = {
  6190. .name = "f4v",
  6191. .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
  6192. .mime_type = "application/f4v",
  6193. .extensions = "f4v",
  6194. .priv_data_size = sizeof(MOVMuxContext),
  6195. .audio_codec = AV_CODEC_ID_AAC,
  6196. .video_codec = AV_CODEC_ID_H264,
  6197. .init = mov_init,
  6198. .write_header = mov_write_header,
  6199. .write_packet = mov_write_packet,
  6200. .write_trailer = mov_write_trailer,
  6201. .deinit = mov_free,
  6202. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
  6203. .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
  6204. .check_bitstream = mov_check_bitstream,
  6205. .priv_class = &f4v_muxer_class,
  6206. };
  6207. #endif