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.

3922 lines
129KB

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