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.

6078 lines
207KB

  1. /*
  2. * MOV demuxer
  3. * Copyright (c) 2001 Fabrice Bellard
  4. * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
  5. *
  6. * first version by Francois Revol <revol@free.fr>
  7. * seek function by Gael Chardon <gael.dev@4now.net>
  8. *
  9. * This file is part of FFmpeg.
  10. *
  11. * FFmpeg is free software; you can redistribute it and/or
  12. * modify it under the terms of the GNU Lesser General Public
  13. * License as published by the Free Software Foundation; either
  14. * version 2.1 of the License, or (at your option) any later version.
  15. *
  16. * FFmpeg is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  19. * Lesser General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Lesser General Public
  22. * License along with FFmpeg; if not, write to the Free Software
  23. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  24. */
  25. #include <inttypes.h>
  26. #include <limits.h>
  27. #include <stdint.h>
  28. #include "libavutil/attributes.h"
  29. #include "libavutil/channel_layout.h"
  30. #include "libavutil/internal.h"
  31. #include "libavutil/intreadwrite.h"
  32. #include "libavutil/intfloat.h"
  33. #include "libavutil/mathematics.h"
  34. #include "libavutil/time_internal.h"
  35. #include "libavutil/avassert.h"
  36. #include "libavutil/avstring.h"
  37. #include "libavutil/dict.h"
  38. #include "libavutil/display.h"
  39. #include "libavutil/opt.h"
  40. #include "libavutil/aes.h"
  41. #include "libavutil/aes_ctr.h"
  42. #include "libavutil/sha.h"
  43. #include "libavutil/timecode.h"
  44. #include "libavcodec/ac3tab.h"
  45. #include "libavcodec/mpegaudiodecheader.h"
  46. #include "avformat.h"
  47. #include "internal.h"
  48. #include "avio_internal.h"
  49. #include "riff.h"
  50. #include "isom.h"
  51. #include "libavcodec/get_bits.h"
  52. #include "id3v1.h"
  53. #include "mov_chan.h"
  54. #include "replaygain.h"
  55. #if CONFIG_ZLIB
  56. #include <zlib.h>
  57. #endif
  58. #include "qtpalette.h"
  59. /* those functions parse an atom */
  60. /* links atom IDs to parse functions */
  61. typedef struct MOVParseTableEntry {
  62. uint32_t type;
  63. int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
  64. } MOVParseTableEntry;
  65. static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
  66. static int mov_read_mfra(MOVContext *c, AVIOContext *f);
  67. static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
  68. unsigned len, const char *key)
  69. {
  70. char buf[16];
  71. short current, total = 0;
  72. avio_rb16(pb); // unknown
  73. current = avio_rb16(pb);
  74. if (len >= 6)
  75. total = avio_rb16(pb);
  76. if (!total)
  77. snprintf(buf, sizeof(buf), "%d", current);
  78. else
  79. snprintf(buf, sizeof(buf), "%d/%d", current, total);
  80. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  81. av_dict_set(&c->fc->metadata, key, buf, 0);
  82. return 0;
  83. }
  84. static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
  85. unsigned len, const char *key)
  86. {
  87. /* bypass padding bytes */
  88. avio_r8(pb);
  89. avio_r8(pb);
  90. avio_r8(pb);
  91. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  92. av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
  93. return 0;
  94. }
  95. static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
  96. unsigned len, const char *key)
  97. {
  98. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  99. av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
  100. return 0;
  101. }
  102. static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
  103. unsigned len, const char *key)
  104. {
  105. short genre;
  106. avio_r8(pb); // unknown
  107. genre = avio_r8(pb);
  108. if (genre < 1 || genre > ID3v1_GENRE_MAX)
  109. return 0;
  110. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  111. av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
  112. return 0;
  113. }
  114. static const uint32_t mac_to_unicode[128] = {
  115. 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
  116. 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
  117. 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
  118. 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
  119. 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
  120. 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
  121. 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
  122. 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
  123. 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
  124. 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
  125. 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
  126. 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
  127. 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
  128. 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
  129. 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
  130. 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
  131. };
  132. static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
  133. char *dst, int dstlen)
  134. {
  135. char *p = dst;
  136. char *end = dst+dstlen-1;
  137. int i;
  138. for (i = 0; i < len; i++) {
  139. uint8_t t, c = avio_r8(pb);
  140. if (c < 0x80 && p < end)
  141. *p++ = c;
  142. else if (p < end)
  143. PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
  144. }
  145. *p = 0;
  146. return p - dst;
  147. }
  148. static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
  149. {
  150. AVPacket pkt;
  151. AVStream *st;
  152. MOVStreamContext *sc;
  153. enum AVCodecID id;
  154. int ret;
  155. switch (type) {
  156. case 0xd: id = AV_CODEC_ID_MJPEG; break;
  157. case 0xe: id = AV_CODEC_ID_PNG; break;
  158. case 0x1b: id = AV_CODEC_ID_BMP; break;
  159. default:
  160. av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
  161. avio_skip(pb, len);
  162. return 0;
  163. }
  164. st = avformat_new_stream(c->fc, NULL);
  165. if (!st)
  166. return AVERROR(ENOMEM);
  167. sc = av_mallocz(sizeof(*sc));
  168. if (!sc)
  169. return AVERROR(ENOMEM);
  170. st->priv_data = sc;
  171. ret = av_get_packet(pb, &pkt, len);
  172. if (ret < 0)
  173. return ret;
  174. if (pkt.size >= 8 && id != AV_CODEC_ID_BMP) {
  175. if (AV_RB64(pkt.data) == 0x89504e470d0a1a0a) {
  176. id = AV_CODEC_ID_PNG;
  177. } else {
  178. id = AV_CODEC_ID_MJPEG;
  179. }
  180. }
  181. st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
  182. st->attached_pic = pkt;
  183. st->attached_pic.stream_index = st->index;
  184. st->attached_pic.flags |= AV_PKT_FLAG_KEY;
  185. st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
  186. st->codecpar->codec_id = id;
  187. return 0;
  188. }
  189. // 3GPP TS 26.244
  190. static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
  191. {
  192. char language[4] = { 0 };
  193. char buf[200], place[100];
  194. uint16_t langcode = 0;
  195. double longitude, latitude, altitude;
  196. const char *key = "location";
  197. if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4) {
  198. av_log(c->fc, AV_LOG_ERROR, "loci too short\n");
  199. return AVERROR_INVALIDDATA;
  200. }
  201. avio_skip(pb, 4); // version+flags
  202. langcode = avio_rb16(pb);
  203. ff_mov_lang_to_iso639(langcode, language);
  204. len -= 6;
  205. len -= avio_get_str(pb, len, place, sizeof(place));
  206. if (len < 1) {
  207. av_log(c->fc, AV_LOG_ERROR, "place name too long\n");
  208. return AVERROR_INVALIDDATA;
  209. }
  210. avio_skip(pb, 1); // role
  211. len -= 1;
  212. if (len < 12) {
  213. av_log(c->fc, AV_LOG_ERROR,
  214. "loci too short (%u bytes left, need at least %d)\n", len, 12);
  215. return AVERROR_INVALIDDATA;
  216. }
  217. longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
  218. latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
  219. altitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
  220. // Try to output in the same format as the ?xyz field
  221. snprintf(buf, sizeof(buf), "%+08.4f%+09.4f", latitude, longitude);
  222. if (altitude)
  223. av_strlcatf(buf, sizeof(buf), "%+f", altitude);
  224. av_strlcatf(buf, sizeof(buf), "/%s", place);
  225. if (*language && strcmp(language, "und")) {
  226. char key2[16];
  227. snprintf(key2, sizeof(key2), "%s-%s", key, language);
  228. av_dict_set(&c->fc->metadata, key2, buf, 0);
  229. }
  230. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  231. return av_dict_set(&c->fc->metadata, key, buf, 0);
  232. }
  233. static int mov_metadata_hmmt(MOVContext *c, AVIOContext *pb, unsigned len)
  234. {
  235. int i, n_hmmt;
  236. if (len < 2)
  237. return 0;
  238. if (c->ignore_chapters)
  239. return 0;
  240. n_hmmt = avio_rb32(pb);
  241. for (i = 0; i < n_hmmt && !pb->eof_reached; i++) {
  242. int moment_time = avio_rb32(pb);
  243. avpriv_new_chapter(c->fc, i, av_make_q(1, 1000), moment_time, AV_NOPTS_VALUE, NULL);
  244. }
  245. return 0;
  246. }
  247. static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  248. {
  249. char tmp_key[5];
  250. char key2[32], language[4] = {0};
  251. char *str = NULL;
  252. const char *key = NULL;
  253. uint16_t langcode = 0;
  254. uint32_t data_type = 0, str_size, str_size_alloc;
  255. int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
  256. int raw = 0;
  257. int num = 0;
  258. switch (atom.type) {
  259. case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
  260. case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
  261. case MKTAG( 'X','M','P','_'):
  262. if (c->export_xmp) { key = "xmp"; raw = 1; } break;
  263. case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
  264. case MKTAG( 'a','k','I','D'): key = "account_type";
  265. parse = mov_metadata_int8_no_padding; break;
  266. case MKTAG( 'a','p','I','D'): key = "account_id"; break;
  267. case MKTAG( 'c','a','t','g'): key = "category"; break;
  268. case MKTAG( 'c','p','i','l'): key = "compilation";
  269. parse = mov_metadata_int8_no_padding; break;
  270. case MKTAG( 'c','p','r','t'): key = "copyright"; break;
  271. case MKTAG( 'd','e','s','c'): key = "description"; break;
  272. case MKTAG( 'd','i','s','k'): key = "disc";
  273. parse = mov_metadata_track_or_disc_number; break;
  274. case MKTAG( 'e','g','i','d'): key = "episode_uid";
  275. parse = mov_metadata_int8_no_padding; break;
  276. case MKTAG( 'F','I','R','M'): key = "firmware"; raw = 1; break;
  277. case MKTAG( 'g','n','r','e'): key = "genre";
  278. parse = mov_metadata_gnre; break;
  279. case MKTAG( 'h','d','v','d'): key = "hd_video";
  280. parse = mov_metadata_int8_no_padding; break;
  281. case MKTAG( 'H','M','M','T'):
  282. return mov_metadata_hmmt(c, pb, atom.size);
  283. case MKTAG( 'k','e','y','w'): key = "keywords"; break;
  284. case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
  285. case MKTAG( 'l','o','c','i'):
  286. return mov_metadata_loci(c, pb, atom.size);
  287. case MKTAG( 'p','c','s','t'): key = "podcast";
  288. parse = mov_metadata_int8_no_padding; break;
  289. case MKTAG( 'p','g','a','p'): key = "gapless_playback";
  290. parse = mov_metadata_int8_no_padding; break;
  291. case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
  292. case MKTAG( 'r','t','n','g'): key = "rating";
  293. parse = mov_metadata_int8_no_padding; break;
  294. case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
  295. case MKTAG( 's','o','a','l'): key = "sort_album"; break;
  296. case MKTAG( 's','o','a','r'): key = "sort_artist"; break;
  297. case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
  298. case MKTAG( 's','o','n','m'): key = "sort_name"; break;
  299. case MKTAG( 's','o','s','n'): key = "sort_show"; break;
  300. case MKTAG( 's','t','i','k'): key = "media_type";
  301. parse = mov_metadata_int8_no_padding; break;
  302. case MKTAG( 't','r','k','n'): key = "track";
  303. parse = mov_metadata_track_or_disc_number; break;
  304. case MKTAG( 't','v','e','n'): key = "episode_id"; break;
  305. case MKTAG( 't','v','e','s'): key = "episode_sort";
  306. parse = mov_metadata_int8_bypass_padding; break;
  307. case MKTAG( 't','v','n','n'): key = "network"; break;
  308. case MKTAG( 't','v','s','h'): key = "show"; break;
  309. case MKTAG( 't','v','s','n'): key = "season_number";
  310. parse = mov_metadata_int8_bypass_padding; break;
  311. case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
  312. case MKTAG(0xa9,'P','R','D'): key = "producer"; break;
  313. case MKTAG(0xa9,'a','l','b'): key = "album"; break;
  314. case MKTAG(0xa9,'a','u','t'): key = "artist"; break;
  315. case MKTAG(0xa9,'c','h','p'): key = "chapter"; break;
  316. case MKTAG(0xa9,'c','m','t'): key = "comment"; break;
  317. case MKTAG(0xa9,'c','o','m'): key = "composer"; break;
  318. case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
  319. case MKTAG(0xa9,'d','a','y'): key = "date"; break;
  320. case MKTAG(0xa9,'d','i','r'): key = "director"; break;
  321. case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
  322. case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
  323. case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
  324. case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
  325. case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
  326. case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
  327. case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
  328. case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
  329. case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
  330. case MKTAG(0xa9,'m','a','k'): key = "make"; break;
  331. case MKTAG(0xa9,'m','o','d'): key = "model"; break;
  332. case MKTAG(0xa9,'n','a','m'): key = "title"; break;
  333. case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
  334. case MKTAG(0xa9,'p','r','d'): key = "producer"; break;
  335. case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
  336. case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
  337. case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
  338. case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break;
  339. case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
  340. case MKTAG(0xa9,'t','o','o'): key = "encoder"; break;
  341. case MKTAG(0xa9,'t','r','k'): key = "track"; break;
  342. case MKTAG(0xa9,'u','r','l'): key = "URL"; break;
  343. case MKTAG(0xa9,'w','r','n'): key = "warning"; break;
  344. case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
  345. case MKTAG(0xa9,'x','y','z'): key = "location"; break;
  346. }
  347. retry:
  348. if (c->itunes_metadata && atom.size > 8) {
  349. int data_size = avio_rb32(pb);
  350. int tag = avio_rl32(pb);
  351. if (tag == MKTAG('d','a','t','a') && data_size <= atom.size) {
  352. data_type = avio_rb32(pb); // type
  353. avio_rb32(pb); // unknown
  354. str_size = data_size - 16;
  355. atom.size -= 16;
  356. if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
  357. int ret = mov_read_covr(c, pb, data_type, str_size);
  358. if (ret < 0) {
  359. av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
  360. }
  361. return ret;
  362. } else if (!key && c->found_hdlr_mdta && c->meta_keys) {
  363. uint32_t index = AV_RB32(&atom.type);
  364. if (index < c->meta_keys_count) {
  365. key = c->meta_keys[index];
  366. } else {
  367. av_log(c->fc, AV_LOG_WARNING,
  368. "The index of 'data' is out of range: %d >= %d.\n",
  369. index, c->meta_keys_count);
  370. }
  371. }
  372. } else return 0;
  373. } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
  374. str_size = avio_rb16(pb); // string length
  375. if (str_size > atom.size) {
  376. raw = 1;
  377. avio_seek(pb, -2, SEEK_CUR);
  378. av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n");
  379. goto retry;
  380. }
  381. langcode = avio_rb16(pb);
  382. ff_mov_lang_to_iso639(langcode, language);
  383. atom.size -= 4;
  384. } else
  385. str_size = atom.size;
  386. if (c->export_all && !key) {
  387. snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
  388. key = tmp_key;
  389. }
  390. if (!key)
  391. return 0;
  392. if (atom.size < 0 || str_size >= INT_MAX/2)
  393. return AVERROR_INVALIDDATA;
  394. // Allocates enough space if data_type is a int32 or float32 number, otherwise
  395. // worst-case requirement for output string in case of utf8 coded input
  396. num = (data_type >= 21 && data_type <= 23);
  397. str_size_alloc = (num ? 512 : (raw ? str_size : str_size * 2)) + 1;
  398. str = av_mallocz(str_size_alloc);
  399. if (!str)
  400. return AVERROR(ENOMEM);
  401. if (parse)
  402. parse(c, pb, str_size, key);
  403. else {
  404. if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
  405. mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
  406. } else if (data_type == 21) { // BE signed integer, variable size
  407. int val = 0;
  408. if (str_size == 1)
  409. val = (int8_t)avio_r8(pb);
  410. else if (str_size == 2)
  411. val = (int16_t)avio_rb16(pb);
  412. else if (str_size == 3)
  413. val = ((int32_t)(avio_rb24(pb)<<8))>>8;
  414. else if (str_size == 4)
  415. val = (int32_t)avio_rb32(pb);
  416. if (snprintf(str, str_size_alloc, "%d", val) >= str_size_alloc) {
  417. av_log(c->fc, AV_LOG_ERROR,
  418. "Failed to store the number (%d) in string.\n", val);
  419. av_free(str);
  420. return AVERROR_INVALIDDATA;
  421. }
  422. } else if (data_type == 22) { // BE unsigned integer, variable size
  423. unsigned int val = 0;
  424. if (str_size == 1)
  425. val = avio_r8(pb);
  426. else if (str_size == 2)
  427. val = avio_rb16(pb);
  428. else if (str_size == 3)
  429. val = avio_rb24(pb);
  430. else if (str_size == 4)
  431. val = avio_rb32(pb);
  432. if (snprintf(str, str_size_alloc, "%u", val) >= str_size_alloc) {
  433. av_log(c->fc, AV_LOG_ERROR,
  434. "Failed to store the number (%u) in string.\n", val);
  435. av_free(str);
  436. return AVERROR_INVALIDDATA;
  437. }
  438. } else if (data_type == 23 && str_size >= 4) { // BE float32
  439. float val = av_int2float(avio_rb32(pb));
  440. if (snprintf(str, str_size_alloc, "%f", val) >= str_size_alloc) {
  441. av_log(c->fc, AV_LOG_ERROR,
  442. "Failed to store the float32 number (%f) in string.\n", val);
  443. av_free(str);
  444. return AVERROR_INVALIDDATA;
  445. }
  446. } else {
  447. int ret = ffio_read_size(pb, str, str_size);
  448. if (ret < 0) {
  449. av_free(str);
  450. return ret;
  451. }
  452. str[str_size] = 0;
  453. }
  454. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  455. av_dict_set(&c->fc->metadata, key, str, 0);
  456. if (*language && strcmp(language, "und")) {
  457. snprintf(key2, sizeof(key2), "%s-%s", key, language);
  458. av_dict_set(&c->fc->metadata, key2, str, 0);
  459. }
  460. if (!strcmp(key, "encoder")) {
  461. int major, minor, micro;
  462. if (sscanf(str, "HandBrake %d.%d.%d", &major, &minor, &micro) == 3) {
  463. c->handbrake_version = 1000000*major + 1000*minor + micro;
  464. }
  465. }
  466. }
  467. av_log(c->fc, AV_LOG_TRACE, "lang \"%3s\" ", language);
  468. av_log(c->fc, AV_LOG_TRACE, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
  469. key, str, (char*)&atom.type, str_size_alloc, atom.size);
  470. av_freep(&str);
  471. return 0;
  472. }
  473. static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  474. {
  475. int64_t start;
  476. int i, nb_chapters, str_len, version;
  477. char str[256+1];
  478. int ret;
  479. if (c->ignore_chapters)
  480. return 0;
  481. if ((atom.size -= 5) < 0)
  482. return 0;
  483. version = avio_r8(pb);
  484. avio_rb24(pb);
  485. if (version)
  486. avio_rb32(pb); // ???
  487. nb_chapters = avio_r8(pb);
  488. for (i = 0; i < nb_chapters; i++) {
  489. if (atom.size < 9)
  490. return 0;
  491. start = avio_rb64(pb);
  492. str_len = avio_r8(pb);
  493. if ((atom.size -= 9+str_len) < 0)
  494. return 0;
  495. ret = ffio_read_size(pb, str, str_len);
  496. if (ret < 0)
  497. return ret;
  498. str[str_len] = 0;
  499. avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
  500. }
  501. return 0;
  502. }
  503. #define MIN_DATA_ENTRY_BOX_SIZE 12
  504. static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  505. {
  506. AVStream *st;
  507. MOVStreamContext *sc;
  508. int entries, i, j;
  509. if (c->fc->nb_streams < 1)
  510. return 0;
  511. st = c->fc->streams[c->fc->nb_streams-1];
  512. sc = st->priv_data;
  513. avio_rb32(pb); // version + flags
  514. entries = avio_rb32(pb);
  515. if (!entries ||
  516. entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
  517. entries >= UINT_MAX / sizeof(*sc->drefs))
  518. return AVERROR_INVALIDDATA;
  519. sc->drefs_count = 0;
  520. av_free(sc->drefs);
  521. sc->drefs_count = 0;
  522. sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
  523. if (!sc->drefs)
  524. return AVERROR(ENOMEM);
  525. sc->drefs_count = entries;
  526. for (i = 0; i < entries; i++) {
  527. MOVDref *dref = &sc->drefs[i];
  528. uint32_t size = avio_rb32(pb);
  529. int64_t next = avio_tell(pb) + size - 4;
  530. if (size < 12)
  531. return AVERROR_INVALIDDATA;
  532. dref->type = avio_rl32(pb);
  533. avio_rb32(pb); // version + flags
  534. av_log(c->fc, AV_LOG_TRACE, "type %.4s size %d\n", (char*)&dref->type, size);
  535. if (dref->type == MKTAG('a','l','i','s') && size > 150) {
  536. /* macintosh alias record */
  537. uint16_t volume_len, len;
  538. int16_t type;
  539. int ret;
  540. avio_skip(pb, 10);
  541. volume_len = avio_r8(pb);
  542. volume_len = FFMIN(volume_len, 27);
  543. ret = ffio_read_size(pb, dref->volume, 27);
  544. if (ret < 0)
  545. return ret;
  546. dref->volume[volume_len] = 0;
  547. av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
  548. avio_skip(pb, 12);
  549. len = avio_r8(pb);
  550. len = FFMIN(len, 63);
  551. ret = ffio_read_size(pb, dref->filename, 63);
  552. if (ret < 0)
  553. return ret;
  554. dref->filename[len] = 0;
  555. av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
  556. avio_skip(pb, 16);
  557. /* read next level up_from_alias/down_to_target */
  558. dref->nlvl_from = avio_rb16(pb);
  559. dref->nlvl_to = avio_rb16(pb);
  560. av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
  561. dref->nlvl_from, dref->nlvl_to);
  562. avio_skip(pb, 16);
  563. for (type = 0; type != -1 && avio_tell(pb) < next; ) {
  564. if(avio_feof(pb))
  565. return AVERROR_EOF;
  566. type = avio_rb16(pb);
  567. len = avio_rb16(pb);
  568. av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
  569. if (len&1)
  570. len += 1;
  571. if (type == 2) { // absolute path
  572. av_free(dref->path);
  573. dref->path = av_mallocz(len+1);
  574. if (!dref->path)
  575. return AVERROR(ENOMEM);
  576. ret = ffio_read_size(pb, dref->path, len);
  577. if (ret < 0) {
  578. av_freep(&dref->path);
  579. return ret;
  580. }
  581. if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
  582. len -= volume_len;
  583. memmove(dref->path, dref->path+volume_len, len);
  584. dref->path[len] = 0;
  585. }
  586. // trim string of any ending zeros
  587. for (j = len - 1; j >= 0; j--) {
  588. if (dref->path[j] == 0)
  589. len--;
  590. else
  591. break;
  592. }
  593. for (j = 0; j < len; j++)
  594. if (dref->path[j] == ':' || dref->path[j] == 0)
  595. dref->path[j] = '/';
  596. av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
  597. } else if (type == 0) { // directory name
  598. av_free(dref->dir);
  599. dref->dir = av_malloc(len+1);
  600. if (!dref->dir)
  601. return AVERROR(ENOMEM);
  602. ret = ffio_read_size(pb, dref->dir, len);
  603. if (ret < 0) {
  604. av_freep(&dref->dir);
  605. return ret;
  606. }
  607. dref->dir[len] = 0;
  608. for (j = 0; j < len; j++)
  609. if (dref->dir[j] == ':')
  610. dref->dir[j] = '/';
  611. av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
  612. } else
  613. avio_skip(pb, len);
  614. }
  615. } else {
  616. av_log(c->fc, AV_LOG_DEBUG, "Unknown dref type 0x08%x size %d\n",
  617. dref->type, size);
  618. entries--;
  619. i--;
  620. }
  621. avio_seek(pb, next, SEEK_SET);
  622. }
  623. return 0;
  624. }
  625. static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  626. {
  627. AVStream *st;
  628. uint32_t type;
  629. uint32_t av_unused ctype;
  630. int64_t title_size;
  631. char *title_str;
  632. int ret;
  633. avio_r8(pb); /* version */
  634. avio_rb24(pb); /* flags */
  635. /* component type */
  636. ctype = avio_rl32(pb);
  637. type = avio_rl32(pb); /* component subtype */
  638. av_log(c->fc, AV_LOG_TRACE, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
  639. av_log(c->fc, AV_LOG_TRACE, "stype= %.4s\n", (char*)&type);
  640. if (c->trak_index < 0) { // meta not inside a trak
  641. if (type == MKTAG('m','d','t','a')) {
  642. c->found_hdlr_mdta = 1;
  643. }
  644. return 0;
  645. }
  646. st = c->fc->streams[c->fc->nb_streams-1];
  647. if (type == MKTAG('v','i','d','e'))
  648. st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
  649. else if (type == MKTAG('s','o','u','n'))
  650. st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  651. else if (type == MKTAG('m','1','a',' '))
  652. st->codecpar->codec_id = AV_CODEC_ID_MP2;
  653. else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
  654. st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
  655. avio_rb32(pb); /* component manufacture */
  656. avio_rb32(pb); /* component flags */
  657. avio_rb32(pb); /* component flags mask */
  658. title_size = atom.size - 24;
  659. if (title_size > 0) {
  660. title_str = av_malloc(title_size + 1); /* Add null terminator */
  661. if (!title_str)
  662. return AVERROR(ENOMEM);
  663. ret = ffio_read_size(pb, title_str, title_size);
  664. if (ret < 0) {
  665. av_freep(&title_str);
  666. return ret;
  667. }
  668. title_str[title_size] = 0;
  669. if (title_str[0]) {
  670. int off = (!c->isom && title_str[0] == title_size - 1);
  671. av_dict_set(&st->metadata, "handler_name", title_str + off, 0);
  672. }
  673. av_freep(&title_str);
  674. }
  675. return 0;
  676. }
  677. int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb)
  678. {
  679. AVStream *st;
  680. int tag;
  681. if (fc->nb_streams < 1)
  682. return 0;
  683. st = fc->streams[fc->nb_streams-1];
  684. avio_rb32(pb); /* version + flags */
  685. ff_mp4_read_descr(fc, pb, &tag);
  686. if (tag == MP4ESDescrTag) {
  687. ff_mp4_parse_es_descr(pb, NULL);
  688. } else
  689. avio_rb16(pb); /* ID */
  690. ff_mp4_read_descr(fc, pb, &tag);
  691. if (tag == MP4DecConfigDescrTag)
  692. ff_mp4_read_dec_config_descr(fc, st, pb);
  693. return 0;
  694. }
  695. static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  696. {
  697. return ff_mov_read_esds(c->fc, pb);
  698. }
  699. static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  700. {
  701. AVStream *st;
  702. enum AVAudioServiceType *ast;
  703. int ac3info, acmod, lfeon, bsmod;
  704. if (c->fc->nb_streams < 1)
  705. return 0;
  706. st = c->fc->streams[c->fc->nb_streams-1];
  707. ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
  708. sizeof(*ast));
  709. if (!ast)
  710. return AVERROR(ENOMEM);
  711. ac3info = avio_rb24(pb);
  712. bsmod = (ac3info >> 14) & 0x7;
  713. acmod = (ac3info >> 11) & 0x7;
  714. lfeon = (ac3info >> 10) & 0x1;
  715. st->codecpar->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
  716. st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
  717. if (lfeon)
  718. st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
  719. *ast = bsmod;
  720. if (st->codecpar->channels > 1 && bsmod == 0x7)
  721. *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
  722. #if FF_API_LAVF_AVCTX
  723. FF_DISABLE_DEPRECATION_WARNINGS
  724. st->codec->audio_service_type = *ast;
  725. FF_ENABLE_DEPRECATION_WARNINGS
  726. #endif
  727. return 0;
  728. }
  729. static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  730. {
  731. AVStream *st;
  732. enum AVAudioServiceType *ast;
  733. int eac3info, acmod, lfeon, bsmod;
  734. if (c->fc->nb_streams < 1)
  735. return 0;
  736. st = c->fc->streams[c->fc->nb_streams-1];
  737. ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
  738. sizeof(*ast));
  739. if (!ast)
  740. return AVERROR(ENOMEM);
  741. /* No need to parse fields for additional independent substreams and its
  742. * associated dependent substreams since libavcodec's E-AC-3 decoder
  743. * does not support them yet. */
  744. avio_rb16(pb); /* data_rate and num_ind_sub */
  745. eac3info = avio_rb24(pb);
  746. bsmod = (eac3info >> 12) & 0x1f;
  747. acmod = (eac3info >> 9) & 0x7;
  748. lfeon = (eac3info >> 8) & 0x1;
  749. st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
  750. if (lfeon)
  751. st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
  752. st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);
  753. *ast = bsmod;
  754. if (st->codecpar->channels > 1 && bsmod == 0x7)
  755. *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
  756. #if FF_API_LAVF_AVCTX
  757. FF_DISABLE_DEPRECATION_WARNINGS
  758. st->codec->audio_service_type = *ast;
  759. FF_ENABLE_DEPRECATION_WARNINGS
  760. #endif
  761. return 0;
  762. }
  763. static int mov_read_ddts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  764. {
  765. const uint32_t ddts_size = 20;
  766. AVStream *st = NULL;
  767. uint8_t *buf = NULL;
  768. uint32_t frame_duration_code = 0;
  769. uint32_t channel_layout_code = 0;
  770. GetBitContext gb;
  771. buf = av_malloc(ddts_size + FF_INPUT_BUFFER_PADDING_SIZE);
  772. if (!buf) {
  773. return AVERROR(ENOMEM);
  774. }
  775. if (avio_read(pb, buf, ddts_size) < ddts_size) {
  776. av_free(buf);
  777. return AVERROR_INVALIDDATA;
  778. }
  779. init_get_bits(&gb, buf, 8*ddts_size);
  780. if (c->fc->nb_streams < 1) {
  781. return 0;
  782. }
  783. st = c->fc->streams[c->fc->nb_streams-1];
  784. st->codecpar->sample_rate = get_bits_long(&gb, 32);
  785. if (st->codecpar->sample_rate <= 0) {
  786. av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
  787. return AVERROR_INVALIDDATA;
  788. }
  789. skip_bits_long(&gb, 32); /* max bitrate */
  790. st->codecpar->bit_rate = get_bits_long(&gb, 32);
  791. st->codecpar->bits_per_coded_sample = get_bits(&gb, 8);
  792. frame_duration_code = get_bits(&gb, 2);
  793. skip_bits(&gb, 30); /* various fields */
  794. channel_layout_code = get_bits(&gb, 16);
  795. st->codecpar->frame_size =
  796. (frame_duration_code == 0) ? 512 :
  797. (frame_duration_code == 1) ? 1024 :
  798. (frame_duration_code == 2) ? 2048 :
  799. (frame_duration_code == 3) ? 4096 : 0;
  800. if (channel_layout_code > 0xff) {
  801. av_log(c->fc, AV_LOG_WARNING, "Unsupported DTS audio channel layout");
  802. }
  803. st->codecpar->channel_layout =
  804. ((channel_layout_code & 0x1) ? AV_CH_FRONT_CENTER : 0) |
  805. ((channel_layout_code & 0x2) ? AV_CH_FRONT_LEFT : 0) |
  806. ((channel_layout_code & 0x2) ? AV_CH_FRONT_RIGHT : 0) |
  807. ((channel_layout_code & 0x4) ? AV_CH_SIDE_LEFT : 0) |
  808. ((channel_layout_code & 0x4) ? AV_CH_SIDE_RIGHT : 0) |
  809. ((channel_layout_code & 0x8) ? AV_CH_LOW_FREQUENCY : 0);
  810. st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);
  811. return 0;
  812. }
  813. static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  814. {
  815. AVStream *st;
  816. if (c->fc->nb_streams < 1)
  817. return 0;
  818. st = c->fc->streams[c->fc->nb_streams-1];
  819. if (atom.size < 16)
  820. return 0;
  821. /* skip version and flags */
  822. avio_skip(pb, 4);
  823. ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
  824. return 0;
  825. }
  826. static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  827. {
  828. AVStream *st;
  829. int ret;
  830. if (c->fc->nb_streams < 1)
  831. return 0;
  832. st = c->fc->streams[c->fc->nb_streams-1];
  833. if ((ret = ff_get_wav_header(c->fc, pb, st->codecpar, atom.size, 0)) < 0)
  834. av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
  835. return ret;
  836. }
  837. static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  838. {
  839. const int num = avio_rb32(pb);
  840. const int den = avio_rb32(pb);
  841. AVStream *st;
  842. if (c->fc->nb_streams < 1)
  843. return 0;
  844. st = c->fc->streams[c->fc->nb_streams-1];
  845. if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
  846. (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
  847. av_log(c->fc, AV_LOG_WARNING,
  848. "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
  849. st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
  850. num, den);
  851. } else if (den != 0) {
  852. av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den,
  853. num, den, 32767);
  854. }
  855. return 0;
  856. }
  857. /* this atom contains actual media data */
  858. static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  859. {
  860. if (atom.size == 0) /* wrong one (MP4) */
  861. return 0;
  862. c->found_mdat=1;
  863. return 0; /* now go for moov */
  864. }
  865. #define DRM_BLOB_SIZE 56
  866. static int mov_read_adrm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  867. {
  868. uint8_t intermediate_key[20];
  869. uint8_t intermediate_iv[20];
  870. uint8_t input[64];
  871. uint8_t output[64];
  872. uint8_t file_checksum[20];
  873. uint8_t calculated_checksum[20];
  874. struct AVSHA *sha;
  875. int i;
  876. int ret = 0;
  877. uint8_t *activation_bytes = c->activation_bytes;
  878. uint8_t *fixed_key = c->audible_fixed_key;
  879. c->aax_mode = 1;
  880. sha = av_sha_alloc();
  881. if (!sha)
  882. return AVERROR(ENOMEM);
  883. c->aes_decrypt = av_aes_alloc();
  884. if (!c->aes_decrypt) {
  885. ret = AVERROR(ENOMEM);
  886. goto fail;
  887. }
  888. /* drm blob processing */
  889. avio_read(pb, output, 8); // go to offset 8, absolute position 0x251
  890. avio_read(pb, input, DRM_BLOB_SIZE);
  891. avio_read(pb, output, 4); // go to offset 4, absolute position 0x28d
  892. avio_read(pb, file_checksum, 20);
  893. av_log(c->fc, AV_LOG_INFO, "[aax] file checksum == "); // required by external tools
  894. for (i = 0; i < 20; i++)
  895. av_log(c->fc, AV_LOG_INFO, "%02x", file_checksum[i]);
  896. av_log(c->fc, AV_LOG_INFO, "\n");
  897. /* verify activation data */
  898. if (!activation_bytes) {
  899. av_log(c->fc, AV_LOG_WARNING, "[aax] activation_bytes option is missing!\n");
  900. ret = 0; /* allow ffprobe to continue working on .aax files */
  901. goto fail;
  902. }
  903. if (c->activation_bytes_size != 4) {
  904. av_log(c->fc, AV_LOG_FATAL, "[aax] activation_bytes value needs to be 4 bytes!\n");
  905. ret = AVERROR(EINVAL);
  906. goto fail;
  907. }
  908. /* verify fixed key */
  909. if (c->audible_fixed_key_size != 16) {
  910. av_log(c->fc, AV_LOG_FATAL, "[aax] audible_fixed_key value needs to be 16 bytes!\n");
  911. ret = AVERROR(EINVAL);
  912. goto fail;
  913. }
  914. /* AAX (and AAX+) key derivation */
  915. av_sha_init(sha, 160);
  916. av_sha_update(sha, fixed_key, 16);
  917. av_sha_update(sha, activation_bytes, 4);
  918. av_sha_final(sha, intermediate_key);
  919. av_sha_init(sha, 160);
  920. av_sha_update(sha, fixed_key, 16);
  921. av_sha_update(sha, intermediate_key, 20);
  922. av_sha_update(sha, activation_bytes, 4);
  923. av_sha_final(sha, intermediate_iv);
  924. av_sha_init(sha, 160);
  925. av_sha_update(sha, intermediate_key, 16);
  926. av_sha_update(sha, intermediate_iv, 16);
  927. av_sha_final(sha, calculated_checksum);
  928. if (memcmp(calculated_checksum, file_checksum, 20)) { // critical error
  929. av_log(c->fc, AV_LOG_ERROR, "[aax] mismatch in checksums!\n");
  930. ret = AVERROR_INVALIDDATA;
  931. goto fail;
  932. }
  933. av_aes_init(c->aes_decrypt, intermediate_key, 128, 1);
  934. av_aes_crypt(c->aes_decrypt, output, input, DRM_BLOB_SIZE >> 4, intermediate_iv, 1);
  935. for (i = 0; i < 4; i++) {
  936. // file data (in output) is stored in big-endian mode
  937. if (activation_bytes[i] != output[3 - i]) { // critical error
  938. av_log(c->fc, AV_LOG_ERROR, "[aax] error in drm blob decryption!\n");
  939. ret = AVERROR_INVALIDDATA;
  940. goto fail;
  941. }
  942. }
  943. memcpy(c->file_key, output + 8, 16);
  944. memcpy(input, output + 26, 16);
  945. av_sha_init(sha, 160);
  946. av_sha_update(sha, input, 16);
  947. av_sha_update(sha, c->file_key, 16);
  948. av_sha_update(sha, fixed_key, 16);
  949. av_sha_final(sha, c->file_iv);
  950. fail:
  951. av_free(sha);
  952. return ret;
  953. }
  954. // Audible AAX (and AAX+) bytestream decryption
  955. static int aax_filter(uint8_t *input, int size, MOVContext *c)
  956. {
  957. int blocks = 0;
  958. unsigned char iv[16];
  959. memcpy(iv, c->file_iv, 16); // iv is overwritten
  960. blocks = size >> 4; // trailing bytes are not encrypted!
  961. av_aes_init(c->aes_decrypt, c->file_key, 128, 1);
  962. av_aes_crypt(c->aes_decrypt, input, input, blocks, iv, 1);
  963. return 0;
  964. }
  965. /* read major brand, minor version and compatible brands and store them as metadata */
  966. static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  967. {
  968. uint32_t minor_ver;
  969. int comp_brand_size;
  970. char* comp_brands_str;
  971. uint8_t type[5] = {0};
  972. int ret = ffio_read_size(pb, type, 4);
  973. if (ret < 0)
  974. return ret;
  975. if (strcmp(type, "qt "))
  976. c->isom = 1;
  977. av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
  978. av_dict_set(&c->fc->metadata, "major_brand", type, 0);
  979. minor_ver = avio_rb32(pb); /* minor version */
  980. av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
  981. comp_brand_size = atom.size - 8;
  982. if (comp_brand_size < 0)
  983. return AVERROR_INVALIDDATA;
  984. comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
  985. if (!comp_brands_str)
  986. return AVERROR(ENOMEM);
  987. ret = ffio_read_size(pb, comp_brands_str, comp_brand_size);
  988. if (ret < 0) {
  989. av_freep(&comp_brands_str);
  990. return ret;
  991. }
  992. comp_brands_str[comp_brand_size] = 0;
  993. av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
  994. av_freep(&comp_brands_str);
  995. return 0;
  996. }
  997. /* this atom should contain all header atoms */
  998. static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  999. {
  1000. int ret;
  1001. if (c->found_moov) {
  1002. av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
  1003. avio_skip(pb, atom.size);
  1004. return 0;
  1005. }
  1006. if ((ret = mov_read_default(c, pb, atom)) < 0)
  1007. return ret;
  1008. /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
  1009. /* so we don't parse the whole file if over a network */
  1010. c->found_moov=1;
  1011. return 0; /* now go for mdat */
  1012. }
  1013. static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1014. {
  1015. if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
  1016. c->has_looked_for_mfra = 1;
  1017. if (pb->seekable) {
  1018. int ret;
  1019. av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
  1020. "for a mfra\n");
  1021. if ((ret = mov_read_mfra(c, pb)) < 0) {
  1022. av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
  1023. "read the mfra (may be a live ismv)\n");
  1024. }
  1025. } else {
  1026. av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
  1027. "seekable, can not look for mfra\n");
  1028. }
  1029. }
  1030. c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
  1031. av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
  1032. return mov_read_default(c, pb, atom);
  1033. }
  1034. static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
  1035. {
  1036. if (time) {
  1037. if(time >= 2082844800)
  1038. time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
  1039. avpriv_dict_set_timestamp(metadata, "creation_time", time * 1000000);
  1040. }
  1041. }
  1042. static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1043. {
  1044. AVStream *st;
  1045. MOVStreamContext *sc;
  1046. int version;
  1047. char language[4] = {0};
  1048. unsigned lang;
  1049. int64_t creation_time;
  1050. if (c->fc->nb_streams < 1)
  1051. return 0;
  1052. st = c->fc->streams[c->fc->nb_streams-1];
  1053. sc = st->priv_data;
  1054. if (sc->time_scale) {
  1055. av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
  1056. return AVERROR_INVALIDDATA;
  1057. }
  1058. version = avio_r8(pb);
  1059. if (version > 1) {
  1060. avpriv_request_sample(c->fc, "Version %d", version);
  1061. return AVERROR_PATCHWELCOME;
  1062. }
  1063. avio_rb24(pb); /* flags */
  1064. if (version == 1) {
  1065. creation_time = avio_rb64(pb);
  1066. avio_rb64(pb);
  1067. } else {
  1068. creation_time = avio_rb32(pb);
  1069. avio_rb32(pb); /* modification time */
  1070. }
  1071. mov_metadata_creation_time(&st->metadata, creation_time);
  1072. sc->time_scale = avio_rb32(pb);
  1073. if (sc->time_scale <= 0) {
  1074. av_log(c->fc, AV_LOG_ERROR, "Invalid mdhd time scale %d\n", sc->time_scale);
  1075. return AVERROR_INVALIDDATA;
  1076. }
  1077. st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
  1078. lang = avio_rb16(pb); /* language */
  1079. if (ff_mov_lang_to_iso639(lang, language))
  1080. av_dict_set(&st->metadata, "language", language, 0);
  1081. avio_rb16(pb); /* quality */
  1082. return 0;
  1083. }
  1084. static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1085. {
  1086. int64_t creation_time;
  1087. int version = avio_r8(pb); /* version */
  1088. avio_rb24(pb); /* flags */
  1089. if (version == 1) {
  1090. creation_time = avio_rb64(pb);
  1091. avio_rb64(pb);
  1092. } else {
  1093. creation_time = avio_rb32(pb);
  1094. avio_rb32(pb); /* modification time */
  1095. }
  1096. mov_metadata_creation_time(&c->fc->metadata, creation_time);
  1097. c->time_scale = avio_rb32(pb); /* time scale */
  1098. if (c->time_scale <= 0) {
  1099. av_log(c->fc, AV_LOG_ERROR, "Invalid mvhd time scale %d\n", c->time_scale);
  1100. return AVERROR_INVALIDDATA;
  1101. }
  1102. av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
  1103. c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
  1104. // set the AVCodecContext duration because the duration of individual tracks
  1105. // may be inaccurate
  1106. if (c->time_scale > 0 && !c->trex_data)
  1107. c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
  1108. avio_rb32(pb); /* preferred scale */
  1109. avio_rb16(pb); /* preferred volume */
  1110. avio_skip(pb, 10); /* reserved */
  1111. avio_skip(pb, 36); /* display matrix */
  1112. avio_rb32(pb); /* preview time */
  1113. avio_rb32(pb); /* preview duration */
  1114. avio_rb32(pb); /* poster time */
  1115. avio_rb32(pb); /* selection time */
  1116. avio_rb32(pb); /* selection duration */
  1117. avio_rb32(pb); /* current time */
  1118. avio_rb32(pb); /* next track ID */
  1119. return 0;
  1120. }
  1121. static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1122. {
  1123. AVStream *st;
  1124. int little_endian;
  1125. if (c->fc->nb_streams < 1)
  1126. return 0;
  1127. st = c->fc->streams[c->fc->nb_streams-1];
  1128. little_endian = avio_rb16(pb) & 0xFF;
  1129. av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
  1130. if (little_endian == 1) {
  1131. switch (st->codecpar->codec_id) {
  1132. case AV_CODEC_ID_PCM_S24BE:
  1133. st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE;
  1134. break;
  1135. case AV_CODEC_ID_PCM_S32BE:
  1136. st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
  1137. break;
  1138. case AV_CODEC_ID_PCM_F32BE:
  1139. st->codecpar->codec_id = AV_CODEC_ID_PCM_F32LE;
  1140. break;
  1141. case AV_CODEC_ID_PCM_F64BE:
  1142. st->codecpar->codec_id = AV_CODEC_ID_PCM_F64LE;
  1143. break;
  1144. default:
  1145. break;
  1146. }
  1147. }
  1148. return 0;
  1149. }
  1150. static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1151. {
  1152. AVStream *st;
  1153. char color_parameter_type[5] = { 0 };
  1154. uint16_t color_primaries, color_trc, color_matrix;
  1155. int ret;
  1156. if (c->fc->nb_streams < 1)
  1157. return 0;
  1158. st = c->fc->streams[c->fc->nb_streams - 1];
  1159. ret = ffio_read_size(pb, color_parameter_type, 4);
  1160. if (ret < 0)
  1161. return ret;
  1162. if (strncmp(color_parameter_type, "nclx", 4) &&
  1163. strncmp(color_parameter_type, "nclc", 4)) {
  1164. av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
  1165. color_parameter_type);
  1166. return 0;
  1167. }
  1168. color_primaries = avio_rb16(pb);
  1169. color_trc = avio_rb16(pb);
  1170. color_matrix = avio_rb16(pb);
  1171. av_log(c->fc, AV_LOG_TRACE,
  1172. "%s: pri %d trc %d matrix %d",
  1173. color_parameter_type, color_primaries, color_trc, color_matrix);
  1174. if (!strncmp(color_parameter_type, "nclx", 4)) {
  1175. uint8_t color_range = avio_r8(pb) >> 7;
  1176. av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
  1177. if (color_range)
  1178. st->codecpar->color_range = AVCOL_RANGE_JPEG;
  1179. else
  1180. st->codecpar->color_range = AVCOL_RANGE_MPEG;
  1181. }
  1182. if (color_primaries >= AVCOL_PRI_NB)
  1183. color_primaries = AVCOL_PRI_UNSPECIFIED;
  1184. if (color_trc >= AVCOL_TRC_NB)
  1185. color_trc = AVCOL_TRC_UNSPECIFIED;
  1186. if (color_matrix >= AVCOL_SPC_NB)
  1187. color_matrix = AVCOL_SPC_UNSPECIFIED;
  1188. st->codecpar->color_primaries = color_primaries;
  1189. st->codecpar->color_trc = color_trc;
  1190. st->codecpar->color_space = color_matrix;
  1191. av_log(c->fc, AV_LOG_TRACE, "\n");
  1192. return 0;
  1193. }
  1194. static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1195. {
  1196. AVStream *st;
  1197. unsigned mov_field_order;
  1198. enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
  1199. if (c->fc->nb_streams < 1) // will happen with jp2 files
  1200. return 0;
  1201. st = c->fc->streams[c->fc->nb_streams-1];
  1202. if (atom.size < 2)
  1203. return AVERROR_INVALIDDATA;
  1204. mov_field_order = avio_rb16(pb);
  1205. if ((mov_field_order & 0xFF00) == 0x0100)
  1206. decoded_field_order = AV_FIELD_PROGRESSIVE;
  1207. else if ((mov_field_order & 0xFF00) == 0x0200) {
  1208. switch (mov_field_order & 0xFF) {
  1209. case 0x01: decoded_field_order = AV_FIELD_TT;
  1210. break;
  1211. case 0x06: decoded_field_order = AV_FIELD_BB;
  1212. break;
  1213. case 0x09: decoded_field_order = AV_FIELD_TB;
  1214. break;
  1215. case 0x0E: decoded_field_order = AV_FIELD_BT;
  1216. break;
  1217. }
  1218. }
  1219. if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
  1220. av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
  1221. }
  1222. st->codecpar->field_order = decoded_field_order;
  1223. return 0;
  1224. }
  1225. static int mov_realloc_extradata(AVCodecParameters *par, MOVAtom atom)
  1226. {
  1227. int err = 0;
  1228. uint64_t size = (uint64_t)par->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
  1229. if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
  1230. return AVERROR_INVALIDDATA;
  1231. if ((err = av_reallocp(&par->extradata, size)) < 0) {
  1232. par->extradata_size = 0;
  1233. return err;
  1234. }
  1235. par->extradata_size = size - AV_INPUT_BUFFER_PADDING_SIZE;
  1236. return 0;
  1237. }
  1238. /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
  1239. static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
  1240. AVCodecParameters *par, uint8_t *buf)
  1241. {
  1242. int64_t result = atom.size;
  1243. int err;
  1244. AV_WB32(buf , atom.size + 8);
  1245. AV_WL32(buf + 4, atom.type);
  1246. err = ffio_read_size(pb, buf + 8, atom.size);
  1247. if (err < 0) {
  1248. par->extradata_size -= atom.size;
  1249. return err;
  1250. } else if (err < atom.size) {
  1251. av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
  1252. par->extradata_size -= atom.size - err;
  1253. result = err;
  1254. }
  1255. memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  1256. return result;
  1257. }
  1258. /* FIXME modify QDM2/SVQ3/H.264 decoders to take full atom as extradata */
  1259. static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
  1260. enum AVCodecID codec_id)
  1261. {
  1262. AVStream *st;
  1263. uint64_t original_size;
  1264. int err;
  1265. if (c->fc->nb_streams < 1) // will happen with jp2 files
  1266. return 0;
  1267. st = c->fc->streams[c->fc->nb_streams-1];
  1268. if (st->codecpar->codec_id != codec_id)
  1269. return 0; /* unexpected codec_id - don't mess with extradata */
  1270. original_size = st->codecpar->extradata_size;
  1271. err = mov_realloc_extradata(st->codecpar, atom);
  1272. if (err)
  1273. return err;
  1274. err = mov_read_atom_into_extradata(c, pb, atom, st->codecpar, st->codecpar->extradata + original_size);
  1275. if (err < 0)
  1276. return err;
  1277. return 0; // Note: this is the original behavior to ignore truncation.
  1278. }
  1279. /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
  1280. static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1281. {
  1282. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
  1283. }
  1284. static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1285. {
  1286. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
  1287. }
  1288. static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1289. {
  1290. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
  1291. }
  1292. static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1293. {
  1294. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
  1295. }
  1296. static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1297. {
  1298. int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
  1299. if(ret == 0)
  1300. ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
  1301. return ret;
  1302. }
  1303. static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1304. {
  1305. int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
  1306. if (!ret && c->fc->nb_streams >= 1) {
  1307. AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
  1308. if (par->extradata_size >= 40) {
  1309. par->height = AV_RB16(&par->extradata[36]);
  1310. par->width = AV_RB16(&par->extradata[38]);
  1311. }
  1312. }
  1313. return ret;
  1314. }
  1315. static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1316. {
  1317. if (c->fc->nb_streams >= 1) {
  1318. AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
  1319. if (par->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
  1320. par->codec_id == AV_CODEC_ID_H264 &&
  1321. atom.size > 11) {
  1322. int cid;
  1323. avio_skip(pb, 10);
  1324. cid = avio_rb16(pb);
  1325. /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
  1326. if (cid == 0xd4d || cid == 0xd4e)
  1327. par->width = 1440;
  1328. return 0;
  1329. } else if ((par->codec_tag == MKTAG('A', 'V', 'd', '1') ||
  1330. par->codec_tag == MKTAG('A', 'V', 'd', 'n')) &&
  1331. atom.size >= 24) {
  1332. int num, den;
  1333. avio_skip(pb, 12);
  1334. num = avio_rb32(pb);
  1335. den = avio_rb32(pb);
  1336. if (num <= 0 || den <= 0)
  1337. return 0;
  1338. switch (avio_rb32(pb)) {
  1339. case 2:
  1340. if (den >= INT_MAX / 2)
  1341. return 0;
  1342. den *= 2;
  1343. case 1:
  1344. c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.num = num;
  1345. c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.den = den;
  1346. default:
  1347. return 0;
  1348. }
  1349. }
  1350. }
  1351. return mov_read_avid(c, pb, atom);
  1352. }
  1353. static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1354. {
  1355. int ret = 0;
  1356. int length = 0;
  1357. uint64_t original_size;
  1358. if (c->fc->nb_streams >= 1) {
  1359. AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
  1360. if (par->codec_id == AV_CODEC_ID_H264)
  1361. return 0;
  1362. if (atom.size == 16) {
  1363. original_size = par->extradata_size;
  1364. ret = mov_realloc_extradata(par, atom);
  1365. if (!ret) {
  1366. length = mov_read_atom_into_extradata(c, pb, atom, par, par->extradata + original_size);
  1367. if (length == atom.size) {
  1368. const uint8_t range_value = par->extradata[original_size + 19];
  1369. switch (range_value) {
  1370. case 1:
  1371. par->color_range = AVCOL_RANGE_MPEG;
  1372. break;
  1373. case 2:
  1374. par->color_range = AVCOL_RANGE_JPEG;
  1375. break;
  1376. default:
  1377. av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
  1378. break;
  1379. }
  1380. ff_dlog(c, "color_range: %d\n", par->color_range);
  1381. } else {
  1382. /* For some reason the whole atom was not added to the extradata */
  1383. av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
  1384. }
  1385. } else {
  1386. av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
  1387. }
  1388. } else {
  1389. av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
  1390. }
  1391. }
  1392. return ret;
  1393. }
  1394. static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1395. {
  1396. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
  1397. }
  1398. static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1399. {
  1400. AVStream *st;
  1401. int ret;
  1402. if (c->fc->nb_streams < 1)
  1403. return 0;
  1404. st = c->fc->streams[c->fc->nb_streams-1];
  1405. if ((uint64_t)atom.size > (1<<30))
  1406. return AVERROR_INVALIDDATA;
  1407. if (st->codecpar->codec_id == AV_CODEC_ID_QDM2 ||
  1408. st->codecpar->codec_id == AV_CODEC_ID_QDMC ||
  1409. st->codecpar->codec_id == AV_CODEC_ID_SPEEX) {
  1410. // pass all frma atom to codec, needed at least for QDMC and QDM2
  1411. av_freep(&st->codecpar->extradata);
  1412. ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
  1413. if (ret < 0)
  1414. return ret;
  1415. } else if (atom.size > 8) { /* to read frma, esds atoms */
  1416. if (st->codecpar->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) {
  1417. uint64_t buffer;
  1418. ret = ffio_ensure_seekback(pb, 8);
  1419. if (ret < 0)
  1420. return ret;
  1421. buffer = avio_rb64(pb);
  1422. atom.size -= 8;
  1423. if ( (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a')
  1424. && buffer >> 32 <= atom.size
  1425. && buffer >> 32 >= 8) {
  1426. avio_skip(pb, -8);
  1427. atom.size += 8;
  1428. } else if (!st->codecpar->extradata_size) {
  1429. #define ALAC_EXTRADATA_SIZE 36
  1430. st->codecpar->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
  1431. if (!st->codecpar->extradata)
  1432. return AVERROR(ENOMEM);
  1433. st->codecpar->extradata_size = ALAC_EXTRADATA_SIZE;
  1434. AV_WB32(st->codecpar->extradata , ALAC_EXTRADATA_SIZE);
  1435. AV_WB32(st->codecpar->extradata + 4, MKTAG('a','l','a','c'));
  1436. AV_WB64(st->codecpar->extradata + 12, buffer);
  1437. avio_read(pb, st->codecpar->extradata + 20, 16);
  1438. avio_skip(pb, atom.size - 24);
  1439. return 0;
  1440. }
  1441. }
  1442. if ((ret = mov_read_default(c, pb, atom)) < 0)
  1443. return ret;
  1444. } else
  1445. avio_skip(pb, atom.size);
  1446. return 0;
  1447. }
  1448. /**
  1449. * This function reads atom content and puts data in extradata without tag
  1450. * nor size unlike mov_read_extradata.
  1451. */
  1452. static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1453. {
  1454. AVStream *st;
  1455. int ret;
  1456. if (c->fc->nb_streams < 1)
  1457. return 0;
  1458. st = c->fc->streams[c->fc->nb_streams-1];
  1459. if ((uint64_t)atom.size > (1<<30))
  1460. return AVERROR_INVALIDDATA;
  1461. if (atom.size >= 10) {
  1462. // Broken files created by legacy versions of libavformat will
  1463. // wrap a whole fiel atom inside of a glbl atom.
  1464. unsigned size = avio_rb32(pb);
  1465. unsigned type = avio_rl32(pb);
  1466. avio_seek(pb, -8, SEEK_CUR);
  1467. if (type == MKTAG('f','i','e','l') && size == atom.size)
  1468. return mov_read_default(c, pb, atom);
  1469. }
  1470. if (st->codecpar->extradata_size > 1 && st->codecpar->extradata) {
  1471. av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
  1472. return 0;
  1473. }
  1474. av_freep(&st->codecpar->extradata);
  1475. ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
  1476. if (ret < 0)
  1477. return ret;
  1478. return 0;
  1479. }
  1480. static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1481. {
  1482. AVStream *st;
  1483. uint8_t profile_level;
  1484. int ret;
  1485. if (c->fc->nb_streams < 1)
  1486. return 0;
  1487. st = c->fc->streams[c->fc->nb_streams-1];
  1488. if (atom.size >= (1<<28) || atom.size < 7)
  1489. return AVERROR_INVALIDDATA;
  1490. profile_level = avio_r8(pb);
  1491. if ((profile_level & 0xf0) != 0xc0)
  1492. return 0;
  1493. avio_seek(pb, 6, SEEK_CUR);
  1494. av_freep(&st->codecpar->extradata);
  1495. ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 7);
  1496. if (ret < 0)
  1497. return ret;
  1498. return 0;
  1499. }
  1500. /**
  1501. * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
  1502. * but can have extradata appended at the end after the 40 bytes belonging
  1503. * to the struct.
  1504. */
  1505. static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1506. {
  1507. AVStream *st;
  1508. int ret;
  1509. if (c->fc->nb_streams < 1)
  1510. return 0;
  1511. if (atom.size <= 40)
  1512. return 0;
  1513. st = c->fc->streams[c->fc->nb_streams-1];
  1514. if ((uint64_t)atom.size > (1<<30))
  1515. return AVERROR_INVALIDDATA;
  1516. avio_skip(pb, 40);
  1517. av_freep(&st->codecpar->extradata);
  1518. ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 40);
  1519. if (ret < 0)
  1520. return ret;
  1521. return 0;
  1522. }
  1523. static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1524. {
  1525. AVStream *st;
  1526. MOVStreamContext *sc;
  1527. unsigned int i, entries;
  1528. if (c->fc->nb_streams < 1)
  1529. return 0;
  1530. st = c->fc->streams[c->fc->nb_streams-1];
  1531. sc = st->priv_data;
  1532. avio_r8(pb); /* version */
  1533. avio_rb24(pb); /* flags */
  1534. entries = avio_rb32(pb);
  1535. if (!entries)
  1536. return 0;
  1537. if (sc->chunk_offsets)
  1538. av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
  1539. av_free(sc->chunk_offsets);
  1540. sc->chunk_count = 0;
  1541. sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
  1542. if (!sc->chunk_offsets)
  1543. return AVERROR(ENOMEM);
  1544. sc->chunk_count = entries;
  1545. if (atom.type == MKTAG('s','t','c','o'))
  1546. for (i = 0; i < entries && !pb->eof_reached; i++)
  1547. sc->chunk_offsets[i] = avio_rb32(pb);
  1548. else if (atom.type == MKTAG('c','o','6','4'))
  1549. for (i = 0; i < entries && !pb->eof_reached; i++)
  1550. sc->chunk_offsets[i] = avio_rb64(pb);
  1551. else
  1552. return AVERROR_INVALIDDATA;
  1553. sc->chunk_count = i;
  1554. if (pb->eof_reached)
  1555. return AVERROR_EOF;
  1556. return 0;
  1557. }
  1558. /**
  1559. * Compute codec id for 'lpcm' tag.
  1560. * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
  1561. */
  1562. enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
  1563. {
  1564. /* lpcm flags:
  1565. * 0x1 = float
  1566. * 0x2 = big-endian
  1567. * 0x4 = signed
  1568. */
  1569. return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
  1570. }
  1571. static int mov_codec_id(AVStream *st, uint32_t format)
  1572. {
  1573. int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
  1574. if (id <= 0 &&
  1575. ((format & 0xFFFF) == 'm' + ('s' << 8) ||
  1576. (format & 0xFFFF) == 'T' + ('S' << 8)))
  1577. id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
  1578. if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
  1579. st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  1580. } else if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO &&
  1581. /* skip old ASF MPEG-4 tag */
  1582. format && format != MKTAG('m','p','4','s')) {
  1583. id = ff_codec_get_id(ff_codec_movvideo_tags, format);
  1584. if (id <= 0)
  1585. id = ff_codec_get_id(ff_codec_bmp_tags, format);
  1586. if (id > 0)
  1587. st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
  1588. else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA ||
  1589. (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE &&
  1590. st->codecpar->codec_id == AV_CODEC_ID_NONE)) {
  1591. id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
  1592. if (id > 0)
  1593. st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1594. }
  1595. }
  1596. st->codecpar->codec_tag = format;
  1597. return id;
  1598. }
  1599. static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
  1600. AVStream *st, MOVStreamContext *sc)
  1601. {
  1602. uint8_t codec_name[32];
  1603. int64_t stsd_start;
  1604. unsigned int len;
  1605. /* The first 16 bytes of the video sample description are already
  1606. * read in ff_mov_read_stsd_entries() */
  1607. stsd_start = avio_tell(pb) - 16;
  1608. avio_rb16(pb); /* version */
  1609. avio_rb16(pb); /* revision level */
  1610. avio_rb32(pb); /* vendor */
  1611. avio_rb32(pb); /* temporal quality */
  1612. avio_rb32(pb); /* spatial quality */
  1613. st->codecpar->width = avio_rb16(pb); /* width */
  1614. st->codecpar->height = avio_rb16(pb); /* height */
  1615. avio_rb32(pb); /* horiz resolution */
  1616. avio_rb32(pb); /* vert resolution */
  1617. avio_rb32(pb); /* data size, always 0 */
  1618. avio_rb16(pb); /* frames per samples */
  1619. len = avio_r8(pb); /* codec name, pascal string */
  1620. if (len > 31)
  1621. len = 31;
  1622. mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
  1623. if (len < 31)
  1624. avio_skip(pb, 31 - len);
  1625. if (codec_name[0])
  1626. av_dict_set(&st->metadata, "encoder", codec_name, 0);
  1627. /* codec_tag YV12 triggers an UV swap in rawdec.c */
  1628. if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
  1629. st->codecpar->codec_tag = MKTAG('I', '4', '2', '0');
  1630. st->codecpar->width &= ~1;
  1631. st->codecpar->height &= ~1;
  1632. }
  1633. /* Flash Media Server uses tag H.263 with Sorenson Spark */
  1634. if (st->codecpar->codec_tag == MKTAG('H','2','6','3') &&
  1635. !memcmp(codec_name, "Sorenson H263", 13))
  1636. st->codecpar->codec_id = AV_CODEC_ID_FLV1;
  1637. st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* depth */
  1638. avio_seek(pb, stsd_start, SEEK_SET);
  1639. if (ff_get_qtpalette(st->codecpar->codec_id, pb, sc->palette)) {
  1640. st->codecpar->bits_per_coded_sample &= 0x1F;
  1641. sc->has_palette = 1;
  1642. }
  1643. }
  1644. static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
  1645. AVStream *st, MOVStreamContext *sc)
  1646. {
  1647. int bits_per_sample, flags;
  1648. uint16_t version = avio_rb16(pb);
  1649. AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
  1650. avio_rb16(pb); /* revision level */
  1651. avio_rb32(pb); /* vendor */
  1652. st->codecpar->channels = avio_rb16(pb); /* channel count */
  1653. st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* sample size */
  1654. av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codecpar->channels);
  1655. sc->audio_cid = avio_rb16(pb);
  1656. avio_rb16(pb); /* packet size = 0 */
  1657. st->codecpar->sample_rate = ((avio_rb32(pb) >> 16));
  1658. // Read QT version 1 fields. In version 0 these do not exist.
  1659. av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
  1660. if (!c->isom ||
  1661. (compatible_brands && strstr(compatible_brands->value, "qt "))) {
  1662. if (version == 1) {
  1663. sc->samples_per_frame = avio_rb32(pb);
  1664. avio_rb32(pb); /* bytes per packet */
  1665. sc->bytes_per_frame = avio_rb32(pb);
  1666. avio_rb32(pb); /* bytes per sample */
  1667. } else if (version == 2) {
  1668. avio_rb32(pb); /* sizeof struct only */
  1669. st->codecpar->sample_rate = av_int2double(avio_rb64(pb));
  1670. st->codecpar->channels = avio_rb32(pb);
  1671. avio_rb32(pb); /* always 0x7F000000 */
  1672. st->codecpar->bits_per_coded_sample = avio_rb32(pb);
  1673. flags = avio_rb32(pb); /* lpcm format specific flag */
  1674. sc->bytes_per_frame = avio_rb32(pb);
  1675. sc->samples_per_frame = avio_rb32(pb);
  1676. if (st->codecpar->codec_tag == MKTAG('l','p','c','m'))
  1677. st->codecpar->codec_id =
  1678. ff_mov_get_lpcm_codec_id(st->codecpar->bits_per_coded_sample,
  1679. flags);
  1680. }
  1681. if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
  1682. /* can't correctly handle variable sized packet as audio unit */
  1683. switch (st->codecpar->codec_id) {
  1684. case AV_CODEC_ID_MP2:
  1685. case AV_CODEC_ID_MP3:
  1686. st->need_parsing = AVSTREAM_PARSE_FULL;
  1687. break;
  1688. }
  1689. }
  1690. }
  1691. if (sc->format == 0) {
  1692. if (st->codecpar->bits_per_coded_sample == 8)
  1693. st->codecpar->codec_id = mov_codec_id(st, MKTAG('r','a','w',' '));
  1694. else if (st->codecpar->bits_per_coded_sample == 16)
  1695. st->codecpar->codec_id = mov_codec_id(st, MKTAG('t','w','o','s'));
  1696. }
  1697. switch (st->codecpar->codec_id) {
  1698. case AV_CODEC_ID_PCM_S8:
  1699. case AV_CODEC_ID_PCM_U8:
  1700. if (st->codecpar->bits_per_coded_sample == 16)
  1701. st->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE;
  1702. break;
  1703. case AV_CODEC_ID_PCM_S16LE:
  1704. case AV_CODEC_ID_PCM_S16BE:
  1705. if (st->codecpar->bits_per_coded_sample == 8)
  1706. st->codecpar->codec_id = AV_CODEC_ID_PCM_S8;
  1707. else if (st->codecpar->bits_per_coded_sample == 24)
  1708. st->codecpar->codec_id =
  1709. st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
  1710. AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
  1711. else if (st->codecpar->bits_per_coded_sample == 32)
  1712. st->codecpar->codec_id =
  1713. st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
  1714. AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
  1715. break;
  1716. /* set values for old format before stsd version 1 appeared */
  1717. case AV_CODEC_ID_MACE3:
  1718. sc->samples_per_frame = 6;
  1719. sc->bytes_per_frame = 2 * st->codecpar->channels;
  1720. break;
  1721. case AV_CODEC_ID_MACE6:
  1722. sc->samples_per_frame = 6;
  1723. sc->bytes_per_frame = 1 * st->codecpar->channels;
  1724. break;
  1725. case AV_CODEC_ID_ADPCM_IMA_QT:
  1726. sc->samples_per_frame = 64;
  1727. sc->bytes_per_frame = 34 * st->codecpar->channels;
  1728. break;
  1729. case AV_CODEC_ID_GSM:
  1730. sc->samples_per_frame = 160;
  1731. sc->bytes_per_frame = 33;
  1732. break;
  1733. default:
  1734. break;
  1735. }
  1736. bits_per_sample = av_get_bits_per_sample(st->codecpar->codec_id);
  1737. if (bits_per_sample) {
  1738. st->codecpar->bits_per_coded_sample = bits_per_sample;
  1739. sc->sample_size = (bits_per_sample >> 3) * st->codecpar->channels;
  1740. }
  1741. }
  1742. static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
  1743. AVStream *st, MOVStreamContext *sc,
  1744. int64_t size)
  1745. {
  1746. // ttxt stsd contains display flags, justification, background
  1747. // color, fonts, and default styles, so fake an atom to read it
  1748. MOVAtom fake_atom = { .size = size };
  1749. // mp4s contains a regular esds atom
  1750. if (st->codecpar->codec_tag != AV_RL32("mp4s"))
  1751. mov_read_glbl(c, pb, fake_atom);
  1752. st->codecpar->width = sc->width;
  1753. st->codecpar->height = sc->height;
  1754. }
  1755. static uint32_t yuv_to_rgba(uint32_t ycbcr)
  1756. {
  1757. uint8_t r, g, b;
  1758. int y, cb, cr;
  1759. y = (ycbcr >> 16) & 0xFF;
  1760. cr = (ycbcr >> 8) & 0xFF;
  1761. cb = ycbcr & 0xFF;
  1762. b = av_clip_uint8((1164 * (y - 16) + 2018 * (cb - 128)) / 1000);
  1763. g = av_clip_uint8((1164 * (y - 16) - 813 * (cr - 128) - 391 * (cb - 128)) / 1000);
  1764. r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128) ) / 1000);
  1765. return (r << 16) | (g << 8) | b;
  1766. }
  1767. static int mov_rewrite_dvd_sub_extradata(AVStream *st)
  1768. {
  1769. char buf[256] = {0};
  1770. uint8_t *src = st->codecpar->extradata;
  1771. int i;
  1772. if (st->codecpar->extradata_size != 64)
  1773. return 0;
  1774. if (st->codecpar->width > 0 && st->codecpar->height > 0)
  1775. snprintf(buf, sizeof(buf), "size: %dx%d\n",
  1776. st->codecpar->width, st->codecpar->height);
  1777. av_strlcat(buf, "palette: ", sizeof(buf));
  1778. for (i = 0; i < 16; i++) {
  1779. uint32_t yuv = AV_RB32(src + i * 4);
  1780. uint32_t rgba = yuv_to_rgba(yuv);
  1781. av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
  1782. }
  1783. if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
  1784. return 0;
  1785. av_freep(&st->codecpar->extradata);
  1786. st->codecpar->extradata_size = 0;
  1787. st->codecpar->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE);
  1788. if (!st->codecpar->extradata)
  1789. return AVERROR(ENOMEM);
  1790. st->codecpar->extradata_size = strlen(buf);
  1791. memcpy(st->codecpar->extradata, buf, st->codecpar->extradata_size);
  1792. return 0;
  1793. }
  1794. static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
  1795. AVStream *st, MOVStreamContext *sc,
  1796. int64_t size)
  1797. {
  1798. int ret;
  1799. if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
  1800. if ((int)size != size)
  1801. return AVERROR(ENOMEM);
  1802. ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
  1803. if (ret < 0)
  1804. return ret;
  1805. if (size > 16) {
  1806. MOVStreamContext *tmcd_ctx = st->priv_data;
  1807. int val;
  1808. val = AV_RB32(st->codecpar->extradata + 4);
  1809. tmcd_ctx->tmcd_flags = val;
  1810. st->avg_frame_rate.num = st->codecpar->extradata[16]; /* number of frame */
  1811. st->avg_frame_rate.den = 1;
  1812. #if FF_API_LAVF_AVCTX
  1813. FF_DISABLE_DEPRECATION_WARNINGS
  1814. st->codec->time_base = av_inv_q(st->avg_frame_rate);
  1815. FF_ENABLE_DEPRECATION_WARNINGS
  1816. #endif
  1817. /* adjust for per frame dur in counter mode */
  1818. if (tmcd_ctx->tmcd_flags & 0x0008) {
  1819. int timescale = AV_RB32(st->codecpar->extradata + 8);
  1820. int framedur = AV_RB32(st->codecpar->extradata + 12);
  1821. st->avg_frame_rate.num *= timescale;
  1822. st->avg_frame_rate.den *= framedur;
  1823. #if FF_API_LAVF_AVCTX
  1824. FF_DISABLE_DEPRECATION_WARNINGS
  1825. st->codec->time_base.den *= timescale;
  1826. st->codec->time_base.num *= framedur;
  1827. FF_ENABLE_DEPRECATION_WARNINGS
  1828. #endif
  1829. }
  1830. if (size > 30) {
  1831. uint32_t len = AV_RB32(st->codecpar->extradata + 18); /* name atom length */
  1832. uint32_t format = AV_RB32(st->codecpar->extradata + 22);
  1833. if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
  1834. uint16_t str_size = AV_RB16(st->codecpar->extradata + 26); /* string length */
  1835. if (str_size > 0 && size >= (int)str_size + 26) {
  1836. char *reel_name = av_malloc(str_size + 1);
  1837. if (!reel_name)
  1838. return AVERROR(ENOMEM);
  1839. memcpy(reel_name, st->codecpar->extradata + 30, str_size);
  1840. reel_name[str_size] = 0; /* Add null terminator */
  1841. /* don't add reel_name if emtpy string */
  1842. if (*reel_name == 0) {
  1843. av_free(reel_name);
  1844. } else {
  1845. av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL);
  1846. }
  1847. }
  1848. }
  1849. }
  1850. }
  1851. } else {
  1852. /* other codec type, just skip (rtp, mp4s ...) */
  1853. avio_skip(pb, size);
  1854. }
  1855. return 0;
  1856. }
  1857. static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
  1858. AVStream *st, MOVStreamContext *sc)
  1859. {
  1860. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
  1861. !st->codecpar->sample_rate && sc->time_scale > 1)
  1862. st->codecpar->sample_rate = sc->time_scale;
  1863. /* special codec parameters handling */
  1864. switch (st->codecpar->codec_id) {
  1865. #if CONFIG_DV_DEMUXER
  1866. case AV_CODEC_ID_DVAUDIO:
  1867. c->dv_fctx = avformat_alloc_context();
  1868. if (!c->dv_fctx) {
  1869. av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
  1870. return AVERROR(ENOMEM);
  1871. }
  1872. c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
  1873. if (!c->dv_demux) {
  1874. av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
  1875. return AVERROR(ENOMEM);
  1876. }
  1877. sc->dv_audio_container = 1;
  1878. st->codecpar->codec_id = AV_CODEC_ID_PCM_S16LE;
  1879. break;
  1880. #endif
  1881. /* no ifdef since parameters are always those */
  1882. case AV_CODEC_ID_QCELP:
  1883. st->codecpar->channels = 1;
  1884. // force sample rate for qcelp when not stored in mov
  1885. if (st->codecpar->codec_tag != MKTAG('Q','c','l','p'))
  1886. st->codecpar->sample_rate = 8000;
  1887. // FIXME: Why is the following needed for some files?
  1888. sc->samples_per_frame = 160;
  1889. if (!sc->bytes_per_frame)
  1890. sc->bytes_per_frame = 35;
  1891. break;
  1892. case AV_CODEC_ID_AMR_NB:
  1893. st->codecpar->channels = 1;
  1894. /* force sample rate for amr, stsd in 3gp does not store sample rate */
  1895. st->codecpar->sample_rate = 8000;
  1896. break;
  1897. case AV_CODEC_ID_AMR_WB:
  1898. st->codecpar->channels = 1;
  1899. st->codecpar->sample_rate = 16000;
  1900. break;
  1901. case AV_CODEC_ID_MP2:
  1902. case AV_CODEC_ID_MP3:
  1903. /* force type after stsd for m1a hdlr */
  1904. st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  1905. break;
  1906. case AV_CODEC_ID_GSM:
  1907. case AV_CODEC_ID_ADPCM_MS:
  1908. case AV_CODEC_ID_ADPCM_IMA_WAV:
  1909. case AV_CODEC_ID_ILBC:
  1910. case AV_CODEC_ID_MACE3:
  1911. case AV_CODEC_ID_MACE6:
  1912. case AV_CODEC_ID_QDM2:
  1913. st->codecpar->block_align = sc->bytes_per_frame;
  1914. break;
  1915. case AV_CODEC_ID_ALAC:
  1916. if (st->codecpar->extradata_size == 36) {
  1917. st->codecpar->channels = AV_RB8 (st->codecpar->extradata + 21);
  1918. st->codecpar->sample_rate = AV_RB32(st->codecpar->extradata + 32);
  1919. }
  1920. break;
  1921. case AV_CODEC_ID_AC3:
  1922. case AV_CODEC_ID_EAC3:
  1923. case AV_CODEC_ID_MPEG1VIDEO:
  1924. case AV_CODEC_ID_VC1:
  1925. case AV_CODEC_ID_VP9:
  1926. st->need_parsing = AVSTREAM_PARSE_FULL;
  1927. break;
  1928. default:
  1929. break;
  1930. }
  1931. return 0;
  1932. }
  1933. static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
  1934. int codec_tag, int format,
  1935. int64_t size)
  1936. {
  1937. int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
  1938. if (codec_tag &&
  1939. (codec_tag != format &&
  1940. // prores is allowed to have differing data format and codec tag
  1941. codec_tag != AV_RL32("apcn") && codec_tag != AV_RL32("apch") &&
  1942. (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
  1943. : codec_tag != MKTAG('j','p','e','g')))) {
  1944. /* Multiple fourcc, we skip JPEG. This is not correct, we should
  1945. * export it as a separate AVStream but this needs a few changes
  1946. * in the MOV demuxer, patch welcome. */
  1947. av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
  1948. avio_skip(pb, size);
  1949. return 1;
  1950. }
  1951. if ( codec_tag == AV_RL32("hvc1") ||
  1952. codec_tag == AV_RL32("hev1")
  1953. )
  1954. av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
  1955. return 0;
  1956. }
  1957. int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
  1958. {
  1959. AVStream *st;
  1960. MOVStreamContext *sc;
  1961. int pseudo_stream_id;
  1962. if (c->fc->nb_streams < 1)
  1963. return 0;
  1964. st = c->fc->streams[c->fc->nb_streams-1];
  1965. sc = st->priv_data;
  1966. for (pseudo_stream_id = 0;
  1967. pseudo_stream_id < entries && !pb->eof_reached;
  1968. pseudo_stream_id++) {
  1969. //Parsing Sample description table
  1970. enum AVCodecID id;
  1971. int ret, dref_id = 1;
  1972. MOVAtom a = { AV_RL32("stsd") };
  1973. int64_t start_pos = avio_tell(pb);
  1974. int64_t size = avio_rb32(pb); /* size */
  1975. uint32_t format = avio_rl32(pb); /* data format */
  1976. if (size >= 16) {
  1977. avio_rb32(pb); /* reserved */
  1978. avio_rb16(pb); /* reserved */
  1979. dref_id = avio_rb16(pb);
  1980. } else if (size <= 7) {
  1981. av_log(c->fc, AV_LOG_ERROR,
  1982. "invalid size %"PRId64" in stsd\n", size);
  1983. return AVERROR_INVALIDDATA;
  1984. }
  1985. if (mov_skip_multiple_stsd(c, pb, st->codecpar->codec_tag, format,
  1986. size - (avio_tell(pb) - start_pos)))
  1987. continue;
  1988. sc->pseudo_stream_id = st->codecpar->codec_tag ? -1 : pseudo_stream_id;
  1989. sc->dref_id= dref_id;
  1990. sc->format = format;
  1991. id = mov_codec_id(st, format);
  1992. av_log(c->fc, AV_LOG_TRACE,
  1993. "size=%"PRId64" 4CC= %c%c%c%c/0x%08x codec_type=%d\n", size,
  1994. (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
  1995. (format >> 24) & 0xff, format, st->codecpar->codec_type);
  1996. if (st->codecpar->codec_type==AVMEDIA_TYPE_VIDEO) {
  1997. st->codecpar->codec_id = id;
  1998. mov_parse_stsd_video(c, pb, st, sc);
  1999. } else if (st->codecpar->codec_type==AVMEDIA_TYPE_AUDIO) {
  2000. st->codecpar->codec_id = id;
  2001. mov_parse_stsd_audio(c, pb, st, sc);
  2002. if (st->codecpar->sample_rate < 0) {
  2003. av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
  2004. return AVERROR_INVALIDDATA;
  2005. }
  2006. } else if (st->codecpar->codec_type==AVMEDIA_TYPE_SUBTITLE){
  2007. st->codecpar->codec_id = id;
  2008. mov_parse_stsd_subtitle(c, pb, st, sc,
  2009. size - (avio_tell(pb) - start_pos));
  2010. } else {
  2011. ret = mov_parse_stsd_data(c, pb, st, sc,
  2012. size - (avio_tell(pb) - start_pos));
  2013. if (ret < 0)
  2014. return ret;
  2015. }
  2016. /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
  2017. a.size = size - (avio_tell(pb) - start_pos);
  2018. if (a.size > 8) {
  2019. if ((ret = mov_read_default(c, pb, a)) < 0)
  2020. return ret;
  2021. } else if (a.size > 0)
  2022. avio_skip(pb, a.size);
  2023. if (sc->extradata) {
  2024. int extra_size = st->codecpar->extradata_size;
  2025. /* Move the current stream extradata to the stream context one. */
  2026. sc->extradata_size[pseudo_stream_id] = extra_size;
  2027. sc->extradata[pseudo_stream_id] = av_malloc(extra_size + AV_INPUT_BUFFER_PADDING_SIZE);
  2028. if (!sc->extradata[pseudo_stream_id])
  2029. return AVERROR(ENOMEM);
  2030. memcpy(sc->extradata[pseudo_stream_id], st->codecpar->extradata, extra_size);
  2031. av_freep(&st->codecpar->extradata);
  2032. st->codecpar->extradata_size = 0;
  2033. }
  2034. }
  2035. if (pb->eof_reached)
  2036. return AVERROR_EOF;
  2037. return 0;
  2038. }
  2039. static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2040. {
  2041. AVStream *st;
  2042. MOVStreamContext *sc;
  2043. int ret;
  2044. int entries;
  2045. if (c->fc->nb_streams < 1)
  2046. return 0;
  2047. st = c->fc->streams[c->fc->nb_streams - 1];
  2048. sc = st->priv_data;
  2049. avio_r8(pb); /* version */
  2050. avio_rb24(pb); /* flags */
  2051. entries = avio_rb32(pb); /* entries */
  2052. if (entries <= 0) {
  2053. av_log(c->fc, AV_LOG_ERROR, "invalid STSD entries %d\n", entries);
  2054. return AVERROR_INVALIDDATA;
  2055. }
  2056. if (sc->extradata) {
  2057. av_log(c->fc, AV_LOG_ERROR, "Duplicate STSD\n");
  2058. return AVERROR_INVALIDDATA;
  2059. }
  2060. /* Prepare space for hosting multiple extradata. */
  2061. sc->extradata = av_mallocz_array(entries, sizeof(*sc->extradata));
  2062. sc->extradata_size = av_mallocz_array(entries, sizeof(*sc->extradata_size));
  2063. if (!sc->extradata_size || !sc->extradata) {
  2064. ret = AVERROR(ENOMEM);
  2065. goto fail;
  2066. }
  2067. ret = ff_mov_read_stsd_entries(c, pb, entries);
  2068. if (ret < 0)
  2069. return ret;
  2070. sc->stsd_count = entries;
  2071. /* Restore back the primary extradata. */
  2072. av_freep(&st->codecpar->extradata);
  2073. st->codecpar->extradata_size = sc->extradata_size[0];
  2074. if (sc->extradata_size[0]) {
  2075. st->codecpar->extradata = av_mallocz(sc->extradata_size[0] + AV_INPUT_BUFFER_PADDING_SIZE);
  2076. if (!st->codecpar->extradata)
  2077. return AVERROR(ENOMEM);
  2078. memcpy(st->codecpar->extradata, sc->extradata[0], sc->extradata_size[0]);
  2079. }
  2080. return mov_finalize_stsd_codec(c, pb, st, sc);
  2081. fail:
  2082. av_freep(&sc->extradata);
  2083. av_freep(&sc->extradata_size);
  2084. return ret;
  2085. }
  2086. static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2087. {
  2088. AVStream *st;
  2089. MOVStreamContext *sc;
  2090. unsigned int i, entries;
  2091. if (c->fc->nb_streams < 1)
  2092. return 0;
  2093. st = c->fc->streams[c->fc->nb_streams-1];
  2094. sc = st->priv_data;
  2095. avio_r8(pb); /* version */
  2096. avio_rb24(pb); /* flags */
  2097. entries = avio_rb32(pb);
  2098. av_log(c->fc, AV_LOG_TRACE, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
  2099. if (!entries)
  2100. return 0;
  2101. if (sc->stsc_data)
  2102. av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
  2103. av_free(sc->stsc_data);
  2104. sc->stsc_count = 0;
  2105. sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
  2106. if (!sc->stsc_data)
  2107. return AVERROR(ENOMEM);
  2108. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2109. sc->stsc_data[i].first = avio_rb32(pb);
  2110. sc->stsc_data[i].count = avio_rb32(pb);
  2111. sc->stsc_data[i].id = avio_rb32(pb);
  2112. }
  2113. sc->stsc_count = i;
  2114. if (pb->eof_reached)
  2115. return AVERROR_EOF;
  2116. return 0;
  2117. }
  2118. /* Compute the samples value for the stsc entry at the given index. */
  2119. static inline int mov_get_stsc_samples(MOVStreamContext *sc, int index)
  2120. {
  2121. int chunk_count;
  2122. if (index < sc->stsc_count - 1)
  2123. chunk_count = sc->stsc_data[index + 1].first - sc->stsc_data[index].first;
  2124. else
  2125. chunk_count = sc->chunk_count - (sc->stsc_data[index].first - 1);
  2126. return sc->stsc_data[index].count * chunk_count;
  2127. }
  2128. static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2129. {
  2130. AVStream *st;
  2131. MOVStreamContext *sc;
  2132. unsigned i, entries;
  2133. if (c->fc->nb_streams < 1)
  2134. return 0;
  2135. st = c->fc->streams[c->fc->nb_streams-1];
  2136. sc = st->priv_data;
  2137. avio_rb32(pb); // version + flags
  2138. entries = avio_rb32(pb);
  2139. if (sc->stps_data)
  2140. av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
  2141. av_free(sc->stps_data);
  2142. sc->stps_count = 0;
  2143. sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
  2144. if (!sc->stps_data)
  2145. return AVERROR(ENOMEM);
  2146. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2147. sc->stps_data[i] = avio_rb32(pb);
  2148. //av_log(c->fc, AV_LOG_TRACE, "stps %d\n", sc->stps_data[i]);
  2149. }
  2150. sc->stps_count = i;
  2151. if (pb->eof_reached)
  2152. return AVERROR_EOF;
  2153. return 0;
  2154. }
  2155. static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2156. {
  2157. AVStream *st;
  2158. MOVStreamContext *sc;
  2159. unsigned int i, entries;
  2160. if (c->fc->nb_streams < 1)
  2161. return 0;
  2162. st = c->fc->streams[c->fc->nb_streams-1];
  2163. sc = st->priv_data;
  2164. avio_r8(pb); /* version */
  2165. avio_rb24(pb); /* flags */
  2166. entries = avio_rb32(pb);
  2167. av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %d\n", entries);
  2168. if (!entries)
  2169. {
  2170. sc->keyframe_absent = 1;
  2171. if (!st->need_parsing && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  2172. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  2173. return 0;
  2174. }
  2175. if (sc->keyframes)
  2176. av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
  2177. if (entries >= UINT_MAX / sizeof(int))
  2178. return AVERROR_INVALIDDATA;
  2179. av_freep(&sc->keyframes);
  2180. sc->keyframe_count = 0;
  2181. sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
  2182. if (!sc->keyframes)
  2183. return AVERROR(ENOMEM);
  2184. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2185. sc->keyframes[i] = avio_rb32(pb);
  2186. //av_log(c->fc, AV_LOG_TRACE, "keyframes[]=%d\n", sc->keyframes[i]);
  2187. }
  2188. sc->keyframe_count = i;
  2189. if (pb->eof_reached)
  2190. return AVERROR_EOF;
  2191. return 0;
  2192. }
  2193. static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2194. {
  2195. AVStream *st;
  2196. MOVStreamContext *sc;
  2197. unsigned int i, entries, sample_size, field_size, num_bytes;
  2198. GetBitContext gb;
  2199. unsigned char* buf;
  2200. int ret;
  2201. if (c->fc->nb_streams < 1)
  2202. return 0;
  2203. st = c->fc->streams[c->fc->nb_streams-1];
  2204. sc = st->priv_data;
  2205. avio_r8(pb); /* version */
  2206. avio_rb24(pb); /* flags */
  2207. if (atom.type == MKTAG('s','t','s','z')) {
  2208. sample_size = avio_rb32(pb);
  2209. if (!sc->sample_size) /* do not overwrite value computed in stsd */
  2210. sc->sample_size = sample_size;
  2211. sc->stsz_sample_size = sample_size;
  2212. field_size = 32;
  2213. } else {
  2214. sample_size = 0;
  2215. avio_rb24(pb); /* reserved */
  2216. field_size = avio_r8(pb);
  2217. }
  2218. entries = avio_rb32(pb);
  2219. av_log(c->fc, AV_LOG_TRACE, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
  2220. sc->sample_count = entries;
  2221. if (sample_size)
  2222. return 0;
  2223. if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
  2224. av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
  2225. return AVERROR_INVALIDDATA;
  2226. }
  2227. if (!entries)
  2228. return 0;
  2229. if (entries >= (UINT_MAX - 4) / field_size)
  2230. return AVERROR_INVALIDDATA;
  2231. if (sc->sample_sizes)
  2232. av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
  2233. av_free(sc->sample_sizes);
  2234. sc->sample_count = 0;
  2235. sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
  2236. if (!sc->sample_sizes)
  2237. return AVERROR(ENOMEM);
  2238. num_bytes = (entries*field_size+4)>>3;
  2239. buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
  2240. if (!buf) {
  2241. av_freep(&sc->sample_sizes);
  2242. return AVERROR(ENOMEM);
  2243. }
  2244. ret = ffio_read_size(pb, buf, num_bytes);
  2245. if (ret < 0) {
  2246. av_freep(&sc->sample_sizes);
  2247. av_free(buf);
  2248. return ret;
  2249. }
  2250. init_get_bits(&gb, buf, 8*num_bytes);
  2251. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2252. sc->sample_sizes[i] = get_bits_long(&gb, field_size);
  2253. sc->data_size += sc->sample_sizes[i];
  2254. }
  2255. sc->sample_count = i;
  2256. av_free(buf);
  2257. if (pb->eof_reached)
  2258. return AVERROR_EOF;
  2259. return 0;
  2260. }
  2261. static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2262. {
  2263. AVStream *st;
  2264. MOVStreamContext *sc;
  2265. unsigned int i, entries;
  2266. int64_t duration=0;
  2267. int64_t total_sample_count=0;
  2268. if (c->fc->nb_streams < 1)
  2269. return 0;
  2270. st = c->fc->streams[c->fc->nb_streams-1];
  2271. sc = st->priv_data;
  2272. avio_r8(pb); /* version */
  2273. avio_rb24(pb); /* flags */
  2274. entries = avio_rb32(pb);
  2275. av_log(c->fc, AV_LOG_TRACE, "track[%i].stts.entries = %i\n",
  2276. c->fc->nb_streams-1, entries);
  2277. if (sc->stts_data)
  2278. av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
  2279. av_free(sc->stts_data);
  2280. sc->stts_count = 0;
  2281. sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data));
  2282. if (!sc->stts_data)
  2283. return AVERROR(ENOMEM);
  2284. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2285. int sample_duration;
  2286. int sample_count;
  2287. sample_count=avio_rb32(pb);
  2288. sample_duration = avio_rb32(pb);
  2289. if (sample_count < 0) {
  2290. av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
  2291. return AVERROR_INVALIDDATA;
  2292. }
  2293. sc->stts_data[i].count= sample_count;
  2294. sc->stts_data[i].duration= sample_duration;
  2295. av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
  2296. sample_count, sample_duration);
  2297. if ( i+1 == entries
  2298. && i
  2299. && sample_count == 1
  2300. && total_sample_count > 100
  2301. && sample_duration/10 > duration / total_sample_count)
  2302. sample_duration = duration / total_sample_count;
  2303. duration+=(int64_t)sample_duration*sample_count;
  2304. total_sample_count+=sample_count;
  2305. }
  2306. sc->stts_count = i;
  2307. sc->duration_for_fps += duration;
  2308. sc->nb_frames_for_fps += total_sample_count;
  2309. if (pb->eof_reached)
  2310. return AVERROR_EOF;
  2311. st->nb_frames= total_sample_count;
  2312. if (duration)
  2313. st->duration= duration;
  2314. sc->track_end = duration;
  2315. return 0;
  2316. }
  2317. static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
  2318. {
  2319. if (duration < 0) {
  2320. if (duration == INT_MIN) {
  2321. av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
  2322. duration++;
  2323. }
  2324. sc->dts_shift = FFMAX(sc->dts_shift, -duration);
  2325. }
  2326. }
  2327. static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2328. {
  2329. AVStream *st;
  2330. MOVStreamContext *sc;
  2331. unsigned int i, entries, ctts_count = 0;
  2332. if (c->fc->nb_streams < 1)
  2333. return 0;
  2334. st = c->fc->streams[c->fc->nb_streams-1];
  2335. sc = st->priv_data;
  2336. avio_r8(pb); /* version */
  2337. avio_rb24(pb); /* flags */
  2338. entries = avio_rb32(pb);
  2339. av_log(c->fc, AV_LOG_TRACE, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
  2340. if (!entries)
  2341. return 0;
  2342. if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
  2343. return AVERROR_INVALIDDATA;
  2344. av_freep(&sc->ctts_data);
  2345. sc->ctts_data = av_realloc(NULL, entries * sizeof(*sc->ctts_data));
  2346. if (!sc->ctts_data)
  2347. return AVERROR(ENOMEM);
  2348. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2349. int count =avio_rb32(pb);
  2350. int duration =avio_rb32(pb);
  2351. if (count <= 0) {
  2352. av_log(c->fc, AV_LOG_TRACE,
  2353. "ignoring CTTS entry with count=%d duration=%d\n",
  2354. count, duration);
  2355. continue;
  2356. }
  2357. sc->ctts_data[ctts_count].count = count;
  2358. sc->ctts_data[ctts_count].duration = duration;
  2359. ctts_count++;
  2360. av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
  2361. count, duration);
  2362. if (FFNABS(duration) < -(1<<28) && i+2<entries) {
  2363. av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
  2364. av_freep(&sc->ctts_data);
  2365. sc->ctts_count = 0;
  2366. return 0;
  2367. }
  2368. if (i+2<entries)
  2369. mov_update_dts_shift(sc, duration);
  2370. }
  2371. sc->ctts_count = ctts_count;
  2372. if (pb->eof_reached)
  2373. return AVERROR_EOF;
  2374. av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
  2375. return 0;
  2376. }
  2377. static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2378. {
  2379. AVStream *st;
  2380. MOVStreamContext *sc;
  2381. unsigned int i, entries;
  2382. uint8_t version;
  2383. uint32_t grouping_type;
  2384. if (c->fc->nb_streams < 1)
  2385. return 0;
  2386. st = c->fc->streams[c->fc->nb_streams-1];
  2387. sc = st->priv_data;
  2388. version = avio_r8(pb); /* version */
  2389. avio_rb24(pb); /* flags */
  2390. grouping_type = avio_rl32(pb);
  2391. if (grouping_type != MKTAG( 'r','a','p',' '))
  2392. return 0; /* only support 'rap ' grouping */
  2393. if (version == 1)
  2394. avio_rb32(pb); /* grouping_type_parameter */
  2395. entries = avio_rb32(pb);
  2396. if (!entries)
  2397. return 0;
  2398. if (sc->rap_group)
  2399. av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
  2400. av_free(sc->rap_group);
  2401. sc->rap_group_count = 0;
  2402. sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
  2403. if (!sc->rap_group)
  2404. return AVERROR(ENOMEM);
  2405. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2406. sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
  2407. sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
  2408. }
  2409. sc->rap_group_count = i;
  2410. return pb->eof_reached ? AVERROR_EOF : 0;
  2411. }
  2412. /**
  2413. * Get ith edit list entry (media time, duration).
  2414. */
  2415. static int get_edit_list_entry(MOVContext *mov,
  2416. const MOVStreamContext *msc,
  2417. unsigned int edit_list_index,
  2418. int64_t *edit_list_media_time,
  2419. int64_t *edit_list_duration,
  2420. int64_t global_timescale)
  2421. {
  2422. if (edit_list_index == msc->elst_count) {
  2423. return 0;
  2424. }
  2425. *edit_list_media_time = msc->elst_data[edit_list_index].time;
  2426. *edit_list_duration = msc->elst_data[edit_list_index].duration;
  2427. /* duration is in global timescale units;convert to msc timescale */
  2428. if (global_timescale == 0) {
  2429. avpriv_request_sample(mov->fc, "Support for mvhd.timescale = 0 with editlists");
  2430. return 0;
  2431. }
  2432. *edit_list_duration = av_rescale(*edit_list_duration, msc->time_scale,
  2433. global_timescale);
  2434. return 1;
  2435. }
  2436. /**
  2437. * Find the closest previous keyframe to the timestamp, in e_old index
  2438. * entries.
  2439. * Returns the index of the entry in st->index_entries if successful,
  2440. * else returns -1.
  2441. */
  2442. static int64_t find_prev_closest_keyframe_index(AVStream *st,
  2443. AVIndexEntry *e_old,
  2444. int nb_old,
  2445. int64_t timestamp,
  2446. int flag)
  2447. {
  2448. AVIndexEntry *e_keep = st->index_entries;
  2449. int nb_keep = st->nb_index_entries;
  2450. int64_t found = -1;
  2451. st->index_entries = e_old;
  2452. st->nb_index_entries = nb_old;
  2453. found = av_index_search_timestamp(st, timestamp, flag | AVSEEK_FLAG_BACKWARD);
  2454. /* restore AVStream state*/
  2455. st->index_entries = e_keep;
  2456. st->nb_index_entries = nb_keep;
  2457. return found;
  2458. }
  2459. /**
  2460. * Add index entry with the given values, to the end of st->index_entries.
  2461. * Returns the new size st->index_entries if successful, else returns -1.
  2462. *
  2463. * This function is similar to ff_add_index_entry in libavformat/utils.c
  2464. * except that here we are always unconditionally adding an index entry to
  2465. * the end, instead of searching the entries list and skipping the add if
  2466. * there is an existing entry with the same timestamp.
  2467. * This is needed because the mov_fix_index calls this func with the same
  2468. * unincremented timestamp for successive discarded frames.
  2469. */
  2470. static int64_t add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
  2471. int size, int distance, int flags)
  2472. {
  2473. AVIndexEntry *entries, *ie;
  2474. int64_t index = -1;
  2475. const size_t min_size_needed = (st->nb_index_entries + 1) * sizeof(AVIndexEntry);
  2476. // Double the allocation each time, to lower memory fragmentation.
  2477. // Another difference from ff_add_index_entry function.
  2478. const size_t requested_size =
  2479. min_size_needed > st->index_entries_allocated_size ?
  2480. FFMAX(min_size_needed, 2 * st->index_entries_allocated_size) :
  2481. min_size_needed;
  2482. if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
  2483. return -1;
  2484. entries = av_fast_realloc(st->index_entries,
  2485. &st->index_entries_allocated_size,
  2486. requested_size);
  2487. if(!entries)
  2488. return -1;
  2489. st->index_entries= entries;
  2490. index= st->nb_index_entries++;
  2491. ie= &entries[index];
  2492. ie->pos = pos;
  2493. ie->timestamp = timestamp;
  2494. ie->min_distance= distance;
  2495. ie->size= size;
  2496. ie->flags = flags;
  2497. return index;
  2498. }
  2499. /**
  2500. * Rewrite timestamps of index entries in the range [end_index - frame_duration_buffer_size, end_index)
  2501. * by subtracting end_ts successively by the amounts given in frame_duration_buffer.
  2502. */
  2503. static void fix_index_entry_timestamps(AVStream* st, int end_index, int64_t end_ts,
  2504. int64_t* frame_duration_buffer,
  2505. int frame_duration_buffer_size) {
  2506. int i = 0;
  2507. av_assert0(end_index >= 0 && end_index <= st->nb_index_entries);
  2508. for (i = 0; i < frame_duration_buffer_size; i++) {
  2509. end_ts -= frame_duration_buffer[frame_duration_buffer_size - 1 - i];
  2510. st->index_entries[end_index - 1 - i].timestamp = end_ts;
  2511. }
  2512. }
  2513. /**
  2514. * Append a new ctts entry to ctts_data.
  2515. * Returns the new ctts_count if successful, else returns -1.
  2516. */
  2517. static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size,
  2518. int count, int duration)
  2519. {
  2520. MOVStts *ctts_buf_new;
  2521. const size_t min_size_needed = (*ctts_count + 1) * sizeof(MOVStts);
  2522. const size_t requested_size =
  2523. min_size_needed > *allocated_size ?
  2524. FFMAX(min_size_needed, 2 * (*allocated_size)) :
  2525. min_size_needed;
  2526. if((unsigned)(*ctts_count) + 1 >= UINT_MAX / sizeof(MOVStts))
  2527. return -1;
  2528. ctts_buf_new = av_fast_realloc(*ctts_data, allocated_size, requested_size);
  2529. if(!ctts_buf_new)
  2530. return -1;
  2531. *ctts_data = ctts_buf_new;
  2532. ctts_buf_new[*ctts_count].count = count;
  2533. ctts_buf_new[*ctts_count].duration = duration;
  2534. *ctts_count = (*ctts_count) + 1;
  2535. return *ctts_count;
  2536. }
  2537. /**
  2538. * Fix st->index_entries, so that it contains only the entries (and the entries
  2539. * which are needed to decode them) that fall in the edit list time ranges.
  2540. * Also fixes the timestamps of the index entries to match the timeline
  2541. * specified the edit lists.
  2542. */
  2543. static void mov_fix_index(MOVContext *mov, AVStream *st)
  2544. {
  2545. MOVStreamContext *msc = st->priv_data;
  2546. AVIndexEntry *e_old = st->index_entries;
  2547. int nb_old = st->nb_index_entries;
  2548. const AVIndexEntry *e_old_end = e_old + nb_old;
  2549. const AVIndexEntry *current = NULL;
  2550. MOVStts *ctts_data_old = msc->ctts_data;
  2551. int64_t ctts_index_old = 0;
  2552. int64_t ctts_sample_old = 0;
  2553. int64_t ctts_count_old = msc->ctts_count;
  2554. int64_t edit_list_media_time = 0;
  2555. int64_t edit_list_duration = 0;
  2556. int64_t frame_duration = 0;
  2557. int64_t edit_list_dts_counter = 0;
  2558. int64_t edit_list_dts_entry_end = 0;
  2559. int64_t edit_list_start_ctts_sample = 0;
  2560. int64_t curr_cts;
  2561. int64_t edit_list_index = 0;
  2562. int64_t index;
  2563. int64_t index_ctts_count;
  2564. int flags;
  2565. unsigned int ctts_allocated_size = 0;
  2566. int64_t start_dts = 0;
  2567. int64_t edit_list_media_time_dts = 0;
  2568. int64_t edit_list_start_encountered = 0;
  2569. int64_t search_timestamp = 0;
  2570. int64_t* frame_duration_buffer = NULL;
  2571. int num_discarded_begin = 0;
  2572. int first_non_zero_audio_edit = -1;
  2573. int packet_skip_samples = 0;
  2574. if (!msc->elst_data || msc->elst_count <= 0 || nb_old <= 0) {
  2575. return;
  2576. }
  2577. // Clean AVStream from traces of old index
  2578. st->index_entries = NULL;
  2579. st->index_entries_allocated_size = 0;
  2580. st->nb_index_entries = 0;
  2581. // Clean ctts fields of MOVStreamContext
  2582. msc->ctts_data = NULL;
  2583. msc->ctts_count = 0;
  2584. msc->ctts_index = 0;
  2585. msc->ctts_sample = 0;
  2586. // If the dts_shift is positive (in case of negative ctts values in mov),
  2587. // then negate the DTS by dts_shift
  2588. if (msc->dts_shift > 0)
  2589. edit_list_dts_entry_end -= msc->dts_shift;
  2590. // Offset the DTS by ctts[0] to make the PTS of the first frame 0
  2591. if (ctts_data_old && ctts_count_old > 0) {
  2592. edit_list_dts_entry_end -= ctts_data_old[0].duration;
  2593. av_log(mov->fc, AV_LOG_DEBUG, "Offset DTS by ctts[%d].duration: %d\n", 0, ctts_data_old[0].duration);
  2594. }
  2595. start_dts = edit_list_dts_entry_end;
  2596. while (get_edit_list_entry(mov, msc, edit_list_index, &edit_list_media_time,
  2597. &edit_list_duration, mov->time_scale)) {
  2598. av_log(mov->fc, AV_LOG_DEBUG, "Processing st: %d, edit list %"PRId64" - media time: %"PRId64", duration: %"PRId64"\n",
  2599. st->index, edit_list_index, edit_list_media_time, edit_list_duration);
  2600. edit_list_index++;
  2601. edit_list_dts_counter = edit_list_dts_entry_end;
  2602. edit_list_dts_entry_end += edit_list_duration;
  2603. num_discarded_begin = 0;
  2604. if (edit_list_media_time == -1) {
  2605. continue;
  2606. }
  2607. // If we encounter a non-negative edit list reset the skip_samples/start_pad fields and set them
  2608. // according to the edit list below.
  2609. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  2610. if (first_non_zero_audio_edit < 0) {
  2611. first_non_zero_audio_edit = 1;
  2612. } else {
  2613. first_non_zero_audio_edit = 0;
  2614. }
  2615. if (first_non_zero_audio_edit > 0)
  2616. st->skip_samples = msc->start_pad = 0;
  2617. }
  2618. //find closest previous key frame
  2619. edit_list_media_time_dts = edit_list_media_time;
  2620. if (msc->dts_shift > 0) {
  2621. edit_list_media_time_dts -= msc->dts_shift;
  2622. }
  2623. // While reordering frame index according to edit list we must handle properly
  2624. // the scenario when edit list entry starts from none key frame.
  2625. // We find closest previous key frame and preserve it and consequent frames in index.
  2626. // All frames which are outside edit list entry time boundaries will be dropped after decoding.
  2627. search_timestamp = edit_list_media_time_dts;
  2628. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  2629. // Audio decoders like AAC need need a decoder delay samples previous to the current sample,
  2630. // to correctly decode this frame. Hence for audio we seek to a frame 1 sec. before the
  2631. // edit_list_media_time to cover the decoder delay.
  2632. search_timestamp = FFMAX(search_timestamp - msc->time_scale, e_old[0].timestamp);
  2633. }
  2634. index = find_prev_closest_keyframe_index(st, e_old, nb_old, search_timestamp, 0);
  2635. if (index == -1) {
  2636. av_log(mov->fc, AV_LOG_ERROR, "Missing key frame while reordering index according to edit list\n");
  2637. continue;
  2638. }
  2639. current = e_old + index;
  2640. ctts_index_old = 0;
  2641. ctts_sample_old = 0;
  2642. // set ctts_index properly for the found key frame
  2643. for (index_ctts_count = 0; index_ctts_count < index; index_ctts_count++) {
  2644. if (ctts_data_old && ctts_index_old < ctts_count_old) {
  2645. ctts_sample_old++;
  2646. if (ctts_data_old[ctts_index_old].count == ctts_sample_old) {
  2647. ctts_index_old++;
  2648. ctts_sample_old = 0;
  2649. }
  2650. }
  2651. }
  2652. edit_list_start_ctts_sample = ctts_sample_old;
  2653. // Iterate over index and arrange it according to edit list
  2654. edit_list_start_encountered = 0;
  2655. for (; current < e_old_end; current++, index++) {
  2656. // check if frame outside edit list mark it for discard
  2657. frame_duration = (current + 1 < e_old_end) ?
  2658. ((current + 1)->timestamp - current->timestamp) : edit_list_duration;
  2659. flags = current->flags;
  2660. // frames (pts) before or after edit list
  2661. curr_cts = current->timestamp + msc->dts_shift;
  2662. if (ctts_data_old && ctts_index_old < ctts_count_old) {
  2663. av_log(mov->fc, AV_LOG_DEBUG, "shifted frame pts, curr_cts: %"PRId64" @ %"PRId64", ctts: %d, ctts_count: %"PRId64"\n",
  2664. curr_cts, ctts_index_old, ctts_data_old[ctts_index_old].duration, ctts_count_old);
  2665. curr_cts += ctts_data_old[ctts_index_old].duration;
  2666. ctts_sample_old++;
  2667. if (ctts_sample_old == ctts_data_old[ctts_index_old].count) {
  2668. if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
  2669. &ctts_allocated_size,
  2670. ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
  2671. ctts_data_old[ctts_index_old].duration) == -1) {
  2672. av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
  2673. ctts_index_old,
  2674. ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
  2675. ctts_data_old[ctts_index_old].duration);
  2676. break;
  2677. }
  2678. ctts_index_old++;
  2679. ctts_sample_old = 0;
  2680. edit_list_start_ctts_sample = 0;
  2681. }
  2682. }
  2683. if (curr_cts < edit_list_media_time || curr_cts >= (edit_list_duration + edit_list_media_time)) {
  2684. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id != AV_CODEC_ID_VORBIS &&
  2685. curr_cts < edit_list_media_time && curr_cts + frame_duration > edit_list_media_time &&
  2686. first_non_zero_audio_edit > 0) {
  2687. packet_skip_samples = edit_list_media_time - curr_cts;
  2688. st->skip_samples += packet_skip_samples;
  2689. // Shift the index entry timestamp by packet_skip_samples to be correct.
  2690. edit_list_dts_counter -= packet_skip_samples;
  2691. if (edit_list_start_encountered == 0) {
  2692. edit_list_start_encountered = 1;
  2693. // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
  2694. // discarded packets.
  2695. if (frame_duration_buffer) {
  2696. fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
  2697. frame_duration_buffer, num_discarded_begin);
  2698. av_freep(&frame_duration_buffer);
  2699. }
  2700. }
  2701. av_log(mov->fc, AV_LOG_DEBUG, "skip %d audio samples from curr_cts: %"PRId64"\n", packet_skip_samples, curr_cts);
  2702. } else {
  2703. flags |= AVINDEX_DISCARD_FRAME;
  2704. av_log(mov->fc, AV_LOG_DEBUG, "drop a frame at curr_cts: %"PRId64" @ %"PRId64"\n", curr_cts, index);
  2705. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && edit_list_start_encountered == 0) {
  2706. num_discarded_begin++;
  2707. frame_duration_buffer = av_realloc(frame_duration_buffer,
  2708. num_discarded_begin * sizeof(int64_t));
  2709. if (!frame_duration_buffer) {
  2710. av_log(mov->fc, AV_LOG_ERROR, "Cannot reallocate frame duration buffer\n");
  2711. break;
  2712. }
  2713. frame_duration_buffer[num_discarded_begin - 1] = frame_duration;
  2714. // Increment skip_samples for the first non-zero audio edit list
  2715. if (first_non_zero_audio_edit > 0 && st->codecpar->codec_id != AV_CODEC_ID_VORBIS) {
  2716. st->skip_samples += frame_duration;
  2717. msc->start_pad = st->skip_samples;
  2718. }
  2719. }
  2720. }
  2721. } else if (edit_list_start_encountered == 0) {
  2722. edit_list_start_encountered = 1;
  2723. // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
  2724. // discarded packets.
  2725. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && frame_duration_buffer) {
  2726. fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
  2727. frame_duration_buffer, num_discarded_begin);
  2728. av_freep(&frame_duration_buffer);
  2729. }
  2730. }
  2731. if (add_index_entry(st, current->pos, edit_list_dts_counter, current->size,
  2732. current->min_distance, flags) == -1) {
  2733. av_log(mov->fc, AV_LOG_ERROR, "Cannot add index entry\n");
  2734. break;
  2735. }
  2736. // Only start incrementing DTS in frame_duration amounts, when we encounter a frame in edit list.
  2737. if (edit_list_start_encountered > 0) {
  2738. edit_list_dts_counter = edit_list_dts_counter + frame_duration;
  2739. }
  2740. // Break when found first key frame after edit entry completion
  2741. if (((curr_cts + frame_duration) >= (edit_list_duration + edit_list_media_time)) &&
  2742. ((flags & AVINDEX_KEYFRAME) || ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)))) {
  2743. if (ctts_data_old && ctts_sample_old != 0) {
  2744. if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
  2745. &ctts_allocated_size,
  2746. ctts_sample_old - edit_list_start_ctts_sample,
  2747. ctts_data_old[ctts_index_old].duration) == -1) {
  2748. av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
  2749. ctts_index_old, ctts_sample_old - edit_list_start_ctts_sample,
  2750. ctts_data_old[ctts_index_old].duration);
  2751. break;
  2752. }
  2753. }
  2754. break;
  2755. }
  2756. }
  2757. }
  2758. // Update av stream length
  2759. st->duration = edit_list_dts_entry_end - start_dts;
  2760. // Free the old index and the old CTTS structures
  2761. av_free(e_old);
  2762. av_free(ctts_data_old);
  2763. }
  2764. static void mov_build_index(MOVContext *mov, AVStream *st)
  2765. {
  2766. MOVStreamContext *sc = st->priv_data;
  2767. int64_t current_offset;
  2768. int64_t current_dts = 0;
  2769. unsigned int stts_index = 0;
  2770. unsigned int stsc_index = 0;
  2771. unsigned int stss_index = 0;
  2772. unsigned int stps_index = 0;
  2773. unsigned int i, j;
  2774. uint64_t stream_size = 0;
  2775. if (sc->elst_count) {
  2776. int i, edit_start_index = 0;
  2777. int64_t empty_duration = 0; // empty duration of the first edit list entry
  2778. int64_t start_time = 0; // start time of the media
  2779. for (i = 0; i < sc->elst_count; i++) {
  2780. const MOVElst *e = &sc->elst_data[i];
  2781. if (i == 0 && e->time == -1) {
  2782. /* if empty, the first entry is the start time of the stream
  2783. * relative to the presentation itself */
  2784. empty_duration = e->duration;
  2785. edit_start_index = 1;
  2786. } else if (i == edit_start_index && e->time >= 0) {
  2787. start_time = e->time;
  2788. }
  2789. }
  2790. /* adjust first dts according to edit list */
  2791. if ((empty_duration || start_time) && mov->time_scale > 0) {
  2792. if (empty_duration)
  2793. empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
  2794. sc->time_offset = start_time - empty_duration;
  2795. }
  2796. }
  2797. /* only use old uncompressed audio chunk demuxing when stts specifies it */
  2798. if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
  2799. sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
  2800. unsigned int current_sample = 0;
  2801. unsigned int stts_sample = 0;
  2802. unsigned int sample_size;
  2803. unsigned int distance = 0;
  2804. unsigned int rap_group_index = 0;
  2805. unsigned int rap_group_sample = 0;
  2806. int64_t last_dts = 0;
  2807. int64_t dts_correction = 0;
  2808. int rap_group_present = sc->rap_group_count && sc->rap_group;
  2809. int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
  2810. current_dts -= sc->dts_shift;
  2811. last_dts = current_dts;
  2812. if (!sc->sample_count || st->nb_index_entries)
  2813. return;
  2814. if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  2815. return;
  2816. if (av_reallocp_array(&st->index_entries,
  2817. st->nb_index_entries + sc->sample_count,
  2818. sizeof(*st->index_entries)) < 0) {
  2819. st->nb_index_entries = 0;
  2820. return;
  2821. }
  2822. st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
  2823. for (i = 0; i < sc->chunk_count; i++) {
  2824. int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
  2825. current_offset = sc->chunk_offsets[i];
  2826. while (stsc_index + 1 < sc->stsc_count &&
  2827. i + 1 == sc->stsc_data[stsc_index + 1].first)
  2828. stsc_index++;
  2829. if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
  2830. sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
  2831. av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
  2832. sc->stsz_sample_size = sc->sample_size;
  2833. }
  2834. if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
  2835. av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
  2836. sc->stsz_sample_size = sc->sample_size;
  2837. }
  2838. for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
  2839. int keyframe = 0;
  2840. if (current_sample >= sc->sample_count) {
  2841. av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
  2842. return;
  2843. }
  2844. if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
  2845. keyframe = 1;
  2846. if (stss_index + 1 < sc->keyframe_count)
  2847. stss_index++;
  2848. } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
  2849. keyframe = 1;
  2850. if (stps_index + 1 < sc->stps_count)
  2851. stps_index++;
  2852. }
  2853. if (rap_group_present && rap_group_index < sc->rap_group_count) {
  2854. if (sc->rap_group[rap_group_index].index > 0)
  2855. keyframe = 1;
  2856. if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
  2857. rap_group_sample = 0;
  2858. rap_group_index++;
  2859. }
  2860. }
  2861. if (sc->keyframe_absent
  2862. && !sc->stps_count
  2863. && !rap_group_present
  2864. && (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
  2865. keyframe = 1;
  2866. if (keyframe)
  2867. distance = 0;
  2868. sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
  2869. if (sc->pseudo_stream_id == -1 ||
  2870. sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
  2871. AVIndexEntry *e;
  2872. if (sample_size > 0x3FFFFFFF) {
  2873. av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", sample_size);
  2874. return;
  2875. }
  2876. e = &st->index_entries[st->nb_index_entries++];
  2877. e->pos = current_offset;
  2878. e->timestamp = current_dts;
  2879. e->size = sample_size;
  2880. e->min_distance = distance;
  2881. e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
  2882. av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  2883. "size %d, distance %d, keyframe %d\n", st->index, current_sample,
  2884. current_offset, current_dts, sample_size, distance, keyframe);
  2885. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
  2886. ff_rfps_add_frame(mov->fc, st, current_dts);
  2887. }
  2888. current_offset += sample_size;
  2889. stream_size += sample_size;
  2890. /* A negative sample duration is invalid based on the spec,
  2891. * but some samples need it to correct the DTS. */
  2892. if (sc->stts_data[stts_index].duration < 0) {
  2893. av_log(mov->fc, AV_LOG_WARNING,
  2894. "Invalid SampleDelta %d in STTS, at %d st:%d\n",
  2895. sc->stts_data[stts_index].duration, stts_index,
  2896. st->index);
  2897. dts_correction += sc->stts_data[stts_index].duration - 1;
  2898. sc->stts_data[stts_index].duration = 1;
  2899. }
  2900. current_dts += sc->stts_data[stts_index].duration;
  2901. if (!dts_correction || current_dts + dts_correction > last_dts) {
  2902. current_dts += dts_correction;
  2903. dts_correction = 0;
  2904. } else {
  2905. /* Avoid creating non-monotonous DTS */
  2906. dts_correction += current_dts - last_dts - 1;
  2907. current_dts = last_dts + 1;
  2908. }
  2909. last_dts = current_dts;
  2910. distance++;
  2911. stts_sample++;
  2912. current_sample++;
  2913. if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
  2914. stts_sample = 0;
  2915. stts_index++;
  2916. }
  2917. }
  2918. }
  2919. if (st->duration > 0)
  2920. st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;
  2921. } else {
  2922. unsigned chunk_samples, total = 0;
  2923. // compute total chunk count
  2924. for (i = 0; i < sc->stsc_count; i++) {
  2925. unsigned count, chunk_count;
  2926. chunk_samples = sc->stsc_data[i].count;
  2927. if (i != sc->stsc_count - 1 &&
  2928. sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
  2929. av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
  2930. return;
  2931. }
  2932. if (sc->samples_per_frame >= 160) { // gsm
  2933. count = chunk_samples / sc->samples_per_frame;
  2934. } else if (sc->samples_per_frame > 1) {
  2935. unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
  2936. count = (chunk_samples+samples-1) / samples;
  2937. } else {
  2938. count = (chunk_samples+1023) / 1024;
  2939. }
  2940. if (i < sc->stsc_count - 1)
  2941. chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
  2942. else
  2943. chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
  2944. total += chunk_count * count;
  2945. }
  2946. av_log(mov->fc, AV_LOG_TRACE, "chunk count %d\n", total);
  2947. if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  2948. return;
  2949. if (av_reallocp_array(&st->index_entries,
  2950. st->nb_index_entries + total,
  2951. sizeof(*st->index_entries)) < 0) {
  2952. st->nb_index_entries = 0;
  2953. return;
  2954. }
  2955. st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
  2956. // populate index
  2957. for (i = 0; i < sc->chunk_count; i++) {
  2958. current_offset = sc->chunk_offsets[i];
  2959. if (stsc_index + 1 < sc->stsc_count &&
  2960. i + 1 == sc->stsc_data[stsc_index + 1].first)
  2961. stsc_index++;
  2962. chunk_samples = sc->stsc_data[stsc_index].count;
  2963. while (chunk_samples > 0) {
  2964. AVIndexEntry *e;
  2965. unsigned size, samples;
  2966. if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
  2967. avpriv_request_sample(mov->fc,
  2968. "Zero bytes per frame, but %d samples per frame",
  2969. sc->samples_per_frame);
  2970. return;
  2971. }
  2972. if (sc->samples_per_frame >= 160) { // gsm
  2973. samples = sc->samples_per_frame;
  2974. size = sc->bytes_per_frame;
  2975. } else {
  2976. if (sc->samples_per_frame > 1) {
  2977. samples = FFMIN((1024 / sc->samples_per_frame)*
  2978. sc->samples_per_frame, chunk_samples);
  2979. size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
  2980. } else {
  2981. samples = FFMIN(1024, chunk_samples);
  2982. size = samples * sc->sample_size;
  2983. }
  2984. }
  2985. if (st->nb_index_entries >= total) {
  2986. av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
  2987. return;
  2988. }
  2989. if (size > 0x3FFFFFFF) {
  2990. av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", size);
  2991. return;
  2992. }
  2993. e = &st->index_entries[st->nb_index_entries++];
  2994. e->pos = current_offset;
  2995. e->timestamp = current_dts;
  2996. e->size = size;
  2997. e->min_distance = 0;
  2998. e->flags = AVINDEX_KEYFRAME;
  2999. av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
  3000. "size %d, duration %d\n", st->index, i, current_offset, current_dts,
  3001. size, samples);
  3002. current_offset += size;
  3003. current_dts += samples;
  3004. chunk_samples -= samples;
  3005. }
  3006. }
  3007. }
  3008. // Fix index according to edit lists.
  3009. mov_fix_index(mov, st);
  3010. }
  3011. static int test_same_origin(const char *src, const char *ref) {
  3012. char src_proto[64];
  3013. char ref_proto[64];
  3014. char src_auth[256];
  3015. char ref_auth[256];
  3016. char src_host[256];
  3017. char ref_host[256];
  3018. int src_port=-1;
  3019. int ref_port=-1;
  3020. av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
  3021. av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
  3022. if (strlen(src) == 0) {
  3023. return -1;
  3024. } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
  3025. strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
  3026. strlen(src_host) + 1 >= sizeof(src_host) ||
  3027. strlen(ref_host) + 1 >= sizeof(ref_host)) {
  3028. return 0;
  3029. } else if (strcmp(src_proto, ref_proto) ||
  3030. strcmp(src_auth, ref_auth) ||
  3031. strcmp(src_host, ref_host) ||
  3032. src_port != ref_port) {
  3033. return 0;
  3034. } else
  3035. return 1;
  3036. }
  3037. static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
  3038. {
  3039. /* try relative path, we do not try the absolute because it can leak information about our
  3040. system to an attacker */
  3041. if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
  3042. char filename[1025];
  3043. const char *src_path;
  3044. int i, l;
  3045. /* find a source dir */
  3046. src_path = strrchr(src, '/');
  3047. if (src_path)
  3048. src_path++;
  3049. else
  3050. src_path = src;
  3051. /* find a next level down to target */
  3052. for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
  3053. if (ref->path[l] == '/') {
  3054. if (i == ref->nlvl_to - 1)
  3055. break;
  3056. else
  3057. i++;
  3058. }
  3059. /* compose filename if next level down to target was found */
  3060. if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
  3061. memcpy(filename, src, src_path - src);
  3062. filename[src_path - src] = 0;
  3063. for (i = 1; i < ref->nlvl_from; i++)
  3064. av_strlcat(filename, "../", sizeof(filename));
  3065. av_strlcat(filename, ref->path + l + 1, sizeof(filename));
  3066. if (!c->use_absolute_path) {
  3067. int same_origin = test_same_origin(src, filename);
  3068. if (!same_origin) {
  3069. av_log(c->fc, AV_LOG_ERROR,
  3070. "Reference with mismatching origin, %s not tried for security reasons, "
  3071. "set demuxer option use_absolute_path to allow it anyway\n",
  3072. ref->path);
  3073. return AVERROR(ENOENT);
  3074. }
  3075. if(strstr(ref->path + l + 1, "..") ||
  3076. strstr(ref->path + l + 1, ":") ||
  3077. (ref->nlvl_from > 1 && same_origin < 0) ||
  3078. (filename[0] == '/' && src_path == src))
  3079. return AVERROR(ENOENT);
  3080. }
  3081. if (strlen(filename) + 1 == sizeof(filename))
  3082. return AVERROR(ENOENT);
  3083. if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL))
  3084. return 0;
  3085. }
  3086. } else if (c->use_absolute_path) {
  3087. av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
  3088. "this is a possible security issue\n");
  3089. if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL))
  3090. return 0;
  3091. } else {
  3092. av_log(c->fc, AV_LOG_ERROR,
  3093. "Absolute path %s not tried for security reasons, "
  3094. "set demuxer option use_absolute_path to allow absolute paths\n",
  3095. ref->path);
  3096. }
  3097. return AVERROR(ENOENT);
  3098. }
  3099. static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
  3100. {
  3101. if (sc->time_scale <= 0) {
  3102. av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
  3103. sc->time_scale = c->time_scale;
  3104. if (sc->time_scale <= 0)
  3105. sc->time_scale = 1;
  3106. }
  3107. }
  3108. static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3109. {
  3110. AVStream *st;
  3111. MOVStreamContext *sc;
  3112. int ret;
  3113. st = avformat_new_stream(c->fc, NULL);
  3114. if (!st) return AVERROR(ENOMEM);
  3115. st->id = c->fc->nb_streams;
  3116. sc = av_mallocz(sizeof(MOVStreamContext));
  3117. if (!sc) return AVERROR(ENOMEM);
  3118. st->priv_data = sc;
  3119. st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  3120. sc->ffindex = st->index;
  3121. c->trak_index = st->index;
  3122. if ((ret = mov_read_default(c, pb, atom)) < 0)
  3123. return ret;
  3124. c->trak_index = -1;
  3125. /* sanity checks */
  3126. if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
  3127. (!sc->sample_size && !sc->sample_count))) {
  3128. av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
  3129. st->index);
  3130. return 0;
  3131. }
  3132. fix_timescale(c, sc);
  3133. avpriv_set_pts_info(st, 64, 1, sc->time_scale);
  3134. mov_build_index(c, st);
  3135. if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
  3136. MOVDref *dref = &sc->drefs[sc->dref_id - 1];
  3137. if (c->enable_drefs) {
  3138. if (mov_open_dref(c, &sc->pb, c->fc->filename, dref) < 0)
  3139. av_log(c->fc, AV_LOG_ERROR,
  3140. "stream %d, error opening alias: path='%s', dir='%s', "
  3141. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
  3142. st->index, dref->path, dref->dir, dref->filename,
  3143. dref->volume, dref->nlvl_from, dref->nlvl_to);
  3144. } else {
  3145. av_log(c->fc, AV_LOG_WARNING,
  3146. "Skipped opening external track: "
  3147. "stream %d, alias: path='%s', dir='%s', "
  3148. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d."
  3149. "Set enable_drefs to allow this.\n",
  3150. st->index, dref->path, dref->dir, dref->filename,
  3151. dref->volume, dref->nlvl_from, dref->nlvl_to);
  3152. }
  3153. } else {
  3154. sc->pb = c->fc->pb;
  3155. sc->pb_is_copied = 1;
  3156. }
  3157. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  3158. if (!st->sample_aspect_ratio.num && st->codecpar->width && st->codecpar->height &&
  3159. sc->height && sc->width &&
  3160. (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) {
  3161. st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) /
  3162. ((double)st->codecpar->width * sc->height), INT_MAX);
  3163. }
  3164. #if FF_API_R_FRAME_RATE
  3165. if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
  3166. av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
  3167. sc->time_scale, sc->stts_data[0].duration, INT_MAX);
  3168. #endif
  3169. }
  3170. // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
  3171. if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
  3172. TAG_IS_AVCI(st->codecpar->codec_tag)) {
  3173. ret = ff_generate_avci_extradata(st);
  3174. if (ret < 0)
  3175. return ret;
  3176. }
  3177. switch (st->codecpar->codec_id) {
  3178. #if CONFIG_H261_DECODER
  3179. case AV_CODEC_ID_H261:
  3180. #endif
  3181. #if CONFIG_H263_DECODER
  3182. case AV_CODEC_ID_H263:
  3183. #endif
  3184. #if CONFIG_MPEG4_DECODER
  3185. case AV_CODEC_ID_MPEG4:
  3186. #endif
  3187. st->codecpar->width = 0; /* let decoder init width/height */
  3188. st->codecpar->height= 0;
  3189. break;
  3190. }
  3191. // If the duration of the mp3 packets is not constant, then they could need a parser
  3192. if (st->codecpar->codec_id == AV_CODEC_ID_MP3
  3193. && sc->stts_count > 3
  3194. && sc->stts_count*10 > st->nb_frames
  3195. && sc->time_scale == st->codecpar->sample_rate) {
  3196. st->need_parsing = AVSTREAM_PARSE_FULL;
  3197. }
  3198. /* Do not need those anymore. */
  3199. av_freep(&sc->chunk_offsets);
  3200. av_freep(&sc->sample_sizes);
  3201. av_freep(&sc->keyframes);
  3202. av_freep(&sc->stts_data);
  3203. av_freep(&sc->stps_data);
  3204. av_freep(&sc->elst_data);
  3205. av_freep(&sc->rap_group);
  3206. return 0;
  3207. }
  3208. static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3209. {
  3210. int ret;
  3211. c->itunes_metadata = 1;
  3212. ret = mov_read_default(c, pb, atom);
  3213. c->itunes_metadata = 0;
  3214. return ret;
  3215. }
  3216. static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3217. {
  3218. uint32_t count;
  3219. uint32_t i;
  3220. if (atom.size < 8)
  3221. return 0;
  3222. avio_skip(pb, 4);
  3223. count = avio_rb32(pb);
  3224. if (count > UINT_MAX / sizeof(*c->meta_keys) - 1) {
  3225. av_log(c->fc, AV_LOG_ERROR,
  3226. "The 'keys' atom with the invalid key count: %d\n", count);
  3227. return AVERROR_INVALIDDATA;
  3228. }
  3229. c->meta_keys_count = count + 1;
  3230. c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
  3231. if (!c->meta_keys)
  3232. return AVERROR(ENOMEM);
  3233. for (i = 1; i <= count; ++i) {
  3234. uint32_t key_size = avio_rb32(pb);
  3235. uint32_t type = avio_rl32(pb);
  3236. if (key_size < 8) {
  3237. av_log(c->fc, AV_LOG_ERROR,
  3238. "The key# %d in meta has invalid size: %d\n", i, key_size);
  3239. return AVERROR_INVALIDDATA;
  3240. }
  3241. key_size -= 8;
  3242. if (type != MKTAG('m','d','t','a')) {
  3243. avio_skip(pb, key_size);
  3244. }
  3245. c->meta_keys[i] = av_mallocz(key_size + 1);
  3246. if (!c->meta_keys[i])
  3247. return AVERROR(ENOMEM);
  3248. avio_read(pb, c->meta_keys[i], key_size);
  3249. }
  3250. return 0;
  3251. }
  3252. static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3253. {
  3254. int64_t end = avio_tell(pb) + atom.size;
  3255. uint8_t *key = NULL, *val = NULL, *mean = NULL;
  3256. int i;
  3257. int ret = 0;
  3258. AVStream *st;
  3259. MOVStreamContext *sc;
  3260. if (c->fc->nb_streams < 1)
  3261. return 0;
  3262. st = c->fc->streams[c->fc->nb_streams-1];
  3263. sc = st->priv_data;
  3264. for (i = 0; i < 3; i++) {
  3265. uint8_t **p;
  3266. uint32_t len, tag;
  3267. if (end - avio_tell(pb) <= 12)
  3268. break;
  3269. len = avio_rb32(pb);
  3270. tag = avio_rl32(pb);
  3271. avio_skip(pb, 4); // flags
  3272. if (len < 12 || len - 12 > end - avio_tell(pb))
  3273. break;
  3274. len -= 12;
  3275. if (tag == MKTAG('m', 'e', 'a', 'n'))
  3276. p = &mean;
  3277. else if (tag == MKTAG('n', 'a', 'm', 'e'))
  3278. p = &key;
  3279. else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
  3280. avio_skip(pb, 4);
  3281. len -= 4;
  3282. p = &val;
  3283. } else
  3284. break;
  3285. *p = av_malloc(len + 1);
  3286. if (!*p)
  3287. break;
  3288. ret = ffio_read_size(pb, *p, len);
  3289. if (ret < 0) {
  3290. av_freep(p);
  3291. break;
  3292. }
  3293. (*p)[len] = 0;
  3294. }
  3295. if (mean && key && val) {
  3296. if (strcmp(key, "iTunSMPB") == 0) {
  3297. int priming, remainder, samples;
  3298. if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
  3299. if(priming>0 && priming<16384)
  3300. sc->start_pad = priming;
  3301. }
  3302. }
  3303. if (strcmp(key, "cdec") != 0) {
  3304. av_dict_set(&c->fc->metadata, key, val,
  3305. AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
  3306. key = val = NULL;
  3307. }
  3308. } else {
  3309. av_log(c->fc, AV_LOG_VERBOSE,
  3310. "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
  3311. }
  3312. avio_seek(pb, end, SEEK_SET);
  3313. av_freep(&key);
  3314. av_freep(&val);
  3315. av_freep(&mean);
  3316. return ret;
  3317. }
  3318. static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3319. {
  3320. while (atom.size > 8) {
  3321. uint32_t tag = avio_rl32(pb);
  3322. atom.size -= 4;
  3323. if (tag == MKTAG('h','d','l','r')) {
  3324. avio_seek(pb, -8, SEEK_CUR);
  3325. atom.size += 8;
  3326. return mov_read_default(c, pb, atom);
  3327. }
  3328. }
  3329. return 0;
  3330. }
  3331. static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3332. {
  3333. int i;
  3334. int width;
  3335. int height;
  3336. int display_matrix[3][3];
  3337. AVStream *st;
  3338. MOVStreamContext *sc;
  3339. int version;
  3340. int flags;
  3341. if (c->fc->nb_streams < 1)
  3342. return 0;
  3343. st = c->fc->streams[c->fc->nb_streams-1];
  3344. sc = st->priv_data;
  3345. version = avio_r8(pb);
  3346. flags = avio_rb24(pb);
  3347. st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
  3348. if (version == 1) {
  3349. avio_rb64(pb);
  3350. avio_rb64(pb);
  3351. } else {
  3352. avio_rb32(pb); /* creation time */
  3353. avio_rb32(pb); /* modification time */
  3354. }
  3355. st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
  3356. avio_rb32(pb); /* reserved */
  3357. /* highlevel (considering edits) duration in movie timebase */
  3358. (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
  3359. avio_rb32(pb); /* reserved */
  3360. avio_rb32(pb); /* reserved */
  3361. avio_rb16(pb); /* layer */
  3362. avio_rb16(pb); /* alternate group */
  3363. avio_rb16(pb); /* volume */
  3364. avio_rb16(pb); /* reserved */
  3365. //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
  3366. // they're kept in fixed point format through all calculations
  3367. // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
  3368. // side data, but the scale factor is not needed to calculate aspect ratio
  3369. for (i = 0; i < 3; i++) {
  3370. display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
  3371. display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
  3372. display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
  3373. }
  3374. width = avio_rb32(pb); // 16.16 fixed point track width
  3375. height = avio_rb32(pb); // 16.16 fixed point track height
  3376. sc->width = width >> 16;
  3377. sc->height = height >> 16;
  3378. // save the matrix and add rotate metadata when it is not the default
  3379. // identity
  3380. if (display_matrix[0][0] != (1 << 16) ||
  3381. display_matrix[1][1] != (1 << 16) ||
  3382. display_matrix[2][2] != (1 << 30) ||
  3383. display_matrix[0][1] || display_matrix[0][2] ||
  3384. display_matrix[1][0] || display_matrix[1][2] ||
  3385. display_matrix[2][0] || display_matrix[2][1]) {
  3386. int i, j;
  3387. double rotate;
  3388. av_freep(&sc->display_matrix);
  3389. sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
  3390. if (!sc->display_matrix)
  3391. return AVERROR(ENOMEM);
  3392. for (i = 0; i < 3; i++)
  3393. for (j = 0; j < 3; j++)
  3394. sc->display_matrix[i * 3 + j] = display_matrix[i][j];
  3395. rotate = av_display_rotation_get(sc->display_matrix);
  3396. if (!isnan(rotate)) {
  3397. char rotate_buf[64];
  3398. rotate = -rotate;
  3399. if (rotate < 0) // for backward compatibility
  3400. rotate += 360;
  3401. snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
  3402. av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
  3403. }
  3404. }
  3405. // transform the display width/height according to the matrix
  3406. // to keep the same scale, use [width height 1<<16]
  3407. if (width && height && sc->display_matrix) {
  3408. double disp_transform[2];
  3409. for (i = 0; i < 2; i++)
  3410. disp_transform[i] = hypot(display_matrix[i][0], display_matrix[i][1]);
  3411. if (disp_transform[0] > 0 && disp_transform[1] > 0 &&
  3412. disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
  3413. fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
  3414. st->sample_aspect_ratio = av_d2q(
  3415. disp_transform[0] / disp_transform[1],
  3416. INT_MAX);
  3417. }
  3418. return 0;
  3419. }
  3420. static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3421. {
  3422. MOVFragment *frag = &c->fragment;
  3423. MOVTrackExt *trex = NULL;
  3424. MOVFragmentIndex* index = NULL;
  3425. int flags, track_id, i, found = 0;
  3426. avio_r8(pb); /* version */
  3427. flags = avio_rb24(pb);
  3428. track_id = avio_rb32(pb);
  3429. if (!track_id)
  3430. return AVERROR_INVALIDDATA;
  3431. frag->track_id = track_id;
  3432. for (i = 0; i < c->trex_count; i++)
  3433. if (c->trex_data[i].track_id == frag->track_id) {
  3434. trex = &c->trex_data[i];
  3435. break;
  3436. }
  3437. if (!trex) {
  3438. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
  3439. return AVERROR_INVALIDDATA;
  3440. }
  3441. frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
  3442. avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
  3443. frag->moof_offset : frag->implicit_offset;
  3444. frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
  3445. frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
  3446. avio_rb32(pb) : trex->duration;
  3447. frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
  3448. avio_rb32(pb) : trex->size;
  3449. frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
  3450. avio_rb32(pb) : trex->flags;
  3451. frag->time = AV_NOPTS_VALUE;
  3452. for (i = 0; i < c->fragment_index_count; i++) {
  3453. int j;
  3454. MOVFragmentIndex* candidate = c->fragment_index_data[i];
  3455. if (candidate->track_id == frag->track_id) {
  3456. av_log(c->fc, AV_LOG_DEBUG,
  3457. "found fragment index for track %u\n", frag->track_id);
  3458. index = candidate;
  3459. for (j = index->current_item; j < index->item_count; j++) {
  3460. if (frag->implicit_offset == index->items[j].moof_offset) {
  3461. av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry "
  3462. "for track %u and moof_offset %"PRId64"\n",
  3463. frag->track_id, index->items[j].moof_offset);
  3464. frag->time = index->items[j].time;
  3465. index->current_item = j + 1;
  3466. found = 1;
  3467. break;
  3468. }
  3469. }
  3470. if (found)
  3471. break;
  3472. }
  3473. }
  3474. if (index && !found) {
  3475. av_log(c->fc, AV_LOG_DEBUG, "track %u has a fragment index but "
  3476. "it doesn't have an (in-order) entry for moof_offset "
  3477. "%"PRId64"\n", frag->track_id, frag->implicit_offset);
  3478. }
  3479. av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
  3480. return 0;
  3481. }
  3482. static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3483. {
  3484. unsigned i, num;
  3485. void *new_tracks;
  3486. num = atom.size / 4;
  3487. if (!(new_tracks = av_malloc_array(num, sizeof(int))))
  3488. return AVERROR(ENOMEM);
  3489. av_free(c->chapter_tracks);
  3490. c->chapter_tracks = new_tracks;
  3491. c->nb_chapter_tracks = num;
  3492. for (i = 0; i < num && !pb->eof_reached; i++)
  3493. c->chapter_tracks[i] = avio_rb32(pb);
  3494. return 0;
  3495. }
  3496. static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3497. {
  3498. MOVTrackExt *trex;
  3499. int err;
  3500. if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
  3501. return AVERROR_INVALIDDATA;
  3502. if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
  3503. sizeof(*c->trex_data))) < 0) {
  3504. c->trex_count = 0;
  3505. return err;
  3506. }
  3507. c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
  3508. trex = &c->trex_data[c->trex_count++];
  3509. avio_r8(pb); /* version */
  3510. avio_rb24(pb); /* flags */
  3511. trex->track_id = avio_rb32(pb);
  3512. trex->stsd_id = avio_rb32(pb);
  3513. trex->duration = avio_rb32(pb);
  3514. trex->size = avio_rb32(pb);
  3515. trex->flags = avio_rb32(pb);
  3516. return 0;
  3517. }
  3518. static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3519. {
  3520. MOVFragment *frag = &c->fragment;
  3521. AVStream *st = NULL;
  3522. MOVStreamContext *sc;
  3523. int version, i;
  3524. for (i = 0; i < c->fc->nb_streams; i++) {
  3525. if (c->fc->streams[i]->id == frag->track_id) {
  3526. st = c->fc->streams[i];
  3527. break;
  3528. }
  3529. }
  3530. if (!st) {
  3531. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  3532. return AVERROR_INVALIDDATA;
  3533. }
  3534. sc = st->priv_data;
  3535. if (sc->pseudo_stream_id + 1 != frag->stsd_id)
  3536. return 0;
  3537. version = avio_r8(pb);
  3538. avio_rb24(pb); /* flags */
  3539. if (version) {
  3540. sc->track_end = avio_rb64(pb);
  3541. } else {
  3542. sc->track_end = avio_rb32(pb);
  3543. }
  3544. return 0;
  3545. }
  3546. static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3547. {
  3548. MOVFragment *frag = &c->fragment;
  3549. AVStream *st = NULL;
  3550. MOVStreamContext *sc;
  3551. MOVStts *ctts_data;
  3552. uint64_t offset;
  3553. int64_t dts;
  3554. int data_offset = 0;
  3555. unsigned entries, first_sample_flags = frag->flags;
  3556. int flags, distance, i, err;
  3557. for (i = 0; i < c->fc->nb_streams; i++) {
  3558. if (c->fc->streams[i]->id == frag->track_id) {
  3559. st = c->fc->streams[i];
  3560. break;
  3561. }
  3562. }
  3563. if (!st) {
  3564. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  3565. return AVERROR_INVALIDDATA;
  3566. }
  3567. sc = st->priv_data;
  3568. if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
  3569. return 0;
  3570. avio_r8(pb); /* version */
  3571. flags = avio_rb24(pb);
  3572. entries = avio_rb32(pb);
  3573. av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %d\n", flags, entries);
  3574. /* Always assume the presence of composition time offsets.
  3575. * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
  3576. * 1) in the initial movie, there are no samples.
  3577. * 2) in the first movie fragment, there is only one sample without composition time offset.
  3578. * 3) in the subsequent movie fragments, there are samples with composition time offset. */
  3579. if (!sc->ctts_count && sc->sample_count)
  3580. {
  3581. /* Complement ctts table if moov atom doesn't have ctts atom. */
  3582. ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
  3583. if (!ctts_data)
  3584. return AVERROR(ENOMEM);
  3585. sc->ctts_data = ctts_data;
  3586. sc->ctts_data[sc->ctts_count].count = sc->sample_count;
  3587. sc->ctts_data[sc->ctts_count].duration = 0;
  3588. sc->ctts_count++;
  3589. }
  3590. if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
  3591. return AVERROR_INVALIDDATA;
  3592. if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
  3593. sizeof(*sc->ctts_data))) < 0) {
  3594. sc->ctts_count = 0;
  3595. return err;
  3596. }
  3597. if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
  3598. if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
  3599. dts = sc->track_end - sc->time_offset;
  3600. offset = frag->base_data_offset + data_offset;
  3601. distance = 0;
  3602. av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
  3603. for (i = 0; i < entries && !pb->eof_reached; i++) {
  3604. unsigned sample_size = frag->size;
  3605. int sample_flags = i ? frag->flags : first_sample_flags;
  3606. unsigned sample_duration = frag->duration;
  3607. int keyframe = 0;
  3608. if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
  3609. if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
  3610. if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
  3611. sc->ctts_data[sc->ctts_count].count = 1;
  3612. sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
  3613. avio_rb32(pb) : 0;
  3614. mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
  3615. if (frag->time != AV_NOPTS_VALUE) {
  3616. if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
  3617. int64_t pts = frag->time;
  3618. av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
  3619. " sc->dts_shift %d ctts.duration %d"
  3620. " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,
  3621. sc->dts_shift, sc->ctts_data[sc->ctts_count].duration,
  3622. sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
  3623. dts = pts - sc->dts_shift;
  3624. if (flags & MOV_TRUN_SAMPLE_CTS) {
  3625. dts -= sc->ctts_data[sc->ctts_count].duration;
  3626. } else {
  3627. dts -= sc->time_offset;
  3628. }
  3629. av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);
  3630. } else {
  3631. dts = frag->time - sc->time_offset;
  3632. av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
  3633. ", using it for dts\n", dts);
  3634. }
  3635. frag->time = AV_NOPTS_VALUE;
  3636. }
  3637. sc->ctts_count++;
  3638. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
  3639. keyframe = 1;
  3640. else
  3641. keyframe =
  3642. !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
  3643. MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
  3644. if (keyframe)
  3645. distance = 0;
  3646. err = av_add_index_entry(st, offset, dts, sample_size, distance,
  3647. keyframe ? AVINDEX_KEYFRAME : 0);
  3648. if (err < 0) {
  3649. av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
  3650. }
  3651. av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  3652. "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
  3653. offset, dts, sample_size, distance, keyframe);
  3654. distance++;
  3655. dts += sample_duration;
  3656. offset += sample_size;
  3657. sc->data_size += sample_size;
  3658. sc->duration_for_fps += sample_duration;
  3659. sc->nb_frames_for_fps ++;
  3660. }
  3661. if (pb->eof_reached)
  3662. return AVERROR_EOF;
  3663. frag->implicit_offset = offset;
  3664. sc->track_end = dts + sc->time_offset;
  3665. if (st->duration < sc->track_end)
  3666. st->duration = sc->track_end;
  3667. return 0;
  3668. }
  3669. static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3670. {
  3671. int64_t offset = avio_tell(pb) + atom.size, pts;
  3672. uint8_t version;
  3673. unsigned i, track_id;
  3674. AVStream *st = NULL;
  3675. AVStream *ref_st;
  3676. MOVStreamContext *sc, *ref_sc;
  3677. MOVFragmentIndex *index = NULL;
  3678. MOVFragmentIndex **tmp;
  3679. AVRational timescale;
  3680. version = avio_r8(pb);
  3681. if (version > 1) {
  3682. avpriv_request_sample(c->fc, "sidx version %u", version);
  3683. return 0;
  3684. }
  3685. avio_rb24(pb); // flags
  3686. track_id = avio_rb32(pb); // Reference ID
  3687. for (i = 0; i < c->fc->nb_streams; i++) {
  3688. if (c->fc->streams[i]->id == track_id) {
  3689. st = c->fc->streams[i];
  3690. break;
  3691. }
  3692. }
  3693. if (!st) {
  3694. av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id);
  3695. return 0;
  3696. }
  3697. sc = st->priv_data;
  3698. timescale = av_make_q(1, avio_rb32(pb));
  3699. if (timescale.den <= 0) {
  3700. av_log(c->fc, AV_LOG_ERROR, "Invalid sidx timescale 1/%d\n", timescale.den);
  3701. return AVERROR_INVALIDDATA;
  3702. }
  3703. if (version == 0) {
  3704. pts = avio_rb32(pb);
  3705. offset += avio_rb32(pb);
  3706. } else {
  3707. pts = avio_rb64(pb);
  3708. offset += avio_rb64(pb);
  3709. }
  3710. avio_rb16(pb); // reserved
  3711. index = av_mallocz(sizeof(MOVFragmentIndex));
  3712. if (!index)
  3713. return AVERROR(ENOMEM);
  3714. index->track_id = track_id;
  3715. index->item_count = avio_rb16(pb);
  3716. index->items = av_mallocz_array(index->item_count, sizeof(MOVFragmentIndexItem));
  3717. if (!index->items) {
  3718. av_freep(&index);
  3719. return AVERROR(ENOMEM);
  3720. }
  3721. for (i = 0; i < index->item_count; i++) {
  3722. uint32_t size = avio_rb32(pb);
  3723. uint32_t duration = avio_rb32(pb);
  3724. if (size & 0x80000000) {
  3725. avpriv_request_sample(c->fc, "sidx reference_type 1");
  3726. av_freep(&index->items);
  3727. av_freep(&index);
  3728. return AVERROR_PATCHWELCOME;
  3729. }
  3730. avio_rb32(pb); // sap_flags
  3731. index->items[i].moof_offset = offset;
  3732. index->items[i].time = av_rescale_q(pts, st->time_base, timescale);
  3733. offset += size;
  3734. pts += duration;
  3735. }
  3736. st->duration = sc->track_end = pts;
  3737. tmp = av_realloc_array(c->fragment_index_data,
  3738. c->fragment_index_count + 1,
  3739. sizeof(MOVFragmentIndex*));
  3740. if (!tmp) {
  3741. av_freep(&index->items);
  3742. av_freep(&index);
  3743. return AVERROR(ENOMEM);
  3744. }
  3745. c->fragment_index_data = tmp;
  3746. c->fragment_index_data[c->fragment_index_count++] = index;
  3747. sc->has_sidx = 1;
  3748. if (offset == avio_size(pb)) {
  3749. for (i = 0; i < c->fc->nb_streams; i++) {
  3750. if (c->fc->streams[i]->id == c->fragment_index_data[0]->track_id) {
  3751. ref_st = c->fc->streams[i];
  3752. ref_sc = ref_st->priv_data;
  3753. break;
  3754. }
  3755. }
  3756. for (i = 0; i < c->fc->nb_streams; i++) {
  3757. st = c->fc->streams[i];
  3758. sc = st->priv_data;
  3759. if (!sc->has_sidx) {
  3760. st->duration = sc->track_end = av_rescale(ref_st->duration, sc->time_scale, ref_sc->time_scale);
  3761. }
  3762. }
  3763. c->fragment_index_complete = 1;
  3764. }
  3765. return 0;
  3766. }
  3767. /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
  3768. /* like the files created with Adobe Premiere 5.0, for samples see */
  3769. /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
  3770. static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3771. {
  3772. int err;
  3773. if (atom.size < 8)
  3774. return 0; /* continue */
  3775. if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
  3776. avio_skip(pb, atom.size - 4);
  3777. return 0;
  3778. }
  3779. atom.type = avio_rl32(pb);
  3780. atom.size -= 8;
  3781. if (atom.type != MKTAG('m','d','a','t')) {
  3782. avio_skip(pb, atom.size);
  3783. return 0;
  3784. }
  3785. err = mov_read_mdat(c, pb, atom);
  3786. return err;
  3787. }
  3788. static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3789. {
  3790. #if CONFIG_ZLIB
  3791. AVIOContext ctx;
  3792. uint8_t *cmov_data;
  3793. uint8_t *moov_data; /* uncompressed data */
  3794. long cmov_len, moov_len;
  3795. int ret = -1;
  3796. avio_rb32(pb); /* dcom atom */
  3797. if (avio_rl32(pb) != MKTAG('d','c','o','m'))
  3798. return AVERROR_INVALIDDATA;
  3799. if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
  3800. av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
  3801. return AVERROR_INVALIDDATA;
  3802. }
  3803. avio_rb32(pb); /* cmvd atom */
  3804. if (avio_rl32(pb) != MKTAG('c','m','v','d'))
  3805. return AVERROR_INVALIDDATA;
  3806. moov_len = avio_rb32(pb); /* uncompressed size */
  3807. cmov_len = atom.size - 6 * 4;
  3808. cmov_data = av_malloc(cmov_len);
  3809. if (!cmov_data)
  3810. return AVERROR(ENOMEM);
  3811. moov_data = av_malloc(moov_len);
  3812. if (!moov_data) {
  3813. av_free(cmov_data);
  3814. return AVERROR(ENOMEM);
  3815. }
  3816. ret = ffio_read_size(pb, cmov_data, cmov_len);
  3817. if (ret < 0)
  3818. goto free_and_return;
  3819. if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
  3820. goto free_and_return;
  3821. if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
  3822. goto free_and_return;
  3823. ctx.seekable = AVIO_SEEKABLE_NORMAL;
  3824. atom.type = MKTAG('m','o','o','v');
  3825. atom.size = moov_len;
  3826. ret = mov_read_default(c, &ctx, atom);
  3827. free_and_return:
  3828. av_free(moov_data);
  3829. av_free(cmov_data);
  3830. return ret;
  3831. #else
  3832. av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
  3833. return AVERROR(ENOSYS);
  3834. #endif
  3835. }
  3836. /* edit list atom */
  3837. static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3838. {
  3839. MOVStreamContext *sc;
  3840. int i, edit_count, version;
  3841. if (c->fc->nb_streams < 1 || c->ignore_editlist)
  3842. return 0;
  3843. sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
  3844. version = avio_r8(pb); /* version */
  3845. avio_rb24(pb); /* flags */
  3846. edit_count = avio_rb32(pb); /* entries */
  3847. if (!edit_count)
  3848. return 0;
  3849. if (sc->elst_data)
  3850. av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
  3851. av_free(sc->elst_data);
  3852. sc->elst_count = 0;
  3853. sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
  3854. if (!sc->elst_data)
  3855. return AVERROR(ENOMEM);
  3856. av_log(c->fc, AV_LOG_TRACE, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
  3857. for (i = 0; i < edit_count && !pb->eof_reached; i++) {
  3858. MOVElst *e = &sc->elst_data[i];
  3859. if (version == 1) {
  3860. e->duration = avio_rb64(pb);
  3861. e->time = avio_rb64(pb);
  3862. } else {
  3863. e->duration = avio_rb32(pb); /* segment duration */
  3864. e->time = (int32_t)avio_rb32(pb); /* media time */
  3865. }
  3866. e->rate = avio_rb32(pb) / 65536.0;
  3867. av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
  3868. e->duration, e->time, e->rate);
  3869. }
  3870. sc->elst_count = i;
  3871. return 0;
  3872. }
  3873. static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3874. {
  3875. MOVStreamContext *sc;
  3876. if (c->fc->nb_streams < 1)
  3877. return AVERROR_INVALIDDATA;
  3878. sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
  3879. sc->timecode_track = avio_rb32(pb);
  3880. return 0;
  3881. }
  3882. static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3883. {
  3884. int ret;
  3885. uint8_t uuid[16];
  3886. static const uint8_t uuid_isml_manifest[] = {
  3887. 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
  3888. 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
  3889. };
  3890. static const uint8_t uuid_xmp[] = {
  3891. 0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8,
  3892. 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac
  3893. };
  3894. if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
  3895. return AVERROR_INVALIDDATA;
  3896. ret = avio_read(pb, uuid, sizeof(uuid));
  3897. if (ret < 0) {
  3898. return ret;
  3899. } else if (ret != sizeof(uuid)) {
  3900. return AVERROR_INVALIDDATA;
  3901. }
  3902. if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
  3903. uint8_t *buffer, *ptr;
  3904. char *endptr;
  3905. size_t len = atom.size - sizeof(uuid);
  3906. if (len < 4) {
  3907. return AVERROR_INVALIDDATA;
  3908. }
  3909. ret = avio_skip(pb, 4); // zeroes
  3910. len -= 4;
  3911. buffer = av_mallocz(len + 1);
  3912. if (!buffer) {
  3913. return AVERROR(ENOMEM);
  3914. }
  3915. ret = avio_read(pb, buffer, len);
  3916. if (ret < 0) {
  3917. av_free(buffer);
  3918. return ret;
  3919. } else if (ret != len) {
  3920. av_free(buffer);
  3921. return AVERROR_INVALIDDATA;
  3922. }
  3923. ptr = buffer;
  3924. while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
  3925. ptr += sizeof("systemBitrate=\"") - 1;
  3926. c->bitrates_count++;
  3927. c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
  3928. if (!c->bitrates) {
  3929. c->bitrates_count = 0;
  3930. av_free(buffer);
  3931. return AVERROR(ENOMEM);
  3932. }
  3933. errno = 0;
  3934. ret = strtol(ptr, &endptr, 10);
  3935. if (ret < 0 || errno || *endptr != '"') {
  3936. c->bitrates[c->bitrates_count - 1] = 0;
  3937. } else {
  3938. c->bitrates[c->bitrates_count - 1] = ret;
  3939. }
  3940. }
  3941. av_free(buffer);
  3942. } else if (!memcmp(uuid, uuid_xmp, sizeof(uuid))) {
  3943. uint8_t *buffer;
  3944. size_t len = atom.size - sizeof(uuid);
  3945. buffer = av_mallocz(len + 1);
  3946. if (!buffer) {
  3947. return AVERROR(ENOMEM);
  3948. }
  3949. ret = avio_read(pb, buffer, len);
  3950. if (ret < 0) {
  3951. av_free(buffer);
  3952. return ret;
  3953. } else if (ret != len) {
  3954. av_free(buffer);
  3955. return AVERROR_INVALIDDATA;
  3956. }
  3957. if (c->export_xmp) {
  3958. buffer[len] = '\0';
  3959. av_dict_set(&c->fc->metadata, "xmp", buffer, 0);
  3960. }
  3961. av_free(buffer);
  3962. }
  3963. return 0;
  3964. }
  3965. static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3966. {
  3967. int ret;
  3968. uint8_t content[16];
  3969. if (atom.size < 8)
  3970. return 0;
  3971. ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
  3972. if (ret < 0)
  3973. return ret;
  3974. if ( !c->found_moov
  3975. && !c->found_mdat
  3976. && !memcmp(content, "Anevia\x1A\x1A", 8)
  3977. && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
  3978. c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
  3979. }
  3980. return 0;
  3981. }
  3982. static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3983. {
  3984. uint32_t format = avio_rl32(pb);
  3985. MOVStreamContext *sc;
  3986. enum AVCodecID id;
  3987. AVStream *st;
  3988. if (c->fc->nb_streams < 1)
  3989. return 0;
  3990. st = c->fc->streams[c->fc->nb_streams - 1];
  3991. sc = st->priv_data;
  3992. switch (sc->format)
  3993. {
  3994. case MKTAG('e','n','c','v'): // encrypted video
  3995. case MKTAG('e','n','c','a'): // encrypted audio
  3996. id = mov_codec_id(st, format);
  3997. if (st->codecpar->codec_id != AV_CODEC_ID_NONE &&
  3998. st->codecpar->codec_id != id) {
  3999. av_log(c->fc, AV_LOG_WARNING,
  4000. "ignoring 'frma' atom of '%.4s', stream has codec id %d\n",
  4001. (char*)&format, st->codecpar->codec_id);
  4002. break;
  4003. }
  4004. st->codecpar->codec_id = id;
  4005. sc->format = format;
  4006. break;
  4007. default:
  4008. if (format != sc->format) {
  4009. av_log(c->fc, AV_LOG_WARNING,
  4010. "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n",
  4011. (char*)&format, (char*)&sc->format);
  4012. }
  4013. break;
  4014. }
  4015. return 0;
  4016. }
  4017. static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4018. {
  4019. AVStream *st;
  4020. MOVStreamContext *sc;
  4021. size_t auxiliary_info_size;
  4022. if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
  4023. return 0;
  4024. st = c->fc->streams[c->fc->nb_streams - 1];
  4025. sc = st->priv_data;
  4026. if (sc->cenc.aes_ctr) {
  4027. av_log(c->fc, AV_LOG_ERROR, "duplicate senc atom\n");
  4028. return AVERROR_INVALIDDATA;
  4029. }
  4030. avio_r8(pb); /* version */
  4031. sc->cenc.use_subsamples = avio_rb24(pb) & 0x02; /* flags */
  4032. avio_rb32(pb); /* entries */
  4033. if (atom.size < 8) {
  4034. av_log(c->fc, AV_LOG_ERROR, "senc atom size %"PRId64" too small\n", atom.size);
  4035. return AVERROR_INVALIDDATA;
  4036. }
  4037. /* save the auxiliary info as is */
  4038. auxiliary_info_size = atom.size - 8;
  4039. sc->cenc.auxiliary_info = av_malloc(auxiliary_info_size);
  4040. if (!sc->cenc.auxiliary_info) {
  4041. return AVERROR(ENOMEM);
  4042. }
  4043. sc->cenc.auxiliary_info_end = sc->cenc.auxiliary_info + auxiliary_info_size;
  4044. sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info;
  4045. if (avio_read(pb, sc->cenc.auxiliary_info, auxiliary_info_size) != auxiliary_info_size) {
  4046. av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info");
  4047. return AVERROR_INVALIDDATA;
  4048. }
  4049. /* initialize the cipher */
  4050. sc->cenc.aes_ctr = av_aes_ctr_alloc();
  4051. if (!sc->cenc.aes_ctr) {
  4052. return AVERROR(ENOMEM);
  4053. }
  4054. return av_aes_ctr_init(sc->cenc.aes_ctr, c->decryption_key);
  4055. }
  4056. static int mov_read_saiz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4057. {
  4058. AVStream *st;
  4059. MOVStreamContext *sc;
  4060. size_t data_size;
  4061. int atom_header_size;
  4062. int flags;
  4063. if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
  4064. return 0;
  4065. st = c->fc->streams[c->fc->nb_streams - 1];
  4066. sc = st->priv_data;
  4067. if (sc->cenc.auxiliary_info_sizes || sc->cenc.auxiliary_info_default_size) {
  4068. av_log(c->fc, AV_LOG_ERROR, "duplicate saiz atom\n");
  4069. return AVERROR_INVALIDDATA;
  4070. }
  4071. atom_header_size = 9;
  4072. avio_r8(pb); /* version */
  4073. flags = avio_rb24(pb);
  4074. if ((flags & 0x01) != 0) {
  4075. atom_header_size += 8;
  4076. avio_rb32(pb); /* info type */
  4077. avio_rb32(pb); /* info type param */
  4078. }
  4079. sc->cenc.auxiliary_info_default_size = avio_r8(pb);
  4080. avio_rb32(pb); /* entries */
  4081. if (atom.size <= atom_header_size) {
  4082. return 0;
  4083. }
  4084. /* save the auxiliary info sizes as is */
  4085. data_size = atom.size - atom_header_size;
  4086. sc->cenc.auxiliary_info_sizes = av_malloc(data_size);
  4087. if (!sc->cenc.auxiliary_info_sizes) {
  4088. return AVERROR(ENOMEM);
  4089. }
  4090. sc->cenc.auxiliary_info_sizes_count = data_size;
  4091. if (avio_read(pb, sc->cenc.auxiliary_info_sizes, data_size) != data_size) {
  4092. av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info sizes");
  4093. return AVERROR_INVALIDDATA;
  4094. }
  4095. return 0;
  4096. }
  4097. static int cenc_filter(MOVContext *c, MOVStreamContext *sc, uint8_t *input, int size)
  4098. {
  4099. uint32_t encrypted_bytes;
  4100. uint16_t subsample_count;
  4101. uint16_t clear_bytes;
  4102. uint8_t* input_end = input + size;
  4103. /* read the iv */
  4104. if (AES_CTR_IV_SIZE > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
  4105. av_log(c->fc, AV_LOG_ERROR, "failed to read iv from the auxiliary info\n");
  4106. return AVERROR_INVALIDDATA;
  4107. }
  4108. av_aes_ctr_set_iv(sc->cenc.aes_ctr, sc->cenc.auxiliary_info_pos);
  4109. sc->cenc.auxiliary_info_pos += AES_CTR_IV_SIZE;
  4110. if (!sc->cenc.use_subsamples)
  4111. {
  4112. /* decrypt the whole packet */
  4113. av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size);
  4114. return 0;
  4115. }
  4116. /* read the subsample count */
  4117. if (sizeof(uint16_t) > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
  4118. av_log(c->fc, AV_LOG_ERROR, "failed to read subsample count from the auxiliary info\n");
  4119. return AVERROR_INVALIDDATA;
  4120. }
  4121. subsample_count = AV_RB16(sc->cenc.auxiliary_info_pos);
  4122. sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
  4123. for (; subsample_count > 0; subsample_count--)
  4124. {
  4125. if (6 > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
  4126. av_log(c->fc, AV_LOG_ERROR, "failed to read subsample from the auxiliary info\n");
  4127. return AVERROR_INVALIDDATA;
  4128. }
  4129. /* read the number of clear / encrypted bytes */
  4130. clear_bytes = AV_RB16(sc->cenc.auxiliary_info_pos);
  4131. sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
  4132. encrypted_bytes = AV_RB32(sc->cenc.auxiliary_info_pos);
  4133. sc->cenc.auxiliary_info_pos += sizeof(uint32_t);
  4134. if ((uint64_t)clear_bytes + encrypted_bytes > input_end - input) {
  4135. av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
  4136. return AVERROR_INVALIDDATA;
  4137. }
  4138. /* skip the clear bytes */
  4139. input += clear_bytes;
  4140. /* decrypt the encrypted bytes */
  4141. av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, encrypted_bytes);
  4142. input += encrypted_bytes;
  4143. }
  4144. if (input < input_end) {
  4145. av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
  4146. return AVERROR_INVALIDDATA;
  4147. }
  4148. return 0;
  4149. }
  4150. static int mov_seek_auxiliary_info(AVFormatContext *s, MOVStreamContext *sc)
  4151. {
  4152. size_t auxiliary_info_seek_offset = 0;
  4153. int i;
  4154. if (sc->cenc.auxiliary_info_default_size) {
  4155. auxiliary_info_seek_offset = (size_t)sc->cenc.auxiliary_info_default_size * sc->current_sample;
  4156. } else if (sc->cenc.auxiliary_info_sizes) {
  4157. if (sc->current_sample > sc->cenc.auxiliary_info_sizes_count) {
  4158. av_log(s, AV_LOG_ERROR, "current sample %d greater than the number of auxiliary info sample sizes %"SIZE_SPECIFIER"\n",
  4159. sc->current_sample, sc->cenc.auxiliary_info_sizes_count);
  4160. return AVERROR_INVALIDDATA;
  4161. }
  4162. for (i = 0; i < sc->current_sample; i++) {
  4163. auxiliary_info_seek_offset += sc->cenc.auxiliary_info_sizes[i];
  4164. }
  4165. }
  4166. if (auxiliary_info_seek_offset > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info) {
  4167. av_log(s, AV_LOG_ERROR, "auxiliary info offset %"SIZE_SPECIFIER" greater than auxiliary info size %"SIZE_SPECIFIER"\n",
  4168. auxiliary_info_seek_offset, (size_t)(sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info));
  4169. return AVERROR_INVALIDDATA;
  4170. }
  4171. sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info + auxiliary_info_seek_offset;
  4172. return 0;
  4173. }
  4174. static const MOVParseTableEntry mov_default_parse_table[] = {
  4175. { MKTAG('A','C','L','R'), mov_read_aclr },
  4176. { MKTAG('A','P','R','G'), mov_read_avid },
  4177. { MKTAG('A','A','L','P'), mov_read_avid },
  4178. { MKTAG('A','R','E','S'), mov_read_ares },
  4179. { MKTAG('a','v','s','s'), mov_read_avss },
  4180. { MKTAG('c','h','p','l'), mov_read_chpl },
  4181. { MKTAG('c','o','6','4'), mov_read_stco },
  4182. { MKTAG('c','o','l','r'), mov_read_colr },
  4183. { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
  4184. { MKTAG('d','i','n','f'), mov_read_default },
  4185. { MKTAG('D','p','x','E'), mov_read_dpxe },
  4186. { MKTAG('d','r','e','f'), mov_read_dref },
  4187. { MKTAG('e','d','t','s'), mov_read_default },
  4188. { MKTAG('e','l','s','t'), mov_read_elst },
  4189. { MKTAG('e','n','d','a'), mov_read_enda },
  4190. { MKTAG('f','i','e','l'), mov_read_fiel },
  4191. { MKTAG('a','d','r','m'), mov_read_adrm },
  4192. { MKTAG('f','t','y','p'), mov_read_ftyp },
  4193. { MKTAG('g','l','b','l'), mov_read_glbl },
  4194. { MKTAG('h','d','l','r'), mov_read_hdlr },
  4195. { MKTAG('i','l','s','t'), mov_read_ilst },
  4196. { MKTAG('j','p','2','h'), mov_read_jp2h },
  4197. { MKTAG('m','d','a','t'), mov_read_mdat },
  4198. { MKTAG('m','d','h','d'), mov_read_mdhd },
  4199. { MKTAG('m','d','i','a'), mov_read_default },
  4200. { MKTAG('m','e','t','a'), mov_read_meta },
  4201. { MKTAG('m','i','n','f'), mov_read_default },
  4202. { MKTAG('m','o','o','f'), mov_read_moof },
  4203. { MKTAG('m','o','o','v'), mov_read_moov },
  4204. { MKTAG('m','v','e','x'), mov_read_default },
  4205. { MKTAG('m','v','h','d'), mov_read_mvhd },
  4206. { MKTAG('S','M','I',' '), mov_read_svq3 },
  4207. { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
  4208. { MKTAG('a','v','c','C'), mov_read_glbl },
  4209. { MKTAG('p','a','s','p'), mov_read_pasp },
  4210. { MKTAG('s','i','d','x'), mov_read_sidx },
  4211. { MKTAG('s','t','b','l'), mov_read_default },
  4212. { MKTAG('s','t','c','o'), mov_read_stco },
  4213. { MKTAG('s','t','p','s'), mov_read_stps },
  4214. { MKTAG('s','t','r','f'), mov_read_strf },
  4215. { MKTAG('s','t','s','c'), mov_read_stsc },
  4216. { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
  4217. { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
  4218. { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
  4219. { MKTAG('s','t','t','s'), mov_read_stts },
  4220. { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
  4221. { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
  4222. { MKTAG('t','f','d','t'), mov_read_tfdt },
  4223. { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
  4224. { MKTAG('t','r','a','k'), mov_read_trak },
  4225. { MKTAG('t','r','a','f'), mov_read_default },
  4226. { MKTAG('t','r','e','f'), mov_read_default },
  4227. { MKTAG('t','m','c','d'), mov_read_tmcd },
  4228. { MKTAG('c','h','a','p'), mov_read_chap },
  4229. { MKTAG('t','r','e','x'), mov_read_trex },
  4230. { MKTAG('t','r','u','n'), mov_read_trun },
  4231. { MKTAG('u','d','t','a'), mov_read_default },
  4232. { MKTAG('w','a','v','e'), mov_read_wave },
  4233. { MKTAG('e','s','d','s'), mov_read_esds },
  4234. { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
  4235. { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
  4236. { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
  4237. { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
  4238. { MKTAG('w','f','e','x'), mov_read_wfex },
  4239. { MKTAG('c','m','o','v'), mov_read_cmov },
  4240. { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
  4241. { MKTAG('d','v','c','1'), mov_read_dvc1 },
  4242. { MKTAG('s','b','g','p'), mov_read_sbgp },
  4243. { MKTAG('h','v','c','C'), mov_read_glbl },
  4244. { MKTAG('u','u','i','d'), mov_read_uuid },
  4245. { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
  4246. { MKTAG('f','r','e','e'), mov_read_free },
  4247. { MKTAG('-','-','-','-'), mov_read_custom },
  4248. { MKTAG('s','i','n','f'), mov_read_default },
  4249. { MKTAG('f','r','m','a'), mov_read_frma },
  4250. { MKTAG('s','e','n','c'), mov_read_senc },
  4251. { MKTAG('s','a','i','z'), mov_read_saiz },
  4252. { 0, NULL }
  4253. };
  4254. static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4255. {
  4256. int64_t total_size = 0;
  4257. MOVAtom a;
  4258. int i;
  4259. if (c->atom_depth > 10) {
  4260. av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
  4261. return AVERROR_INVALIDDATA;
  4262. }
  4263. c->atom_depth ++;
  4264. if (atom.size < 0)
  4265. atom.size = INT64_MAX;
  4266. while (total_size + 8 <= atom.size && !avio_feof(pb)) {
  4267. int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
  4268. a.size = atom.size;
  4269. a.type=0;
  4270. if (atom.size >= 8) {
  4271. a.size = avio_rb32(pb);
  4272. a.type = avio_rl32(pb);
  4273. if (a.type == MKTAG('f','r','e','e') &&
  4274. a.size >= 8 &&
  4275. c->fc->strict_std_compliance < FF_COMPLIANCE_STRICT &&
  4276. c->moov_retry) {
  4277. uint8_t buf[8];
  4278. uint32_t *type = (uint32_t *)buf + 1;
  4279. if (avio_read(pb, buf, 8) != 8)
  4280. return AVERROR_INVALIDDATA;
  4281. avio_seek(pb, -8, SEEK_CUR);
  4282. if (*type == MKTAG('m','v','h','d') ||
  4283. *type == MKTAG('c','m','o','v')) {
  4284. av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
  4285. a.type = MKTAG('m','o','o','v');
  4286. }
  4287. }
  4288. if (atom.type != MKTAG('r','o','o','t') &&
  4289. atom.type != MKTAG('m','o','o','v'))
  4290. {
  4291. if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
  4292. {
  4293. av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
  4294. avio_skip(pb, -8);
  4295. c->atom_depth --;
  4296. return 0;
  4297. }
  4298. }
  4299. total_size += 8;
  4300. if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
  4301. a.size = avio_rb64(pb) - 8;
  4302. total_size += 8;
  4303. }
  4304. }
  4305. av_log(c->fc, AV_LOG_TRACE, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
  4306. a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
  4307. if (a.size == 0) {
  4308. a.size = atom.size - total_size + 8;
  4309. }
  4310. a.size -= 8;
  4311. if (a.size < 0)
  4312. break;
  4313. a.size = FFMIN(a.size, atom.size - total_size);
  4314. for (i = 0; mov_default_parse_table[i].type; i++)
  4315. if (mov_default_parse_table[i].type == a.type) {
  4316. parse = mov_default_parse_table[i].parse;
  4317. break;
  4318. }
  4319. // container is user data
  4320. if (!parse && (atom.type == MKTAG('u','d','t','a') ||
  4321. atom.type == MKTAG('i','l','s','t')))
  4322. parse = mov_read_udta_string;
  4323. // Supports parsing the QuickTime Metadata Keys.
  4324. // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
  4325. if (!parse && c->found_hdlr_mdta &&
  4326. atom.type == MKTAG('m','e','t','a') &&
  4327. a.type == MKTAG('k','e','y','s')) {
  4328. parse = mov_read_keys;
  4329. }
  4330. if (!parse) { /* skip leaf atoms data */
  4331. avio_skip(pb, a.size);
  4332. } else {
  4333. int64_t start_pos = avio_tell(pb);
  4334. int64_t left;
  4335. int err = parse(c, pb, a);
  4336. if (err < 0) {
  4337. c->atom_depth --;
  4338. return err;
  4339. }
  4340. if (c->found_moov && c->found_mdat &&
  4341. ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete) ||
  4342. start_pos + a.size == avio_size(pb))) {
  4343. if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete)
  4344. c->next_root_atom = start_pos + a.size;
  4345. c->atom_depth --;
  4346. return 0;
  4347. }
  4348. left = a.size - avio_tell(pb) + start_pos;
  4349. if (left > 0) /* skip garbage at atom end */
  4350. avio_skip(pb, left);
  4351. else if (left < 0) {
  4352. av_log(c->fc, AV_LOG_WARNING,
  4353. "overread end of atom '%.4s' by %"PRId64" bytes\n",
  4354. (char*)&a.type, -left);
  4355. avio_seek(pb, left, SEEK_CUR);
  4356. }
  4357. }
  4358. total_size += a.size;
  4359. }
  4360. if (total_size < atom.size && atom.size < 0x7ffff)
  4361. avio_skip(pb, atom.size - total_size);
  4362. c->atom_depth --;
  4363. return 0;
  4364. }
  4365. static int mov_probe(AVProbeData *p)
  4366. {
  4367. int64_t offset;
  4368. uint32_t tag;
  4369. int score = 0;
  4370. int moov_offset = -1;
  4371. /* check file header */
  4372. offset = 0;
  4373. for (;;) {
  4374. /* ignore invalid offset */
  4375. if ((offset + 8) > (unsigned int)p->buf_size)
  4376. break;
  4377. tag = AV_RL32(p->buf + offset + 4);
  4378. switch(tag) {
  4379. /* check for obvious tags */
  4380. case MKTAG('m','o','o','v'):
  4381. moov_offset = offset + 4;
  4382. case MKTAG('m','d','a','t'):
  4383. case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
  4384. case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
  4385. case MKTAG('f','t','y','p'):
  4386. if (AV_RB32(p->buf+offset) < 8 &&
  4387. (AV_RB32(p->buf+offset) != 1 ||
  4388. offset + 12 > (unsigned int)p->buf_size ||
  4389. AV_RB64(p->buf+offset + 8) == 0)) {
  4390. score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
  4391. } else if (tag == MKTAG('f','t','y','p') &&
  4392. ( AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
  4393. || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
  4394. )) {
  4395. score = FFMAX(score, 5);
  4396. } else {
  4397. score = AVPROBE_SCORE_MAX;
  4398. }
  4399. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  4400. break;
  4401. /* those are more common words, so rate then a bit less */
  4402. case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
  4403. case MKTAG('w','i','d','e'):
  4404. case MKTAG('f','r','e','e'):
  4405. case MKTAG('j','u','n','k'):
  4406. case MKTAG('p','i','c','t'):
  4407. score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
  4408. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  4409. break;
  4410. case MKTAG(0x82,0x82,0x7f,0x7d):
  4411. case MKTAG('s','k','i','p'):
  4412. case MKTAG('u','u','i','d'):
  4413. case MKTAG('p','r','f','l'):
  4414. /* if we only find those cause probedata is too small at least rate them */
  4415. score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
  4416. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  4417. break;
  4418. default:
  4419. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  4420. }
  4421. }
  4422. if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
  4423. /* moov atom in the header - we should make sure that this is not a
  4424. * MOV-packed MPEG-PS */
  4425. offset = moov_offset;
  4426. while(offset < (p->buf_size - 16)){ /* Sufficient space */
  4427. /* We found an actual hdlr atom */
  4428. if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
  4429. AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
  4430. AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
  4431. av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
  4432. /* We found a media handler reference atom describing an
  4433. * MPEG-PS-in-MOV, return a
  4434. * low score to force expanding the probe window until
  4435. * mpegps_probe finds what it needs */
  4436. return 5;
  4437. }else
  4438. /* Keep looking */
  4439. offset+=2;
  4440. }
  4441. }
  4442. return score;
  4443. }
  4444. // must be done after parsing all trak because there's no order requirement
  4445. static void mov_read_chapters(AVFormatContext *s)
  4446. {
  4447. MOVContext *mov = s->priv_data;
  4448. AVStream *st;
  4449. MOVStreamContext *sc;
  4450. int64_t cur_pos;
  4451. int i, j;
  4452. int chapter_track;
  4453. for (j = 0; j < mov->nb_chapter_tracks; j++) {
  4454. chapter_track = mov->chapter_tracks[j];
  4455. st = NULL;
  4456. for (i = 0; i < s->nb_streams; i++)
  4457. if (s->streams[i]->id == chapter_track) {
  4458. st = s->streams[i];
  4459. break;
  4460. }
  4461. if (!st) {
  4462. av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
  4463. continue;
  4464. }
  4465. sc = st->priv_data;
  4466. cur_pos = avio_tell(sc->pb);
  4467. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  4468. st->disposition |= AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS;
  4469. if (st->nb_index_entries) {
  4470. // Retrieve the first frame, if possible
  4471. AVPacket pkt;
  4472. AVIndexEntry *sample = &st->index_entries[0];
  4473. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  4474. av_log(s, AV_LOG_ERROR, "Failed to retrieve first frame\n");
  4475. goto finish;
  4476. }
  4477. if (av_get_packet(sc->pb, &pkt, sample->size) < 0)
  4478. goto finish;
  4479. st->attached_pic = pkt;
  4480. st->attached_pic.stream_index = st->index;
  4481. st->attached_pic.flags |= AV_PKT_FLAG_KEY;
  4482. }
  4483. } else {
  4484. st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  4485. st->codecpar->codec_id = AV_CODEC_ID_BIN_DATA;
  4486. st->discard = AVDISCARD_ALL;
  4487. for (i = 0; i < st->nb_index_entries; i++) {
  4488. AVIndexEntry *sample = &st->index_entries[i];
  4489. int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
  4490. uint8_t *title;
  4491. uint16_t ch;
  4492. int len, title_len;
  4493. if (end < sample->timestamp) {
  4494. av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
  4495. end = AV_NOPTS_VALUE;
  4496. }
  4497. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  4498. av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
  4499. goto finish;
  4500. }
  4501. // the first two bytes are the length of the title
  4502. len = avio_rb16(sc->pb);
  4503. if (len > sample->size-2)
  4504. continue;
  4505. title_len = 2*len + 1;
  4506. if (!(title = av_mallocz(title_len)))
  4507. goto finish;
  4508. // The samples could theoretically be in any encoding if there's an encd
  4509. // atom following, but in practice are only utf-8 or utf-16, distinguished
  4510. // instead by the presence of a BOM
  4511. if (!len) {
  4512. title[0] = 0;
  4513. } else {
  4514. ch = avio_rb16(sc->pb);
  4515. if (ch == 0xfeff)
  4516. avio_get_str16be(sc->pb, len, title, title_len);
  4517. else if (ch == 0xfffe)
  4518. avio_get_str16le(sc->pb, len, title, title_len);
  4519. else {
  4520. AV_WB16(title, ch);
  4521. if (len == 1 || len == 2)
  4522. title[len] = 0;
  4523. else
  4524. avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
  4525. }
  4526. }
  4527. avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
  4528. av_freep(&title);
  4529. }
  4530. }
  4531. finish:
  4532. avio_seek(sc->pb, cur_pos, SEEK_SET);
  4533. }
  4534. }
  4535. static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
  4536. uint32_t value, int flags)
  4537. {
  4538. AVTimecode tc;
  4539. char buf[AV_TIMECODE_STR_SIZE];
  4540. AVRational rate = st->avg_frame_rate;
  4541. int ret = av_timecode_init(&tc, rate, flags, 0, s);
  4542. if (ret < 0)
  4543. return ret;
  4544. av_dict_set(&st->metadata, "timecode",
  4545. av_timecode_make_string(&tc, buf, value), 0);
  4546. return 0;
  4547. }
  4548. static int mov_read_rtmd_track(AVFormatContext *s, AVStream *st)
  4549. {
  4550. MOVStreamContext *sc = st->priv_data;
  4551. char buf[AV_TIMECODE_STR_SIZE];
  4552. int64_t cur_pos = avio_tell(sc->pb);
  4553. int hh, mm, ss, ff, drop;
  4554. if (!st->nb_index_entries)
  4555. return -1;
  4556. avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
  4557. avio_skip(s->pb, 13);
  4558. hh = avio_r8(s->pb);
  4559. mm = avio_r8(s->pb);
  4560. ss = avio_r8(s->pb);
  4561. drop = avio_r8(s->pb);
  4562. ff = avio_r8(s->pb);
  4563. snprintf(buf, AV_TIMECODE_STR_SIZE, "%02d:%02d:%02d%c%02d",
  4564. hh, mm, ss, drop ? ';' : ':', ff);
  4565. av_dict_set(&st->metadata, "timecode", buf, 0);
  4566. avio_seek(sc->pb, cur_pos, SEEK_SET);
  4567. return 0;
  4568. }
  4569. static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
  4570. {
  4571. MOVStreamContext *sc = st->priv_data;
  4572. int flags = 0;
  4573. int64_t cur_pos = avio_tell(sc->pb);
  4574. uint32_t value;
  4575. if (!st->nb_index_entries)
  4576. return -1;
  4577. avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
  4578. value = avio_rb32(s->pb);
  4579. if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
  4580. if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  4581. if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
  4582. /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
  4583. * not the case) and thus assume "frame number format" instead of QT one.
  4584. * No sample with tmcd track can be found with a QT timecode at the moment,
  4585. * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
  4586. * format). */
  4587. parse_timecode_in_framenum_format(s, st, value, flags);
  4588. avio_seek(sc->pb, cur_pos, SEEK_SET);
  4589. return 0;
  4590. }
  4591. static int mov_read_close(AVFormatContext *s)
  4592. {
  4593. MOVContext *mov = s->priv_data;
  4594. int i, j;
  4595. for (i = 0; i < s->nb_streams; i++) {
  4596. AVStream *st = s->streams[i];
  4597. MOVStreamContext *sc = st->priv_data;
  4598. if (!sc)
  4599. continue;
  4600. av_freep(&sc->ctts_data);
  4601. for (j = 0; j < sc->drefs_count; j++) {
  4602. av_freep(&sc->drefs[j].path);
  4603. av_freep(&sc->drefs[j].dir);
  4604. }
  4605. av_freep(&sc->drefs);
  4606. sc->drefs_count = 0;
  4607. if (!sc->pb_is_copied)
  4608. ff_format_io_close(s, &sc->pb);
  4609. sc->pb = NULL;
  4610. av_freep(&sc->chunk_offsets);
  4611. av_freep(&sc->stsc_data);
  4612. av_freep(&sc->sample_sizes);
  4613. av_freep(&sc->keyframes);
  4614. av_freep(&sc->stts_data);
  4615. av_freep(&sc->stps_data);
  4616. av_freep(&sc->elst_data);
  4617. av_freep(&sc->rap_group);
  4618. av_freep(&sc->display_matrix);
  4619. if (sc->extradata)
  4620. for (j = 0; j < sc->stsd_count; j++)
  4621. av_free(sc->extradata[j]);
  4622. av_freep(&sc->extradata);
  4623. av_freep(&sc->extradata_size);
  4624. av_freep(&sc->cenc.auxiliary_info);
  4625. av_freep(&sc->cenc.auxiliary_info_sizes);
  4626. av_aes_ctr_free(sc->cenc.aes_ctr);
  4627. }
  4628. if (mov->dv_demux) {
  4629. avformat_free_context(mov->dv_fctx);
  4630. mov->dv_fctx = NULL;
  4631. }
  4632. if (mov->meta_keys) {
  4633. for (i = 1; i < mov->meta_keys_count; i++) {
  4634. av_freep(&mov->meta_keys[i]);
  4635. }
  4636. av_freep(&mov->meta_keys);
  4637. }
  4638. av_freep(&mov->trex_data);
  4639. av_freep(&mov->bitrates);
  4640. for (i = 0; i < mov->fragment_index_count; i++) {
  4641. MOVFragmentIndex* index = mov->fragment_index_data[i];
  4642. av_freep(&index->items);
  4643. av_freep(&mov->fragment_index_data[i]);
  4644. }
  4645. av_freep(&mov->fragment_index_data);
  4646. av_freep(&mov->aes_decrypt);
  4647. return 0;
  4648. }
  4649. static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
  4650. {
  4651. int i;
  4652. for (i = 0; i < s->nb_streams; i++) {
  4653. AVStream *st = s->streams[i];
  4654. MOVStreamContext *sc = st->priv_data;
  4655. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
  4656. sc->timecode_track == tmcd_id)
  4657. return 1;
  4658. }
  4659. return 0;
  4660. }
  4661. /* look for a tmcd track not referenced by any video track, and export it globally */
  4662. static void export_orphan_timecode(AVFormatContext *s)
  4663. {
  4664. int i;
  4665. for (i = 0; i < s->nb_streams; i++) {
  4666. AVStream *st = s->streams[i];
  4667. if (st->codecpar->codec_tag == MKTAG('t','m','c','d') &&
  4668. !tmcd_is_referenced(s, i + 1)) {
  4669. AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
  4670. if (tcr) {
  4671. av_dict_set(&s->metadata, "timecode", tcr->value, 0);
  4672. break;
  4673. }
  4674. }
  4675. }
  4676. }
  4677. static int read_tfra(MOVContext *mov, AVIOContext *f)
  4678. {
  4679. MOVFragmentIndex* index = NULL;
  4680. int version, fieldlength, i, j;
  4681. int64_t pos = avio_tell(f);
  4682. uint32_t size = avio_rb32(f);
  4683. void *tmp;
  4684. if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
  4685. return 1;
  4686. }
  4687. av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
  4688. index = av_mallocz(sizeof(MOVFragmentIndex));
  4689. if (!index) {
  4690. return AVERROR(ENOMEM);
  4691. }
  4692. tmp = av_realloc_array(mov->fragment_index_data,
  4693. mov->fragment_index_count + 1,
  4694. sizeof(MOVFragmentIndex*));
  4695. if (!tmp) {
  4696. av_freep(&index);
  4697. return AVERROR(ENOMEM);
  4698. }
  4699. mov->fragment_index_data = tmp;
  4700. mov->fragment_index_data[mov->fragment_index_count++] = index;
  4701. version = avio_r8(f);
  4702. avio_rb24(f);
  4703. index->track_id = avio_rb32(f);
  4704. fieldlength = avio_rb32(f);
  4705. index->item_count = avio_rb32(f);
  4706. index->items = av_mallocz_array(
  4707. index->item_count, sizeof(MOVFragmentIndexItem));
  4708. if (!index->items) {
  4709. index->item_count = 0;
  4710. return AVERROR(ENOMEM);
  4711. }
  4712. for (i = 0; i < index->item_count; i++) {
  4713. int64_t time, offset;
  4714. if (version == 1) {
  4715. time = avio_rb64(f);
  4716. offset = avio_rb64(f);
  4717. } else {
  4718. time = avio_rb32(f);
  4719. offset = avio_rb32(f);
  4720. }
  4721. index->items[i].time = time;
  4722. index->items[i].moof_offset = offset;
  4723. for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
  4724. avio_r8(f);
  4725. for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
  4726. avio_r8(f);
  4727. for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
  4728. avio_r8(f);
  4729. }
  4730. avio_seek(f, pos + size, SEEK_SET);
  4731. return 0;
  4732. }
  4733. static int mov_read_mfra(MOVContext *c, AVIOContext *f)
  4734. {
  4735. int64_t stream_size = avio_size(f);
  4736. int64_t original_pos = avio_tell(f);
  4737. int64_t seek_ret;
  4738. int32_t mfra_size;
  4739. int ret = -1;
  4740. if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
  4741. ret = seek_ret;
  4742. goto fail;
  4743. }
  4744. mfra_size = avio_rb32(f);
  4745. if (mfra_size < 0 || mfra_size > stream_size) {
  4746. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
  4747. goto fail;
  4748. }
  4749. if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
  4750. ret = seek_ret;
  4751. goto fail;
  4752. }
  4753. if (avio_rb32(f) != mfra_size) {
  4754. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
  4755. goto fail;
  4756. }
  4757. if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
  4758. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
  4759. goto fail;
  4760. }
  4761. av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
  4762. do {
  4763. ret = read_tfra(c, f);
  4764. if (ret < 0)
  4765. goto fail;
  4766. } while (!ret);
  4767. ret = 0;
  4768. fail:
  4769. seek_ret = avio_seek(f, original_pos, SEEK_SET);
  4770. if (seek_ret < 0) {
  4771. av_log(c->fc, AV_LOG_ERROR,
  4772. "failed to seek back after looking for mfra\n");
  4773. ret = seek_ret;
  4774. }
  4775. return ret;
  4776. }
  4777. static int mov_read_header(AVFormatContext *s)
  4778. {
  4779. MOVContext *mov = s->priv_data;
  4780. AVIOContext *pb = s->pb;
  4781. int j, err;
  4782. MOVAtom atom = { AV_RL32("root") };
  4783. int i;
  4784. if (mov->decryption_key_len != 0 && mov->decryption_key_len != AES_CTR_KEY_SIZE) {
  4785. av_log(s, AV_LOG_ERROR, "Invalid decryption key len %d expected %d\n",
  4786. mov->decryption_key_len, AES_CTR_KEY_SIZE);
  4787. return AVERROR(EINVAL);
  4788. }
  4789. mov->fc = s;
  4790. mov->trak_index = -1;
  4791. /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
  4792. if (pb->seekable)
  4793. atom.size = avio_size(pb);
  4794. else
  4795. atom.size = INT64_MAX;
  4796. /* check MOV header */
  4797. do {
  4798. if (mov->moov_retry)
  4799. avio_seek(pb, 0, SEEK_SET);
  4800. if ((err = mov_read_default(mov, pb, atom)) < 0) {
  4801. av_log(s, AV_LOG_ERROR, "error reading header\n");
  4802. mov_read_close(s);
  4803. return err;
  4804. }
  4805. } while (pb->seekable && !mov->found_moov && !mov->moov_retry++);
  4806. if (!mov->found_moov) {
  4807. av_log(s, AV_LOG_ERROR, "moov atom not found\n");
  4808. mov_read_close(s);
  4809. return AVERROR_INVALIDDATA;
  4810. }
  4811. av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
  4812. if (pb->seekable) {
  4813. if (mov->nb_chapter_tracks > 0 && !mov->ignore_chapters)
  4814. mov_read_chapters(s);
  4815. for (i = 0; i < s->nb_streams; i++)
  4816. if (s->streams[i]->codecpar->codec_tag == AV_RL32("tmcd")) {
  4817. mov_read_timecode_track(s, s->streams[i]);
  4818. } else if (s->streams[i]->codecpar->codec_tag == AV_RL32("rtmd")) {
  4819. mov_read_rtmd_track(s, s->streams[i]);
  4820. }
  4821. }
  4822. /* copy timecode metadata from tmcd tracks to the related video streams */
  4823. for (i = 0; i < s->nb_streams; i++) {
  4824. AVStream *st = s->streams[i];
  4825. MOVStreamContext *sc = st->priv_data;
  4826. if (sc->timecode_track > 0) {
  4827. AVDictionaryEntry *tcr;
  4828. int tmcd_st_id = -1;
  4829. for (j = 0; j < s->nb_streams; j++)
  4830. if (s->streams[j]->id == sc->timecode_track)
  4831. tmcd_st_id = j;
  4832. if (tmcd_st_id < 0 || tmcd_st_id == i)
  4833. continue;
  4834. tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
  4835. if (tcr)
  4836. av_dict_set(&st->metadata, "timecode", tcr->value, 0);
  4837. }
  4838. }
  4839. export_orphan_timecode(s);
  4840. for (i = 0; i < s->nb_streams; i++) {
  4841. AVStream *st = s->streams[i];
  4842. MOVStreamContext *sc = st->priv_data;
  4843. fix_timescale(mov, sc);
  4844. if(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id == AV_CODEC_ID_AAC) {
  4845. st->skip_samples = sc->start_pad;
  4846. }
  4847. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
  4848. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  4849. sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
  4850. if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  4851. if (st->codecpar->width <= 0 || st->codecpar->height <= 0) {
  4852. st->codecpar->width = sc->width;
  4853. st->codecpar->height = sc->height;
  4854. }
  4855. if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
  4856. if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
  4857. return err;
  4858. }
  4859. }
  4860. if (mov->handbrake_version &&
  4861. mov->handbrake_version <= 1000000*0 + 1000*10 + 2 && // 0.10.2
  4862. st->codecpar->codec_id == AV_CODEC_ID_MP3
  4863. ) {
  4864. av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n");
  4865. st->need_parsing = AVSTREAM_PARSE_FULL;
  4866. }
  4867. }
  4868. if (mov->trex_data) {
  4869. for (i = 0; i < s->nb_streams; i++) {
  4870. AVStream *st = s->streams[i];
  4871. MOVStreamContext *sc = st->priv_data;
  4872. if (st->duration > 0)
  4873. st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
  4874. }
  4875. }
  4876. if (mov->use_mfra_for > 0) {
  4877. for (i = 0; i < s->nb_streams; i++) {
  4878. AVStream *st = s->streams[i];
  4879. MOVStreamContext *sc = st->priv_data;
  4880. if (sc->duration_for_fps > 0) {
  4881. st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale /
  4882. sc->duration_for_fps;
  4883. }
  4884. }
  4885. }
  4886. for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
  4887. if (mov->bitrates[i]) {
  4888. s->streams[i]->codecpar->bit_rate = mov->bitrates[i];
  4889. }
  4890. }
  4891. ff_rfps_calculate(s);
  4892. for (i = 0; i < s->nb_streams; i++) {
  4893. AVStream *st = s->streams[i];
  4894. MOVStreamContext *sc = st->priv_data;
  4895. switch (st->codecpar->codec_type) {
  4896. case AVMEDIA_TYPE_AUDIO:
  4897. err = ff_replaygain_export(st, s->metadata);
  4898. if (err < 0) {
  4899. mov_read_close(s);
  4900. return err;
  4901. }
  4902. break;
  4903. case AVMEDIA_TYPE_VIDEO:
  4904. if (sc->display_matrix) {
  4905. AVPacketSideData *sd, *tmp;
  4906. tmp = av_realloc_array(st->side_data,
  4907. st->nb_side_data + 1, sizeof(*tmp));
  4908. if (!tmp)
  4909. return AVERROR(ENOMEM);
  4910. st->side_data = tmp;
  4911. st->nb_side_data++;
  4912. sd = &st->side_data[st->nb_side_data - 1];
  4913. sd->type = AV_PKT_DATA_DISPLAYMATRIX;
  4914. sd->size = sizeof(int32_t) * 9;
  4915. sd->data = (uint8_t*)sc->display_matrix;
  4916. sc->display_matrix = NULL;
  4917. }
  4918. break;
  4919. }
  4920. }
  4921. ff_configure_buffers_for_index(s, AV_TIME_BASE);
  4922. return 0;
  4923. }
  4924. static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
  4925. {
  4926. AVIndexEntry *sample = NULL;
  4927. int64_t best_dts = INT64_MAX;
  4928. int i;
  4929. for (i = 0; i < s->nb_streams; i++) {
  4930. AVStream *avst = s->streams[i];
  4931. MOVStreamContext *msc = avst->priv_data;
  4932. if (msc->pb && msc->current_sample < avst->nb_index_entries) {
  4933. AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
  4934. int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
  4935. av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
  4936. if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
  4937. (s->pb->seekable &&
  4938. ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
  4939. ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
  4940. (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
  4941. sample = current_sample;
  4942. best_dts = dts;
  4943. *st = avst;
  4944. }
  4945. }
  4946. }
  4947. return sample;
  4948. }
  4949. static int should_retry(AVIOContext *pb, int error_code) {
  4950. if (error_code == AVERROR_EOF || avio_feof(pb))
  4951. return 0;
  4952. return 1;
  4953. }
  4954. static int mov_switch_root(AVFormatContext *s, int64_t target)
  4955. {
  4956. MOVContext *mov = s->priv_data;
  4957. int i, j;
  4958. int already_read = 0;
  4959. if (avio_seek(s->pb, target, SEEK_SET) != target) {
  4960. av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
  4961. return AVERROR_INVALIDDATA;
  4962. }
  4963. mov->next_root_atom = 0;
  4964. for (i = 0; i < mov->fragment_index_count; i++) {
  4965. MOVFragmentIndex *index = mov->fragment_index_data[i];
  4966. int found = 0;
  4967. for (j = 0; j < index->item_count; j++) {
  4968. MOVFragmentIndexItem *item = &index->items[j];
  4969. if (found) {
  4970. mov->next_root_atom = item->moof_offset;
  4971. break; // Advance to next index in outer loop
  4972. } else if (item->moof_offset == target) {
  4973. index->current_item = FFMIN(j, index->current_item);
  4974. if (item->headers_read)
  4975. already_read = 1;
  4976. item->headers_read = 1;
  4977. found = 1;
  4978. }
  4979. }
  4980. if (!found)
  4981. index->current_item = 0;
  4982. }
  4983. if (already_read)
  4984. return 0;
  4985. mov->found_mdat = 0;
  4986. if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
  4987. avio_feof(s->pb))
  4988. return AVERROR_EOF;
  4989. av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
  4990. return 1;
  4991. }
  4992. static int mov_change_extradata(MOVStreamContext *sc, AVPacket *pkt)
  4993. {
  4994. uint8_t *side, *extradata;
  4995. int extradata_size;
  4996. /* Save the current index. */
  4997. sc->last_stsd_index = sc->stsc_data[sc->stsc_index].id - 1;
  4998. /* Notify the decoder that extradata changed. */
  4999. extradata_size = sc->extradata_size[sc->last_stsd_index];
  5000. extradata = sc->extradata[sc->last_stsd_index];
  5001. if (extradata_size > 0 && extradata) {
  5002. side = av_packet_new_side_data(pkt,
  5003. AV_PKT_DATA_NEW_EXTRADATA,
  5004. extradata_size);
  5005. if (!side)
  5006. return AVERROR(ENOMEM);
  5007. memcpy(side, extradata, extradata_size);
  5008. }
  5009. return 0;
  5010. }
  5011. static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
  5012. {
  5013. MOVContext *mov = s->priv_data;
  5014. MOVStreamContext *sc;
  5015. AVIndexEntry *sample;
  5016. AVStream *st = NULL;
  5017. int ret;
  5018. mov->fc = s;
  5019. retry:
  5020. sample = mov_find_next_sample(s, &st);
  5021. if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
  5022. if (!mov->next_root_atom)
  5023. return AVERROR_EOF;
  5024. if ((ret = mov_switch_root(s, mov->next_root_atom)) < 0)
  5025. return ret;
  5026. goto retry;
  5027. }
  5028. sc = st->priv_data;
  5029. /* must be done just before reading, to avoid infinite loop on sample */
  5030. sc->current_sample++;
  5031. if (mov->next_root_atom) {
  5032. sample->pos = FFMIN(sample->pos, mov->next_root_atom);
  5033. sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
  5034. }
  5035. if (st->discard != AVDISCARD_ALL) {
  5036. int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
  5037. if (ret64 != sample->pos) {
  5038. av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
  5039. sc->ffindex, sample->pos);
  5040. sc->current_sample -= should_retry(sc->pb, ret64);
  5041. return AVERROR_INVALIDDATA;
  5042. }
  5043. if( st->discard == AVDISCARD_NONKEY && 0==(sample->flags & AVINDEX_KEYFRAME) ) {
  5044. av_log(mov->fc, AV_LOG_DEBUG, "Nonkey frame from stream %d discarded due to AVDISCARD_NONKEY\n", sc->ffindex);
  5045. goto retry;
  5046. }
  5047. ret = av_get_packet(sc->pb, pkt, sample->size);
  5048. if (ret < 0) {
  5049. sc->current_sample -= should_retry(sc->pb, ret);
  5050. return ret;
  5051. }
  5052. if (sc->has_palette) {
  5053. uint8_t *pal;
  5054. pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
  5055. if (!pal) {
  5056. av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
  5057. } else {
  5058. memcpy(pal, sc->palette, AVPALETTE_SIZE);
  5059. sc->has_palette = 0;
  5060. }
  5061. }
  5062. #if CONFIG_DV_DEMUXER
  5063. if (mov->dv_demux && sc->dv_audio_container) {
  5064. avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
  5065. av_freep(&pkt->data);
  5066. pkt->size = 0;
  5067. ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
  5068. if (ret < 0)
  5069. return ret;
  5070. }
  5071. #endif
  5072. if (st->codecpar->codec_id == AV_CODEC_ID_MP3 && !st->need_parsing && pkt->size > 4) {
  5073. if (ff_mpa_check_header(AV_RB32(pkt->data)) < 0)
  5074. st->need_parsing = AVSTREAM_PARSE_FULL;
  5075. }
  5076. }
  5077. pkt->stream_index = sc->ffindex;
  5078. pkt->dts = sample->timestamp;
  5079. if (sample->flags & AVINDEX_DISCARD_FRAME) {
  5080. pkt->flags |= AV_PKT_FLAG_DISCARD;
  5081. }
  5082. if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
  5083. pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
  5084. /* update ctts context */
  5085. sc->ctts_sample++;
  5086. if (sc->ctts_index < sc->ctts_count &&
  5087. sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
  5088. sc->ctts_index++;
  5089. sc->ctts_sample = 0;
  5090. }
  5091. } else {
  5092. int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
  5093. st->index_entries[sc->current_sample].timestamp : st->duration;
  5094. pkt->duration = next_dts - pkt->dts;
  5095. pkt->pts = pkt->dts;
  5096. }
  5097. if (st->discard == AVDISCARD_ALL)
  5098. goto retry;
  5099. pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
  5100. pkt->pos = sample->pos;
  5101. /* Multiple stsd handling. */
  5102. if (sc->stsc_data) {
  5103. /* Keep track of the stsc index for the given sample, then check
  5104. * if the stsd index is different from the last used one. */
  5105. sc->stsc_sample++;
  5106. if (sc->stsc_index < sc->stsc_count - 1 &&
  5107. mov_get_stsc_samples(sc, sc->stsc_index) == sc->stsc_sample) {
  5108. sc->stsc_index++;
  5109. sc->stsc_sample = 0;
  5110. /* Do not check indexes after a switch. */
  5111. } else if (sc->stsc_data[sc->stsc_index].id > 0 &&
  5112. sc->stsc_data[sc->stsc_index].id - 1 < sc->stsd_count &&
  5113. sc->stsc_data[sc->stsc_index].id - 1 != sc->last_stsd_index) {
  5114. ret = mov_change_extradata(sc, pkt);
  5115. if (ret < 0)
  5116. return ret;
  5117. }
  5118. }
  5119. if (mov->aax_mode)
  5120. aax_filter(pkt->data, pkt->size, mov);
  5121. if (sc->cenc.aes_ctr) {
  5122. ret = cenc_filter(mov, sc, pkt->data, pkt->size);
  5123. if (ret) {
  5124. return ret;
  5125. }
  5126. }
  5127. return 0;
  5128. }
  5129. static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
  5130. {
  5131. MOVContext *mov = s->priv_data;
  5132. MOVStreamContext *sc = st->priv_data;
  5133. int i, j;
  5134. if (!mov->fragment_index_complete)
  5135. return 0;
  5136. for (i = 0; i < mov->fragment_index_count; i++) {
  5137. if (mov->fragment_index_data[i]->track_id == st->id || !sc->has_sidx) {
  5138. MOVFragmentIndex *index = mov->fragment_index_data[i];
  5139. for (j = index->item_count - 1; j >= 0; j--) {
  5140. if (index->items[j].time <= timestamp) {
  5141. if (index->items[j].headers_read)
  5142. return 0;
  5143. return mov_switch_root(s, index->items[j].moof_offset);
  5144. }
  5145. }
  5146. }
  5147. }
  5148. return 0;
  5149. }
  5150. static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
  5151. {
  5152. MOVStreamContext *sc = st->priv_data;
  5153. int sample, time_sample;
  5154. int i;
  5155. int ret = mov_seek_fragment(s, st, timestamp);
  5156. if (ret < 0)
  5157. return ret;
  5158. sample = av_index_search_timestamp(st, timestamp, flags);
  5159. av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
  5160. if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
  5161. sample = 0;
  5162. if (sample < 0) /* not sure what to do */
  5163. return AVERROR_INVALIDDATA;
  5164. sc->current_sample = sample;
  5165. av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
  5166. /* adjust ctts index */
  5167. if (sc->ctts_data) {
  5168. time_sample = 0;
  5169. for (i = 0; i < sc->ctts_count; i++) {
  5170. int next = time_sample + sc->ctts_data[i].count;
  5171. if (next > sc->current_sample) {
  5172. sc->ctts_index = i;
  5173. sc->ctts_sample = sc->current_sample - time_sample;
  5174. break;
  5175. }
  5176. time_sample = next;
  5177. }
  5178. }
  5179. /* adjust stsd index */
  5180. time_sample = 0;
  5181. for (i = 0; i < sc->stsc_count; i++) {
  5182. int next = time_sample + mov_get_stsc_samples(sc, i);
  5183. if (next > sc->current_sample) {
  5184. sc->stsc_index = i;
  5185. sc->stsc_sample = sc->current_sample - time_sample;
  5186. break;
  5187. }
  5188. time_sample = next;
  5189. }
  5190. ret = mov_seek_auxiliary_info(s, sc);
  5191. if (ret < 0) {
  5192. return ret;
  5193. }
  5194. return sample;
  5195. }
  5196. static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  5197. {
  5198. MOVContext *mc = s->priv_data;
  5199. AVStream *st;
  5200. int sample;
  5201. int i;
  5202. if (stream_index >= s->nb_streams)
  5203. return AVERROR_INVALIDDATA;
  5204. st = s->streams[stream_index];
  5205. sample = mov_seek_stream(s, st, sample_time, flags);
  5206. if (sample < 0)
  5207. return sample;
  5208. if (mc->seek_individually) {
  5209. /* adjust seek timestamp to found sample timestamp */
  5210. int64_t seek_timestamp = st->index_entries[sample].timestamp;
  5211. for (i = 0; i < s->nb_streams; i++) {
  5212. int64_t timestamp;
  5213. MOVStreamContext *sc = s->streams[i]->priv_data;
  5214. st = s->streams[i];
  5215. st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
  5216. if (stream_index == i)
  5217. continue;
  5218. timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
  5219. mov_seek_stream(s, st, timestamp, flags);
  5220. }
  5221. } else {
  5222. for (i = 0; i < s->nb_streams; i++) {
  5223. MOVStreamContext *sc;
  5224. st = s->streams[i];
  5225. sc = st->priv_data;
  5226. sc->current_sample = 0;
  5227. }
  5228. while (1) {
  5229. MOVStreamContext *sc;
  5230. AVIndexEntry *entry = mov_find_next_sample(s, &st);
  5231. if (!entry)
  5232. return AVERROR_INVALIDDATA;
  5233. sc = st->priv_data;
  5234. if (sc->ffindex == stream_index && sc->current_sample == sample)
  5235. break;
  5236. sc->current_sample++;
  5237. }
  5238. }
  5239. return 0;
  5240. }
  5241. #define OFFSET(x) offsetof(MOVContext, x)
  5242. #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  5243. static const AVOption mov_options[] = {
  5244. {"use_absolute_path",
  5245. "allow using absolute path when opening alias, this is a possible security issue",
  5246. OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0},
  5247. 0, 1, FLAGS},
  5248. {"seek_streams_individually",
  5249. "Seek each stream individually to the to the closest point",
  5250. OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 },
  5251. 0, 1, FLAGS},
  5252. {"ignore_editlist", "", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0},
  5253. 0, 1, FLAGS},
  5254. {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0},
  5255. 0, 1, FLAGS},
  5256. {"use_mfra_for",
  5257. "use mfra for fragment timestamps",
  5258. OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
  5259. -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
  5260. "use_mfra_for"},
  5261. {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
  5262. FLAGS, "use_mfra_for" },
  5263. {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
  5264. FLAGS, "use_mfra_for" },
  5265. {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
  5266. FLAGS, "use_mfra_for" },
  5267. { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
  5268. AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
  5269. { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
  5270. AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
  5271. { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
  5272. AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
  5273. { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
  5274. "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
  5275. AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
  5276. .flags = AV_OPT_FLAG_DECODING_PARAM },
  5277. { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
  5278. { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs), AV_OPT_TYPE_BOOL,
  5279. {.i64 = 0}, 0, 1, FLAGS },
  5280. { NULL },
  5281. };
  5282. static const AVClass mov_class = {
  5283. .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
  5284. .item_name = av_default_item_name,
  5285. .option = mov_options,
  5286. .version = LIBAVUTIL_VERSION_INT,
  5287. };
  5288. AVInputFormat ff_mov_demuxer = {
  5289. .name = "mov,mp4,m4a,3gp,3g2,mj2",
  5290. .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
  5291. .priv_class = &mov_class,
  5292. .priv_data_size = sizeof(MOVContext),
  5293. .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
  5294. .read_probe = mov_probe,
  5295. .read_header = mov_read_header,
  5296. .read_packet = mov_read_packet,
  5297. .read_close = mov_read_close,
  5298. .read_seek = mov_read_seek,
  5299. .flags = AVFMT_NO_BYTE_SEEK,
  5300. };