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.

3875 lines
127KB

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