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.

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