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.

1943 lines
67KB

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