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.

1619 lines
54KB

  1. /*
  2. * AVI demuxer
  3. * Copyright (c) 2001 Fabrice Bellard
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * Libav is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include <inttypes.h>
  22. #include "libavutil/avstring.h"
  23. #include "libavutil/bswap.h"
  24. #include "libavutil/dict.h"
  25. #include "libavutil/internal.h"
  26. #include "libavutil/intreadwrite.h"
  27. #include "libavutil/mathematics.h"
  28. #include "avformat.h"
  29. #include "avi.h"
  30. #include "dv.h"
  31. #include "internal.h"
  32. #include "isom.h"
  33. #include "riff.h"
  34. #undef NDEBUG
  35. #include <assert.h>
  36. typedef struct AVIStream {
  37. int64_t frame_offset; /* current frame (video) or byte (audio) counter
  38. * (used to compute the pts) */
  39. int remaining;
  40. int packet_size;
  41. uint32_t handler;
  42. uint32_t scale;
  43. uint32_t rate;
  44. int sample_size; /* size of one sample (or packet)
  45. * (in the rate/scale sense) in bytes */
  46. int64_t cum_len; /* temporary storage (used during seek) */
  47. int prefix; /* normally 'd'<<8 + 'c' or 'w'<<8 + 'b' */
  48. int prefix_count;
  49. uint32_t pal[256];
  50. int has_pal;
  51. int dshow_block_align; /* block align variable used to emulate bugs in
  52. * the MS dshow demuxer */
  53. AVFormatContext *sub_ctx;
  54. AVPacket sub_pkt;
  55. uint8_t *sub_buffer;
  56. } AVIStream;
  57. typedef struct AVIContext {
  58. int64_t riff_end;
  59. int64_t movi_end;
  60. int64_t fsize;
  61. int64_t movi_list;
  62. int64_t last_pkt_pos;
  63. int index_loaded;
  64. int is_odml;
  65. int non_interleaved;
  66. int stream_index;
  67. DVDemuxContext *dv_demux;
  68. int odml_depth;
  69. #define MAX_ODML_DEPTH 1000
  70. } AVIContext;
  71. static const char avi_headers[][8] = {
  72. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
  73. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
  74. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19 },
  75. { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
  76. { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
  77. { 0 }
  78. };
  79. static const AVMetadataConv avi_metadata_conv[] = {
  80. { "strn", "title" },
  81. { 0 },
  82. };
  83. static int avi_load_index(AVFormatContext *s);
  84. static int guess_ni_flag(AVFormatContext *s);
  85. #define print_tag(str, tag, size) \
  86. av_dlog(NULL, "%s: tag=%c%c%c%c size=0x%x\n", \
  87. str, tag & 0xff, \
  88. (tag >> 8) & 0xff, \
  89. (tag >> 16) & 0xff, \
  90. (tag >> 24) & 0xff, \
  91. size)
  92. static inline int get_duration(AVIStream *ast, int len)
  93. {
  94. if (ast->sample_size)
  95. return len;
  96. else if (ast->dshow_block_align)
  97. return (len + ast->dshow_block_align - 1) / ast->dshow_block_align;
  98. else
  99. return 1;
  100. }
  101. static int get_riff(AVFormatContext *s, AVIOContext *pb)
  102. {
  103. AVIContext *avi = s->priv_data;
  104. char header[8];
  105. int i;
  106. /* check RIFF header */
  107. avio_read(pb, header, 4);
  108. avi->riff_end = avio_rl32(pb); /* RIFF chunk size */
  109. avi->riff_end += avio_tell(pb); /* RIFF chunk end */
  110. avio_read(pb, header + 4, 4);
  111. for (i = 0; avi_headers[i][0]; i++)
  112. if (!memcmp(header, avi_headers[i], 8))
  113. break;
  114. if (!avi_headers[i][0])
  115. return AVERROR_INVALIDDATA;
  116. if (header[7] == 0x19)
  117. av_log(s, AV_LOG_INFO,
  118. "This file has been generated by a totally broken muxer.\n");
  119. return 0;
  120. }
  121. static int read_braindead_odml_indx(AVFormatContext *s, int frame_num)
  122. {
  123. AVIContext *avi = s->priv_data;
  124. AVIOContext *pb = s->pb;
  125. int longs_pre_entry = avio_rl16(pb);
  126. int index_sub_type = avio_r8(pb);
  127. int index_type = avio_r8(pb);
  128. int entries_in_use = avio_rl32(pb);
  129. int chunk_id = avio_rl32(pb);
  130. int64_t base = avio_rl64(pb);
  131. int stream_id = ((chunk_id & 0xFF) - '0') * 10 +
  132. ((chunk_id >> 8 & 0xFF) - '0');
  133. AVStream *st;
  134. AVIStream *ast;
  135. int i;
  136. int64_t last_pos = -1;
  137. int64_t filesize = avi->fsize;
  138. av_dlog(s,
  139. "longs_pre_entry:%d index_type:%d entries_in_use:%d "
  140. "chunk_id:%X base:%16"PRIX64"\n",
  141. longs_pre_entry,
  142. index_type,
  143. entries_in_use,
  144. chunk_id,
  145. base);
  146. if (stream_id >= s->nb_streams || stream_id < 0)
  147. return AVERROR_INVALIDDATA;
  148. st = s->streams[stream_id];
  149. ast = st->priv_data;
  150. if (index_sub_type)
  151. return AVERROR_INVALIDDATA;
  152. avio_rl32(pb);
  153. if (index_type && longs_pre_entry != 2)
  154. return AVERROR_INVALIDDATA;
  155. if (index_type > 1)
  156. return AVERROR_INVALIDDATA;
  157. if (filesize > 0 && base >= filesize) {
  158. av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
  159. if (base >> 32 == (base & 0xFFFFFFFF) &&
  160. (base & 0xFFFFFFFF) < filesize &&
  161. filesize <= 0xFFFFFFFF)
  162. base &= 0xFFFFFFFF;
  163. else
  164. return AVERROR_INVALIDDATA;
  165. }
  166. for (i = 0; i < entries_in_use; i++) {
  167. if (index_type) {
  168. int64_t pos = avio_rl32(pb) + base - 8;
  169. int len = avio_rl32(pb);
  170. int key = len >= 0;
  171. len &= 0x7FFFFFFF;
  172. av_dlog(s, "pos:%"PRId64", len:%X\n", pos, len);
  173. if (pb->eof_reached)
  174. return AVERROR_INVALIDDATA;
  175. if (last_pos == pos || pos == base - 8)
  176. avi->non_interleaved = 1;
  177. if (last_pos != pos && (len || !ast->sample_size))
  178. av_add_index_entry(st, pos, ast->cum_len, len, 0,
  179. key ? AVINDEX_KEYFRAME : 0);
  180. ast->cum_len += get_duration(ast, len);
  181. last_pos = pos;
  182. } else {
  183. int64_t offset, pos;
  184. int duration;
  185. offset = avio_rl64(pb);
  186. avio_rl32(pb); /* size */
  187. duration = avio_rl32(pb);
  188. if (pb->eof_reached)
  189. return AVERROR_INVALIDDATA;
  190. pos = avio_tell(pb);
  191. if (avi->odml_depth > MAX_ODML_DEPTH) {
  192. av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
  193. return AVERROR_INVALIDDATA;
  194. }
  195. avio_seek(pb, offset + 8, SEEK_SET);
  196. avi->odml_depth++;
  197. read_braindead_odml_indx(s, frame_num);
  198. avi->odml_depth--;
  199. frame_num += duration;
  200. avio_seek(pb, pos, SEEK_SET);
  201. }
  202. }
  203. avi->index_loaded = 1;
  204. return 0;
  205. }
  206. static void clean_index(AVFormatContext *s)
  207. {
  208. int i;
  209. int64_t j;
  210. for (i = 0; i < s->nb_streams; i++) {
  211. AVStream *st = s->streams[i];
  212. AVIStream *ast = st->priv_data;
  213. int n = st->nb_index_entries;
  214. int max = ast->sample_size;
  215. int64_t pos, size, ts;
  216. if (n != 1 || ast->sample_size == 0)
  217. continue;
  218. while (max < 1024)
  219. max += max;
  220. pos = st->index_entries[0].pos;
  221. size = st->index_entries[0].size;
  222. ts = st->index_entries[0].timestamp;
  223. for (j = 0; j < size; j += max)
  224. av_add_index_entry(st, pos + j, ts + j, FFMIN(max, size - j), 0,
  225. AVINDEX_KEYFRAME);
  226. }
  227. }
  228. static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag,
  229. uint32_t size)
  230. {
  231. AVIOContext *pb = s->pb;
  232. char key[5] = { 0 };
  233. char *value;
  234. size += (size & 1);
  235. if (size == UINT_MAX)
  236. return AVERROR(EINVAL);
  237. value = av_malloc(size + 1);
  238. if (!value)
  239. return AVERROR(ENOMEM);
  240. avio_read(pb, value, size);
  241. value[size] = 0;
  242. AV_WL32(key, tag);
  243. return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
  244. AV_DICT_DONT_STRDUP_VAL);
  245. }
  246. static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  247. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  248. static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
  249. {
  250. char month[4], time[9], buffer[64];
  251. int i, day, year;
  252. /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
  253. if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
  254. month, &day, time, &year) == 4) {
  255. for (i = 0; i < 12; i++)
  256. if (!av_strcasecmp(month, months[i])) {
  257. snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
  258. year, i + 1, day, time);
  259. av_dict_set(metadata, "creation_time", buffer, 0);
  260. }
  261. } else if (date[4] == '/' && date[7] == '/') {
  262. date[4] = date[7] = '-';
  263. av_dict_set(metadata, "creation_time", date, 0);
  264. }
  265. }
  266. static void avi_read_nikon(AVFormatContext *s, uint64_t end)
  267. {
  268. while (avio_tell(s->pb) < end) {
  269. uint32_t tag = avio_rl32(s->pb);
  270. uint32_t size = avio_rl32(s->pb);
  271. switch (tag) {
  272. case MKTAG('n', 'c', 't', 'g'): /* Nikon Tags */
  273. {
  274. uint64_t tag_end = avio_tell(s->pb) + size;
  275. while (avio_tell(s->pb) < tag_end) {
  276. uint16_t tag = avio_rl16(s->pb);
  277. uint16_t size = avio_rl16(s->pb);
  278. const char *name = NULL;
  279. char buffer[64] = { 0 };
  280. size -= avio_read(s->pb, buffer,
  281. FFMIN(size, sizeof(buffer) - 1));
  282. switch (tag) {
  283. case 0x03:
  284. name = "maker";
  285. break;
  286. case 0x04:
  287. name = "model";
  288. break;
  289. case 0x13:
  290. name = "creation_time";
  291. if (buffer[4] == ':' && buffer[7] == ':')
  292. buffer[4] = buffer[7] = '-';
  293. break;
  294. }
  295. if (name)
  296. av_dict_set(&s->metadata, name, buffer, 0);
  297. avio_skip(s->pb, size);
  298. }
  299. break;
  300. }
  301. default:
  302. avio_skip(s->pb, size);
  303. break;
  304. }
  305. }
  306. }
  307. static int avi_read_header(AVFormatContext *s)
  308. {
  309. AVIContext *avi = s->priv_data;
  310. AVIOContext *pb = s->pb;
  311. unsigned int tag, tag1, handler;
  312. int codec_type, stream_index, frame_period;
  313. unsigned int size;
  314. int i;
  315. AVStream *st;
  316. AVIStream *ast = NULL;
  317. int avih_width = 0, avih_height = 0;
  318. int amv_file_format = 0;
  319. uint64_t list_end = 0;
  320. int ret;
  321. avi->stream_index = -1;
  322. ret = get_riff(s, pb);
  323. if (ret < 0)
  324. return ret;
  325. avi->fsize = avio_size(pb);
  326. if (avi->fsize <= 0 || avi->fsize < avi->riff_end)
  327. avi->fsize = avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
  328. /* first list tag */
  329. stream_index = -1;
  330. codec_type = -1;
  331. frame_period = 0;
  332. for (;;) {
  333. if (pb->eof_reached)
  334. goto fail;
  335. tag = avio_rl32(pb);
  336. size = avio_rl32(pb);
  337. print_tag("tag", tag, size);
  338. switch (tag) {
  339. case MKTAG('L', 'I', 'S', 'T'):
  340. list_end = avio_tell(pb) + size;
  341. /* Ignored, except at start of video packets. */
  342. tag1 = avio_rl32(pb);
  343. print_tag("list", tag1, 0);
  344. if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
  345. avi->movi_list = avio_tell(pb) - 4;
  346. if (size)
  347. avi->movi_end = avi->movi_list + size + (size & 1);
  348. else
  349. avi->movi_end = avi->fsize;
  350. av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
  351. goto end_of_header;
  352. } else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
  353. ff_read_riff_info(s, size - 4);
  354. else if (tag1 == MKTAG('n', 'c', 'd', 't'))
  355. avi_read_nikon(s, list_end);
  356. break;
  357. case MKTAG('I', 'D', 'I', 'T'):
  358. {
  359. unsigned char date[64] = { 0 };
  360. size += (size & 1);
  361. size -= avio_read(pb, date, FFMIN(size, sizeof(date) - 1));
  362. avio_skip(pb, size);
  363. avi_metadata_creation_time(&s->metadata, date);
  364. break;
  365. }
  366. case MKTAG('d', 'm', 'l', 'h'):
  367. avi->is_odml = 1;
  368. avio_skip(pb, size + (size & 1));
  369. break;
  370. case MKTAG('a', 'm', 'v', 'h'):
  371. amv_file_format = 1;
  372. case MKTAG('a', 'v', 'i', 'h'):
  373. /* AVI header */
  374. /* using frame_period is bad idea */
  375. frame_period = avio_rl32(pb);
  376. avio_skip(pb, 4);
  377. avio_rl32(pb);
  378. avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
  379. avio_skip(pb, 2 * 4);
  380. avio_rl32(pb);
  381. avio_rl32(pb);
  382. avih_width = avio_rl32(pb);
  383. avih_height = avio_rl32(pb);
  384. avio_skip(pb, size - 10 * 4);
  385. break;
  386. case MKTAG('s', 't', 'r', 'h'):
  387. /* stream header */
  388. tag1 = avio_rl32(pb);
  389. handler = avio_rl32(pb); /* codec tag */
  390. if (tag1 == MKTAG('p', 'a', 'd', 's')) {
  391. avio_skip(pb, size - 8);
  392. break;
  393. } else {
  394. stream_index++;
  395. st = avformat_new_stream(s, NULL);
  396. if (!st)
  397. goto fail;
  398. st->id = stream_index;
  399. ast = av_mallocz(sizeof(AVIStream));
  400. if (!ast)
  401. goto fail;
  402. st->priv_data = ast;
  403. }
  404. if (amv_file_format)
  405. tag1 = stream_index ? MKTAG('a', 'u', 'd', 's')
  406. : MKTAG('v', 'i', 'd', 's');
  407. print_tag("strh", tag1, -1);
  408. if (tag1 == MKTAG('i', 'a', 'v', 's') ||
  409. tag1 == MKTAG('i', 'v', 'a', 's')) {
  410. int64_t dv_dur;
  411. /* After some consideration -- I don't think we
  412. * have to support anything but DV in type1 AVIs. */
  413. if (s->nb_streams != 1)
  414. goto fail;
  415. if (handler != MKTAG('d', 'v', 's', 'd') &&
  416. handler != MKTAG('d', 'v', 'h', 'd') &&
  417. handler != MKTAG('d', 'v', 's', 'l'))
  418. goto fail;
  419. ast = s->streams[0]->priv_data;
  420. av_freep(&s->streams[0]->codec->extradata);
  421. av_freep(&s->streams[0]->codec);
  422. av_freep(&s->streams[0]->info);
  423. av_freep(&s->streams[0]);
  424. s->nb_streams = 0;
  425. if (CONFIG_DV_DEMUXER) {
  426. avi->dv_demux = avpriv_dv_init_demux(s);
  427. if (!avi->dv_demux)
  428. goto fail;
  429. } else
  430. goto fail;
  431. s->streams[0]->priv_data = ast;
  432. avio_skip(pb, 3 * 4);
  433. ast->scale = avio_rl32(pb);
  434. ast->rate = avio_rl32(pb);
  435. avio_skip(pb, 4); /* start time */
  436. dv_dur = avio_rl32(pb);
  437. if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
  438. dv_dur *= AV_TIME_BASE;
  439. s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
  440. }
  441. /* else, leave duration alone; timing estimation in utils.c
  442. * will make a guess based on bitrate. */
  443. stream_index = s->nb_streams - 1;
  444. avio_skip(pb, size - 9 * 4);
  445. break;
  446. }
  447. assert(stream_index < s->nb_streams);
  448. ast->handler = handler;
  449. avio_rl32(pb); /* flags */
  450. avio_rl16(pb); /* priority */
  451. avio_rl16(pb); /* language */
  452. avio_rl32(pb); /* initial frame */
  453. ast->scale = avio_rl32(pb);
  454. ast->rate = avio_rl32(pb);
  455. if (!(ast->scale && ast->rate)) {
  456. av_log(s, AV_LOG_WARNING,
  457. "scale/rate is %"PRIu32"/%"PRIu32" which is invalid. "
  458. "(This file has been generated by broken software.)\n",
  459. ast->scale,
  460. ast->rate);
  461. if (frame_period) {
  462. ast->rate = 1000000;
  463. ast->scale = frame_period;
  464. } else {
  465. ast->rate = 25;
  466. ast->scale = 1;
  467. }
  468. }
  469. avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
  470. ast->cum_len = avio_rl32(pb); /* start */
  471. st->nb_frames = avio_rl32(pb);
  472. st->start_time = 0;
  473. avio_rl32(pb); /* buffer size */
  474. avio_rl32(pb); /* quality */
  475. ast->sample_size = avio_rl32(pb); /* sample ssize */
  476. ast->cum_len *= FFMAX(1, ast->sample_size);
  477. av_dlog(s, "%"PRIu32" %"PRIu32" %d\n",
  478. ast->rate, ast->scale, ast->sample_size);
  479. switch (tag1) {
  480. case MKTAG('v', 'i', 'd', 's'):
  481. codec_type = AVMEDIA_TYPE_VIDEO;
  482. ast->sample_size = 0;
  483. break;
  484. case MKTAG('a', 'u', 'd', 's'):
  485. codec_type = AVMEDIA_TYPE_AUDIO;
  486. break;
  487. case MKTAG('t', 'x', 't', 's'):
  488. codec_type = AVMEDIA_TYPE_SUBTITLE;
  489. break;
  490. case MKTAG('d', 'a', 't', 's'):
  491. codec_type = AVMEDIA_TYPE_DATA;
  492. break;
  493. default:
  494. av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
  495. goto fail;
  496. }
  497. if (ast->sample_size == 0)
  498. st->duration = st->nb_frames;
  499. ast->frame_offset = ast->cum_len;
  500. avio_skip(pb, size - 12 * 4);
  501. break;
  502. case MKTAG('s', 't', 'r', 'f'):
  503. /* stream header */
  504. if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
  505. avio_skip(pb, size);
  506. } else {
  507. uint64_t cur_pos = avio_tell(pb);
  508. if (cur_pos < list_end)
  509. size = FFMIN(size, list_end - cur_pos);
  510. st = s->streams[stream_index];
  511. switch (codec_type) {
  512. case AVMEDIA_TYPE_VIDEO:
  513. if (amv_file_format) {
  514. st->codec->width = avih_width;
  515. st->codec->height = avih_height;
  516. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  517. st->codec->codec_id = AV_CODEC_ID_AMV;
  518. avio_skip(pb, size);
  519. break;
  520. }
  521. tag1 = ff_get_bmp_header(pb, st);
  522. if (tag1 == MKTAG('D', 'X', 'S', 'B') ||
  523. tag1 == MKTAG('D', 'X', 'S', 'A')) {
  524. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  525. st->codec->codec_tag = tag1;
  526. st->codec->codec_id = AV_CODEC_ID_XSUB;
  527. break;
  528. }
  529. if (size > 10 * 4 && size < (1 << 30)) {
  530. st->codec->extradata_size = size - 10 * 4;
  531. st->codec->extradata = av_malloc(st->codec->extradata_size +
  532. FF_INPUT_BUFFER_PADDING_SIZE);
  533. if (!st->codec->extradata) {
  534. st->codec->extradata_size = 0;
  535. return AVERROR(ENOMEM);
  536. }
  537. avio_read(pb,
  538. st->codec->extradata,
  539. st->codec->extradata_size);
  540. }
  541. // FIXME: check if the encoder really did this correctly
  542. if (st->codec->extradata_size & 1)
  543. avio_r8(pb);
  544. /* Extract palette from extradata if bpp <= 8.
  545. * This code assumes that extradata contains only palette.
  546. * This is true for all paletted codecs implemented in
  547. * Libav. */
  548. if (st->codec->extradata_size &&
  549. (st->codec->bits_per_coded_sample <= 8)) {
  550. int pal_size = (1 << st->codec->bits_per_coded_sample) << 2;
  551. const uint8_t *pal_src;
  552. pal_size = FFMIN(pal_size, st->codec->extradata_size);
  553. pal_src = st->codec->extradata +
  554. st->codec->extradata_size - pal_size;
  555. #if HAVE_BIGENDIAN
  556. for (i = 0; i < pal_size / 4; i++)
  557. ast->pal[i] = av_bswap32(((uint32_t *)pal_src)[i]);
  558. #else
  559. memcpy(ast->pal, pal_src, pal_size);
  560. #endif
  561. ast->has_pal = 1;
  562. }
  563. print_tag("video", tag1, 0);
  564. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  565. st->codec->codec_tag = tag1;
  566. st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags,
  567. tag1);
  568. /* If codec is not found yet, try with the mov tags. */
  569. if (!st->codec->codec_id) {
  570. char tag_buf[32];
  571. av_get_codec_tag_string(tag_buf, sizeof(tag_buf), tag1);
  572. st->codec->codec_id =
  573. ff_codec_get_id(ff_codec_movvideo_tags, tag1);
  574. if (st->codec->codec_id)
  575. av_log(s, AV_LOG_WARNING,
  576. "mov tag found in avi (fourcc %s)\n",
  577. tag_buf);
  578. }
  579. /* This is needed to get the pict type which is necessary
  580. * for generating correct pts. */
  581. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  582. if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
  583. ast->handler == MKTAG('X', 'V', 'I', 'D'))
  584. st->codec->codec_tag = MKTAG('X', 'V', 'I', 'D');
  585. // Support "Resolution 1:1" for Avid AVI Codec
  586. if (tag1 == MKTAG('A', 'V', 'R', 'n') &&
  587. st->codec->extradata_size >= 31 &&
  588. !memcmp(&st->codec->extradata[28], "1:1", 3))
  589. st->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
  590. if (st->codec->codec_tag == 0 && st->codec->height > 0 &&
  591. st->codec->extradata_size < 1U << 30) {
  592. st->codec->extradata_size += 9;
  593. if ((ret = av_reallocp(&st->codec->extradata,
  594. st->codec->extradata_size +
  595. FF_INPUT_BUFFER_PADDING_SIZE)) < 0) {
  596. st->codec->extradata_size = 0;
  597. return ret;
  598. } else
  599. memcpy(st->codec->extradata + st->codec->extradata_size - 9,
  600. "BottomUp", 9);
  601. }
  602. st->codec->height = FFABS(st->codec->height);
  603. // avio_skip(pb, size - 5 * 4);
  604. break;
  605. case AVMEDIA_TYPE_AUDIO:
  606. ret = ff_get_wav_header(pb, st->codec, size);
  607. if (ret < 0)
  608. return ret;
  609. ast->dshow_block_align = st->codec->block_align;
  610. if (ast->sample_size && st->codec->block_align &&
  611. ast->sample_size != st->codec->block_align) {
  612. av_log(s,
  613. AV_LOG_WARNING,
  614. "sample size (%d) != block align (%d)\n",
  615. ast->sample_size,
  616. st->codec->block_align);
  617. ast->sample_size = st->codec->block_align;
  618. }
  619. /* 2-aligned
  620. * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
  621. if (size & 1)
  622. avio_skip(pb, 1);
  623. /* Force parsing as several audio frames can be in
  624. * one packet and timestamps refer to packet start. */
  625. st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
  626. /* ADTS header is in extradata, AAC without header must be
  627. * stored as exact frames. Parser not needed and it will
  628. * fail. */
  629. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  630. st->codec->extradata_size)
  631. st->need_parsing = AVSTREAM_PARSE_NONE;
  632. /* AVI files with Xan DPCM audio (wrongly) declare PCM
  633. * audio in the header but have Axan as stream_code_tag. */
  634. if (ast->handler == AV_RL32("Axan")) {
  635. st->codec->codec_id = AV_CODEC_ID_XAN_DPCM;
  636. st->codec->codec_tag = 0;
  637. }
  638. if (amv_file_format) {
  639. st->codec->codec_id = AV_CODEC_ID_ADPCM_IMA_AMV;
  640. ast->dshow_block_align = 0;
  641. }
  642. break;
  643. case AVMEDIA_TYPE_SUBTITLE:
  644. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  645. st->codec->codec_id = AV_CODEC_ID_PROBE;
  646. break;
  647. default:
  648. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  649. st->codec->codec_id = AV_CODEC_ID_NONE;
  650. st->codec->codec_tag = 0;
  651. avio_skip(pb, size);
  652. break;
  653. }
  654. }
  655. break;
  656. case MKTAG('i', 'n', 'd', 'x'):
  657. i = avio_tell(pb);
  658. if (pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) &&
  659. read_braindead_odml_indx(s, 0) < 0 &&
  660. (s->error_recognition & AV_EF_EXPLODE))
  661. goto fail;
  662. avio_seek(pb, i + size, SEEK_SET);
  663. break;
  664. case MKTAG('v', 'p', 'r', 'p'):
  665. if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) {
  666. AVRational active, active_aspect;
  667. st = s->streams[stream_index];
  668. avio_rl32(pb);
  669. avio_rl32(pb);
  670. avio_rl32(pb);
  671. avio_rl32(pb);
  672. avio_rl32(pb);
  673. active_aspect.den = avio_rl16(pb);
  674. active_aspect.num = avio_rl16(pb);
  675. active.num = avio_rl32(pb);
  676. active.den = avio_rl32(pb);
  677. avio_rl32(pb); // nbFieldsPerFrame
  678. if (active_aspect.num && active_aspect.den &&
  679. active.num && active.den) {
  680. st->sample_aspect_ratio = av_div_q(active_aspect, active);
  681. av_dlog(s, "vprp %d/%d %d/%d\n",
  682. active_aspect.num, active_aspect.den,
  683. active.num, active.den);
  684. }
  685. size -= 9 * 4;
  686. }
  687. avio_skip(pb, size);
  688. break;
  689. case MKTAG('s', 't', 'r', 'n'):
  690. if (s->nb_streams) {
  691. ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size);
  692. if (ret < 0)
  693. return ret;
  694. break;
  695. }
  696. default:
  697. if (size > 1000000) {
  698. av_log(s, AV_LOG_ERROR,
  699. "Something went wrong during header parsing, "
  700. "I will ignore it and try to continue anyway.\n");
  701. if (s->error_recognition & AV_EF_EXPLODE)
  702. goto fail;
  703. avi->movi_list = avio_tell(pb) - 4;
  704. avi->movi_end = avi->fsize;
  705. goto end_of_header;
  706. }
  707. /* skip tag */
  708. size += (size & 1);
  709. avio_skip(pb, size);
  710. break;
  711. }
  712. }
  713. end_of_header:
  714. /* check stream number */
  715. if (stream_index != s->nb_streams - 1) {
  716. fail:
  717. return AVERROR_INVALIDDATA;
  718. }
  719. if (!avi->index_loaded && pb->seekable)
  720. avi_load_index(s);
  721. avi->index_loaded = 1;
  722. if ((ret = guess_ni_flag(s)) < 0)
  723. return ret;
  724. avi->non_interleaved |= ret;
  725. for (i = 0; i < s->nb_streams; i++) {
  726. AVStream *st = s->streams[i];
  727. if (st->nb_index_entries)
  728. break;
  729. }
  730. if (i == s->nb_streams && avi->non_interleaved) {
  731. av_log(s, AV_LOG_WARNING,
  732. "Non-interleaved AVI without index, switching to interleaved\n");
  733. avi->non_interleaved = 0;
  734. }
  735. if (avi->non_interleaved) {
  736. av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
  737. clean_index(s);
  738. }
  739. ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
  740. ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
  741. return 0;
  742. }
  743. static int read_gab2_sub(AVStream *st, AVPacket *pkt)
  744. {
  745. if (pkt->size >= 7 &&
  746. !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
  747. uint8_t desc[256];
  748. int score = AVPROBE_SCORE_EXTENSION, ret;
  749. AVIStream *ast = st->priv_data;
  750. AVInputFormat *sub_demuxer;
  751. AVRational time_base;
  752. AVIOContext *pb = avio_alloc_context(pkt->data + 7,
  753. pkt->size - 7,
  754. 0, NULL, NULL, NULL, NULL);
  755. AVProbeData pd;
  756. unsigned int desc_len = avio_rl32(pb);
  757. if (desc_len > pb->buf_end - pb->buf_ptr)
  758. goto error;
  759. ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
  760. avio_skip(pb, desc_len - ret);
  761. if (*desc)
  762. av_dict_set(&st->metadata, "title", desc, 0);
  763. avio_rl16(pb); /* flags? */
  764. avio_rl32(pb); /* data size */
  765. pd = (AVProbeData) { .buf = pb->buf_ptr,
  766. .buf_size = pb->buf_end - pb->buf_ptr };
  767. if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
  768. goto error;
  769. if (!(ast->sub_ctx = avformat_alloc_context()))
  770. goto error;
  771. ast->sub_ctx->pb = pb;
  772. if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
  773. ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
  774. *st->codec = *ast->sub_ctx->streams[0]->codec;
  775. ast->sub_ctx->streams[0]->codec->extradata = NULL;
  776. time_base = ast->sub_ctx->streams[0]->time_base;
  777. avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
  778. }
  779. ast->sub_buffer = pkt->data;
  780. memset(pkt, 0, sizeof(*pkt));
  781. return 1;
  782. error:
  783. av_freep(&pb);
  784. }
  785. return 0;
  786. }
  787. static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
  788. AVPacket *pkt)
  789. {
  790. AVIStream *ast, *next_ast = next_st->priv_data;
  791. int64_t ts, next_ts, ts_min = INT64_MAX;
  792. AVStream *st, *sub_st = NULL;
  793. int i;
  794. next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
  795. AV_TIME_BASE_Q);
  796. for (i = 0; i < s->nb_streams; i++) {
  797. st = s->streams[i];
  798. ast = st->priv_data;
  799. if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
  800. ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
  801. if (ts <= next_ts && ts < ts_min) {
  802. ts_min = ts;
  803. sub_st = st;
  804. }
  805. }
  806. }
  807. if (sub_st) {
  808. ast = sub_st->priv_data;
  809. *pkt = ast->sub_pkt;
  810. pkt->stream_index = sub_st->index;
  811. if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
  812. ast->sub_pkt.data = NULL;
  813. }
  814. return sub_st;
  815. }
  816. static int get_stream_idx(int *d)
  817. {
  818. if (d[0] >= '0' && d[0] <= '9' &&
  819. d[1] >= '0' && d[1] <= '9') {
  820. return (d[0] - '0') * 10 + (d[1] - '0');
  821. } else {
  822. return 100; // invalid stream ID
  823. }
  824. }
  825. static int avi_sync(AVFormatContext *s, int exit_early)
  826. {
  827. AVIContext *avi = s->priv_data;
  828. AVIOContext *pb = s->pb;
  829. int n;
  830. unsigned int d[8];
  831. unsigned int size;
  832. int64_t i, sync;
  833. start_sync:
  834. memset(d, -1, sizeof(d));
  835. for (i = sync = avio_tell(pb); !pb->eof_reached; i++) {
  836. int j;
  837. for (j = 0; j < 7; j++)
  838. d[j] = d[j + 1];
  839. d[7] = avio_r8(pb);
  840. size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24);
  841. n = get_stream_idx(d + 2);
  842. av_dlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
  843. d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
  844. if (i + (uint64_t)size > avi->fsize || d[0] > 127)
  845. continue;
  846. // parse ix##
  847. if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) ||
  848. // parse JUNK
  849. (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') ||
  850. (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')) {
  851. avio_skip(pb, size);
  852. goto start_sync;
  853. }
  854. // parse stray LIST
  855. if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') {
  856. avio_skip(pb, 4);
  857. goto start_sync;
  858. }
  859. n = avi->dv_demux ? 0 : get_stream_idx(d);
  860. if (!((i - avi->last_pkt_pos) & 1) &&
  861. get_stream_idx(d + 1) < s->nb_streams)
  862. continue;
  863. // detect ##ix chunk and skip
  864. if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) {
  865. avio_skip(pb, size);
  866. goto start_sync;
  867. }
  868. // parse ##dc/##wb
  869. if (n < s->nb_streams) {
  870. AVStream *st;
  871. AVIStream *ast;
  872. st = s->streams[n];
  873. ast = st->priv_data;
  874. if (s->nb_streams >= 2) {
  875. AVStream *st1 = s->streams[1];
  876. AVIStream *ast1 = st1->priv_data;
  877. // workaround for broken small-file-bug402.avi
  878. if (d[2] == 'w' && d[3] == 'b' && n == 0 &&
  879. st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
  880. st1->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  881. ast->prefix == 'd' * 256 + 'c' &&
  882. (d[2] * 256 + d[3] == ast1->prefix ||
  883. !ast1->prefix_count)) {
  884. n = 1;
  885. st = st1;
  886. ast = ast1;
  887. av_log(s, AV_LOG_WARNING,
  888. "Invalid stream + prefix combination, assuming audio.\n");
  889. }
  890. }
  891. if (!avi->dv_demux &&
  892. ((st->discard >= AVDISCARD_DEFAULT && size == 0) /* ||
  893. // FIXME: needs a little reordering
  894. (st->discard >= AVDISCARD_NONKEY &&
  895. !(pkt->flags & AV_PKT_FLAG_KEY)) */
  896. || st->discard >= AVDISCARD_ALL)) {
  897. if (!exit_early) {
  898. ast->frame_offset += get_duration(ast, size);
  899. }
  900. avio_skip(pb, size);
  901. goto start_sync;
  902. }
  903. if (d[2] == 'p' && d[3] == 'c' && size <= 4 * 256 + 4) {
  904. int k = avio_r8(pb);
  905. int last = (k + avio_r8(pb) - 1) & 0xFF;
  906. avio_rl16(pb); // flags
  907. // b + (g << 8) + (r << 16);
  908. for (; k <= last; k++)
  909. ast->pal[k] = avio_rb32(pb) >> 8;
  910. ast->has_pal = 1;
  911. goto start_sync;
  912. } else if (((ast->prefix_count < 5 || sync + 9 > i) &&
  913. d[2] < 128 && d[3] < 128) ||
  914. d[2] * 256 + d[3] == ast->prefix /* ||
  915. (d[2] == 'd' && d[3] == 'c') ||
  916. (d[2] == 'w' && d[3] == 'b') */) {
  917. if (exit_early)
  918. return 0;
  919. if (d[2] * 256 + d[3] == ast->prefix)
  920. ast->prefix_count++;
  921. else {
  922. ast->prefix = d[2] * 256 + d[3];
  923. ast->prefix_count = 0;
  924. }
  925. avi->stream_index = n;
  926. ast->packet_size = size + 8;
  927. ast->remaining = size;
  928. if (size || !ast->sample_size) {
  929. uint64_t pos = avio_tell(pb) - 8;
  930. if (!st->index_entries || !st->nb_index_entries ||
  931. st->index_entries[st->nb_index_entries - 1].pos < pos) {
  932. av_add_index_entry(st, pos, ast->frame_offset, size,
  933. 0, AVINDEX_KEYFRAME);
  934. }
  935. }
  936. return 0;
  937. }
  938. }
  939. }
  940. return AVERROR_EOF;
  941. }
  942. static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
  943. {
  944. AVIContext *avi = s->priv_data;
  945. AVIOContext *pb = s->pb;
  946. int err;
  947. #if FF_API_DESTRUCT_PACKET
  948. void *dstr;
  949. #endif
  950. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  951. int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
  952. if (size >= 0)
  953. return size;
  954. else
  955. goto resync;
  956. }
  957. if (avi->non_interleaved) {
  958. int best_stream_index = 0;
  959. AVStream *best_st = NULL;
  960. AVIStream *best_ast;
  961. int64_t best_ts = INT64_MAX;
  962. int i;
  963. for (i = 0; i < s->nb_streams; i++) {
  964. AVStream *st = s->streams[i];
  965. AVIStream *ast = st->priv_data;
  966. int64_t ts = ast->frame_offset;
  967. int64_t last_ts;
  968. if (!st->nb_index_entries)
  969. continue;
  970. last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
  971. if (!ast->remaining && ts > last_ts)
  972. continue;
  973. ts = av_rescale_q(ts, st->time_base,
  974. (AVRational) { FFMAX(1, ast->sample_size),
  975. AV_TIME_BASE });
  976. av_dlog(s, "%"PRId64" %d/%d %"PRId64"\n", ts,
  977. st->time_base.num, st->time_base.den, ast->frame_offset);
  978. if (ts < best_ts) {
  979. best_ts = ts;
  980. best_st = st;
  981. best_stream_index = i;
  982. }
  983. }
  984. if (!best_st)
  985. return AVERROR_EOF;
  986. best_ast = best_st->priv_data;
  987. best_ts = av_rescale_q(best_ts,
  988. (AVRational) { FFMAX(1, best_ast->sample_size),
  989. AV_TIME_BASE },
  990. best_st->time_base);
  991. if (best_ast->remaining) {
  992. i = av_index_search_timestamp(best_st,
  993. best_ts,
  994. AVSEEK_FLAG_ANY |
  995. AVSEEK_FLAG_BACKWARD);
  996. } else {
  997. i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
  998. if (i >= 0)
  999. best_ast->frame_offset = best_st->index_entries[i].timestamp;
  1000. }
  1001. if (i >= 0) {
  1002. int64_t pos = best_st->index_entries[i].pos;
  1003. pos += best_ast->packet_size - best_ast->remaining;
  1004. avio_seek(s->pb, pos + 8, SEEK_SET);
  1005. assert(best_ast->remaining <= best_ast->packet_size);
  1006. avi->stream_index = best_stream_index;
  1007. if (!best_ast->remaining)
  1008. best_ast->packet_size =
  1009. best_ast->remaining = best_st->index_entries[i].size;
  1010. }
  1011. }
  1012. resync:
  1013. if (avi->stream_index >= 0) {
  1014. AVStream *st = s->streams[avi->stream_index];
  1015. AVIStream *ast = st->priv_data;
  1016. int size, err;
  1017. if (get_subtitle_pkt(s, st, pkt))
  1018. return 0;
  1019. // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  1020. if (ast->sample_size <= 1)
  1021. size = INT_MAX;
  1022. else if (ast->sample_size < 32)
  1023. // arbitrary multiplier to avoid tiny packets for raw PCM data
  1024. size = 1024 * ast->sample_size;
  1025. else
  1026. size = ast->sample_size;
  1027. if (size > ast->remaining)
  1028. size = ast->remaining;
  1029. avi->last_pkt_pos = avio_tell(pb);
  1030. err = av_get_packet(pb, pkt, size);
  1031. if (err < 0)
  1032. return err;
  1033. if (ast->has_pal && pkt->data && pkt->size < (unsigned)INT_MAX / 2) {
  1034. uint8_t *pal;
  1035. pal = av_packet_new_side_data(pkt,
  1036. AV_PKT_DATA_PALETTE,
  1037. AVPALETTE_SIZE);
  1038. if (!pal) {
  1039. av_log(s, AV_LOG_ERROR,
  1040. "Failed to allocate data for palette\n");
  1041. } else {
  1042. memcpy(pal, ast->pal, AVPALETTE_SIZE);
  1043. ast->has_pal = 0;
  1044. }
  1045. }
  1046. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1047. AVBufferRef *avbuf = pkt->buf;
  1048. #if FF_API_DESTRUCT_PACKET
  1049. FF_DISABLE_DEPRECATION_WARNINGS
  1050. dstr = pkt->destruct;
  1051. FF_ENABLE_DEPRECATION_WARNINGS
  1052. #endif
  1053. size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
  1054. pkt->data, pkt->size);
  1055. #if FF_API_DESTRUCT_PACKET
  1056. FF_DISABLE_DEPRECATION_WARNINGS
  1057. pkt->destruct = dstr;
  1058. FF_ENABLE_DEPRECATION_WARNINGS
  1059. #endif
  1060. pkt->buf = avbuf;
  1061. pkt->flags |= AV_PKT_FLAG_KEY;
  1062. if (size < 0)
  1063. av_free_packet(pkt);
  1064. } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
  1065. !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
  1066. ast->frame_offset++;
  1067. avi->stream_index = -1;
  1068. ast->remaining = 0;
  1069. goto resync;
  1070. } else {
  1071. /* XXX: How to handle B-frames in AVI? */
  1072. pkt->dts = ast->frame_offset;
  1073. // pkt->dts += ast->start;
  1074. if (ast->sample_size)
  1075. pkt->dts /= ast->sample_size;
  1076. av_dlog(s,
  1077. "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d "
  1078. "base:%d st:%d size:%d\n",
  1079. pkt->dts,
  1080. ast->frame_offset,
  1081. ast->scale,
  1082. ast->rate,
  1083. ast->sample_size,
  1084. AV_TIME_BASE,
  1085. avi->stream_index,
  1086. size);
  1087. pkt->stream_index = avi->stream_index;
  1088. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1089. AVIndexEntry *e;
  1090. int index;
  1091. assert(st->index_entries);
  1092. index = av_index_search_timestamp(st, ast->frame_offset, 0);
  1093. e = &st->index_entries[index];
  1094. if (index >= 0 && e->timestamp == ast->frame_offset)
  1095. if (e->flags & AVINDEX_KEYFRAME)
  1096. pkt->flags |= AV_PKT_FLAG_KEY;
  1097. } else {
  1098. pkt->flags |= AV_PKT_FLAG_KEY;
  1099. }
  1100. ast->frame_offset += get_duration(ast, pkt->size);
  1101. }
  1102. ast->remaining -= err;
  1103. if (!ast->remaining) {
  1104. avi->stream_index = -1;
  1105. ast->packet_size = 0;
  1106. }
  1107. return 0;
  1108. }
  1109. if ((err = avi_sync(s, 0)) < 0)
  1110. return err;
  1111. goto resync;
  1112. }
  1113. /* XXX: We make the implicit supposition that the positions are sorted
  1114. * for each stream. */
  1115. static int avi_read_idx1(AVFormatContext *s, int size)
  1116. {
  1117. AVIContext *avi = s->priv_data;
  1118. AVIOContext *pb = s->pb;
  1119. int nb_index_entries, i;
  1120. AVStream *st;
  1121. AVIStream *ast;
  1122. unsigned int index, tag, flags, pos, len, first_packet = 1;
  1123. unsigned last_pos = -1;
  1124. int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
  1125. nb_index_entries = size / 16;
  1126. if (nb_index_entries <= 0)
  1127. return AVERROR_INVALIDDATA;
  1128. idx1_pos = avio_tell(pb);
  1129. avio_seek(pb, avi->movi_list + 4, SEEK_SET);
  1130. if (avi_sync(s, 1) == 0)
  1131. first_packet_pos = avio_tell(pb) - 8;
  1132. avi->stream_index = -1;
  1133. avio_seek(pb, idx1_pos, SEEK_SET);
  1134. /* Read the entries and sort them in each stream component. */
  1135. for (i = 0; i < nb_index_entries; i++) {
  1136. tag = avio_rl32(pb);
  1137. flags = avio_rl32(pb);
  1138. pos = avio_rl32(pb);
  1139. len = avio_rl32(pb);
  1140. av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
  1141. i, tag, flags, pos, len);
  1142. index = ((tag & 0xff) - '0') * 10;
  1143. index += (tag >> 8 & 0xff) - '0';
  1144. if (index >= s->nb_streams)
  1145. continue;
  1146. st = s->streams[index];
  1147. ast = st->priv_data;
  1148. if (first_packet && first_packet_pos && len) {
  1149. data_offset = first_packet_pos - pos;
  1150. first_packet = 0;
  1151. }
  1152. pos += data_offset;
  1153. av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  1154. if (pb->eof_reached)
  1155. return AVERROR_INVALIDDATA;
  1156. if (last_pos == pos)
  1157. avi->non_interleaved = 1;
  1158. else if (len || !ast->sample_size)
  1159. av_add_index_entry(st, pos, ast->cum_len, len, 0,
  1160. (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  1161. ast->cum_len += get_duration(ast, len);
  1162. last_pos = pos;
  1163. }
  1164. return 0;
  1165. }
  1166. /* Scan the index and consider any file with streams more than
  1167. * 2 seconds or 64MB apart non-interleaved. */
  1168. static int check_stream_max_drift(AVFormatContext *s)
  1169. {
  1170. int64_t min_pos, pos;
  1171. int i;
  1172. int *idx = av_mallocz_array(s->nb_streams, sizeof(*idx));
  1173. if (!idx)
  1174. return AVERROR(ENOMEM);
  1175. for (min_pos = pos = 0; min_pos != INT64_MAX; pos = min_pos + 1LU) {
  1176. int64_t max_dts = INT64_MIN / 2;
  1177. int64_t min_dts = INT64_MAX / 2;
  1178. int64_t max_buffer = 0;
  1179. min_pos = INT64_MAX;
  1180. for (i = 0; i < s->nb_streams; i++) {
  1181. AVStream *st = s->streams[i];
  1182. AVIStream *ast = st->priv_data;
  1183. int n = st->nb_index_entries;
  1184. while (idx[i] < n && st->index_entries[idx[i]].pos < pos)
  1185. idx[i]++;
  1186. if (idx[i] < n) {
  1187. int64_t dts;
  1188. dts = av_rescale_q(st->index_entries[idx[i]].timestamp /
  1189. FFMAX(ast->sample_size, 1),
  1190. st->time_base, AV_TIME_BASE_Q);
  1191. min_dts = FFMIN(min_dts, dts);
  1192. min_pos = FFMIN(min_pos, st->index_entries[idx[i]].pos);
  1193. }
  1194. }
  1195. for (i = 0; i < s->nb_streams; i++) {
  1196. AVStream *st = s->streams[i];
  1197. AVIStream *ast = st->priv_data;
  1198. if (idx[i] && min_dts != INT64_MAX / 2) {
  1199. int64_t dts;
  1200. dts = av_rescale_q(st->index_entries[idx[i] - 1].timestamp /
  1201. FFMAX(ast->sample_size, 1),
  1202. st->time_base, AV_TIME_BASE_Q);
  1203. max_dts = FFMAX(max_dts, dts);
  1204. max_buffer = FFMAX(max_buffer,
  1205. av_rescale(dts - min_dts,
  1206. st->codec->bit_rate,
  1207. AV_TIME_BASE));
  1208. }
  1209. }
  1210. if (max_dts - min_dts > 2 * AV_TIME_BASE ||
  1211. max_buffer > 1024 * 1024 * 8 * 8) {
  1212. av_free(idx);
  1213. return 1;
  1214. }
  1215. }
  1216. av_free(idx);
  1217. return 0;
  1218. }
  1219. static int guess_ni_flag(AVFormatContext *s)
  1220. {
  1221. int i;
  1222. int64_t last_start = 0;
  1223. int64_t first_end = INT64_MAX;
  1224. int64_t oldpos = avio_tell(s->pb);
  1225. for (i = 0; i < s->nb_streams; i++) {
  1226. AVStream *st = s->streams[i];
  1227. int n = st->nb_index_entries;
  1228. unsigned int size;
  1229. if (n <= 0)
  1230. continue;
  1231. if (n >= 2) {
  1232. int64_t pos = st->index_entries[0].pos;
  1233. avio_seek(s->pb, pos + 4, SEEK_SET);
  1234. size = avio_rl32(s->pb);
  1235. if (pos + size > st->index_entries[1].pos)
  1236. last_start = INT64_MAX;
  1237. }
  1238. if (st->index_entries[0].pos > last_start)
  1239. last_start = st->index_entries[0].pos;
  1240. if (st->index_entries[n - 1].pos < first_end)
  1241. first_end = st->index_entries[n - 1].pos;
  1242. }
  1243. avio_seek(s->pb, oldpos, SEEK_SET);
  1244. if (last_start > first_end)
  1245. return 1;
  1246. return check_stream_max_drift(s);
  1247. }
  1248. static int avi_load_index(AVFormatContext *s)
  1249. {
  1250. AVIContext *avi = s->priv_data;
  1251. AVIOContext *pb = s->pb;
  1252. uint32_t tag, size;
  1253. int64_t pos = avio_tell(pb);
  1254. int ret = -1;
  1255. if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
  1256. goto the_end; // maybe truncated file
  1257. av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
  1258. for (;;) {
  1259. if (pb->eof_reached)
  1260. break;
  1261. tag = avio_rl32(pb);
  1262. size = avio_rl32(pb);
  1263. av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
  1264. tag & 0xff,
  1265. (tag >> 8) & 0xff,
  1266. (tag >> 16) & 0xff,
  1267. (tag >> 24) & 0xff,
  1268. size);
  1269. if (tag == MKTAG('i', 'd', 'x', '1') &&
  1270. avi_read_idx1(s, size) >= 0) {
  1271. ret = 0;
  1272. break;
  1273. }
  1274. size += (size & 1);
  1275. if (avio_skip(pb, size) < 0)
  1276. break; // something is wrong here
  1277. }
  1278. the_end:
  1279. avio_seek(pb, pos, SEEK_SET);
  1280. return ret;
  1281. }
  1282. static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
  1283. {
  1284. AVIStream *ast2 = st2->priv_data;
  1285. int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
  1286. av_free_packet(&ast2->sub_pkt);
  1287. if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
  1288. avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
  1289. ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
  1290. }
  1291. static int avi_read_seek(AVFormatContext *s, int stream_index,
  1292. int64_t timestamp, int flags)
  1293. {
  1294. AVIContext *avi = s->priv_data;
  1295. AVStream *st;
  1296. int i, index;
  1297. int64_t pos;
  1298. AVIStream *ast;
  1299. /* Does not matter which stream is requested dv in avi has the
  1300. * stream information in the first video stream.
  1301. */
  1302. if (avi->dv_demux)
  1303. stream_index = 0;
  1304. if (!avi->index_loaded) {
  1305. /* we only load the index on demand */
  1306. avi_load_index(s);
  1307. avi->index_loaded = 1;
  1308. }
  1309. st = s->streams[stream_index];
  1310. ast = st->priv_data;
  1311. index = av_index_search_timestamp(st,
  1312. timestamp * FFMAX(ast->sample_size, 1),
  1313. flags);
  1314. if (index < 0)
  1315. return AVERROR_INVALIDDATA;
  1316. /* find the position */
  1317. pos = st->index_entries[index].pos;
  1318. timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
  1319. av_dlog(s, "XX %"PRId64" %d %"PRId64"\n",
  1320. timestamp, index, st->index_entries[index].timestamp);
  1321. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1322. /* One and only one real stream for DV in AVI, and it has video */
  1323. /* offsets. Calling with other stream indexes should have failed */
  1324. /* the av_index_search_timestamp call above. */
  1325. /* Feed the DV video stream version of the timestamp to the */
  1326. /* DV demux so it can synthesize correct timestamps. */
  1327. ff_dv_offset_reset(avi->dv_demux, timestamp);
  1328. avio_seek(s->pb, pos, SEEK_SET);
  1329. avi->stream_index = -1;
  1330. return 0;
  1331. }
  1332. for (i = 0; i < s->nb_streams; i++) {
  1333. AVStream *st2 = s->streams[i];
  1334. AVIStream *ast2 = st2->priv_data;
  1335. ast2->packet_size =
  1336. ast2->remaining = 0;
  1337. if (ast2->sub_ctx) {
  1338. seek_subtitle(st, st2, timestamp);
  1339. continue;
  1340. }
  1341. if (st2->nb_index_entries <= 0)
  1342. continue;
  1343. // assert(st2->codec->block_align);
  1344. assert((int64_t)st2->time_base.num * ast2->rate ==
  1345. (int64_t)st2->time_base.den * ast2->scale);
  1346. index = av_index_search_timestamp(st2,
  1347. av_rescale_q(timestamp,
  1348. st->time_base,
  1349. st2->time_base) *
  1350. FFMAX(ast2->sample_size, 1),
  1351. flags | AVSEEK_FLAG_BACKWARD);
  1352. if (index < 0)
  1353. index = 0;
  1354. if (!avi->non_interleaved) {
  1355. while (index > 0 && st2->index_entries[index].pos > pos)
  1356. index--;
  1357. while (index + 1 < st2->nb_index_entries &&
  1358. st2->index_entries[index].pos < pos)
  1359. index++;
  1360. }
  1361. av_dlog(s, "%"PRId64" %d %"PRId64"\n",
  1362. timestamp, index, st2->index_entries[index].timestamp);
  1363. /* extract the current frame number */
  1364. ast2->frame_offset = st2->index_entries[index].timestamp;
  1365. }
  1366. /* do the seek */
  1367. avio_seek(s->pb, pos, SEEK_SET);
  1368. avi->stream_index = -1;
  1369. return 0;
  1370. }
  1371. static int avi_read_close(AVFormatContext *s)
  1372. {
  1373. int i;
  1374. AVIContext *avi = s->priv_data;
  1375. for (i = 0; i < s->nb_streams; i++) {
  1376. AVStream *st = s->streams[i];
  1377. AVIStream *ast = st->priv_data;
  1378. if (ast) {
  1379. if (ast->sub_ctx) {
  1380. av_freep(&ast->sub_ctx->pb);
  1381. avformat_close_input(&ast->sub_ctx);
  1382. }
  1383. av_free(ast->sub_buffer);
  1384. av_free_packet(&ast->sub_pkt);
  1385. }
  1386. }
  1387. av_free(avi->dv_demux);
  1388. return 0;
  1389. }
  1390. static int avi_probe(AVProbeData *p)
  1391. {
  1392. int i;
  1393. /* check file header */
  1394. for (i = 0; avi_headers[i][0]; i++)
  1395. if (!memcmp(p->buf, avi_headers[i], 4) &&
  1396. !memcmp(p->buf + 8, avi_headers[i] + 4, 4))
  1397. return AVPROBE_SCORE_MAX;
  1398. return 0;
  1399. }
  1400. AVInputFormat ff_avi_demuxer = {
  1401. .name = "avi",
  1402. .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
  1403. .priv_data_size = sizeof(AVIContext),
  1404. .extensions = "avi",
  1405. .read_probe = avi_probe,
  1406. .read_header = avi_read_header,
  1407. .read_packet = avi_read_packet,
  1408. .read_close = avi_read_close,
  1409. .read_seek = avi_read_seek,
  1410. };