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.

3628 lines
119KB

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