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.

3619 lines
119KB

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