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.

4222 lines
140KB

  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. //#define MOV_EXPORT_ALL_METADATA
  29. #include "libavutil/attributes.h"
  30. #include "libavutil/channel_layout.h"
  31. #include "libavutil/display.h"
  32. #include "libavutil/intreadwrite.h"
  33. #include "libavutil/intfloat.h"
  34. #include "libavutil/mathematics.h"
  35. #include "libavutil/avstring.h"
  36. #include "libavutil/dict.h"
  37. #include "libavutil/opt.h"
  38. #include "libavutil/timecode.h"
  39. #include "libavcodec/ac3tab.h"
  40. #include "avformat.h"
  41. #include "internal.h"
  42. #include "avio_internal.h"
  43. #include "riff.h"
  44. #include "isom.h"
  45. #include "libavcodec/get_bits.h"
  46. #include "id3v1.h"
  47. #include "mov_chan.h"
  48. #include "replaygain.h"
  49. #if CONFIG_ZLIB
  50. #include <zlib.h>
  51. #endif
  52. #include "qtpalette.h"
  53. #undef NDEBUG
  54. #include <assert.h>
  55. /* those functions parse an atom */
  56. /* links atom IDs to parse functions */
  57. typedef struct MOVParseTableEntry {
  58. uint32_t type;
  59. int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
  60. } MOVParseTableEntry;
  61. static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
  62. static int mov_read_mfra(MOVContext *c, AVIOContext *f);
  63. static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
  64. unsigned len, const char *key)
  65. {
  66. char buf[16];
  67. short current, total = 0;
  68. avio_rb16(pb); // unknown
  69. current = avio_rb16(pb);
  70. if (len >= 6)
  71. total = avio_rb16(pb);
  72. if (!total)
  73. snprintf(buf, sizeof(buf), "%d", current);
  74. else
  75. snprintf(buf, sizeof(buf), "%d/%d", current, total);
  76. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  77. av_dict_set(&c->fc->metadata, key, buf, 0);
  78. return 0;
  79. }
  80. static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
  81. unsigned len, const char *key)
  82. {
  83. /* bypass padding bytes */
  84. avio_r8(pb);
  85. avio_r8(pb);
  86. avio_r8(pb);
  87. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  88. av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
  89. return 0;
  90. }
  91. static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
  92. unsigned len, const char *key)
  93. {
  94. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  95. av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
  96. return 0;
  97. }
  98. static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
  99. unsigned len, const char *key)
  100. {
  101. short genre;
  102. avio_r8(pb); // unknown
  103. genre = avio_r8(pb);
  104. if (genre < 1 || genre > ID3v1_GENRE_MAX)
  105. return 0;
  106. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  107. av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
  108. return 0;
  109. }
  110. static const uint32_t mac_to_unicode[128] = {
  111. 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
  112. 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
  113. 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
  114. 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
  115. 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
  116. 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
  117. 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
  118. 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
  119. 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
  120. 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
  121. 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
  122. 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
  123. 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
  124. 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
  125. 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
  126. 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
  127. };
  128. static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
  129. char *dst, int dstlen)
  130. {
  131. char *p = dst;
  132. char *end = dst+dstlen-1;
  133. int i;
  134. for (i = 0; i < len; i++) {
  135. uint8_t t, c = avio_r8(pb);
  136. if (c < 0x80 && p < end)
  137. *p++ = c;
  138. else if (p < end)
  139. PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
  140. }
  141. *p = 0;
  142. return p - dst;
  143. }
  144. static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
  145. {
  146. AVPacket pkt;
  147. AVStream *st;
  148. MOVStreamContext *sc;
  149. enum AVCodecID id;
  150. int ret;
  151. switch (type) {
  152. case 0xd: id = AV_CODEC_ID_MJPEG; break;
  153. case 0xe: id = AV_CODEC_ID_PNG; break;
  154. case 0x1b: id = AV_CODEC_ID_BMP; break;
  155. default:
  156. av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
  157. avio_skip(pb, len);
  158. return 0;
  159. }
  160. st = avformat_new_stream(c->fc, NULL);
  161. if (!st)
  162. return AVERROR(ENOMEM);
  163. sc = av_mallocz(sizeof(*sc));
  164. if (!sc)
  165. return AVERROR(ENOMEM);
  166. st->priv_data = sc;
  167. ret = av_get_packet(pb, &pkt, len);
  168. if (ret < 0)
  169. return ret;
  170. st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
  171. st->attached_pic = pkt;
  172. st->attached_pic.stream_index = st->index;
  173. st->attached_pic.flags |= AV_PKT_FLAG_KEY;
  174. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  175. st->codec->codec_id = id;
  176. return 0;
  177. }
  178. static int mov_metadata_raw(MOVContext *c, AVIOContext *pb,
  179. unsigned len, const char *key)
  180. {
  181. char *value = av_malloc(len + 1);
  182. if (!value)
  183. return AVERROR(ENOMEM);
  184. avio_read(pb, value, len);
  185. value[len] = 0;
  186. return av_dict_set(&c->fc->metadata, key, value, AV_DICT_DONT_STRDUP_VAL);
  187. }
  188. static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
  189. {
  190. char language[4] = { 0 };
  191. char buf[100];
  192. uint16_t langcode = 0;
  193. double longitude, latitude;
  194. const char *key = "location";
  195. if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4)
  196. return AVERROR_INVALIDDATA;
  197. avio_skip(pb, 4); // version+flags
  198. langcode = avio_rb16(pb);
  199. ff_mov_lang_to_iso639(langcode, language);
  200. len -= 6;
  201. len -= avio_get_str(pb, len, buf, sizeof(buf)); // place name
  202. if (len < 1)
  203. return AVERROR_INVALIDDATA;
  204. avio_skip(pb, 1); // role
  205. len -= 1;
  206. if (len < 14)
  207. return AVERROR_INVALIDDATA;
  208. longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
  209. latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
  210. // Try to output in the same format as the ?xyz field
  211. snprintf(buf, sizeof(buf), "%+08.4f%+09.4f/", latitude, longitude);
  212. if (*language && strcmp(language, "und")) {
  213. char key2[16];
  214. snprintf(key2, sizeof(key2), "%s-%s", key, language);
  215. av_dict_set(&c->fc->metadata, key2, buf, 0);
  216. }
  217. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  218. return av_dict_set(&c->fc->metadata, key, buf, 0);
  219. }
  220. static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  221. {
  222. #ifdef MOV_EXPORT_ALL_METADATA
  223. char tmp_key[5];
  224. #endif
  225. char key2[16], language[4] = {0};
  226. char *str = NULL;
  227. const char *key = NULL;
  228. uint16_t langcode = 0;
  229. uint32_t data_type = 0, str_size, str_size_alloc;
  230. int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
  231. switch (atom.type) {
  232. case MKTAG(0xa9,'n','a','m'): key = "title"; break;
  233. case MKTAG(0xa9,'a','u','t'):
  234. case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
  235. case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
  236. case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
  237. case MKTAG( 'c','p','i','l'): key = "compilation";
  238. parse = mov_metadata_int8_no_padding; break;
  239. case MKTAG( 'c','p','r','t'):
  240. case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
  241. case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
  242. case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
  243. case MKTAG(0xa9,'c','m','t'):
  244. case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
  245. case MKTAG(0xa9,'a','l','b'): key = "album"; break;
  246. case MKTAG(0xa9,'d','a','y'): key = "date"; break;
  247. case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
  248. case MKTAG( 'g','n','r','e'): key = "genre";
  249. parse = mov_metadata_gnre; break;
  250. case MKTAG(0xa9,'t','o','o'):
  251. case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
  252. case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
  253. case MKTAG(0xa9,'m','a','k'): key = "make"; break;
  254. case MKTAG(0xa9,'m','o','d'): key = "model"; break;
  255. case MKTAG(0xa9,'x','y','z'): key = "location"; break;
  256. case MKTAG( 'd','e','s','c'): key = "description";break;
  257. case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
  258. case MKTAG( 't','v','s','h'): key = "show"; break;
  259. case MKTAG( 't','v','e','n'): key = "episode_id";break;
  260. case MKTAG( 't','v','n','n'): key = "network"; break;
  261. case MKTAG( 't','r','k','n'): key = "track";
  262. parse = mov_metadata_track_or_disc_number; break;
  263. case MKTAG( 'd','i','s','k'): key = "disc";
  264. parse = mov_metadata_track_or_disc_number; break;
  265. case MKTAG( 't','v','e','s'): key = "episode_sort";
  266. parse = mov_metadata_int8_bypass_padding; break;
  267. case MKTAG( 't','v','s','n'): key = "season_number";
  268. parse = mov_metadata_int8_bypass_padding; break;
  269. case MKTAG( 's','t','i','k'): key = "media_type";
  270. parse = mov_metadata_int8_no_padding; break;
  271. case MKTAG( 'h','d','v','d'): key = "hd_video";
  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','R','M'):
  276. return mov_metadata_raw(c, pb, atom.size, "premiere_version");
  277. case MKTAG( '@','P','R','Q'):
  278. return mov_metadata_raw(c, pb, atom.size, "quicktime_version");
  279. case MKTAG( 'l','o','c','i'):
  280. return mov_metadata_loci(c, pb, atom.size);
  281. case MKTAG( 'X','M','P','_'):
  282. return mov_metadata_raw(c, pb, atom.size, "xmp");
  283. }
  284. if (c->itunes_metadata && atom.size > 8) {
  285. int data_size = avio_rb32(pb);
  286. int tag = avio_rl32(pb);
  287. if (tag == MKTAG('d','a','t','a')) {
  288. data_type = avio_rb32(pb); // type
  289. avio_rb32(pb); // unknown
  290. str_size = data_size - 16;
  291. atom.size -= 16;
  292. if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
  293. int ret = mov_read_covr(c, pb, data_type, str_size);
  294. if (ret < 0) {
  295. av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
  296. }
  297. return ret;
  298. }
  299. } else return 0;
  300. } else if (atom.size > 4 && key && !c->itunes_metadata) {
  301. str_size = avio_rb16(pb); // string length
  302. langcode = avio_rb16(pb);
  303. ff_mov_lang_to_iso639(langcode, language);
  304. atom.size -= 4;
  305. } else
  306. str_size = atom.size;
  307. #ifdef MOV_EXPORT_ALL_METADATA
  308. if (!key) {
  309. snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
  310. key = tmp_key;
  311. }
  312. #endif
  313. if (!key)
  314. return 0;
  315. if (atom.size < 0)
  316. return AVERROR_INVALIDDATA;
  317. str_size_alloc = str_size << 1; // worst-case requirement for output string in case of utf8 coded input
  318. str = av_malloc(str_size_alloc);
  319. if (!str)
  320. return AVERROR(ENOMEM);
  321. if (parse)
  322. parse(c, pb, str_size, key);
  323. else {
  324. if (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff))) { // MAC Encoded
  325. mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
  326. } else {
  327. int ret = avio_read(pb, str, str_size);
  328. if (ret != str_size) {
  329. av_freep(&str);
  330. return ret < 0 ? ret : AVERROR_INVALIDDATA;
  331. }
  332. str[str_size] = 0;
  333. }
  334. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  335. av_dict_set(&c->fc->metadata, key, str, 0);
  336. if (*language && strcmp(language, "und")) {
  337. snprintf(key2, sizeof(key2), "%s-%s", key, language);
  338. av_dict_set(&c->fc->metadata, key2, str, 0);
  339. }
  340. }
  341. av_dlog(c->fc, "lang \"%3s\" ", language);
  342. av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
  343. key, str, (char*)&atom.type, str_size_alloc, atom.size);
  344. av_freep(&str);
  345. return 0;
  346. }
  347. static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  348. {
  349. int64_t start;
  350. int i, nb_chapters, str_len, version;
  351. char str[256+1];
  352. if ((atom.size -= 5) < 0)
  353. return 0;
  354. version = avio_r8(pb);
  355. avio_rb24(pb);
  356. if (version)
  357. avio_rb32(pb); // ???
  358. nb_chapters = avio_r8(pb);
  359. for (i = 0; i < nb_chapters; i++) {
  360. if (atom.size < 9)
  361. return 0;
  362. start = avio_rb64(pb);
  363. str_len = avio_r8(pb);
  364. if ((atom.size -= 9+str_len) < 0)
  365. return 0;
  366. avio_read(pb, str, str_len);
  367. str[str_len] = 0;
  368. avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
  369. }
  370. return 0;
  371. }
  372. #define MIN_DATA_ENTRY_BOX_SIZE 12
  373. static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  374. {
  375. AVStream *st;
  376. MOVStreamContext *sc;
  377. int entries, i, j;
  378. if (c->fc->nb_streams < 1)
  379. return 0;
  380. st = c->fc->streams[c->fc->nb_streams-1];
  381. sc = st->priv_data;
  382. avio_rb32(pb); // version + flags
  383. entries = avio_rb32(pb);
  384. if (entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
  385. entries >= UINT_MAX / sizeof(*sc->drefs))
  386. return AVERROR_INVALIDDATA;
  387. av_free(sc->drefs);
  388. sc->drefs_count = 0;
  389. sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
  390. if (!sc->drefs)
  391. return AVERROR(ENOMEM);
  392. sc->drefs_count = entries;
  393. for (i = 0; i < sc->drefs_count; i++) {
  394. MOVDref *dref = &sc->drefs[i];
  395. uint32_t size = avio_rb32(pb);
  396. int64_t next = avio_tell(pb) + size - 4;
  397. if (size < 12)
  398. return AVERROR_INVALIDDATA;
  399. dref->type = avio_rl32(pb);
  400. avio_rb32(pb); // version + flags
  401. av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
  402. if (dref->type == MKTAG('a','l','i','s') && size > 150) {
  403. /* macintosh alias record */
  404. uint16_t volume_len, len;
  405. int16_t type;
  406. avio_skip(pb, 10);
  407. volume_len = avio_r8(pb);
  408. volume_len = FFMIN(volume_len, 27);
  409. avio_read(pb, dref->volume, 27);
  410. dref->volume[volume_len] = 0;
  411. av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
  412. avio_skip(pb, 12);
  413. len = avio_r8(pb);
  414. len = FFMIN(len, 63);
  415. avio_read(pb, dref->filename, 63);
  416. dref->filename[len] = 0;
  417. av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
  418. avio_skip(pb, 16);
  419. /* read next level up_from_alias/down_to_target */
  420. dref->nlvl_from = avio_rb16(pb);
  421. dref->nlvl_to = avio_rb16(pb);
  422. av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
  423. dref->nlvl_from, dref->nlvl_to);
  424. avio_skip(pb, 16);
  425. for (type = 0; type != -1 && avio_tell(pb) < next; ) {
  426. if(avio_feof(pb))
  427. return AVERROR_EOF;
  428. type = avio_rb16(pb);
  429. len = avio_rb16(pb);
  430. av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
  431. if (len&1)
  432. len += 1;
  433. if (type == 2) { // absolute path
  434. av_free(dref->path);
  435. dref->path = av_mallocz(len+1);
  436. if (!dref->path)
  437. return AVERROR(ENOMEM);
  438. avio_read(pb, dref->path, len);
  439. if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
  440. len -= volume_len;
  441. memmove(dref->path, dref->path+volume_len, len);
  442. dref->path[len] = 0;
  443. }
  444. for (j = 0; j < len; j++)
  445. if (dref->path[j] == ':')
  446. dref->path[j] = '/';
  447. av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
  448. } else if (type == 0) { // directory name
  449. av_free(dref->dir);
  450. dref->dir = av_malloc(len+1);
  451. if (!dref->dir)
  452. return AVERROR(ENOMEM);
  453. if (avio_read(pb, dref->dir, len) != len)
  454. return AVERROR_INVALIDDATA;
  455. dref->dir[len] = 0;
  456. for (j = 0; j < len; j++)
  457. if (dref->dir[j] == ':')
  458. dref->dir[j] = '/';
  459. av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
  460. } else
  461. avio_skip(pb, len);
  462. }
  463. }
  464. avio_seek(pb, next, SEEK_SET);
  465. }
  466. return 0;
  467. }
  468. static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  469. {
  470. AVStream *st;
  471. uint32_t type;
  472. uint32_t av_unused ctype;
  473. int title_size;
  474. char *title_str;
  475. if (c->fc->nb_streams < 1) // meta before first trak
  476. return 0;
  477. st = c->fc->streams[c->fc->nb_streams-1];
  478. avio_r8(pb); /* version */
  479. avio_rb24(pb); /* flags */
  480. /* component type */
  481. ctype = avio_rl32(pb);
  482. type = avio_rl32(pb); /* component subtype */
  483. av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
  484. av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
  485. if (type == MKTAG('v','i','d','e'))
  486. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  487. else if (type == MKTAG('s','o','u','n'))
  488. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  489. else if (type == MKTAG('m','1','a',' '))
  490. st->codec->codec_id = AV_CODEC_ID_MP2;
  491. else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
  492. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  493. avio_rb32(pb); /* component manufacture */
  494. avio_rb32(pb); /* component flags */
  495. avio_rb32(pb); /* component flags mask */
  496. title_size = atom.size - 24;
  497. if (title_size > 0) {
  498. title_str = av_malloc(title_size + 1); /* Add null terminator */
  499. if (!title_str)
  500. return AVERROR(ENOMEM);
  501. avio_read(pb, title_str, title_size);
  502. title_str[title_size] = 0;
  503. if (title_str[0])
  504. av_dict_set(&st->metadata, "handler_name", title_str +
  505. (!c->isom && title_str[0] == title_size - 1), 0);
  506. av_freep(&title_str);
  507. }
  508. return 0;
  509. }
  510. int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb)
  511. {
  512. AVStream *st;
  513. int tag;
  514. if (fc->nb_streams < 1)
  515. return 0;
  516. st = fc->streams[fc->nb_streams-1];
  517. avio_rb32(pb); /* version + flags */
  518. ff_mp4_read_descr(fc, pb, &tag);
  519. if (tag == MP4ESDescrTag) {
  520. ff_mp4_parse_es_descr(pb, NULL);
  521. } else
  522. avio_rb16(pb); /* ID */
  523. ff_mp4_read_descr(fc, pb, &tag);
  524. if (tag == MP4DecConfigDescrTag)
  525. ff_mp4_read_dec_config_descr(fc, st, pb);
  526. return 0;
  527. }
  528. static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  529. {
  530. return ff_mov_read_esds(c->fc, pb);
  531. }
  532. static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  533. {
  534. AVStream *st;
  535. int ac3info, acmod, lfeon, bsmod;
  536. if (c->fc->nb_streams < 1)
  537. return 0;
  538. st = c->fc->streams[c->fc->nb_streams-1];
  539. ac3info = avio_rb24(pb);
  540. bsmod = (ac3info >> 14) & 0x7;
  541. acmod = (ac3info >> 11) & 0x7;
  542. lfeon = (ac3info >> 10) & 0x1;
  543. st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
  544. st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
  545. if (lfeon)
  546. st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
  547. st->codec->audio_service_type = bsmod;
  548. if (st->codec->channels > 1 && bsmod == 0x7)
  549. st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
  550. return 0;
  551. }
  552. static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  553. {
  554. AVStream *st;
  555. int eac3info, acmod, lfeon, bsmod;
  556. if (c->fc->nb_streams < 1)
  557. return 0;
  558. st = c->fc->streams[c->fc->nb_streams-1];
  559. /* No need to parse fields for additional independent substreams and its
  560. * associated dependent substreams since libavcodec's E-AC-3 decoder
  561. * does not support them yet. */
  562. avio_rb16(pb); /* data_rate and num_ind_sub */
  563. eac3info = avio_rb24(pb);
  564. bsmod = (eac3info >> 12) & 0x1f;
  565. acmod = (eac3info >> 9) & 0x7;
  566. lfeon = (eac3info >> 8) & 0x1;
  567. st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
  568. if (lfeon)
  569. st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
  570. st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
  571. st->codec->audio_service_type = bsmod;
  572. if (st->codec->channels > 1 && bsmod == 0x7)
  573. st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
  574. return 0;
  575. }
  576. static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  577. {
  578. AVStream *st;
  579. if (c->fc->nb_streams < 1)
  580. return 0;
  581. st = c->fc->streams[c->fc->nb_streams-1];
  582. if (atom.size < 16)
  583. return 0;
  584. /* skip version and flags */
  585. avio_skip(pb, 4);
  586. ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
  587. return 0;
  588. }
  589. static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  590. {
  591. AVStream *st;
  592. if (c->fc->nb_streams < 1)
  593. return 0;
  594. st = c->fc->streams[c->fc->nb_streams-1];
  595. if (ff_get_wav_header(pb, st->codec, atom.size) < 0) {
  596. av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
  597. }
  598. return 0;
  599. }
  600. static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  601. {
  602. const int num = avio_rb32(pb);
  603. const int den = avio_rb32(pb);
  604. AVStream *st;
  605. if (c->fc->nb_streams < 1)
  606. return 0;
  607. st = c->fc->streams[c->fc->nb_streams-1];
  608. if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
  609. (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
  610. av_log(c->fc, AV_LOG_WARNING,
  611. "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
  612. st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
  613. num, den);
  614. } else if (den != 0) {
  615. st->sample_aspect_ratio.num = num;
  616. st->sample_aspect_ratio.den = den;
  617. }
  618. return 0;
  619. }
  620. /* this atom contains actual media data */
  621. static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  622. {
  623. if (atom.size == 0) /* wrong one (MP4) */
  624. return 0;
  625. c->found_mdat=1;
  626. return 0; /* now go for moov */
  627. }
  628. /* read major brand, minor version and compatible brands and store them as metadata */
  629. static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  630. {
  631. uint32_t minor_ver;
  632. int comp_brand_size;
  633. char* comp_brands_str;
  634. uint8_t type[5] = {0};
  635. avio_read(pb, type, 4);
  636. if (strcmp(type, "qt "))
  637. c->isom = 1;
  638. av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
  639. av_dict_set(&c->fc->metadata, "major_brand", type, 0);
  640. minor_ver = avio_rb32(pb); /* minor version */
  641. av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
  642. comp_brand_size = atom.size - 8;
  643. if (comp_brand_size < 0)
  644. return AVERROR_INVALIDDATA;
  645. comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
  646. if (!comp_brands_str)
  647. return AVERROR(ENOMEM);
  648. avio_read(pb, comp_brands_str, comp_brand_size);
  649. comp_brands_str[comp_brand_size] = 0;
  650. av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
  651. av_freep(&comp_brands_str);
  652. return 0;
  653. }
  654. /* this atom should contain all header atoms */
  655. static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  656. {
  657. int ret;
  658. if (c->found_moov) {
  659. av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
  660. avio_skip(pb, atom.size);
  661. return 0;
  662. }
  663. if ((ret = mov_read_default(c, pb, atom)) < 0)
  664. return ret;
  665. /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
  666. /* so we don't parse the whole file if over a network */
  667. c->found_moov=1;
  668. return 0; /* now go for mdat */
  669. }
  670. static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  671. {
  672. if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
  673. c->has_looked_for_mfra = 1;
  674. if (pb->seekable) {
  675. int ret;
  676. av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
  677. "for a mfra\n");
  678. if ((ret = mov_read_mfra(c, pb)) < 0) {
  679. av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
  680. "read the mfra (may be a live ismv)\n");
  681. }
  682. } else {
  683. av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
  684. "seekable, can not look for mfra\n");
  685. }
  686. }
  687. c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
  688. av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
  689. return mov_read_default(c, pb, atom);
  690. }
  691. static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
  692. {
  693. char buffer[32];
  694. if (time) {
  695. struct tm *ptm;
  696. time_t timet;
  697. if(time >= 2082844800)
  698. time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
  699. timet = time;
  700. ptm = gmtime(&timet);
  701. if (!ptm) return;
  702. strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
  703. av_dict_set(metadata, "creation_time", buffer, 0);
  704. }
  705. }
  706. static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  707. {
  708. AVStream *st;
  709. MOVStreamContext *sc;
  710. int version;
  711. char language[4] = {0};
  712. unsigned lang;
  713. int64_t creation_time;
  714. if (c->fc->nb_streams < 1)
  715. return 0;
  716. st = c->fc->streams[c->fc->nb_streams-1];
  717. sc = st->priv_data;
  718. if (sc->time_scale) {
  719. av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
  720. return AVERROR_INVALIDDATA;
  721. }
  722. version = avio_r8(pb);
  723. if (version > 1) {
  724. avpriv_request_sample(c->fc, "Version %d", version);
  725. return AVERROR_PATCHWELCOME;
  726. }
  727. avio_rb24(pb); /* flags */
  728. if (version == 1) {
  729. creation_time = avio_rb64(pb);
  730. avio_rb64(pb);
  731. } else {
  732. creation_time = avio_rb32(pb);
  733. avio_rb32(pb); /* modification time */
  734. }
  735. mov_metadata_creation_time(&st->metadata, creation_time);
  736. sc->time_scale = avio_rb32(pb);
  737. st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
  738. lang = avio_rb16(pb); /* language */
  739. if (ff_mov_lang_to_iso639(lang, language))
  740. av_dict_set(&st->metadata, "language", language, 0);
  741. avio_rb16(pb); /* quality */
  742. return 0;
  743. }
  744. static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  745. {
  746. int64_t creation_time;
  747. int version = avio_r8(pb); /* version */
  748. avio_rb24(pb); /* flags */
  749. if (version == 1) {
  750. creation_time = avio_rb64(pb);
  751. avio_rb64(pb);
  752. } else {
  753. creation_time = avio_rb32(pb);
  754. avio_rb32(pb); /* modification time */
  755. }
  756. mov_metadata_creation_time(&c->fc->metadata, creation_time);
  757. c->time_scale = avio_rb32(pb); /* time scale */
  758. av_dlog(c->fc, "time scale = %i\n", c->time_scale);
  759. c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
  760. // set the AVCodecContext duration because the duration of individual tracks
  761. // may be inaccurate
  762. if (c->time_scale > 0 && !c->trex_data)
  763. c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
  764. avio_rb32(pb); /* preferred scale */
  765. avio_rb16(pb); /* preferred volume */
  766. avio_skip(pb, 10); /* reserved */
  767. avio_skip(pb, 36); /* display matrix */
  768. avio_rb32(pb); /* preview time */
  769. avio_rb32(pb); /* preview duration */
  770. avio_rb32(pb); /* poster time */
  771. avio_rb32(pb); /* selection time */
  772. avio_rb32(pb); /* selection duration */
  773. avio_rb32(pb); /* current time */
  774. avio_rb32(pb); /* next track ID */
  775. return 0;
  776. }
  777. static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  778. {
  779. AVStream *st;
  780. int little_endian;
  781. if (c->fc->nb_streams < 1)
  782. return 0;
  783. st = c->fc->streams[c->fc->nb_streams-1];
  784. little_endian = avio_rb16(pb) & 0xFF;
  785. av_dlog(c->fc, "enda %d\n", little_endian);
  786. if (little_endian == 1) {
  787. switch (st->codec->codec_id) {
  788. case AV_CODEC_ID_PCM_S24BE:
  789. st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
  790. break;
  791. case AV_CODEC_ID_PCM_S32BE:
  792. st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
  793. break;
  794. case AV_CODEC_ID_PCM_F32BE:
  795. st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
  796. break;
  797. case AV_CODEC_ID_PCM_F64BE:
  798. st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
  799. break;
  800. default:
  801. break;
  802. }
  803. }
  804. return 0;
  805. }
  806. static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  807. {
  808. AVStream *st;
  809. char color_parameter_type[5] = { 0 };
  810. int color_primaries, color_trc, color_matrix;
  811. if (c->fc->nb_streams < 1)
  812. return 0;
  813. st = c->fc->streams[c->fc->nb_streams - 1];
  814. avio_read(pb, color_parameter_type, 4);
  815. if (strncmp(color_parameter_type, "nclx", 4) &&
  816. strncmp(color_parameter_type, "nclc", 4)) {
  817. av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
  818. color_parameter_type);
  819. return 0;
  820. }
  821. color_primaries = avio_rb16(pb);
  822. color_trc = avio_rb16(pb);
  823. color_matrix = avio_rb16(pb);
  824. av_dlog(c->fc, "%s: pri %d trc %d matrix %d",
  825. color_parameter_type, color_primaries, color_trc, color_matrix);
  826. if (c->isom) {
  827. uint8_t color_range = avio_r8(pb) >> 7;
  828. av_dlog(c->fc, " full %"PRIu8"", color_range);
  829. if (color_range)
  830. st->codec->color_range = AVCOL_RANGE_JPEG;
  831. else
  832. st->codec->color_range = AVCOL_RANGE_MPEG;
  833. /* 14496-12 references JPEG XR specs (rather than the more complete
  834. * 23001-8) so some adjusting is required */
  835. if (color_primaries >= AVCOL_PRI_FILM)
  836. color_primaries = AVCOL_PRI_UNSPECIFIED;
  837. if ((color_trc >= AVCOL_TRC_LINEAR &&
  838. color_trc <= AVCOL_TRC_LOG_SQRT) ||
  839. color_trc >= AVCOL_TRC_BT2020_10)
  840. color_trc = AVCOL_TRC_UNSPECIFIED;
  841. if (color_matrix >= AVCOL_SPC_BT2020_NCL)
  842. color_matrix = AVCOL_SPC_UNSPECIFIED;
  843. st->codec->color_primaries = color_primaries;
  844. st->codec->color_trc = color_trc;
  845. st->codec->colorspace = color_matrix;
  846. } else {
  847. /* color primaries, Table 4-4 */
  848. switch (color_primaries) {
  849. case 1: st->codec->color_primaries = AVCOL_PRI_BT709; break;
  850. case 5: st->codec->color_primaries = AVCOL_PRI_SMPTE170M; break;
  851. case 6: st->codec->color_primaries = AVCOL_PRI_SMPTE240M; break;
  852. }
  853. /* color transfer, Table 4-5 */
  854. switch (color_trc) {
  855. case 1: st->codec->color_trc = AVCOL_TRC_BT709; break;
  856. case 7: st->codec->color_trc = AVCOL_TRC_SMPTE240M; break;
  857. }
  858. /* color matrix, Table 4-6 */
  859. switch (color_matrix) {
  860. case 1: st->codec->colorspace = AVCOL_SPC_BT709; break;
  861. case 6: st->codec->colorspace = AVCOL_SPC_BT470BG; break;
  862. case 7: st->codec->colorspace = AVCOL_SPC_SMPTE240M; break;
  863. }
  864. }
  865. av_dlog(c->fc, "\n");
  866. return 0;
  867. }
  868. static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  869. {
  870. AVStream *st;
  871. unsigned mov_field_order;
  872. enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
  873. if (c->fc->nb_streams < 1) // will happen with jp2 files
  874. return 0;
  875. st = c->fc->streams[c->fc->nb_streams-1];
  876. if (atom.size < 2)
  877. return AVERROR_INVALIDDATA;
  878. mov_field_order = avio_rb16(pb);
  879. if ((mov_field_order & 0xFF00) == 0x0100)
  880. decoded_field_order = AV_FIELD_PROGRESSIVE;
  881. else if ((mov_field_order & 0xFF00) == 0x0200) {
  882. switch (mov_field_order & 0xFF) {
  883. case 0x01: decoded_field_order = AV_FIELD_TT;
  884. break;
  885. case 0x06: decoded_field_order = AV_FIELD_BB;
  886. break;
  887. case 0x09: decoded_field_order = AV_FIELD_TB;
  888. break;
  889. case 0x0E: decoded_field_order = AV_FIELD_BT;
  890. break;
  891. }
  892. }
  893. if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
  894. av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
  895. }
  896. st->codec->field_order = decoded_field_order;
  897. return 0;
  898. }
  899. /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
  900. static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
  901. enum AVCodecID codec_id)
  902. {
  903. AVStream *st;
  904. uint64_t size;
  905. uint8_t *buf;
  906. int err;
  907. if (c->fc->nb_streams < 1) // will happen with jp2 files
  908. return 0;
  909. st= c->fc->streams[c->fc->nb_streams-1];
  910. if (st->codec->codec_id != codec_id)
  911. return 0; /* unexpected codec_id - don't mess with extradata */
  912. size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
  913. if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
  914. return AVERROR_INVALIDDATA;
  915. if ((err = av_reallocp(&st->codec->extradata, size)) < 0) {
  916. st->codec->extradata_size = 0;
  917. return err;
  918. }
  919. buf = st->codec->extradata + st->codec->extradata_size;
  920. st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
  921. AV_WB32( buf , atom.size + 8);
  922. AV_WL32( buf + 4, atom.type);
  923. err = avio_read(pb, buf + 8, atom.size);
  924. if (err < 0) {
  925. return err;
  926. } else if (err < atom.size) {
  927. av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
  928. st->codec->extradata_size -= atom.size - err;
  929. }
  930. memset(buf + 8 + err, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  931. return 0;
  932. }
  933. /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
  934. static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  935. {
  936. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
  937. }
  938. static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  939. {
  940. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
  941. }
  942. static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  943. {
  944. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
  945. }
  946. static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  947. {
  948. int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
  949. if(ret == 0)
  950. ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
  951. return ret;
  952. }
  953. static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  954. {
  955. int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
  956. if (!ret && c->fc->nb_streams >= 1) {
  957. AVCodecContext *avctx = c->fc->streams[c->fc->nb_streams-1]->codec;
  958. if (avctx->extradata_size >= 40) {
  959. avctx->height = AV_RB16(&avctx->extradata[36]);
  960. avctx->width = AV_RB16(&avctx->extradata[38]);
  961. }
  962. }
  963. return ret;
  964. }
  965. static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  966. {
  967. if (c->fc->nb_streams >= 1) {
  968. AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
  969. if (codec->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
  970. codec->codec_id == AV_CODEC_ID_H264 &&
  971. atom.size > 11) {
  972. avio_skip(pb, 10);
  973. /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
  974. if (avio_rb16(pb) == 0xd4d)
  975. codec->width = 1440;
  976. return 0;
  977. }
  978. }
  979. return mov_read_avid(c, pb, atom);
  980. }
  981. static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  982. {
  983. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
  984. }
  985. static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  986. {
  987. AVStream *st;
  988. if (c->fc->nb_streams < 1)
  989. return 0;
  990. st = c->fc->streams[c->fc->nb_streams-1];
  991. if ((uint64_t)atom.size > (1<<30))
  992. return AVERROR_INVALIDDATA;
  993. if (st->codec->codec_id == AV_CODEC_ID_QDM2 ||
  994. st->codec->codec_id == AV_CODEC_ID_QDMC ||
  995. st->codec->codec_id == AV_CODEC_ID_SPEEX) {
  996. // pass all frma atom to codec, needed at least for QDMC and QDM2
  997. av_free(st->codec->extradata);
  998. if (ff_get_extradata(st->codec, pb, atom.size) < 0)
  999. return AVERROR(ENOMEM);
  1000. } else if (atom.size > 8) { /* to read frma, esds atoms */
  1001. int ret;
  1002. if ((ret = mov_read_default(c, pb, atom)) < 0)
  1003. return ret;
  1004. } else
  1005. avio_skip(pb, atom.size);
  1006. return 0;
  1007. }
  1008. /**
  1009. * This function reads atom content and puts data in extradata without tag
  1010. * nor size unlike mov_read_extradata.
  1011. */
  1012. static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1013. {
  1014. AVStream *st;
  1015. if (c->fc->nb_streams < 1)
  1016. return 0;
  1017. st = c->fc->streams[c->fc->nb_streams-1];
  1018. if ((uint64_t)atom.size > (1<<30))
  1019. return AVERROR_INVALIDDATA;
  1020. if (atom.size >= 10) {
  1021. // Broken files created by legacy versions of libavformat will
  1022. // wrap a whole fiel atom inside of a glbl atom.
  1023. unsigned size = avio_rb32(pb);
  1024. unsigned type = avio_rl32(pb);
  1025. avio_seek(pb, -8, SEEK_CUR);
  1026. if (type == MKTAG('f','i','e','l') && size == atom.size)
  1027. return mov_read_default(c, pb, atom);
  1028. }
  1029. if (st->codec->extradata_size > 1 && st->codec->extradata) {
  1030. av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
  1031. return 0;
  1032. }
  1033. av_free(st->codec->extradata);
  1034. if (ff_get_extradata(st->codec, pb, atom.size) < 0)
  1035. return AVERROR(ENOMEM);
  1036. return 0;
  1037. }
  1038. static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1039. {
  1040. AVStream *st;
  1041. uint8_t profile_level;
  1042. int ret;
  1043. if (c->fc->nb_streams < 1)
  1044. return 0;
  1045. st = c->fc->streams[c->fc->nb_streams-1];
  1046. if (atom.size >= (1<<28) || atom.size < 7)
  1047. return AVERROR_INVALIDDATA;
  1048. profile_level = avio_r8(pb);
  1049. if ((profile_level & 0xf0) != 0xc0)
  1050. return 0;
  1051. avio_seek(pb, 6, SEEK_CUR);
  1052. av_free(st->codec->extradata);
  1053. if ((ret = ff_get_extradata(st->codec, pb, atom.size - 7)) < 0)
  1054. return ret;
  1055. return 0;
  1056. }
  1057. /**
  1058. * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
  1059. * but can have extradata appended at the end after the 40 bytes belonging
  1060. * to the struct.
  1061. */
  1062. static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1063. {
  1064. AVStream *st;
  1065. if (c->fc->nb_streams < 1)
  1066. return 0;
  1067. if (atom.size <= 40)
  1068. return 0;
  1069. st = c->fc->streams[c->fc->nb_streams-1];
  1070. if ((uint64_t)atom.size > (1<<30))
  1071. return AVERROR_INVALIDDATA;
  1072. avio_skip(pb, 40);
  1073. av_free(st->codec->extradata);
  1074. if (ff_get_extradata(st->codec, pb, atom.size - 40) < 0)
  1075. return AVERROR(ENOMEM);
  1076. return 0;
  1077. }
  1078. static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1079. {
  1080. AVStream *st;
  1081. MOVStreamContext *sc;
  1082. unsigned int i, entries;
  1083. if (c->fc->nb_streams < 1)
  1084. return 0;
  1085. st = c->fc->streams[c->fc->nb_streams-1];
  1086. sc = st->priv_data;
  1087. avio_r8(pb); /* version */
  1088. avio_rb24(pb); /* flags */
  1089. entries = avio_rb32(pb);
  1090. if (!entries)
  1091. return 0;
  1092. if (entries >= UINT_MAX/sizeof(int64_t))
  1093. return AVERROR_INVALIDDATA;
  1094. sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
  1095. if (!sc->chunk_offsets)
  1096. return AVERROR(ENOMEM);
  1097. sc->chunk_count = entries;
  1098. if (atom.type == MKTAG('s','t','c','o'))
  1099. for (i = 0; i < entries && !pb->eof_reached; i++)
  1100. sc->chunk_offsets[i] = avio_rb32(pb);
  1101. else if (atom.type == MKTAG('c','o','6','4'))
  1102. for (i = 0; i < entries && !pb->eof_reached; i++)
  1103. sc->chunk_offsets[i] = avio_rb64(pb);
  1104. else
  1105. return AVERROR_INVALIDDATA;
  1106. sc->chunk_count = i;
  1107. if (pb->eof_reached)
  1108. return AVERROR_EOF;
  1109. return 0;
  1110. }
  1111. /**
  1112. * Compute codec id for 'lpcm' tag.
  1113. * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
  1114. */
  1115. enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
  1116. {
  1117. /* lpcm flags:
  1118. * 0x1 = float
  1119. * 0x2 = big-endian
  1120. * 0x4 = signed
  1121. */
  1122. return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
  1123. }
  1124. static int mov_codec_id(AVStream *st, uint32_t format)
  1125. {
  1126. int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
  1127. if (id <= 0 &&
  1128. ((format & 0xFFFF) == 'm' + ('s' << 8) ||
  1129. (format & 0xFFFF) == 'T' + ('S' << 8)))
  1130. id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
  1131. if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
  1132. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1133. } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
  1134. /* skip old asf mpeg4 tag */
  1135. format && format != MKTAG('m','p','4','s')) {
  1136. id = ff_codec_get_id(ff_codec_movvideo_tags, format);
  1137. if (id <= 0)
  1138. id = ff_codec_get_id(ff_codec_bmp_tags, format);
  1139. if (id > 0)
  1140. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1141. else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
  1142. (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
  1143. st->codec->codec_id == AV_CODEC_ID_NONE)) {
  1144. id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
  1145. if (id > 0)
  1146. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1147. }
  1148. }
  1149. st->codec->codec_tag = format;
  1150. return id;
  1151. }
  1152. static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
  1153. AVStream *st, MOVStreamContext *sc)
  1154. {
  1155. uint8_t codec_name[32];
  1156. unsigned int color_depth, len, j;
  1157. int color_greyscale;
  1158. int color_table_id;
  1159. avio_rb16(pb); /* version */
  1160. avio_rb16(pb); /* revision level */
  1161. avio_rb32(pb); /* vendor */
  1162. avio_rb32(pb); /* temporal quality */
  1163. avio_rb32(pb); /* spatial quality */
  1164. st->codec->width = avio_rb16(pb); /* width */
  1165. st->codec->height = avio_rb16(pb); /* height */
  1166. avio_rb32(pb); /* horiz resolution */
  1167. avio_rb32(pb); /* vert resolution */
  1168. avio_rb32(pb); /* data size, always 0 */
  1169. avio_rb16(pb); /* frames per samples */
  1170. len = avio_r8(pb); /* codec name, pascal string */
  1171. if (len > 31)
  1172. len = 31;
  1173. mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
  1174. if (len < 31)
  1175. avio_skip(pb, 31 - len);
  1176. if (codec_name[0])
  1177. av_dict_set(&st->metadata, "encoder", codec_name, 0);
  1178. /* codec_tag YV12 triggers an UV swap in rawdec.c */
  1179. if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
  1180. st->codec->codec_tag = MKTAG('I', '4', '2', '0');
  1181. st->codec->width &= ~1;
  1182. st->codec->height &= ~1;
  1183. }
  1184. /* Flash Media Server uses tag H263 with Sorenson Spark */
  1185. if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
  1186. !memcmp(codec_name, "Sorenson H263", 13))
  1187. st->codec->codec_id = AV_CODEC_ID_FLV1;
  1188. st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
  1189. color_table_id = avio_rb16(pb); /* colortable id */
  1190. av_dlog(c->fc, "depth %d, ctab id %d\n",
  1191. st->codec->bits_per_coded_sample, color_table_id);
  1192. /* figure out the palette situation */
  1193. color_depth = st->codec->bits_per_coded_sample & 0x1F;
  1194. color_greyscale = st->codec->bits_per_coded_sample & 0x20;
  1195. /* Do not create a greyscale palette for cinepak */
  1196. if (color_greyscale && st->codec->codec_id == AV_CODEC_ID_CINEPAK)
  1197. return;
  1198. /* if the depth is 2, 4, or 8 bpp, file is palettized */
  1199. if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
  1200. /* for palette traversal */
  1201. unsigned int color_start, color_count, color_end;
  1202. unsigned char a, r, g, b;
  1203. if (color_greyscale) {
  1204. int color_index, color_dec;
  1205. /* compute the greyscale palette */
  1206. st->codec->bits_per_coded_sample = color_depth;
  1207. color_count = 1 << color_depth;
  1208. color_index = 255;
  1209. color_dec = 256 / (color_count - 1);
  1210. for (j = 0; j < color_count; j++) {
  1211. r = g = b = color_index;
  1212. sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
  1213. color_index -= color_dec;
  1214. if (color_index < 0)
  1215. color_index = 0;
  1216. }
  1217. } else if (color_table_id) {
  1218. const uint8_t *color_table;
  1219. /* if flag bit 3 is set, use the default palette */
  1220. color_count = 1 << color_depth;
  1221. if (color_depth == 2)
  1222. color_table = ff_qt_default_palette_4;
  1223. else if (color_depth == 4)
  1224. color_table = ff_qt_default_palette_16;
  1225. else
  1226. color_table = ff_qt_default_palette_256;
  1227. for (j = 0; j < color_count; j++) {
  1228. r = color_table[j * 3 + 0];
  1229. g = color_table[j * 3 + 1];
  1230. b = color_table[j * 3 + 2];
  1231. sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
  1232. }
  1233. } else {
  1234. /* load the palette from the file */
  1235. color_start = avio_rb32(pb);
  1236. color_count = avio_rb16(pb);
  1237. color_end = avio_rb16(pb);
  1238. if ((color_start <= 255) && (color_end <= 255)) {
  1239. for (j = color_start; j <= color_end; j++) {
  1240. /* each A, R, G, or B component is 16 bits;
  1241. * only use the top 8 bits */
  1242. a = avio_r8(pb);
  1243. avio_r8(pb);
  1244. r = avio_r8(pb);
  1245. avio_r8(pb);
  1246. g = avio_r8(pb);
  1247. avio_r8(pb);
  1248. b = avio_r8(pb);
  1249. avio_r8(pb);
  1250. sc->palette[j] = (a << 24 ) | (r << 16) | (g << 8) | (b);
  1251. }
  1252. }
  1253. }
  1254. sc->has_palette = 1;
  1255. }
  1256. }
  1257. static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
  1258. AVStream *st, MOVStreamContext *sc)
  1259. {
  1260. int bits_per_sample, flags;
  1261. uint16_t version = avio_rb16(pb);
  1262. AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
  1263. avio_rb16(pb); /* revision level */
  1264. avio_rb32(pb); /* vendor */
  1265. st->codec->channels = avio_rb16(pb); /* channel count */
  1266. st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
  1267. av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
  1268. sc->audio_cid = avio_rb16(pb);
  1269. avio_rb16(pb); /* packet size = 0 */
  1270. st->codec->sample_rate = ((avio_rb32(pb) >> 16));
  1271. // Read QT version 1 fields. In version 0 these do not exist.
  1272. av_dlog(c->fc, "version =%d, isom =%d\n", version, c->isom);
  1273. if (!c->isom ||
  1274. (compatible_brands && strstr(compatible_brands->value, "qt "))) {
  1275. if (version == 1) {
  1276. sc->samples_per_frame = avio_rb32(pb);
  1277. avio_rb32(pb); /* bytes per packet */
  1278. sc->bytes_per_frame = avio_rb32(pb);
  1279. avio_rb32(pb); /* bytes per sample */
  1280. } else if (version == 2) {
  1281. avio_rb32(pb); /* sizeof struct only */
  1282. st->codec->sample_rate = av_int2double(avio_rb64(pb));
  1283. st->codec->channels = avio_rb32(pb);
  1284. avio_rb32(pb); /* always 0x7F000000 */
  1285. st->codec->bits_per_coded_sample = avio_rb32(pb);
  1286. flags = avio_rb32(pb); /* lpcm format specific flag */
  1287. sc->bytes_per_frame = avio_rb32(pb);
  1288. sc->samples_per_frame = avio_rb32(pb);
  1289. if (st->codec->codec_tag == MKTAG('l','p','c','m'))
  1290. st->codec->codec_id =
  1291. ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
  1292. flags);
  1293. }
  1294. }
  1295. switch (st->codec->codec_id) {
  1296. case AV_CODEC_ID_PCM_S8:
  1297. case AV_CODEC_ID_PCM_U8:
  1298. if (st->codec->bits_per_coded_sample == 16)
  1299. st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
  1300. break;
  1301. case AV_CODEC_ID_PCM_S16LE:
  1302. case AV_CODEC_ID_PCM_S16BE:
  1303. if (st->codec->bits_per_coded_sample == 8)
  1304. st->codec->codec_id = AV_CODEC_ID_PCM_S8;
  1305. else if (st->codec->bits_per_coded_sample == 24)
  1306. st->codec->codec_id =
  1307. st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
  1308. AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
  1309. else if (st->codec->bits_per_coded_sample == 32)
  1310. st->codec->codec_id =
  1311. st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
  1312. AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
  1313. break;
  1314. /* set values for old format before stsd version 1 appeared */
  1315. case AV_CODEC_ID_MACE3:
  1316. sc->samples_per_frame = 6;
  1317. sc->bytes_per_frame = 2 * st->codec->channels;
  1318. break;
  1319. case AV_CODEC_ID_MACE6:
  1320. sc->samples_per_frame = 6;
  1321. sc->bytes_per_frame = 1 * st->codec->channels;
  1322. break;
  1323. case AV_CODEC_ID_ADPCM_IMA_QT:
  1324. sc->samples_per_frame = 64;
  1325. sc->bytes_per_frame = 34 * st->codec->channels;
  1326. break;
  1327. case AV_CODEC_ID_GSM:
  1328. sc->samples_per_frame = 160;
  1329. sc->bytes_per_frame = 33;
  1330. break;
  1331. default:
  1332. break;
  1333. }
  1334. bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
  1335. if (bits_per_sample) {
  1336. st->codec->bits_per_coded_sample = bits_per_sample;
  1337. sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
  1338. }
  1339. }
  1340. static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
  1341. AVStream *st, MOVStreamContext *sc,
  1342. int size)
  1343. {
  1344. // ttxt stsd contains display flags, justification, background
  1345. // color, fonts, and default styles, so fake an atom to read it
  1346. MOVAtom fake_atom = { .size = size };
  1347. // mp4s contains a regular esds atom
  1348. if (st->codec->codec_tag != AV_RL32("mp4s"))
  1349. mov_read_glbl(c, pb, fake_atom);
  1350. st->codec->width = sc->width;
  1351. st->codec->height = sc->height;
  1352. }
  1353. static uint32_t yuv_to_rgba(uint32_t ycbcr)
  1354. {
  1355. uint8_t r, g, b;
  1356. int y, cb, cr;
  1357. y = (ycbcr >> 16) & 0xFF;
  1358. cr = (ycbcr >> 8) & 0xFF;
  1359. cb = ycbcr & 0xFF;
  1360. b = av_clip_uint8(1.164 * (y - 16) + 2.018 * (cb - 128));
  1361. g = av_clip_uint8(1.164 * (y - 16) - 0.813 * (cr - 128) - 0.391 * (cb - 128));
  1362. r = av_clip_uint8(1.164 * (y - 16) + 1.596 * (cr - 128));
  1363. return (r << 16) | (g << 8) | b;
  1364. }
  1365. static int mov_rewrite_dvd_sub_extradata(AVStream *st)
  1366. {
  1367. char buf[256] = {0};
  1368. uint8_t *src = st->codec->extradata;
  1369. int i;
  1370. if (st->codec->extradata_size != 64)
  1371. return 0;
  1372. if (st->codec->width > 0 && st->codec->height > 0)
  1373. snprintf(buf, sizeof(buf), "size: %dx%d\n",
  1374. st->codec->width, st->codec->height);
  1375. av_strlcat(buf, "palette: ", sizeof(buf));
  1376. for (i = 0; i < 16; i++) {
  1377. uint32_t yuv = AV_RB32(src + i * 4);
  1378. uint32_t rgba = yuv_to_rgba(yuv);
  1379. av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
  1380. }
  1381. if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
  1382. return 0;
  1383. av_freep(&st->codec->extradata);
  1384. st->codec->extradata_size = 0;
  1385. st->codec->extradata = av_mallocz(strlen(buf) + FF_INPUT_BUFFER_PADDING_SIZE);
  1386. if (!st->codec->extradata)
  1387. return AVERROR(ENOMEM);
  1388. st->codec->extradata_size = strlen(buf);
  1389. memcpy(st->codec->extradata, buf, st->codec->extradata_size);
  1390. return 0;
  1391. }
  1392. static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
  1393. AVStream *st, MOVStreamContext *sc,
  1394. int size)
  1395. {
  1396. if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
  1397. if (ff_get_extradata(st->codec, pb, size) < 0)
  1398. return AVERROR(ENOMEM);
  1399. if (size > 16) {
  1400. MOVStreamContext *tmcd_ctx = st->priv_data;
  1401. int val;
  1402. val = AV_RB32(st->codec->extradata + 4);
  1403. tmcd_ctx->tmcd_flags = val;
  1404. if (val & 1)
  1405. st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE;
  1406. st->codec->time_base.den = st->codec->extradata[16]; /* number of frame */
  1407. st->codec->time_base.num = 1;
  1408. if (size > 30) {
  1409. uint32_t len = AV_RB32(st->codec->extradata + 18); /* name atom length */
  1410. uint32_t format = AV_RB32(st->codec->extradata + 22);
  1411. if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
  1412. uint16_t str_size = AV_RB16(st->codec->extradata + 26); /* string length */
  1413. if (str_size > 0 && size >= (int)str_size + 26) {
  1414. char *reel_name = av_malloc(str_size + 1);
  1415. if (!reel_name)
  1416. return AVERROR(ENOMEM);
  1417. memcpy(reel_name, st->codec->extradata + 30, str_size);
  1418. reel_name[str_size] = 0; /* Add null terminator */
  1419. /* don't add reel_name if emtpy string */
  1420. if (*reel_name == 0) {
  1421. av_free(reel_name);
  1422. } else {
  1423. av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL);
  1424. }
  1425. }
  1426. }
  1427. }
  1428. }
  1429. } else {
  1430. /* other codec type, just skip (rtp, mp4s ...) */
  1431. avio_skip(pb, size);
  1432. }
  1433. return 0;
  1434. }
  1435. static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
  1436. AVStream *st, MOVStreamContext *sc)
  1437. {
  1438. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  1439. !st->codec->sample_rate && sc->time_scale > 1)
  1440. st->codec->sample_rate = sc->time_scale;
  1441. /* special codec parameters handling */
  1442. switch (st->codec->codec_id) {
  1443. #if CONFIG_DV_DEMUXER
  1444. case AV_CODEC_ID_DVAUDIO:
  1445. c->dv_fctx = avformat_alloc_context();
  1446. c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
  1447. if (!c->dv_demux) {
  1448. av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
  1449. return AVERROR(ENOMEM);
  1450. }
  1451. sc->dv_audio_container = 1;
  1452. st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
  1453. break;
  1454. #endif
  1455. /* no ifdef since parameters are always those */
  1456. case AV_CODEC_ID_QCELP:
  1457. st->codec->channels = 1;
  1458. // force sample rate for qcelp when not stored in mov
  1459. if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
  1460. st->codec->sample_rate = 8000;
  1461. // FIXME: Why is the following needed for some files?
  1462. sc->samples_per_frame = 160;
  1463. if (!sc->bytes_per_frame)
  1464. sc->bytes_per_frame = 35;
  1465. break;
  1466. case AV_CODEC_ID_AMR_NB:
  1467. st->codec->channels = 1;
  1468. /* force sample rate for amr, stsd in 3gp does not store sample rate */
  1469. st->codec->sample_rate = 8000;
  1470. break;
  1471. case AV_CODEC_ID_AMR_WB:
  1472. st->codec->channels = 1;
  1473. st->codec->sample_rate = 16000;
  1474. break;
  1475. case AV_CODEC_ID_MP2:
  1476. case AV_CODEC_ID_MP3:
  1477. /* force type after stsd for m1a hdlr */
  1478. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1479. st->need_parsing = AVSTREAM_PARSE_FULL;
  1480. break;
  1481. case AV_CODEC_ID_GSM:
  1482. case AV_CODEC_ID_ADPCM_MS:
  1483. case AV_CODEC_ID_ADPCM_IMA_WAV:
  1484. case AV_CODEC_ID_ILBC:
  1485. case AV_CODEC_ID_MACE3:
  1486. case AV_CODEC_ID_MACE6:
  1487. case AV_CODEC_ID_QDM2:
  1488. st->codec->block_align = sc->bytes_per_frame;
  1489. break;
  1490. case AV_CODEC_ID_ALAC:
  1491. if (st->codec->extradata_size == 36) {
  1492. st->codec->channels = AV_RB8 (st->codec->extradata + 21);
  1493. st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
  1494. }
  1495. break;
  1496. case AV_CODEC_ID_AC3:
  1497. case AV_CODEC_ID_EAC3:
  1498. case AV_CODEC_ID_MPEG1VIDEO:
  1499. case AV_CODEC_ID_VC1:
  1500. st->need_parsing = AVSTREAM_PARSE_FULL;
  1501. break;
  1502. default:
  1503. break;
  1504. }
  1505. return 0;
  1506. }
  1507. static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
  1508. int codec_tag, int format,
  1509. int64_t size)
  1510. {
  1511. int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
  1512. if (codec_tag &&
  1513. (codec_tag != format &&
  1514. (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
  1515. : codec_tag != MKTAG('j','p','e','g')))) {
  1516. /* Multiple fourcc, we skip JPEG. This is not correct, we should
  1517. * export it as a separate AVStream but this needs a few changes
  1518. * in the MOV demuxer, patch welcome. */
  1519. av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
  1520. avio_skip(pb, size);
  1521. return 1;
  1522. }
  1523. if ( codec_tag == AV_RL32("avc1") ||
  1524. codec_tag == AV_RL32("hvc1") ||
  1525. codec_tag == AV_RL32("hev1")
  1526. )
  1527. av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
  1528. return 0;
  1529. }
  1530. int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
  1531. {
  1532. AVStream *st;
  1533. MOVStreamContext *sc;
  1534. int pseudo_stream_id;
  1535. if (c->fc->nb_streams < 1)
  1536. return 0;
  1537. st = c->fc->streams[c->fc->nb_streams-1];
  1538. sc = st->priv_data;
  1539. for (pseudo_stream_id = 0;
  1540. pseudo_stream_id < entries && !pb->eof_reached;
  1541. pseudo_stream_id++) {
  1542. //Parsing Sample description table
  1543. enum AVCodecID id;
  1544. int ret, dref_id = 1;
  1545. MOVAtom a = { AV_RL32("stsd") };
  1546. int64_t start_pos = avio_tell(pb);
  1547. int64_t size = avio_rb32(pb); /* size */
  1548. uint32_t format = avio_rl32(pb); /* data format */
  1549. if (size >= 16) {
  1550. avio_rb32(pb); /* reserved */
  1551. avio_rb16(pb); /* reserved */
  1552. dref_id = avio_rb16(pb);
  1553. }else if (size <= 7){
  1554. av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRId64" in stsd\n", size);
  1555. return AVERROR_INVALIDDATA;
  1556. }
  1557. if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
  1558. size - (avio_tell(pb) - start_pos)))
  1559. continue;
  1560. sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
  1561. sc->dref_id= dref_id;
  1562. id = mov_codec_id(st, format);
  1563. av_dlog(c->fc, "size=%"PRId64" 4CC= %c%c%c%c codec_type=%d\n", size,
  1564. (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
  1565. (format >> 24) & 0xff, st->codec->codec_type);
  1566. if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
  1567. st->codec->codec_id = id;
  1568. mov_parse_stsd_video(c, pb, st, sc);
  1569. } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
  1570. st->codec->codec_id = id;
  1571. mov_parse_stsd_audio(c, pb, st, sc);
  1572. } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
  1573. st->codec->codec_id = id;
  1574. mov_parse_stsd_subtitle(c, pb, st, sc,
  1575. size - (avio_tell(pb) - start_pos));
  1576. } else {
  1577. ret = mov_parse_stsd_data(c, pb, st, sc,
  1578. size - (avio_tell(pb) - start_pos));
  1579. if (ret < 0)
  1580. return ret;
  1581. }
  1582. /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
  1583. a.size = size - (avio_tell(pb) - start_pos);
  1584. if (a.size > 8) {
  1585. if ((ret = mov_read_default(c, pb, a)) < 0)
  1586. return ret;
  1587. } else if (a.size > 0)
  1588. avio_skip(pb, a.size);
  1589. }
  1590. if (pb->eof_reached)
  1591. return AVERROR_EOF;
  1592. return mov_finalize_stsd_codec(c, pb, st, sc);
  1593. }
  1594. static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1595. {
  1596. int entries;
  1597. avio_r8(pb); /* version */
  1598. avio_rb24(pb); /* flags */
  1599. entries = avio_rb32(pb);
  1600. return ff_mov_read_stsd_entries(c, pb, entries);
  1601. }
  1602. static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1603. {
  1604. AVStream *st;
  1605. MOVStreamContext *sc;
  1606. unsigned int i, entries;
  1607. if (c->fc->nb_streams < 1)
  1608. return 0;
  1609. st = c->fc->streams[c->fc->nb_streams-1];
  1610. sc = st->priv_data;
  1611. avio_r8(pb); /* version */
  1612. avio_rb24(pb); /* flags */
  1613. entries = avio_rb32(pb);
  1614. av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
  1615. if (!entries)
  1616. return 0;
  1617. if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
  1618. return AVERROR_INVALIDDATA;
  1619. sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
  1620. if (!sc->stsc_data)
  1621. return AVERROR(ENOMEM);
  1622. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1623. sc->stsc_data[i].first = avio_rb32(pb);
  1624. sc->stsc_data[i].count = avio_rb32(pb);
  1625. sc->stsc_data[i].id = avio_rb32(pb);
  1626. }
  1627. sc->stsc_count = i;
  1628. if (pb->eof_reached)
  1629. return AVERROR_EOF;
  1630. return 0;
  1631. }
  1632. static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1633. {
  1634. AVStream *st;
  1635. MOVStreamContext *sc;
  1636. unsigned i, entries;
  1637. if (c->fc->nb_streams < 1)
  1638. return 0;
  1639. st = c->fc->streams[c->fc->nb_streams-1];
  1640. sc = st->priv_data;
  1641. avio_rb32(pb); // version + flags
  1642. entries = avio_rb32(pb);
  1643. if (entries >= UINT_MAX / sizeof(*sc->stps_data))
  1644. return AVERROR_INVALIDDATA;
  1645. sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
  1646. if (!sc->stps_data)
  1647. return AVERROR(ENOMEM);
  1648. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1649. sc->stps_data[i] = avio_rb32(pb);
  1650. //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
  1651. }
  1652. sc->stps_count = i;
  1653. if (pb->eof_reached)
  1654. return AVERROR_EOF;
  1655. return 0;
  1656. }
  1657. static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1658. {
  1659. AVStream *st;
  1660. MOVStreamContext *sc;
  1661. unsigned int i, entries;
  1662. if (c->fc->nb_streams < 1)
  1663. return 0;
  1664. st = c->fc->streams[c->fc->nb_streams-1];
  1665. sc = st->priv_data;
  1666. avio_r8(pb); /* version */
  1667. avio_rb24(pb); /* flags */
  1668. entries = avio_rb32(pb);
  1669. av_dlog(c->fc, "keyframe_count = %d\n", entries);
  1670. if (!entries)
  1671. {
  1672. sc->keyframe_absent = 1;
  1673. if (!st->need_parsing && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  1674. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1675. return 0;
  1676. }
  1677. if (entries >= UINT_MAX / sizeof(int))
  1678. return AVERROR_INVALIDDATA;
  1679. sc->keyframes = av_malloc(entries * sizeof(int));
  1680. if (!sc->keyframes)
  1681. return AVERROR(ENOMEM);
  1682. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1683. sc->keyframes[i] = avio_rb32(pb);
  1684. //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
  1685. }
  1686. sc->keyframe_count = i;
  1687. if (pb->eof_reached)
  1688. return AVERROR_EOF;
  1689. return 0;
  1690. }
  1691. static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1692. {
  1693. AVStream *st;
  1694. MOVStreamContext *sc;
  1695. unsigned int i, entries, sample_size, field_size, num_bytes;
  1696. GetBitContext gb;
  1697. unsigned char* buf;
  1698. if (c->fc->nb_streams < 1)
  1699. return 0;
  1700. st = c->fc->streams[c->fc->nb_streams-1];
  1701. sc = st->priv_data;
  1702. avio_r8(pb); /* version */
  1703. avio_rb24(pb); /* flags */
  1704. if (atom.type == MKTAG('s','t','s','z')) {
  1705. sample_size = avio_rb32(pb);
  1706. if (!sc->sample_size) /* do not overwrite value computed in stsd */
  1707. sc->sample_size = sample_size;
  1708. sc->stsz_sample_size = sample_size;
  1709. field_size = 32;
  1710. } else {
  1711. sample_size = 0;
  1712. avio_rb24(pb); /* reserved */
  1713. field_size = avio_r8(pb);
  1714. }
  1715. entries = avio_rb32(pb);
  1716. av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
  1717. sc->sample_count = entries;
  1718. if (sample_size)
  1719. return 0;
  1720. if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
  1721. av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
  1722. return AVERROR_INVALIDDATA;
  1723. }
  1724. if (!entries)
  1725. return 0;
  1726. if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
  1727. return AVERROR_INVALIDDATA;
  1728. sc->sample_sizes = av_malloc(entries * sizeof(int));
  1729. if (!sc->sample_sizes)
  1730. return AVERROR(ENOMEM);
  1731. num_bytes = (entries*field_size+4)>>3;
  1732. buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
  1733. if (!buf) {
  1734. av_freep(&sc->sample_sizes);
  1735. return AVERROR(ENOMEM);
  1736. }
  1737. if (avio_read(pb, buf, num_bytes) < num_bytes) {
  1738. av_freep(&sc->sample_sizes);
  1739. av_free(buf);
  1740. return AVERROR_INVALIDDATA;
  1741. }
  1742. init_get_bits(&gb, buf, 8*num_bytes);
  1743. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1744. sc->sample_sizes[i] = get_bits_long(&gb, field_size);
  1745. sc->data_size += sc->sample_sizes[i];
  1746. }
  1747. sc->sample_count = i;
  1748. if (pb->eof_reached)
  1749. return AVERROR_EOF;
  1750. av_free(buf);
  1751. return 0;
  1752. }
  1753. static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1754. {
  1755. AVStream *st;
  1756. MOVStreamContext *sc;
  1757. unsigned int i, entries;
  1758. int64_t duration=0;
  1759. int64_t total_sample_count=0;
  1760. if (c->fc->nb_streams < 1)
  1761. return 0;
  1762. st = c->fc->streams[c->fc->nb_streams-1];
  1763. sc = st->priv_data;
  1764. avio_r8(pb); /* version */
  1765. avio_rb24(pb); /* flags */
  1766. entries = avio_rb32(pb);
  1767. av_dlog(c->fc, "track[%i].stts.entries = %i\n",
  1768. c->fc->nb_streams-1, entries);
  1769. if (entries >= UINT_MAX / sizeof(*sc->stts_data))
  1770. return -1;
  1771. av_free(sc->stts_data);
  1772. sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
  1773. if (!sc->stts_data)
  1774. return AVERROR(ENOMEM);
  1775. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1776. int sample_duration;
  1777. int sample_count;
  1778. sample_count=avio_rb32(pb);
  1779. sample_duration = avio_rb32(pb);
  1780. /* sample_duration < 0 is invalid based on the spec */
  1781. if (sample_duration < 0) {
  1782. av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta %d in STTS, at %d st:%d\n",
  1783. sample_duration, i, c->fc->nb_streams-1);
  1784. sample_duration = 1;
  1785. }
  1786. if (sample_count < 0) {
  1787. av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
  1788. return AVERROR_INVALIDDATA;
  1789. }
  1790. sc->stts_data[i].count= sample_count;
  1791. sc->stts_data[i].duration= sample_duration;
  1792. av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
  1793. sample_count, sample_duration);
  1794. if ( i+1 == entries
  1795. && i
  1796. && sample_count == 1
  1797. && total_sample_count > 100
  1798. && sample_duration/10 > duration / total_sample_count)
  1799. sample_duration = duration / total_sample_count;
  1800. duration+=(int64_t)sample_duration*sample_count;
  1801. total_sample_count+=sample_count;
  1802. }
  1803. sc->stts_count = i;
  1804. sc->duration_for_fps += duration;
  1805. sc->nb_frames_for_fps += total_sample_count;
  1806. if (pb->eof_reached)
  1807. return AVERROR_EOF;
  1808. st->nb_frames= total_sample_count;
  1809. if (duration)
  1810. st->duration= duration;
  1811. sc->track_end = duration;
  1812. return 0;
  1813. }
  1814. static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
  1815. {
  1816. if (duration < 0) {
  1817. sc->dts_shift = FFMAX(sc->dts_shift, -duration);
  1818. }
  1819. }
  1820. static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1821. {
  1822. AVStream *st;
  1823. MOVStreamContext *sc;
  1824. unsigned int i, entries;
  1825. if (c->fc->nb_streams < 1)
  1826. return 0;
  1827. st = c->fc->streams[c->fc->nb_streams-1];
  1828. sc = st->priv_data;
  1829. avio_r8(pb); /* version */
  1830. avio_rb24(pb); /* flags */
  1831. entries = avio_rb32(pb);
  1832. av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
  1833. if (!entries)
  1834. return 0;
  1835. if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
  1836. return AVERROR_INVALIDDATA;
  1837. sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
  1838. if (!sc->ctts_data)
  1839. return AVERROR(ENOMEM);
  1840. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1841. int count =avio_rb32(pb);
  1842. int duration =avio_rb32(pb);
  1843. sc->ctts_data[i].count = count;
  1844. sc->ctts_data[i].duration= duration;
  1845. av_dlog(c->fc, "count=%d, duration=%d\n",
  1846. count, duration);
  1847. if (FFABS(duration) > (1<<28) && i+2<entries) {
  1848. av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
  1849. av_freep(&sc->ctts_data);
  1850. sc->ctts_count = 0;
  1851. return 0;
  1852. }
  1853. if (i+2<entries)
  1854. mov_update_dts_shift(sc, duration);
  1855. }
  1856. sc->ctts_count = i;
  1857. if (pb->eof_reached)
  1858. return AVERROR_EOF;
  1859. av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
  1860. return 0;
  1861. }
  1862. static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1863. {
  1864. AVStream *st;
  1865. MOVStreamContext *sc;
  1866. unsigned int i, entries;
  1867. uint8_t version;
  1868. uint32_t grouping_type;
  1869. if (c->fc->nb_streams < 1)
  1870. return 0;
  1871. st = c->fc->streams[c->fc->nb_streams-1];
  1872. sc = st->priv_data;
  1873. version = avio_r8(pb); /* version */
  1874. avio_rb24(pb); /* flags */
  1875. grouping_type = avio_rl32(pb);
  1876. if (grouping_type != MKTAG( 'r','a','p',' '))
  1877. return 0; /* only support 'rap ' grouping */
  1878. if (version == 1)
  1879. avio_rb32(pb); /* grouping_type_parameter */
  1880. entries = avio_rb32(pb);
  1881. if (!entries)
  1882. return 0;
  1883. if (entries >= UINT_MAX / sizeof(*sc->rap_group))
  1884. return AVERROR_INVALIDDATA;
  1885. sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
  1886. if (!sc->rap_group)
  1887. return AVERROR(ENOMEM);
  1888. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1889. sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
  1890. sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
  1891. }
  1892. sc->rap_group_count = i;
  1893. return pb->eof_reached ? AVERROR_EOF : 0;
  1894. }
  1895. static void mov_build_index(MOVContext *mov, AVStream *st)
  1896. {
  1897. MOVStreamContext *sc = st->priv_data;
  1898. int64_t current_offset;
  1899. int64_t current_dts = 0;
  1900. unsigned int stts_index = 0;
  1901. unsigned int stsc_index = 0;
  1902. unsigned int stss_index = 0;
  1903. unsigned int stps_index = 0;
  1904. unsigned int i, j;
  1905. uint64_t stream_size = 0;
  1906. /* adjust first dts according to edit list */
  1907. if ((sc->empty_duration || sc->start_time) && mov->time_scale > 0) {
  1908. if (sc->empty_duration)
  1909. sc->empty_duration = av_rescale(sc->empty_duration, sc->time_scale, mov->time_scale);
  1910. sc->time_offset = sc->start_time - sc->empty_duration;
  1911. current_dts = -sc->time_offset;
  1912. if (sc->ctts_count>0 && sc->stts_count>0 &&
  1913. sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
  1914. /* more than 16 frames delay, dts are likely wrong
  1915. this happens with files created by iMovie */
  1916. sc->wrong_dts = 1;
  1917. st->codec->has_b_frames = 1;
  1918. }
  1919. }
  1920. /* only use old uncompressed audio chunk demuxing when stts specifies it */
  1921. if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  1922. sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
  1923. unsigned int current_sample = 0;
  1924. unsigned int stts_sample = 0;
  1925. unsigned int sample_size;
  1926. unsigned int distance = 0;
  1927. unsigned int rap_group_index = 0;
  1928. unsigned int rap_group_sample = 0;
  1929. int rap_group_present = sc->rap_group_count && sc->rap_group;
  1930. int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
  1931. current_dts -= sc->dts_shift;
  1932. if (!sc->sample_count || st->nb_index_entries)
  1933. return;
  1934. if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  1935. return;
  1936. if (av_reallocp_array(&st->index_entries,
  1937. st->nb_index_entries + sc->sample_count,
  1938. sizeof(*st->index_entries)) < 0) {
  1939. st->nb_index_entries = 0;
  1940. return;
  1941. }
  1942. st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
  1943. for (i = 0; i < sc->chunk_count; i++) {
  1944. int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
  1945. current_offset = sc->chunk_offsets[i];
  1946. while (stsc_index + 1 < sc->stsc_count &&
  1947. i + 1 == sc->stsc_data[stsc_index + 1].first)
  1948. stsc_index++;
  1949. if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
  1950. sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
  1951. av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
  1952. sc->stsz_sample_size = sc->sample_size;
  1953. }
  1954. if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
  1955. av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
  1956. sc->stsz_sample_size = sc->sample_size;
  1957. }
  1958. for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
  1959. int keyframe = 0;
  1960. if (current_sample >= sc->sample_count) {
  1961. av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
  1962. return;
  1963. }
  1964. if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
  1965. keyframe = 1;
  1966. if (stss_index + 1 < sc->keyframe_count)
  1967. stss_index++;
  1968. } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
  1969. keyframe = 1;
  1970. if (stps_index + 1 < sc->stps_count)
  1971. stps_index++;
  1972. }
  1973. if (rap_group_present && rap_group_index < sc->rap_group_count) {
  1974. if (sc->rap_group[rap_group_index].index > 0)
  1975. keyframe = 1;
  1976. if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
  1977. rap_group_sample = 0;
  1978. rap_group_index++;
  1979. }
  1980. }
  1981. if (sc->keyframe_absent
  1982. && !sc->stps_count
  1983. && !rap_group_present
  1984. && (st->codec->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
  1985. keyframe = 1;
  1986. if (keyframe)
  1987. distance = 0;
  1988. sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
  1989. if (sc->pseudo_stream_id == -1 ||
  1990. sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
  1991. AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
  1992. e->pos = current_offset;
  1993. e->timestamp = current_dts;
  1994. e->size = sample_size;
  1995. e->min_distance = distance;
  1996. e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
  1997. av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  1998. "size %d, distance %d, keyframe %d\n", st->index, current_sample,
  1999. current_offset, current_dts, sample_size, distance, keyframe);
  2000. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
  2001. ff_rfps_add_frame(mov->fc, st, current_dts);
  2002. }
  2003. current_offset += sample_size;
  2004. stream_size += sample_size;
  2005. current_dts += sc->stts_data[stts_index].duration;
  2006. distance++;
  2007. stts_sample++;
  2008. current_sample++;
  2009. if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
  2010. stts_sample = 0;
  2011. stts_index++;
  2012. }
  2013. }
  2014. }
  2015. if (st->duration > 0)
  2016. st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
  2017. } else {
  2018. unsigned chunk_samples, total = 0;
  2019. // compute total chunk count
  2020. for (i = 0; i < sc->stsc_count; i++) {
  2021. unsigned count, chunk_count;
  2022. chunk_samples = sc->stsc_data[i].count;
  2023. if (i != sc->stsc_count - 1 &&
  2024. sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
  2025. av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
  2026. return;
  2027. }
  2028. if (sc->samples_per_frame >= 160) { // gsm
  2029. count = chunk_samples / sc->samples_per_frame;
  2030. } else if (sc->samples_per_frame > 1) {
  2031. unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
  2032. count = (chunk_samples+samples-1) / samples;
  2033. } else {
  2034. count = (chunk_samples+1023) / 1024;
  2035. }
  2036. if (i < sc->stsc_count - 1)
  2037. chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
  2038. else
  2039. chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
  2040. total += chunk_count * count;
  2041. }
  2042. av_dlog(mov->fc, "chunk count %d\n", total);
  2043. if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  2044. return;
  2045. if (av_reallocp_array(&st->index_entries,
  2046. st->nb_index_entries + total,
  2047. sizeof(*st->index_entries)) < 0) {
  2048. st->nb_index_entries = 0;
  2049. return;
  2050. }
  2051. st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
  2052. // populate index
  2053. for (i = 0; i < sc->chunk_count; i++) {
  2054. current_offset = sc->chunk_offsets[i];
  2055. if (stsc_index + 1 < sc->stsc_count &&
  2056. i + 1 == sc->stsc_data[stsc_index + 1].first)
  2057. stsc_index++;
  2058. chunk_samples = sc->stsc_data[stsc_index].count;
  2059. while (chunk_samples > 0) {
  2060. AVIndexEntry *e;
  2061. unsigned size, samples;
  2062. if (sc->samples_per_frame >= 160) { // gsm
  2063. samples = sc->samples_per_frame;
  2064. size = sc->bytes_per_frame;
  2065. } else {
  2066. if (sc->samples_per_frame > 1) {
  2067. samples = FFMIN((1024 / sc->samples_per_frame)*
  2068. sc->samples_per_frame, chunk_samples);
  2069. size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
  2070. } else {
  2071. samples = FFMIN(1024, chunk_samples);
  2072. size = samples * sc->sample_size;
  2073. }
  2074. }
  2075. if (st->nb_index_entries >= total) {
  2076. av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
  2077. return;
  2078. }
  2079. e = &st->index_entries[st->nb_index_entries++];
  2080. e->pos = current_offset;
  2081. e->timestamp = current_dts;
  2082. e->size = size;
  2083. e->min_distance = 0;
  2084. e->flags = AVINDEX_KEYFRAME;
  2085. av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
  2086. "size %d, duration %d\n", st->index, i, current_offset, current_dts,
  2087. size, samples);
  2088. current_offset += size;
  2089. current_dts += samples;
  2090. chunk_samples -= samples;
  2091. }
  2092. }
  2093. }
  2094. }
  2095. static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref,
  2096. AVIOInterruptCB *int_cb, int use_absolute_path, AVFormatContext *fc)
  2097. {
  2098. /* try relative path, we do not try the absolute because it can leak information about our
  2099. system to an attacker */
  2100. if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
  2101. char filename[1024];
  2102. const char *src_path;
  2103. int i, l;
  2104. /* find a source dir */
  2105. src_path = strrchr(src, '/');
  2106. if (src_path)
  2107. src_path++;
  2108. else
  2109. src_path = src;
  2110. /* find a next level down to target */
  2111. for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
  2112. if (ref->path[l] == '/') {
  2113. if (i == ref->nlvl_to - 1)
  2114. break;
  2115. else
  2116. i++;
  2117. }
  2118. /* compose filename if next level down to target was found */
  2119. if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
  2120. memcpy(filename, src, src_path - src);
  2121. filename[src_path - src] = 0;
  2122. for (i = 1; i < ref->nlvl_from; i++)
  2123. av_strlcat(filename, "../", 1024);
  2124. av_strlcat(filename, ref->path + l + 1, 1024);
  2125. if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
  2126. return 0;
  2127. }
  2128. } else if (use_absolute_path) {
  2129. av_log(fc, AV_LOG_WARNING, "Using absolute path on user request, "
  2130. "this is a possible security issue\n");
  2131. if (!avio_open2(pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
  2132. return 0;
  2133. }
  2134. return AVERROR(ENOENT);
  2135. }
  2136. static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
  2137. {
  2138. if (sc->time_scale <= 0) {
  2139. av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
  2140. sc->time_scale = c->time_scale;
  2141. if (sc->time_scale <= 0)
  2142. sc->time_scale = 1;
  2143. }
  2144. }
  2145. static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2146. {
  2147. AVStream *st;
  2148. MOVStreamContext *sc;
  2149. int ret;
  2150. st = avformat_new_stream(c->fc, NULL);
  2151. if (!st) return AVERROR(ENOMEM);
  2152. st->id = c->fc->nb_streams;
  2153. sc = av_mallocz(sizeof(MOVStreamContext));
  2154. if (!sc) return AVERROR(ENOMEM);
  2155. st->priv_data = sc;
  2156. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  2157. sc->ffindex = st->index;
  2158. if ((ret = mov_read_default(c, pb, atom)) < 0)
  2159. return ret;
  2160. /* sanity checks */
  2161. if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
  2162. (!sc->sample_size && !sc->sample_count))) {
  2163. av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
  2164. st->index);
  2165. return 0;
  2166. }
  2167. fix_timescale(c, sc);
  2168. avpriv_set_pts_info(st, 64, 1, sc->time_scale);
  2169. mov_build_index(c, st);
  2170. if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
  2171. MOVDref *dref = &sc->drefs[sc->dref_id - 1];
  2172. if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback,
  2173. c->use_absolute_path, c->fc) < 0)
  2174. av_log(c->fc, AV_LOG_ERROR,
  2175. "stream %d, error opening alias: path='%s', dir='%s', "
  2176. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
  2177. st->index, dref->path, dref->dir, dref->filename,
  2178. dref->volume, dref->nlvl_from, dref->nlvl_to);
  2179. } else {
  2180. sc->pb = c->fc->pb;
  2181. sc->pb_is_copied = 1;
  2182. }
  2183. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  2184. if (!st->sample_aspect_ratio.num &&
  2185. (st->codec->width != sc->width || st->codec->height != sc->height)) {
  2186. st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
  2187. ((double)st->codec->width * sc->height), INT_MAX);
  2188. }
  2189. #if FF_API_R_FRAME_RATE
  2190. if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
  2191. av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
  2192. sc->time_scale, sc->stts_data[0].duration, INT_MAX);
  2193. #endif
  2194. }
  2195. // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
  2196. if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
  2197. TAG_IS_AVCI(st->codec->codec_tag)) {
  2198. ret = ff_generate_avci_extradata(st);
  2199. if (ret < 0)
  2200. return ret;
  2201. }
  2202. switch (st->codec->codec_id) {
  2203. #if CONFIG_H261_DECODER
  2204. case AV_CODEC_ID_H261:
  2205. #endif
  2206. #if CONFIG_H263_DECODER
  2207. case AV_CODEC_ID_H263:
  2208. #endif
  2209. #if CONFIG_MPEG4_DECODER
  2210. case AV_CODEC_ID_MPEG4:
  2211. #endif
  2212. st->codec->width = 0; /* let decoder init width/height */
  2213. st->codec->height= 0;
  2214. break;
  2215. }
  2216. /* Do not need those anymore. */
  2217. av_freep(&sc->chunk_offsets);
  2218. av_freep(&sc->stsc_data);
  2219. av_freep(&sc->sample_sizes);
  2220. av_freep(&sc->keyframes);
  2221. av_freep(&sc->stts_data);
  2222. av_freep(&sc->stps_data);
  2223. av_freep(&sc->rap_group);
  2224. return 0;
  2225. }
  2226. static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2227. {
  2228. int ret;
  2229. c->itunes_metadata = 1;
  2230. ret = mov_read_default(c, pb, atom);
  2231. c->itunes_metadata = 0;
  2232. return ret;
  2233. }
  2234. static int mov_read_custom_2plus(MOVContext *c, AVIOContext *pb, int size)
  2235. {
  2236. int64_t end = avio_tell(pb) + size;
  2237. uint8_t *key = NULL, *val = NULL;
  2238. int i;
  2239. AVStream *st;
  2240. MOVStreamContext *sc;
  2241. if (c->fc->nb_streams < 1)
  2242. return 0;
  2243. st = c->fc->streams[c->fc->nb_streams-1];
  2244. sc = st->priv_data;
  2245. for (i = 0; i < 2; i++) {
  2246. uint8_t **p;
  2247. uint32_t len, tag;
  2248. if (end - avio_tell(pb) <= 12)
  2249. break;
  2250. len = avio_rb32(pb);
  2251. tag = avio_rl32(pb);
  2252. avio_skip(pb, 4); // flags
  2253. if (len < 12 || len - 12 > end - avio_tell(pb))
  2254. break;
  2255. len -= 12;
  2256. if (tag == MKTAG('n', 'a', 'm', 'e'))
  2257. p = &key;
  2258. else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
  2259. avio_skip(pb, 4);
  2260. len -= 4;
  2261. p = &val;
  2262. } else
  2263. break;
  2264. *p = av_malloc(len + 1);
  2265. if (!*p)
  2266. break;
  2267. avio_read(pb, *p, len);
  2268. (*p)[len] = 0;
  2269. }
  2270. if (key && val) {
  2271. if (strcmp(key, "iTunSMPB") == 0) {
  2272. int priming, remainder, samples;
  2273. if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
  2274. if(priming>0 && priming<16384)
  2275. sc->start_pad = priming;
  2276. }
  2277. }
  2278. if (strcmp(key, "cdec") != 0) {
  2279. av_dict_set(&c->fc->metadata, key, val,
  2280. AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
  2281. key = val = NULL;
  2282. }
  2283. }
  2284. avio_seek(pb, end, SEEK_SET);
  2285. av_freep(&key);
  2286. av_freep(&val);
  2287. return 0;
  2288. }
  2289. static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2290. {
  2291. int64_t end = avio_tell(pb) + atom.size;
  2292. uint32_t tag, len;
  2293. if (atom.size < 8)
  2294. goto fail;
  2295. len = avio_rb32(pb);
  2296. tag = avio_rl32(pb);
  2297. if (len > atom.size)
  2298. goto fail;
  2299. if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
  2300. uint8_t domain[128];
  2301. int domain_len;
  2302. avio_skip(pb, 4); // flags
  2303. len -= 12;
  2304. domain_len = avio_get_str(pb, len, domain, sizeof(domain));
  2305. avio_skip(pb, len - domain_len);
  2306. return mov_read_custom_2plus(c, pb, end - avio_tell(pb));
  2307. }
  2308. fail:
  2309. av_log(c->fc, AV_LOG_VERBOSE,
  2310. "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
  2311. return 0;
  2312. }
  2313. static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2314. {
  2315. while (atom.size > 8) {
  2316. uint32_t tag = avio_rl32(pb);
  2317. atom.size -= 4;
  2318. if (tag == MKTAG('h','d','l','r')) {
  2319. avio_seek(pb, -8, SEEK_CUR);
  2320. atom.size += 8;
  2321. return mov_read_default(c, pb, atom);
  2322. }
  2323. }
  2324. return 0;
  2325. }
  2326. static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2327. {
  2328. int i;
  2329. int width;
  2330. int height;
  2331. int64_t disp_transform[2];
  2332. int display_matrix[3][3];
  2333. AVStream *st;
  2334. MOVStreamContext *sc;
  2335. int version;
  2336. int flags;
  2337. if (c->fc->nb_streams < 1)
  2338. return 0;
  2339. st = c->fc->streams[c->fc->nb_streams-1];
  2340. sc = st->priv_data;
  2341. version = avio_r8(pb);
  2342. flags = avio_rb24(pb);
  2343. st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
  2344. if (version == 1) {
  2345. avio_rb64(pb);
  2346. avio_rb64(pb);
  2347. } else {
  2348. avio_rb32(pb); /* creation time */
  2349. avio_rb32(pb); /* modification time */
  2350. }
  2351. st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
  2352. avio_rb32(pb); /* reserved */
  2353. /* highlevel (considering edits) duration in movie timebase */
  2354. (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
  2355. avio_rb32(pb); /* reserved */
  2356. avio_rb32(pb); /* reserved */
  2357. avio_rb16(pb); /* layer */
  2358. avio_rb16(pb); /* alternate group */
  2359. avio_rb16(pb); /* volume */
  2360. avio_rb16(pb); /* reserved */
  2361. //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
  2362. // they're kept in fixed point format through all calculations
  2363. // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
  2364. // side data, but the scale factor is not needed to calculate aspect ratio
  2365. for (i = 0; i < 3; i++) {
  2366. display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
  2367. display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
  2368. display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
  2369. }
  2370. width = avio_rb32(pb); // 16.16 fixed point track width
  2371. height = avio_rb32(pb); // 16.16 fixed point track height
  2372. sc->width = width >> 16;
  2373. sc->height = height >> 16;
  2374. // save the matrix and add rotate metadata when it is not the default
  2375. // identity
  2376. if (display_matrix[0][0] != (1 << 16) ||
  2377. display_matrix[1][1] != (1 << 16) ||
  2378. display_matrix[2][2] != (1 << 30) ||
  2379. display_matrix[0][1] || display_matrix[0][2] ||
  2380. display_matrix[1][0] || display_matrix[1][2] ||
  2381. display_matrix[2][0] || display_matrix[2][1]) {
  2382. int i, j;
  2383. double rotate;
  2384. av_freep(&sc->display_matrix);
  2385. sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
  2386. if (!sc->display_matrix)
  2387. return AVERROR(ENOMEM);
  2388. for (i = 0; i < 3; i++)
  2389. for (j = 0; j < 3; j++)
  2390. sc->display_matrix[i * 3 + j] = display_matrix[j][i];
  2391. rotate = av_display_rotation_get(sc->display_matrix);
  2392. if (!isnan(rotate)) {
  2393. char rotate_buf[64];
  2394. rotate = -rotate;
  2395. if (rotate < 0) // for backward compatibility
  2396. rotate += 360;
  2397. snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
  2398. av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
  2399. }
  2400. }
  2401. // transform the display width/height according to the matrix
  2402. // skip this if the display matrix is the default identity matrix
  2403. // or if it is rotating the picture, ex iPhone 3GS
  2404. // to keep the same scale, use [width height 1<<16]
  2405. if (width && height &&
  2406. ((display_matrix[0][0] != 65536 ||
  2407. display_matrix[1][1] != 65536) &&
  2408. !display_matrix[0][1] &&
  2409. !display_matrix[1][0] &&
  2410. !display_matrix[2][0] && !display_matrix[2][1])) {
  2411. for (i = 0; i < 2; i++)
  2412. disp_transform[i] =
  2413. (int64_t) width * display_matrix[0][i] +
  2414. (int64_t) height * display_matrix[1][i] +
  2415. ((int64_t) display_matrix[2][i] << 16);
  2416. //sample aspect ratio is new width/height divided by old width/height
  2417. st->sample_aspect_ratio = av_d2q(
  2418. ((double) disp_transform[0] * height) /
  2419. ((double) disp_transform[1] * width), INT_MAX);
  2420. }
  2421. return 0;
  2422. }
  2423. static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2424. {
  2425. MOVFragment *frag = &c->fragment;
  2426. MOVTrackExt *trex = NULL;
  2427. MOVFragmentIndex* index = NULL;
  2428. int flags, track_id, i;
  2429. avio_r8(pb); /* version */
  2430. flags = avio_rb24(pb);
  2431. track_id = avio_rb32(pb);
  2432. if (!track_id)
  2433. return AVERROR_INVALIDDATA;
  2434. frag->track_id = track_id;
  2435. for (i = 0; i < c->trex_count; i++)
  2436. if (c->trex_data[i].track_id == frag->track_id) {
  2437. trex = &c->trex_data[i];
  2438. break;
  2439. }
  2440. if (!trex) {
  2441. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
  2442. return AVERROR_INVALIDDATA;
  2443. }
  2444. for (i = 0; i < c->fragment_index_count; i++) {
  2445. MOVFragmentIndex* candidate = c->fragment_index_data[i];
  2446. if (candidate->track_id == frag->track_id) {
  2447. av_log(c->fc, AV_LOG_DEBUG,
  2448. "found fragment index for track %u\n", frag->track_id);
  2449. index = candidate;
  2450. break;
  2451. }
  2452. }
  2453. frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
  2454. avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
  2455. frag->moof_offset : frag->implicit_offset;
  2456. frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
  2457. frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
  2458. avio_rb32(pb) : trex->duration;
  2459. frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
  2460. avio_rb32(pb) : trex->size;
  2461. frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
  2462. avio_rb32(pb) : trex->flags;
  2463. frag->time = AV_NOPTS_VALUE;
  2464. if (index) {
  2465. int i, found = 0;
  2466. for (i = index->current_item; i < index->item_count; i++) {
  2467. if (frag->implicit_offset == index->items[i].moof_offset) {
  2468. av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry "
  2469. "for track %u and moof_offset %"PRId64"\n",
  2470. frag->track_id, index->items[i].moof_offset);
  2471. frag->time = index->items[i].time;
  2472. index->current_item = i + 1;
  2473. found = 1;
  2474. }
  2475. }
  2476. if (!found) {
  2477. av_log(c->fc, AV_LOG_WARNING, "track %u has a fragment index "
  2478. "but it doesn't have an (in-order) entry for moof_offset "
  2479. "%"PRId64"\n", frag->track_id, frag->implicit_offset);
  2480. }
  2481. }
  2482. av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
  2483. return 0;
  2484. }
  2485. static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2486. {
  2487. c->chapter_track = avio_rb32(pb);
  2488. return 0;
  2489. }
  2490. static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2491. {
  2492. MOVTrackExt *trex;
  2493. int err;
  2494. if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
  2495. return AVERROR_INVALIDDATA;
  2496. if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
  2497. sizeof(*c->trex_data))) < 0) {
  2498. c->trex_count = 0;
  2499. return err;
  2500. }
  2501. c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
  2502. trex = &c->trex_data[c->trex_count++];
  2503. avio_r8(pb); /* version */
  2504. avio_rb24(pb); /* flags */
  2505. trex->track_id = avio_rb32(pb);
  2506. trex->stsd_id = avio_rb32(pb);
  2507. trex->duration = avio_rb32(pb);
  2508. trex->size = avio_rb32(pb);
  2509. trex->flags = avio_rb32(pb);
  2510. return 0;
  2511. }
  2512. static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2513. {
  2514. MOVFragment *frag = &c->fragment;
  2515. AVStream *st = NULL;
  2516. MOVStreamContext *sc;
  2517. int version, i;
  2518. for (i = 0; i < c->fc->nb_streams; i++) {
  2519. if (c->fc->streams[i]->id == frag->track_id) {
  2520. st = c->fc->streams[i];
  2521. break;
  2522. }
  2523. }
  2524. if (!st) {
  2525. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  2526. return AVERROR_INVALIDDATA;
  2527. }
  2528. sc = st->priv_data;
  2529. if (sc->pseudo_stream_id + 1 != frag->stsd_id)
  2530. return 0;
  2531. version = avio_r8(pb);
  2532. avio_rb24(pb); /* flags */
  2533. if (version) {
  2534. sc->track_end = avio_rb64(pb);
  2535. } else {
  2536. sc->track_end = avio_rb32(pb);
  2537. }
  2538. return 0;
  2539. }
  2540. static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2541. {
  2542. MOVFragment *frag = &c->fragment;
  2543. AVStream *st = NULL;
  2544. MOVStreamContext *sc;
  2545. MOVStts *ctts_data;
  2546. uint64_t offset;
  2547. int64_t dts;
  2548. int data_offset = 0;
  2549. unsigned entries, first_sample_flags = frag->flags;
  2550. int flags, distance, i, found_keyframe = 0, err;
  2551. for (i = 0; i < c->fc->nb_streams; i++) {
  2552. if (c->fc->streams[i]->id == frag->track_id) {
  2553. st = c->fc->streams[i];
  2554. break;
  2555. }
  2556. }
  2557. if (!st) {
  2558. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  2559. return AVERROR_INVALIDDATA;
  2560. }
  2561. sc = st->priv_data;
  2562. if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
  2563. return 0;
  2564. avio_r8(pb); /* version */
  2565. flags = avio_rb24(pb);
  2566. entries = avio_rb32(pb);
  2567. av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
  2568. /* Always assume the presence of composition time offsets.
  2569. * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
  2570. * 1) in the initial movie, there are no samples.
  2571. * 2) in the first movie fragment, there is only one sample without composition time offset.
  2572. * 3) in the subsequent movie fragments, there are samples with composition time offset. */
  2573. if (!sc->ctts_count && sc->sample_count)
  2574. {
  2575. /* Complement ctts table if moov atom doesn't have ctts atom. */
  2576. ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
  2577. if (!ctts_data)
  2578. return AVERROR(ENOMEM);
  2579. sc->ctts_data = ctts_data;
  2580. sc->ctts_data[sc->ctts_count].count = sc->sample_count;
  2581. sc->ctts_data[sc->ctts_count].duration = 0;
  2582. sc->ctts_count++;
  2583. }
  2584. if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
  2585. return AVERROR_INVALIDDATA;
  2586. if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
  2587. sizeof(*sc->ctts_data))) < 0) {
  2588. sc->ctts_count = 0;
  2589. return err;
  2590. }
  2591. if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
  2592. if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
  2593. dts = sc->track_end - sc->time_offset;
  2594. offset = frag->base_data_offset + data_offset;
  2595. distance = 0;
  2596. av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
  2597. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2598. unsigned sample_size = frag->size;
  2599. int sample_flags = i ? frag->flags : first_sample_flags;
  2600. unsigned sample_duration = frag->duration;
  2601. int keyframe = 0;
  2602. if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
  2603. if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
  2604. if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
  2605. sc->ctts_data[sc->ctts_count].count = 1;
  2606. sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
  2607. avio_rb32(pb) : 0;
  2608. mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
  2609. if (frag->time != AV_NOPTS_VALUE) {
  2610. if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
  2611. int64_t pts = frag->time;
  2612. av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
  2613. " sc->dts_shift %d ctts.duration %d"
  2614. " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,
  2615. sc->dts_shift, sc->ctts_data[sc->ctts_count].duration,
  2616. sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
  2617. dts = pts - sc->dts_shift;
  2618. if (flags & MOV_TRUN_SAMPLE_CTS) {
  2619. dts -= sc->ctts_data[sc->ctts_count].duration;
  2620. } else {
  2621. dts -= sc->time_offset;
  2622. }
  2623. av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);
  2624. } else {
  2625. dts = frag->time;
  2626. av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
  2627. ", using it for dts\n", dts);
  2628. }
  2629. frag->time = AV_NOPTS_VALUE;
  2630. }
  2631. sc->ctts_count++;
  2632. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  2633. keyframe = 1;
  2634. else if (!found_keyframe)
  2635. keyframe = found_keyframe =
  2636. !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
  2637. MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
  2638. if (keyframe)
  2639. distance = 0;
  2640. av_add_index_entry(st, offset, dts, sample_size, distance,
  2641. keyframe ? AVINDEX_KEYFRAME : 0);
  2642. av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  2643. "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
  2644. offset, dts, sample_size, distance, keyframe);
  2645. distance++;
  2646. dts += sample_duration;
  2647. offset += sample_size;
  2648. sc->data_size += sample_size;
  2649. sc->duration_for_fps += sample_duration;
  2650. sc->nb_frames_for_fps ++;
  2651. }
  2652. if (pb->eof_reached)
  2653. return AVERROR_EOF;
  2654. frag->implicit_offset = offset;
  2655. st->duration = sc->track_end = dts + sc->time_offset;
  2656. return 0;
  2657. }
  2658. /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
  2659. /* like the files created with Adobe Premiere 5.0, for samples see */
  2660. /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
  2661. static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2662. {
  2663. int err;
  2664. if (atom.size < 8)
  2665. return 0; /* continue */
  2666. if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
  2667. avio_skip(pb, atom.size - 4);
  2668. return 0;
  2669. }
  2670. atom.type = avio_rl32(pb);
  2671. atom.size -= 8;
  2672. if (atom.type != MKTAG('m','d','a','t')) {
  2673. avio_skip(pb, atom.size);
  2674. return 0;
  2675. }
  2676. err = mov_read_mdat(c, pb, atom);
  2677. return err;
  2678. }
  2679. static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2680. {
  2681. #if CONFIG_ZLIB
  2682. AVIOContext ctx;
  2683. uint8_t *cmov_data;
  2684. uint8_t *moov_data; /* uncompressed data */
  2685. long cmov_len, moov_len;
  2686. int ret = -1;
  2687. avio_rb32(pb); /* dcom atom */
  2688. if (avio_rl32(pb) != MKTAG('d','c','o','m'))
  2689. return AVERROR_INVALIDDATA;
  2690. if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
  2691. av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
  2692. return AVERROR_INVALIDDATA;
  2693. }
  2694. avio_rb32(pb); /* cmvd atom */
  2695. if (avio_rl32(pb) != MKTAG('c','m','v','d'))
  2696. return AVERROR_INVALIDDATA;
  2697. moov_len = avio_rb32(pb); /* uncompressed size */
  2698. cmov_len = atom.size - 6 * 4;
  2699. cmov_data = av_malloc(cmov_len);
  2700. if (!cmov_data)
  2701. return AVERROR(ENOMEM);
  2702. moov_data = av_malloc(moov_len);
  2703. if (!moov_data) {
  2704. av_free(cmov_data);
  2705. return AVERROR(ENOMEM);
  2706. }
  2707. avio_read(pb, cmov_data, cmov_len);
  2708. if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
  2709. goto free_and_return;
  2710. if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
  2711. goto free_and_return;
  2712. atom.type = MKTAG('m','o','o','v');
  2713. atom.size = moov_len;
  2714. ret = mov_read_default(c, &ctx, atom);
  2715. free_and_return:
  2716. av_free(moov_data);
  2717. av_free(cmov_data);
  2718. return ret;
  2719. #else
  2720. av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
  2721. return AVERROR(ENOSYS);
  2722. #endif
  2723. }
  2724. /* edit list atom */
  2725. static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2726. {
  2727. MOVStreamContext *sc;
  2728. int i, edit_count, version, edit_start_index = 0;
  2729. int unsupported = 0;
  2730. if (c->fc->nb_streams < 1 || c->ignore_editlist)
  2731. return 0;
  2732. sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
  2733. version = avio_r8(pb); /* version */
  2734. avio_rb24(pb); /* flags */
  2735. edit_count = avio_rb32(pb); /* entries */
  2736. if ((uint64_t)edit_count*12+8 > atom.size)
  2737. return AVERROR_INVALIDDATA;
  2738. av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
  2739. for (i=0; i<edit_count; i++){
  2740. int64_t time;
  2741. int64_t duration;
  2742. int rate;
  2743. if (version == 1) {
  2744. duration = avio_rb64(pb);
  2745. time = avio_rb64(pb);
  2746. } else {
  2747. duration = avio_rb32(pb); /* segment duration */
  2748. time = (int32_t)avio_rb32(pb); /* media time */
  2749. }
  2750. rate = avio_rb32(pb);
  2751. if (i == 0 && time == -1) {
  2752. sc->empty_duration = duration;
  2753. edit_start_index = 1;
  2754. } else if (i == edit_start_index && time >= 0)
  2755. sc->start_time = time;
  2756. else
  2757. unsupported = 1;
  2758. av_dlog(c->fc, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
  2759. duration, time, rate / 65536.0);
  2760. }
  2761. if (unsupported)
  2762. av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
  2763. "a/v desync might occur, patch welcome\n");
  2764. return 0;
  2765. }
  2766. static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2767. {
  2768. MOVStreamContext *sc;
  2769. if (c->fc->nb_streams < 1)
  2770. return AVERROR_INVALIDDATA;
  2771. sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
  2772. sc->timecode_track = avio_rb32(pb);
  2773. return 0;
  2774. }
  2775. static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2776. {
  2777. int ret;
  2778. uint8_t uuid[16];
  2779. static const uint8_t uuid_isml_manifest[] = {
  2780. 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
  2781. 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
  2782. };
  2783. if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
  2784. return AVERROR_INVALIDDATA;
  2785. ret = avio_read(pb, uuid, sizeof(uuid));
  2786. if (ret < 0) {
  2787. return ret;
  2788. } else if (ret != sizeof(uuid)) {
  2789. return AVERROR_INVALIDDATA;
  2790. }
  2791. if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
  2792. uint8_t *buffer, *ptr;
  2793. char *endptr;
  2794. size_t len = atom.size - sizeof(uuid);
  2795. if (len < 4) {
  2796. return AVERROR_INVALIDDATA;
  2797. }
  2798. ret = avio_skip(pb, 4); // zeroes
  2799. len -= 4;
  2800. buffer = av_mallocz(len + 1);
  2801. if (!buffer) {
  2802. return AVERROR(ENOMEM);
  2803. }
  2804. ret = avio_read(pb, buffer, len);
  2805. if (ret < 0) {
  2806. av_free(buffer);
  2807. return ret;
  2808. } else if (ret != len) {
  2809. av_free(buffer);
  2810. return AVERROR_INVALIDDATA;
  2811. }
  2812. ptr = buffer;
  2813. while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
  2814. ptr += sizeof("systemBitrate=\"") - 1;
  2815. c->bitrates_count++;
  2816. c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
  2817. if (!c->bitrates) {
  2818. c->bitrates_count = 0;
  2819. av_free(buffer);
  2820. return AVERROR(ENOMEM);
  2821. }
  2822. errno = 0;
  2823. ret = strtol(ptr, &endptr, 10);
  2824. if (ret < 0 || errno || *endptr != '"') {
  2825. c->bitrates[c->bitrates_count - 1] = 0;
  2826. } else {
  2827. c->bitrates[c->bitrates_count - 1] = ret;
  2828. }
  2829. }
  2830. av_free(buffer);
  2831. }
  2832. return 0;
  2833. }
  2834. static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2835. {
  2836. int ret;
  2837. uint8_t content[16];
  2838. if (atom.size < 8)
  2839. return 0;
  2840. ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
  2841. if (ret < 0)
  2842. return ret;
  2843. if ( !c->found_moov
  2844. && !c->found_mdat
  2845. && !memcmp(content, "Anevia\x1A\x1A", 8)
  2846. && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
  2847. c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
  2848. }
  2849. return 0;
  2850. }
  2851. static const MOVParseTableEntry mov_default_parse_table[] = {
  2852. { MKTAG('A','C','L','R'), mov_read_avid },
  2853. { MKTAG('A','P','R','G'), mov_read_avid },
  2854. { MKTAG('A','A','L','P'), mov_read_avid },
  2855. { MKTAG('A','R','E','S'), mov_read_ares },
  2856. { MKTAG('a','v','s','s'), mov_read_avss },
  2857. { MKTAG('c','h','p','l'), mov_read_chpl },
  2858. { MKTAG('c','o','6','4'), mov_read_stco },
  2859. { MKTAG('c','o','l','r'), mov_read_colr },
  2860. { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
  2861. { MKTAG('d','i','n','f'), mov_read_default },
  2862. { MKTAG('d','r','e','f'), mov_read_dref },
  2863. { MKTAG('e','d','t','s'), mov_read_default },
  2864. { MKTAG('e','l','s','t'), mov_read_elst },
  2865. { MKTAG('e','n','d','a'), mov_read_enda },
  2866. { MKTAG('f','i','e','l'), mov_read_fiel },
  2867. { MKTAG('f','t','y','p'), mov_read_ftyp },
  2868. { MKTAG('g','l','b','l'), mov_read_glbl },
  2869. { MKTAG('h','d','l','r'), mov_read_hdlr },
  2870. { MKTAG('i','l','s','t'), mov_read_ilst },
  2871. { MKTAG('j','p','2','h'), mov_read_jp2h },
  2872. { MKTAG('m','d','a','t'), mov_read_mdat },
  2873. { MKTAG('m','d','h','d'), mov_read_mdhd },
  2874. { MKTAG('m','d','i','a'), mov_read_default },
  2875. { MKTAG('m','e','t','a'), mov_read_meta },
  2876. { MKTAG('m','i','n','f'), mov_read_default },
  2877. { MKTAG('m','o','o','f'), mov_read_moof },
  2878. { MKTAG('m','o','o','v'), mov_read_moov },
  2879. { MKTAG('m','v','e','x'), mov_read_default },
  2880. { MKTAG('m','v','h','d'), mov_read_mvhd },
  2881. { MKTAG('S','M','I',' '), mov_read_svq3 },
  2882. { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
  2883. { MKTAG('a','v','c','C'), mov_read_glbl },
  2884. { MKTAG('p','a','s','p'), mov_read_pasp },
  2885. { MKTAG('s','t','b','l'), mov_read_default },
  2886. { MKTAG('s','t','c','o'), mov_read_stco },
  2887. { MKTAG('s','t','p','s'), mov_read_stps },
  2888. { MKTAG('s','t','r','f'), mov_read_strf },
  2889. { MKTAG('s','t','s','c'), mov_read_stsc },
  2890. { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
  2891. { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
  2892. { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
  2893. { MKTAG('s','t','t','s'), mov_read_stts },
  2894. { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
  2895. { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
  2896. { MKTAG('t','f','d','t'), mov_read_tfdt },
  2897. { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
  2898. { MKTAG('t','r','a','k'), mov_read_trak },
  2899. { MKTAG('t','r','a','f'), mov_read_default },
  2900. { MKTAG('t','r','e','f'), mov_read_default },
  2901. { MKTAG('t','m','c','d'), mov_read_tmcd },
  2902. { MKTAG('c','h','a','p'), mov_read_chap },
  2903. { MKTAG('t','r','e','x'), mov_read_trex },
  2904. { MKTAG('t','r','u','n'), mov_read_trun },
  2905. { MKTAG('u','d','t','a'), mov_read_default },
  2906. { MKTAG('w','a','v','e'), mov_read_wave },
  2907. { MKTAG('e','s','d','s'), mov_read_esds },
  2908. { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
  2909. { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
  2910. { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
  2911. { MKTAG('w','f','e','x'), mov_read_wfex },
  2912. { MKTAG('c','m','o','v'), mov_read_cmov },
  2913. { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
  2914. { MKTAG('d','v','c','1'), mov_read_dvc1 },
  2915. { MKTAG('s','b','g','p'), mov_read_sbgp },
  2916. { MKTAG('h','v','c','C'), mov_read_glbl },
  2917. { MKTAG('u','u','i','d'), mov_read_uuid },
  2918. { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
  2919. { MKTAG('f','r','e','e'), mov_read_free },
  2920. { MKTAG('-','-','-','-'), mov_read_custom },
  2921. { 0, NULL }
  2922. };
  2923. static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2924. {
  2925. int64_t total_size = 0;
  2926. MOVAtom a;
  2927. int i;
  2928. if (atom.size < 0)
  2929. atom.size = INT64_MAX;
  2930. while (total_size + 8 <= atom.size && !avio_feof(pb)) {
  2931. int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
  2932. a.size = atom.size;
  2933. a.type=0;
  2934. if (atom.size >= 8) {
  2935. a.size = avio_rb32(pb);
  2936. a.type = avio_rl32(pb);
  2937. if (a.type == MKTAG('f','r','e','e') &&
  2938. a.size >= 8 &&
  2939. c->moov_retry) {
  2940. uint8_t buf[8];
  2941. uint32_t *type = (uint32_t *)buf + 1;
  2942. avio_read(pb, buf, 8);
  2943. avio_seek(pb, -8, SEEK_CUR);
  2944. if (*type == MKTAG('m','v','h','d') ||
  2945. *type == MKTAG('c','m','o','v')) {
  2946. av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
  2947. a.type = MKTAG('m','o','o','v');
  2948. }
  2949. }
  2950. if (atom.type != MKTAG('r','o','o','t') &&
  2951. atom.type != MKTAG('m','o','o','v'))
  2952. {
  2953. if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
  2954. {
  2955. av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
  2956. avio_skip(pb, -8);
  2957. return 0;
  2958. }
  2959. }
  2960. total_size += 8;
  2961. if (a.size == 1) { /* 64 bit extended size */
  2962. a.size = avio_rb64(pb) - 8;
  2963. total_size += 8;
  2964. }
  2965. }
  2966. av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
  2967. a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
  2968. if (a.size == 0) {
  2969. a.size = atom.size - total_size + 8;
  2970. }
  2971. a.size -= 8;
  2972. if (a.size < 0)
  2973. break;
  2974. a.size = FFMIN(a.size, atom.size - total_size);
  2975. for (i = 0; mov_default_parse_table[i].type; i++)
  2976. if (mov_default_parse_table[i].type == a.type) {
  2977. parse = mov_default_parse_table[i].parse;
  2978. break;
  2979. }
  2980. // container is user data
  2981. if (!parse && (atom.type == MKTAG('u','d','t','a') ||
  2982. atom.type == MKTAG('i','l','s','t')))
  2983. parse = mov_read_udta_string;
  2984. if (!parse) { /* skip leaf atoms data */
  2985. avio_skip(pb, a.size);
  2986. } else {
  2987. int64_t start_pos = avio_tell(pb);
  2988. int64_t left;
  2989. int err = parse(c, pb, a);
  2990. if (err < 0)
  2991. return err;
  2992. if (c->found_moov && c->found_mdat &&
  2993. ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
  2994. start_pos + a.size == avio_size(pb))) {
  2995. if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
  2996. c->next_root_atom = start_pos + a.size;
  2997. return 0;
  2998. }
  2999. left = a.size - avio_tell(pb) + start_pos;
  3000. if (left > 0) /* skip garbage at atom end */
  3001. avio_skip(pb, left);
  3002. else if (left < 0) {
  3003. av_log(c->fc, AV_LOG_WARNING,
  3004. "overread end of atom '%.4s' by %"PRId64" bytes\n",
  3005. (char*)&a.type, -left);
  3006. avio_seek(pb, left, SEEK_CUR);
  3007. }
  3008. }
  3009. total_size += a.size;
  3010. }
  3011. if (total_size < atom.size && atom.size < 0x7ffff)
  3012. avio_skip(pb, atom.size - total_size);
  3013. return 0;
  3014. }
  3015. static int mov_probe(AVProbeData *p)
  3016. {
  3017. int64_t offset;
  3018. uint32_t tag;
  3019. int score = 0;
  3020. int moov_offset = -1;
  3021. /* check file header */
  3022. offset = 0;
  3023. for (;;) {
  3024. /* ignore invalid offset */
  3025. if ((offset + 8) > (unsigned int)p->buf_size)
  3026. break;
  3027. tag = AV_RL32(p->buf + offset + 4);
  3028. switch(tag) {
  3029. /* check for obvious tags */
  3030. case MKTAG('m','o','o','v'):
  3031. moov_offset = offset + 4;
  3032. case MKTAG('m','d','a','t'):
  3033. case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
  3034. case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
  3035. case MKTAG('f','t','y','p'):
  3036. if (AV_RB32(p->buf+offset) < 8 &&
  3037. (AV_RB32(p->buf+offset) != 1 ||
  3038. offset + 12 > (unsigned int)p->buf_size ||
  3039. AV_RB64(p->buf+offset + 8) == 0)) {
  3040. score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
  3041. } else if (tag == MKTAG('f','t','y','p') &&
  3042. AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')) {
  3043. score = FFMAX(score, 5);
  3044. } else {
  3045. score = AVPROBE_SCORE_MAX;
  3046. }
  3047. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  3048. break;
  3049. /* those are more common words, so rate then a bit less */
  3050. case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
  3051. case MKTAG('w','i','d','e'):
  3052. case MKTAG('f','r','e','e'):
  3053. case MKTAG('j','u','n','k'):
  3054. case MKTAG('p','i','c','t'):
  3055. score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
  3056. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  3057. break;
  3058. case MKTAG(0x82,0x82,0x7f,0x7d):
  3059. case MKTAG('s','k','i','p'):
  3060. case MKTAG('u','u','i','d'):
  3061. case MKTAG('p','r','f','l'):
  3062. /* if we only find those cause probedata is too small at least rate them */
  3063. score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
  3064. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  3065. break;
  3066. default:
  3067. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  3068. }
  3069. }
  3070. if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
  3071. /* moov atom in the header - we should make sure that this is not a
  3072. * MOV-packed MPEG-PS */
  3073. offset = moov_offset;
  3074. while(offset < (p->buf_size - 16)){ /* Sufficient space */
  3075. /* We found an actual hdlr atom */
  3076. if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
  3077. AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
  3078. AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
  3079. av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
  3080. /* We found a media handler reference atom describing an
  3081. * MPEG-PS-in-MOV, return a
  3082. * low score to force expanding the probe window until
  3083. * mpegps_probe finds what it needs */
  3084. return 5;
  3085. }else
  3086. /* Keep looking */
  3087. offset+=2;
  3088. }
  3089. }
  3090. return score;
  3091. }
  3092. // must be done after parsing all trak because there's no order requirement
  3093. static void mov_read_chapters(AVFormatContext *s)
  3094. {
  3095. MOVContext *mov = s->priv_data;
  3096. AVStream *st = NULL;
  3097. MOVStreamContext *sc;
  3098. int64_t cur_pos;
  3099. int i;
  3100. for (i = 0; i < s->nb_streams; i++)
  3101. if (s->streams[i]->id == mov->chapter_track) {
  3102. st = s->streams[i];
  3103. break;
  3104. }
  3105. if (!st) {
  3106. av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
  3107. return;
  3108. }
  3109. st->discard = AVDISCARD_ALL;
  3110. sc = st->priv_data;
  3111. cur_pos = avio_tell(sc->pb);
  3112. for (i = 0; i < st->nb_index_entries; i++) {
  3113. AVIndexEntry *sample = &st->index_entries[i];
  3114. int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
  3115. uint8_t *title;
  3116. uint16_t ch;
  3117. int len, title_len;
  3118. if (end < sample->timestamp) {
  3119. av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
  3120. end = AV_NOPTS_VALUE;
  3121. }
  3122. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  3123. av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
  3124. goto finish;
  3125. }
  3126. // the first two bytes are the length of the title
  3127. len = avio_rb16(sc->pb);
  3128. if (len > sample->size-2)
  3129. continue;
  3130. title_len = 2*len + 1;
  3131. if (!(title = av_mallocz(title_len)))
  3132. goto finish;
  3133. // The samples could theoretically be in any encoding if there's an encd
  3134. // atom following, but in practice are only utf-8 or utf-16, distinguished
  3135. // instead by the presence of a BOM
  3136. if (!len) {
  3137. title[0] = 0;
  3138. } else {
  3139. ch = avio_rb16(sc->pb);
  3140. if (ch == 0xfeff)
  3141. avio_get_str16be(sc->pb, len, title, title_len);
  3142. else if (ch == 0xfffe)
  3143. avio_get_str16le(sc->pb, len, title, title_len);
  3144. else {
  3145. AV_WB16(title, ch);
  3146. if (len == 1 || len == 2)
  3147. title[len] = 0;
  3148. else
  3149. avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
  3150. }
  3151. }
  3152. avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
  3153. av_freep(&title);
  3154. }
  3155. finish:
  3156. avio_seek(sc->pb, cur_pos, SEEK_SET);
  3157. }
  3158. static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
  3159. uint32_t value, int flags)
  3160. {
  3161. AVTimecode tc;
  3162. char buf[AV_TIMECODE_STR_SIZE];
  3163. AVRational rate = {st->codec->time_base.den,
  3164. st->codec->time_base.num};
  3165. int ret = av_timecode_init(&tc, rate, flags, 0, s);
  3166. if (ret < 0)
  3167. return ret;
  3168. av_dict_set(&st->metadata, "timecode",
  3169. av_timecode_make_string(&tc, buf, value), 0);
  3170. return 0;
  3171. }
  3172. static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
  3173. {
  3174. MOVStreamContext *sc = st->priv_data;
  3175. int flags = 0;
  3176. int64_t cur_pos = avio_tell(sc->pb);
  3177. uint32_t value;
  3178. if (!st->nb_index_entries)
  3179. return -1;
  3180. avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
  3181. value = avio_rb32(s->pb);
  3182. if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
  3183. if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  3184. if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
  3185. /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
  3186. * not the case) and thus assume "frame number format" instead of QT one.
  3187. * No sample with tmcd track can be found with a QT timecode at the moment,
  3188. * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
  3189. * format). */
  3190. parse_timecode_in_framenum_format(s, st, value, flags);
  3191. avio_seek(sc->pb, cur_pos, SEEK_SET);
  3192. return 0;
  3193. }
  3194. static int mov_read_close(AVFormatContext *s)
  3195. {
  3196. MOVContext *mov = s->priv_data;
  3197. int i, j;
  3198. for (i = 0; i < s->nb_streams; i++) {
  3199. AVStream *st = s->streams[i];
  3200. MOVStreamContext *sc = st->priv_data;
  3201. av_freep(&sc->ctts_data);
  3202. for (j = 0; j < sc->drefs_count; j++) {
  3203. av_freep(&sc->drefs[j].path);
  3204. av_freep(&sc->drefs[j].dir);
  3205. }
  3206. av_freep(&sc->drefs);
  3207. sc->drefs_count = 0;
  3208. if (!sc->pb_is_copied)
  3209. avio_close(sc->pb);
  3210. sc->pb = NULL;
  3211. av_freep(&sc->chunk_offsets);
  3212. av_freep(&sc->stsc_data);
  3213. av_freep(&sc->sample_sizes);
  3214. av_freep(&sc->keyframes);
  3215. av_freep(&sc->stts_data);
  3216. av_freep(&sc->stps_data);
  3217. av_freep(&sc->rap_group);
  3218. av_freep(&sc->display_matrix);
  3219. }
  3220. if (mov->dv_demux) {
  3221. avformat_free_context(mov->dv_fctx);
  3222. mov->dv_fctx = NULL;
  3223. }
  3224. av_freep(&mov->trex_data);
  3225. av_freep(&mov->bitrates);
  3226. for (i = 0; i < mov->fragment_index_count; i++) {
  3227. MOVFragmentIndex* index = mov->fragment_index_data[i];
  3228. av_freep(&index->items);
  3229. av_freep(&mov->fragment_index_data[i]);
  3230. }
  3231. av_freep(&mov->fragment_index_data);
  3232. return 0;
  3233. }
  3234. static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
  3235. {
  3236. int i;
  3237. for (i = 0; i < s->nb_streams; i++) {
  3238. AVStream *st = s->streams[i];
  3239. MOVStreamContext *sc = st->priv_data;
  3240. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
  3241. sc->timecode_track == tmcd_id)
  3242. return 1;
  3243. }
  3244. return 0;
  3245. }
  3246. /* look for a tmcd track not referenced by any video track, and export it globally */
  3247. static void export_orphan_timecode(AVFormatContext *s)
  3248. {
  3249. int i;
  3250. for (i = 0; i < s->nb_streams; i++) {
  3251. AVStream *st = s->streams[i];
  3252. if (st->codec->codec_tag == MKTAG('t','m','c','d') &&
  3253. !tmcd_is_referenced(s, i + 1)) {
  3254. AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
  3255. if (tcr) {
  3256. av_dict_set(&s->metadata, "timecode", tcr->value, 0);
  3257. break;
  3258. }
  3259. }
  3260. }
  3261. }
  3262. static int read_tfra(MOVContext *mov, AVIOContext *f)
  3263. {
  3264. MOVFragmentIndex* index = NULL;
  3265. int version, fieldlength, i, j, err;
  3266. int64_t pos = avio_tell(f);
  3267. uint32_t size = avio_rb32(f);
  3268. if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
  3269. return -1;
  3270. }
  3271. av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
  3272. index = av_mallocz(sizeof(MOVFragmentIndex));
  3273. if (!index) {
  3274. return AVERROR(ENOMEM);
  3275. }
  3276. mov->fragment_index_count++;
  3277. if ((err = av_reallocp(&mov->fragment_index_data,
  3278. mov->fragment_index_count *
  3279. sizeof(MOVFragmentIndex*))) < 0) {
  3280. av_freep(&index);
  3281. return err;
  3282. }
  3283. mov->fragment_index_data[mov->fragment_index_count - 1] =
  3284. index;
  3285. version = avio_r8(f);
  3286. avio_rb24(f);
  3287. index->track_id = avio_rb32(f);
  3288. fieldlength = avio_rb32(f);
  3289. index->item_count = avio_rb32(f);
  3290. index->items = av_mallocz(
  3291. index->item_count * sizeof(MOVFragmentIndexItem));
  3292. if (!index->items) {
  3293. return AVERROR(ENOMEM);
  3294. }
  3295. for (i = 0; i < index->item_count; i++) {
  3296. int64_t time, offset;
  3297. if (version == 1) {
  3298. time = avio_rb64(f);
  3299. offset = avio_rb64(f);
  3300. } else {
  3301. time = avio_rb32(f);
  3302. offset = avio_rb32(f);
  3303. }
  3304. index->items[i].time = time;
  3305. index->items[i].moof_offset = offset;
  3306. for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
  3307. avio_r8(f);
  3308. for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
  3309. avio_r8(f);
  3310. for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
  3311. avio_r8(f);
  3312. }
  3313. avio_seek(f, pos + size, SEEK_SET);
  3314. return 0;
  3315. }
  3316. static int mov_read_mfra(MOVContext *c, AVIOContext *f)
  3317. {
  3318. int64_t stream_size = avio_size(f);
  3319. int64_t original_pos = avio_tell(f);
  3320. int32_t mfra_size;
  3321. int ret = -1;
  3322. if ((ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) goto fail;
  3323. mfra_size = avio_rb32(f);
  3324. if (mfra_size < 0 || mfra_size > stream_size) {
  3325. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
  3326. ret = -1;
  3327. goto fail;
  3328. }
  3329. if ((ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) goto fail;
  3330. if (avio_rb32(f) != mfra_size) {
  3331. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
  3332. ret = -1;
  3333. goto fail;
  3334. }
  3335. if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
  3336. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
  3337. goto fail;
  3338. }
  3339. av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
  3340. while (!read_tfra(c, f)) {
  3341. /* Empty */
  3342. }
  3343. fail:
  3344. ret = avio_seek(f, original_pos, SEEK_SET);
  3345. if (ret < 0)
  3346. av_log(c->fc, AV_LOG_ERROR,
  3347. "failed to seek back after looking for mfra\n");
  3348. else
  3349. ret = 0;
  3350. return ret;
  3351. }
  3352. static int mov_read_header(AVFormatContext *s)
  3353. {
  3354. MOVContext *mov = s->priv_data;
  3355. AVIOContext *pb = s->pb;
  3356. int j, err;
  3357. MOVAtom atom = { AV_RL32("root") };
  3358. int i;
  3359. mov->fc = s;
  3360. /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
  3361. if (pb->seekable)
  3362. atom.size = avio_size(pb);
  3363. else
  3364. atom.size = INT64_MAX;
  3365. /* check MOV header */
  3366. do {
  3367. if (mov->moov_retry)
  3368. avio_seek(pb, 0, SEEK_SET);
  3369. if ((err = mov_read_default(mov, pb, atom)) < 0) {
  3370. av_log(s, AV_LOG_ERROR, "error reading header\n");
  3371. mov_read_close(s);
  3372. return err;
  3373. }
  3374. } while (pb->seekable && !mov->found_moov && !mov->moov_retry++);
  3375. if (!mov->found_moov) {
  3376. av_log(s, AV_LOG_ERROR, "moov atom not found\n");
  3377. mov_read_close(s);
  3378. return AVERROR_INVALIDDATA;
  3379. }
  3380. av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
  3381. if (pb->seekable) {
  3382. if (mov->chapter_track > 0)
  3383. mov_read_chapters(s);
  3384. for (i = 0; i < s->nb_streams; i++)
  3385. if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
  3386. mov_read_timecode_track(s, s->streams[i]);
  3387. }
  3388. /* copy timecode metadata from tmcd tracks to the related video streams */
  3389. for (i = 0; i < s->nb_streams; i++) {
  3390. AVStream *st = s->streams[i];
  3391. MOVStreamContext *sc = st->priv_data;
  3392. if (sc->timecode_track > 0) {
  3393. AVDictionaryEntry *tcr;
  3394. int tmcd_st_id = -1;
  3395. for (j = 0; j < s->nb_streams; j++)
  3396. if (s->streams[j]->id == sc->timecode_track)
  3397. tmcd_st_id = j;
  3398. if (tmcd_st_id < 0 || tmcd_st_id == i)
  3399. continue;
  3400. tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
  3401. if (tcr)
  3402. av_dict_set(&st->metadata, "timecode", tcr->value, 0);
  3403. }
  3404. }
  3405. export_orphan_timecode(s);
  3406. for (i = 0; i < s->nb_streams; i++) {
  3407. AVStream *st = s->streams[i];
  3408. MOVStreamContext *sc = st->priv_data;
  3409. fix_timescale(mov, sc);
  3410. if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
  3411. st->skip_samples = sc->start_pad;
  3412. }
  3413. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
  3414. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  3415. sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
  3416. if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  3417. if (st->codec->width <= 0 && st->codec->height <= 0) {
  3418. st->codec->width = sc->width;
  3419. st->codec->height = sc->height;
  3420. }
  3421. if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
  3422. if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
  3423. return err;
  3424. }
  3425. }
  3426. }
  3427. if (mov->trex_data) {
  3428. for (i = 0; i < s->nb_streams; i++) {
  3429. AVStream *st = s->streams[i];
  3430. MOVStreamContext *sc = st->priv_data;
  3431. if (st->duration > 0)
  3432. st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
  3433. }
  3434. }
  3435. if (mov->use_mfra_for > 0) {
  3436. for (i = 0; i < s->nb_streams; i++) {
  3437. AVStream *st = s->streams[i];
  3438. MOVStreamContext *sc = st->priv_data;
  3439. if (sc->duration_for_fps > 0) {
  3440. st->codec->bit_rate = sc->data_size * 8 * sc->time_scale /
  3441. sc->duration_for_fps;
  3442. }
  3443. }
  3444. }
  3445. for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
  3446. if (mov->bitrates[i]) {
  3447. s->streams[i]->codec->bit_rate = mov->bitrates[i];
  3448. }
  3449. }
  3450. ff_rfps_calculate(s);
  3451. for (i = 0; i < s->nb_streams; i++) {
  3452. AVStream *st = s->streams[i];
  3453. MOVStreamContext *sc = st->priv_data;
  3454. switch (st->codec->codec_type) {
  3455. case AVMEDIA_TYPE_AUDIO:
  3456. err = ff_replaygain_export(st, s->metadata);
  3457. if (err < 0) {
  3458. mov_read_close(s);
  3459. return err;
  3460. }
  3461. break;
  3462. case AVMEDIA_TYPE_VIDEO:
  3463. if (sc->display_matrix) {
  3464. AVPacketSideData *sd, *tmp;
  3465. tmp = av_realloc_array(st->side_data,
  3466. st->nb_side_data + 1, sizeof(*tmp));
  3467. if (!tmp)
  3468. return AVERROR(ENOMEM);
  3469. st->side_data = tmp;
  3470. st->nb_side_data++;
  3471. sd = &st->side_data[st->nb_side_data - 1];
  3472. sd->type = AV_PKT_DATA_DISPLAYMATRIX;
  3473. sd->size = sizeof(int32_t) * 9;
  3474. sd->data = (uint8_t*)sc->display_matrix;
  3475. sc->display_matrix = NULL;
  3476. }
  3477. break;
  3478. }
  3479. }
  3480. return 0;
  3481. }
  3482. static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
  3483. {
  3484. AVIndexEntry *sample = NULL;
  3485. int64_t best_dts = INT64_MAX;
  3486. int i;
  3487. for (i = 0; i < s->nb_streams; i++) {
  3488. AVStream *avst = s->streams[i];
  3489. MOVStreamContext *msc = avst->priv_data;
  3490. if (msc->pb && msc->current_sample < avst->nb_index_entries) {
  3491. AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
  3492. int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
  3493. av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
  3494. if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
  3495. (s->pb->seekable &&
  3496. ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
  3497. ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
  3498. (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
  3499. sample = current_sample;
  3500. best_dts = dts;
  3501. *st = avst;
  3502. }
  3503. }
  3504. }
  3505. return sample;
  3506. }
  3507. static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
  3508. {
  3509. MOVContext *mov = s->priv_data;
  3510. MOVStreamContext *sc;
  3511. AVIndexEntry *sample;
  3512. AVStream *st = NULL;
  3513. int ret;
  3514. mov->fc = s;
  3515. retry:
  3516. sample = mov_find_next_sample(s, &st);
  3517. if (!sample) {
  3518. mov->found_mdat = 0;
  3519. if (!mov->next_root_atom)
  3520. return AVERROR_EOF;
  3521. avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
  3522. mov->next_root_atom = 0;
  3523. if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
  3524. avio_feof(s->pb))
  3525. return AVERROR_EOF;
  3526. av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
  3527. goto retry;
  3528. }
  3529. sc = st->priv_data;
  3530. /* must be done just before reading, to avoid infinite loop on sample */
  3531. sc->current_sample++;
  3532. if (mov->next_root_atom) {
  3533. sample->pos = FFMIN(sample->pos, mov->next_root_atom);
  3534. sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
  3535. }
  3536. if (st->discard != AVDISCARD_ALL) {
  3537. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  3538. av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
  3539. sc->ffindex, sample->pos);
  3540. return AVERROR_INVALIDDATA;
  3541. }
  3542. ret = av_get_packet(sc->pb, pkt, sample->size);
  3543. if (ret < 0)
  3544. return ret;
  3545. if (sc->has_palette) {
  3546. uint8_t *pal;
  3547. pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
  3548. if (!pal) {
  3549. av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
  3550. } else {
  3551. memcpy(pal, sc->palette, AVPALETTE_SIZE);
  3552. sc->has_palette = 0;
  3553. }
  3554. }
  3555. #if CONFIG_DV_DEMUXER
  3556. if (mov->dv_demux && sc->dv_audio_container) {
  3557. avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
  3558. av_free(pkt->data);
  3559. pkt->size = 0;
  3560. ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
  3561. if (ret < 0)
  3562. return ret;
  3563. }
  3564. #endif
  3565. }
  3566. pkt->stream_index = sc->ffindex;
  3567. pkt->dts = sample->timestamp;
  3568. if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
  3569. pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
  3570. /* update ctts context */
  3571. sc->ctts_sample++;
  3572. if (sc->ctts_index < sc->ctts_count &&
  3573. sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
  3574. sc->ctts_index++;
  3575. sc->ctts_sample = 0;
  3576. }
  3577. if (sc->wrong_dts)
  3578. pkt->dts = AV_NOPTS_VALUE;
  3579. } else {
  3580. int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
  3581. st->index_entries[sc->current_sample].timestamp : st->duration;
  3582. pkt->duration = next_dts - pkt->dts;
  3583. pkt->pts = pkt->dts;
  3584. }
  3585. if (st->discard == AVDISCARD_ALL)
  3586. goto retry;
  3587. pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
  3588. pkt->pos = sample->pos;
  3589. av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
  3590. pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
  3591. return 0;
  3592. }
  3593. static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
  3594. {
  3595. MOVStreamContext *sc = st->priv_data;
  3596. int sample, time_sample;
  3597. int i;
  3598. sample = av_index_search_timestamp(st, timestamp, flags);
  3599. av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
  3600. if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
  3601. sample = 0;
  3602. if (sample < 0) /* not sure what to do */
  3603. return AVERROR_INVALIDDATA;
  3604. sc->current_sample = sample;
  3605. av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
  3606. /* adjust ctts index */
  3607. if (sc->ctts_data) {
  3608. time_sample = 0;
  3609. for (i = 0; i < sc->ctts_count; i++) {
  3610. int next = time_sample + sc->ctts_data[i].count;
  3611. if (next > sc->current_sample) {
  3612. sc->ctts_index = i;
  3613. sc->ctts_sample = sc->current_sample - time_sample;
  3614. break;
  3615. }
  3616. time_sample = next;
  3617. }
  3618. }
  3619. return sample;
  3620. }
  3621. static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  3622. {
  3623. AVStream *st;
  3624. int64_t seek_timestamp, timestamp;
  3625. int sample;
  3626. int i;
  3627. if (stream_index >= s->nb_streams)
  3628. return AVERROR_INVALIDDATA;
  3629. st = s->streams[stream_index];
  3630. sample = mov_seek_stream(s, st, sample_time, flags);
  3631. if (sample < 0)
  3632. return sample;
  3633. /* adjust seek timestamp to found sample timestamp */
  3634. seek_timestamp = st->index_entries[sample].timestamp;
  3635. for (i = 0; i < s->nb_streams; i++) {
  3636. MOVStreamContext *sc = s->streams[i]->priv_data;
  3637. st = s->streams[i];
  3638. st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
  3639. if (stream_index == i)
  3640. continue;
  3641. timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
  3642. mov_seek_stream(s, st, timestamp, flags);
  3643. }
  3644. return 0;
  3645. }
  3646. static const AVOption options[] = {
  3647. {"use_absolute_path",
  3648. "allow using absolute path when opening alias, this is a possible security issue",
  3649. offsetof(MOVContext, use_absolute_path), FF_OPT_TYPE_INT, {.i64 = 0},
  3650. 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
  3651. {"ignore_editlist", "", offsetof(MOVContext, ignore_editlist), FF_OPT_TYPE_INT, {.i64 = 0},
  3652. 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
  3653. {"use_mfra_for",
  3654. "use mfra for fragment timestamps",
  3655. offsetof(MOVContext, use_mfra_for), FF_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
  3656. -1, FF_MOV_FLAG_MFRA_PTS, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM,
  3657. "use_mfra_for"},
  3658. {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
  3659. AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM, "use_mfra_for" },
  3660. {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
  3661. AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM, "use_mfra_for" },
  3662. {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
  3663. AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM, "use_mfra_for" },
  3664. {NULL}
  3665. };
  3666. static const AVClass mov_class = {
  3667. .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
  3668. .item_name = av_default_item_name,
  3669. .option = options,
  3670. .version = LIBAVUTIL_VERSION_INT,
  3671. };
  3672. AVInputFormat ff_mov_demuxer = {
  3673. .name = "mov,mp4,m4a,3gp,3g2,mj2",
  3674. .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
  3675. .priv_data_size = sizeof(MOVContext),
  3676. .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
  3677. .read_probe = mov_probe,
  3678. .read_header = mov_read_header,
  3679. .read_packet = mov_read_packet,
  3680. .read_close = mov_read_close,
  3681. .read_seek = mov_read_seek,
  3682. .priv_class = &mov_class,
  3683. .flags = AVFMT_NO_BYTE_SEEK,
  3684. };