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.

3654 lines
120KB

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