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.

5978 lines
203KB

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