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.

1618 lines
54KB

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