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.

1524 lines
51KB

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