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.

1925 lines
66KB

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