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.

3770 lines
123KB

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