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.

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