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.

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