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.

6487 lines
220KB

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