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.

3539 lines
119KB

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