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.

1531 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. } else
  426. goto fail;
  427. s->streams[0]->priv_data = ast;
  428. avio_skip(pb, 3 * 4);
  429. ast->scale = avio_rl32(pb);
  430. ast->rate = avio_rl32(pb);
  431. avio_skip(pb, 4); /* start time */
  432. dv_dur = avio_rl32(pb);
  433. if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
  434. dv_dur *= AV_TIME_BASE;
  435. s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
  436. }
  437. /* else, leave duration alone; timing estimation in utils.c
  438. * will make a guess based on bitrate. */
  439. stream_index = s->nb_streams - 1;
  440. avio_skip(pb, size - 9 * 4);
  441. break;
  442. }
  443. assert(stream_index < s->nb_streams);
  444. st->codec->stream_codec_tag = handler;
  445. avio_rl32(pb); /* flags */
  446. avio_rl16(pb); /* priority */
  447. avio_rl16(pb); /* language */
  448. avio_rl32(pb); /* initial frame */
  449. ast->scale = avio_rl32(pb);
  450. ast->rate = avio_rl32(pb);
  451. if (!(ast->scale && ast->rate)) {
  452. av_log(s, AV_LOG_WARNING,
  453. "scale/rate is %u/%u which is invalid. "
  454. "(This file has been generated by broken software.)\n",
  455. ast->scale,
  456. ast->rate);
  457. if (frame_period) {
  458. ast->rate = 1000000;
  459. ast->scale = frame_period;
  460. } else {
  461. ast->rate = 25;
  462. ast->scale = 1;
  463. }
  464. }
  465. avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
  466. ast->cum_len = avio_rl32(pb); /* start */
  467. st->nb_frames = avio_rl32(pb);
  468. st->start_time = 0;
  469. avio_rl32(pb); /* buffer size */
  470. avio_rl32(pb); /* quality */
  471. ast->sample_size = avio_rl32(pb); /* sample ssize */
  472. ast->cum_len *= FFMAX(1, ast->sample_size);
  473. av_dlog(s, "%"PRIu32" %"PRIu32" %d\n",
  474. ast->rate, ast->scale, ast->sample_size);
  475. switch (tag1) {
  476. case MKTAG('v', 'i', 'd', 's'):
  477. codec_type = AVMEDIA_TYPE_VIDEO;
  478. ast->sample_size = 0;
  479. break;
  480. case MKTAG('a', 'u', 'd', 's'):
  481. codec_type = AVMEDIA_TYPE_AUDIO;
  482. break;
  483. case MKTAG('t', 'x', 't', 's'):
  484. codec_type = AVMEDIA_TYPE_SUBTITLE;
  485. break;
  486. case MKTAG('d', 'a', 't', 's'):
  487. codec_type = AVMEDIA_TYPE_DATA;
  488. break;
  489. default:
  490. av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
  491. goto fail;
  492. }
  493. if (ast->sample_size == 0)
  494. st->duration = st->nb_frames;
  495. ast->frame_offset = ast->cum_len;
  496. avio_skip(pb, size - 12 * 4);
  497. break;
  498. case MKTAG('s', 't', 'r', 'f'):
  499. /* stream header */
  500. if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
  501. avio_skip(pb, size);
  502. } else {
  503. uint64_t cur_pos = avio_tell(pb);
  504. if (cur_pos < list_end)
  505. size = FFMIN(size, list_end - cur_pos);
  506. st = s->streams[stream_index];
  507. switch (codec_type) {
  508. case AVMEDIA_TYPE_VIDEO:
  509. if (amv_file_format) {
  510. st->codec->width = avih_width;
  511. st->codec->height = avih_height;
  512. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  513. st->codec->codec_id = AV_CODEC_ID_AMV;
  514. avio_skip(pb, size);
  515. break;
  516. }
  517. tag1 = ff_get_bmp_header(pb, st);
  518. if (tag1 == MKTAG('D', 'X', 'S', 'B') ||
  519. tag1 == MKTAG('D', 'X', 'S', 'A')) {
  520. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  521. st->codec->codec_tag = tag1;
  522. st->codec->codec_id = AV_CODEC_ID_XSUB;
  523. break;
  524. }
  525. if (size > 10 * 4 && size < (1 << 30)) {
  526. st->codec->extradata_size = size - 10 * 4;
  527. st->codec->extradata = av_malloc(st->codec->extradata_size +
  528. FF_INPUT_BUFFER_PADDING_SIZE);
  529. if (!st->codec->extradata) {
  530. st->codec->extradata_size = 0;
  531. return AVERROR(ENOMEM);
  532. }
  533. avio_read(pb,
  534. st->codec->extradata,
  535. st->codec->extradata_size);
  536. }
  537. // FIXME: check if the encoder really did this correctly
  538. if (st->codec->extradata_size & 1)
  539. avio_r8(pb);
  540. /* Extract palette from extradata if bpp <= 8.
  541. * This code assumes that extradata contains only palette.
  542. * This is true for all paletted codecs implemented in
  543. * Libav. */
  544. if (st->codec->extradata_size &&
  545. (st->codec->bits_per_coded_sample <= 8)) {
  546. int pal_size = (1 << st->codec->bits_per_coded_sample) << 2;
  547. const uint8_t *pal_src;
  548. pal_size = FFMIN(pal_size, st->codec->extradata_size);
  549. pal_src = st->codec->extradata +
  550. st->codec->extradata_size - pal_size;
  551. #if HAVE_BIGENDIAN
  552. for (i = 0; i < pal_size / 4; i++)
  553. ast->pal[i] = av_bswap32(((uint32_t *)pal_src)[i]);
  554. #else
  555. memcpy(ast->pal, pal_src, pal_size);
  556. #endif
  557. ast->has_pal = 1;
  558. }
  559. print_tag("video", tag1, 0);
  560. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  561. st->codec->codec_tag = tag1;
  562. st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags,
  563. tag1);
  564. /* This is needed to get the pict type which is necessary
  565. * for generating correct pts. */
  566. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  567. // Support "Resolution 1:1" for Avid AVI Codec
  568. if (tag1 == MKTAG('A', 'V', 'R', 'n') &&
  569. st->codec->extradata_size >= 31 &&
  570. !memcmp(&st->codec->extradata[28], "1:1", 3))
  571. st->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
  572. if (st->codec->codec_tag == 0 && st->codec->height > 0 &&
  573. st->codec->extradata_size < 1U << 30) {
  574. st->codec->extradata_size += 9;
  575. if ((ret = av_reallocp(&st->codec->extradata,
  576. st->codec->extradata_size +
  577. FF_INPUT_BUFFER_PADDING_SIZE)) < 0) {
  578. st->codec->extradata_size = 0;
  579. return ret;
  580. } else
  581. memcpy(st->codec->extradata + st->codec->extradata_size - 9,
  582. "BottomUp", 9);
  583. }
  584. st->codec->height = FFABS(st->codec->height);
  585. // avio_skip(pb, size - 5 * 4);
  586. break;
  587. case AVMEDIA_TYPE_AUDIO:
  588. ret = ff_get_wav_header(pb, st->codec, size);
  589. if (ret < 0)
  590. return ret;
  591. ast->dshow_block_align = st->codec->block_align;
  592. if (ast->sample_size && st->codec->block_align &&
  593. ast->sample_size != st->codec->block_align) {
  594. av_log(s,
  595. AV_LOG_WARNING,
  596. "sample size (%d) != block align (%d)\n",
  597. ast->sample_size,
  598. st->codec->block_align);
  599. ast->sample_size = st->codec->block_align;
  600. }
  601. /* 2-aligned
  602. * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
  603. if (size & 1)
  604. avio_skip(pb, 1);
  605. /* Force parsing as several audio frames can be in
  606. * one packet and timestamps refer to packet start. */
  607. st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
  608. /* ADTS header is in extradata, AAC without header must be
  609. * stored as exact frames. Parser not needed and it will
  610. * fail. */
  611. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  612. st->codec->extradata_size)
  613. st->need_parsing = AVSTREAM_PARSE_NONE;
  614. /* AVI files with Xan DPCM audio (wrongly) declare PCM
  615. * audio in the header but have Axan as stream_code_tag. */
  616. if (st->codec->stream_codec_tag == AV_RL32("Axan")) {
  617. st->codec->codec_id = AV_CODEC_ID_XAN_DPCM;
  618. st->codec->codec_tag = 0;
  619. }
  620. if (amv_file_format) {
  621. st->codec->codec_id = AV_CODEC_ID_ADPCM_IMA_AMV;
  622. ast->dshow_block_align = 0;
  623. }
  624. break;
  625. case AVMEDIA_TYPE_SUBTITLE:
  626. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  627. st->codec->codec_id = AV_CODEC_ID_PROBE;
  628. break;
  629. default:
  630. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  631. st->codec->codec_id = AV_CODEC_ID_NONE;
  632. st->codec->codec_tag = 0;
  633. avio_skip(pb, size);
  634. break;
  635. }
  636. }
  637. break;
  638. case MKTAG('i', 'n', 'd', 'x'):
  639. i = avio_tell(pb);
  640. if (pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) &&
  641. read_braindead_odml_indx(s, 0) < 0 &&
  642. (s->error_recognition & AV_EF_EXPLODE))
  643. goto fail;
  644. avio_seek(pb, i + size, SEEK_SET);
  645. break;
  646. case MKTAG('v', 'p', 'r', 'p'):
  647. if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) {
  648. AVRational active, active_aspect;
  649. st = s->streams[stream_index];
  650. avio_rl32(pb);
  651. avio_rl32(pb);
  652. avio_rl32(pb);
  653. avio_rl32(pb);
  654. avio_rl32(pb);
  655. active_aspect.den = avio_rl16(pb);
  656. active_aspect.num = avio_rl16(pb);
  657. active.num = avio_rl32(pb);
  658. active.den = avio_rl32(pb);
  659. avio_rl32(pb); // nbFieldsPerFrame
  660. if (active_aspect.num && active_aspect.den &&
  661. active.num && active.den) {
  662. st->sample_aspect_ratio = av_div_q(active_aspect, active);
  663. av_dlog(s, "vprp %d/%d %d/%d\n",
  664. active_aspect.num, active_aspect.den,
  665. active.num, active.den);
  666. }
  667. size -= 9 * 4;
  668. }
  669. avio_skip(pb, size);
  670. break;
  671. case MKTAG('s', 't', 'r', 'n'):
  672. if (s->nb_streams) {
  673. ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size);
  674. if (ret < 0)
  675. return ret;
  676. break;
  677. }
  678. default:
  679. if (size > 1000000) {
  680. av_log(s, AV_LOG_ERROR,
  681. "Something went wrong during header parsing, "
  682. "I will ignore it and try to continue anyway.\n");
  683. if (s->error_recognition & AV_EF_EXPLODE)
  684. goto fail;
  685. avi->movi_list = avio_tell(pb) - 4;
  686. avi->movi_end = avio_size(pb);
  687. goto end_of_header;
  688. }
  689. /* skip tag */
  690. size += (size & 1);
  691. avio_skip(pb, size);
  692. break;
  693. }
  694. }
  695. end_of_header:
  696. /* check stream number */
  697. if (stream_index != s->nb_streams - 1) {
  698. fail:
  699. return AVERROR_INVALIDDATA;
  700. }
  701. if (!avi->index_loaded && pb->seekable)
  702. avi_load_index(s);
  703. avi->index_loaded = 1;
  704. avi->non_interleaved |= guess_ni_flag(s);
  705. for (i = 0; i < s->nb_streams; i++) {
  706. AVStream *st = s->streams[i];
  707. if (st->nb_index_entries)
  708. break;
  709. }
  710. if (i == s->nb_streams && avi->non_interleaved) {
  711. av_log(s, AV_LOG_WARNING,
  712. "Non-interleaved AVI without index, switching to interleaved\n");
  713. avi->non_interleaved = 0;
  714. }
  715. if (avi->non_interleaved) {
  716. av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
  717. clean_index(s);
  718. }
  719. ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
  720. ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
  721. return 0;
  722. }
  723. static int read_gab2_sub(AVStream *st, AVPacket *pkt)
  724. {
  725. if (pkt->size >= 7 &&
  726. !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
  727. uint8_t desc[256];
  728. int score = AVPROBE_SCORE_EXTENSION, ret;
  729. AVIStream *ast = st->priv_data;
  730. AVInputFormat *sub_demuxer;
  731. AVRational time_base;
  732. AVIOContext *pb = avio_alloc_context(pkt->data + 7,
  733. pkt->size - 7,
  734. 0, NULL, NULL, NULL, NULL);
  735. AVProbeData pd;
  736. unsigned int desc_len = avio_rl32(pb);
  737. if (desc_len > pb->buf_end - pb->buf_ptr)
  738. goto error;
  739. ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
  740. avio_skip(pb, desc_len - ret);
  741. if (*desc)
  742. av_dict_set(&st->metadata, "title", desc, 0);
  743. avio_rl16(pb); /* flags? */
  744. avio_rl32(pb); /* data size */
  745. pd = (AVProbeData) { .buf = pb->buf_ptr,
  746. .buf_size = pb->buf_end - pb->buf_ptr };
  747. if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
  748. goto error;
  749. if (!(ast->sub_ctx = avformat_alloc_context()))
  750. goto error;
  751. ast->sub_ctx->pb = pb;
  752. if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
  753. ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
  754. *st->codec = *ast->sub_ctx->streams[0]->codec;
  755. ast->sub_ctx->streams[0]->codec->extradata = NULL;
  756. time_base = ast->sub_ctx->streams[0]->time_base;
  757. avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
  758. }
  759. ast->sub_buffer = pkt->data;
  760. memset(pkt, 0, sizeof(*pkt));
  761. return 1;
  762. error:
  763. av_freep(&pb);
  764. }
  765. return 0;
  766. }
  767. static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
  768. AVPacket *pkt)
  769. {
  770. AVIStream *ast, *next_ast = next_st->priv_data;
  771. int64_t ts, next_ts, ts_min = INT64_MAX;
  772. AVStream *st, *sub_st = NULL;
  773. int i;
  774. next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
  775. AV_TIME_BASE_Q);
  776. for (i = 0; i < s->nb_streams; i++) {
  777. st = s->streams[i];
  778. ast = st->priv_data;
  779. if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
  780. ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
  781. if (ts <= next_ts && ts < ts_min) {
  782. ts_min = ts;
  783. sub_st = st;
  784. }
  785. }
  786. }
  787. if (sub_st) {
  788. ast = sub_st->priv_data;
  789. *pkt = ast->sub_pkt;
  790. pkt->stream_index = sub_st->index;
  791. if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
  792. ast->sub_pkt.data = NULL;
  793. }
  794. return sub_st;
  795. }
  796. static int get_stream_idx(int *d)
  797. {
  798. if (d[0] >= '0' && d[0] <= '9' &&
  799. d[1] >= '0' && d[1] <= '9') {
  800. return (d[0] - '0') * 10 + (d[1] - '0');
  801. } else {
  802. return 100; // invalid stream ID
  803. }
  804. }
  805. static int avi_sync(AVFormatContext *s, int exit_early)
  806. {
  807. AVIContext *avi = s->priv_data;
  808. AVIOContext *pb = s->pb;
  809. int n;
  810. unsigned int d[8];
  811. unsigned int size;
  812. int64_t i, sync;
  813. start_sync:
  814. memset(d, -1, sizeof(d));
  815. for (i = sync = avio_tell(pb); !pb->eof_reached; i++) {
  816. int j;
  817. for (j = 0; j < 7; j++)
  818. d[j] = d[j + 1];
  819. d[7] = avio_r8(pb);
  820. size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24);
  821. n = get_stream_idx(d + 2);
  822. av_dlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
  823. d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
  824. if (i + (uint64_t)size > avi->fsize || d[0] > 127)
  825. continue;
  826. // parse ix##
  827. if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) ||
  828. // parse JUNK
  829. (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') ||
  830. (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')) {
  831. avio_skip(pb, size);
  832. goto start_sync;
  833. }
  834. // parse stray LIST
  835. if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') {
  836. avio_skip(pb, 4);
  837. goto start_sync;
  838. }
  839. n = avi->dv_demux ? 0 : get_stream_idx(d);
  840. if (!((i - avi->last_pkt_pos) & 1) &&
  841. get_stream_idx(d + 1) < s->nb_streams)
  842. continue;
  843. // detect ##ix chunk and skip
  844. if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) {
  845. avio_skip(pb, size);
  846. goto start_sync;
  847. }
  848. // parse ##dc/##wb
  849. if (n < s->nb_streams) {
  850. AVStream *st;
  851. AVIStream *ast;
  852. st = s->streams[n];
  853. ast = st->priv_data;
  854. if (s->nb_streams >= 2) {
  855. AVStream *st1 = s->streams[1];
  856. AVIStream *ast1 = st1->priv_data;
  857. // workaround for broken small-file-bug402.avi
  858. if (d[2] == 'w' && d[3] == 'b' && n == 0 &&
  859. st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
  860. st1->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  861. ast->prefix == 'd' * 256 + 'c' &&
  862. (d[2] * 256 + d[3] == ast1->prefix ||
  863. !ast1->prefix_count)) {
  864. n = 1;
  865. st = st1;
  866. ast = ast1;
  867. av_log(s, AV_LOG_WARNING,
  868. "Invalid stream + prefix combination, assuming audio.\n");
  869. }
  870. }
  871. if (!avi->dv_demux &&
  872. ((st->discard >= AVDISCARD_DEFAULT && size == 0) /* ||
  873. // FIXME: needs a little reordering
  874. (st->discard >= AVDISCARD_NONKEY &&
  875. !(pkt->flags & AV_PKT_FLAG_KEY)) */
  876. || st->discard >= AVDISCARD_ALL)) {
  877. if (!exit_early) {
  878. ast->frame_offset += get_duration(ast, size);
  879. }
  880. avio_skip(pb, size);
  881. goto start_sync;
  882. }
  883. if (d[2] == 'p' && d[3] == 'c' && size <= 4 * 256 + 4) {
  884. int k = avio_r8(pb);
  885. int last = (k + avio_r8(pb) - 1) & 0xFF;
  886. avio_rl16(pb); // flags
  887. // b + (g << 8) + (r << 16);
  888. for (; k <= last; k++)
  889. ast->pal[k] = avio_rb32(pb) >> 8;
  890. ast->has_pal = 1;
  891. goto start_sync;
  892. } else if (((ast->prefix_count < 5 || sync + 9 > i) &&
  893. d[2] < 128 && d[3] < 128) ||
  894. d[2] * 256 + d[3] == ast->prefix /* ||
  895. (d[2] == 'd' && d[3] == 'c') ||
  896. (d[2] == 'w' && d[3] == 'b') */) {
  897. if (exit_early)
  898. return 0;
  899. if (d[2] * 256 + d[3] == ast->prefix)
  900. ast->prefix_count++;
  901. else {
  902. ast->prefix = d[2] * 256 + d[3];
  903. ast->prefix_count = 0;
  904. }
  905. avi->stream_index = n;
  906. ast->packet_size = size + 8;
  907. ast->remaining = size;
  908. if (size || !ast->sample_size) {
  909. uint64_t pos = avio_tell(pb) - 8;
  910. if (!st->index_entries || !st->nb_index_entries ||
  911. st->index_entries[st->nb_index_entries - 1].pos < pos) {
  912. av_add_index_entry(st, pos, ast->frame_offset, size,
  913. 0, AVINDEX_KEYFRAME);
  914. }
  915. }
  916. return 0;
  917. }
  918. }
  919. }
  920. return AVERROR_EOF;
  921. }
  922. static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
  923. {
  924. AVIContext *avi = s->priv_data;
  925. AVIOContext *pb = s->pb;
  926. int err;
  927. #if FF_API_DESTRUCT_PACKET
  928. void *dstr;
  929. #endif
  930. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  931. int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
  932. if (size >= 0)
  933. return size;
  934. else
  935. goto resync;
  936. }
  937. if (avi->non_interleaved) {
  938. int best_stream_index = 0;
  939. AVStream *best_st = NULL;
  940. AVIStream *best_ast;
  941. int64_t best_ts = INT64_MAX;
  942. int i;
  943. for (i = 0; i < s->nb_streams; i++) {
  944. AVStream *st = s->streams[i];
  945. AVIStream *ast = st->priv_data;
  946. int64_t ts = ast->frame_offset;
  947. int64_t last_ts;
  948. if (!st->nb_index_entries)
  949. continue;
  950. last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
  951. if (!ast->remaining && ts > last_ts)
  952. continue;
  953. ts = av_rescale_q(ts, st->time_base,
  954. (AVRational) { FFMAX(1, ast->sample_size),
  955. AV_TIME_BASE });
  956. av_dlog(s, "%"PRId64" %d/%d %"PRId64"\n", ts,
  957. st->time_base.num, st->time_base.den, ast->frame_offset);
  958. if (ts < best_ts) {
  959. best_ts = ts;
  960. best_st = st;
  961. best_stream_index = i;
  962. }
  963. }
  964. if (!best_st)
  965. return AVERROR_EOF;
  966. best_ast = best_st->priv_data;
  967. best_ts = av_rescale_q(best_ts,
  968. (AVRational) { FFMAX(1, best_ast->sample_size),
  969. AV_TIME_BASE },
  970. best_st->time_base);
  971. if (best_ast->remaining) {
  972. i = av_index_search_timestamp(best_st,
  973. best_ts,
  974. AVSEEK_FLAG_ANY |
  975. AVSEEK_FLAG_BACKWARD);
  976. } else {
  977. i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
  978. if (i >= 0)
  979. best_ast->frame_offset = best_st->index_entries[i].timestamp;
  980. }
  981. if (i >= 0) {
  982. int64_t pos = best_st->index_entries[i].pos;
  983. pos += best_ast->packet_size - best_ast->remaining;
  984. avio_seek(s->pb, pos + 8, SEEK_SET);
  985. assert(best_ast->remaining <= best_ast->packet_size);
  986. avi->stream_index = best_stream_index;
  987. if (!best_ast->remaining)
  988. best_ast->packet_size =
  989. best_ast->remaining = best_st->index_entries[i].size;
  990. }
  991. }
  992. resync:
  993. if (avi->stream_index >= 0) {
  994. AVStream *st = s->streams[avi->stream_index];
  995. AVIStream *ast = st->priv_data;
  996. int size, err;
  997. if (get_subtitle_pkt(s, st, pkt))
  998. return 0;
  999. // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  1000. if (ast->sample_size <= 1)
  1001. size = INT_MAX;
  1002. else if (ast->sample_size < 32)
  1003. // arbitrary multiplier to avoid tiny packets for raw PCM data
  1004. size = 1024 * ast->sample_size;
  1005. else
  1006. size = ast->sample_size;
  1007. if (size > ast->remaining)
  1008. size = ast->remaining;
  1009. avi->last_pkt_pos = avio_tell(pb);
  1010. err = av_get_packet(pb, pkt, size);
  1011. if (err < 0)
  1012. return err;
  1013. if (ast->has_pal && pkt->data && pkt->size < (unsigned)INT_MAX / 2) {
  1014. uint8_t *pal;
  1015. pal = av_packet_new_side_data(pkt,
  1016. AV_PKT_DATA_PALETTE,
  1017. AVPALETTE_SIZE);
  1018. if (!pal) {
  1019. av_log(s, AV_LOG_ERROR,
  1020. "Failed to allocate data for palette\n");
  1021. } else {
  1022. memcpy(pal, ast->pal, AVPALETTE_SIZE);
  1023. ast->has_pal = 0;
  1024. }
  1025. }
  1026. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1027. AVBufferRef *avbuf = pkt->buf;
  1028. #if FF_API_DESTRUCT_PACKET
  1029. FF_DISABLE_DEPRECATION_WARNINGS
  1030. dstr = pkt->destruct;
  1031. FF_ENABLE_DEPRECATION_WARNINGS
  1032. #endif
  1033. size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
  1034. pkt->data, pkt->size);
  1035. #if FF_API_DESTRUCT_PACKET
  1036. FF_DISABLE_DEPRECATION_WARNINGS
  1037. pkt->destruct = dstr;
  1038. FF_ENABLE_DEPRECATION_WARNINGS
  1039. #endif
  1040. pkt->buf = avbuf;
  1041. pkt->flags |= AV_PKT_FLAG_KEY;
  1042. if (size < 0)
  1043. av_free_packet(pkt);
  1044. } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
  1045. !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
  1046. ast->frame_offset++;
  1047. avi->stream_index = -1;
  1048. ast->remaining = 0;
  1049. goto resync;
  1050. } else {
  1051. /* XXX: How to handle B-frames in AVI? */
  1052. pkt->dts = ast->frame_offset;
  1053. // pkt->dts += ast->start;
  1054. if (ast->sample_size)
  1055. pkt->dts /= ast->sample_size;
  1056. av_dlog(s,
  1057. "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d "
  1058. "base:%d st:%d size:%d\n",
  1059. pkt->dts,
  1060. ast->frame_offset,
  1061. ast->scale,
  1062. ast->rate,
  1063. ast->sample_size,
  1064. AV_TIME_BASE,
  1065. avi->stream_index,
  1066. size);
  1067. pkt->stream_index = avi->stream_index;
  1068. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1069. AVIndexEntry *e;
  1070. int index;
  1071. assert(st->index_entries);
  1072. index = av_index_search_timestamp(st, ast->frame_offset, 0);
  1073. e = &st->index_entries[index];
  1074. if (index >= 0 && e->timestamp == ast->frame_offset)
  1075. if (e->flags & AVINDEX_KEYFRAME)
  1076. pkt->flags |= AV_PKT_FLAG_KEY;
  1077. } else {
  1078. pkt->flags |= AV_PKT_FLAG_KEY;
  1079. }
  1080. ast->frame_offset += get_duration(ast, pkt->size);
  1081. }
  1082. ast->remaining -= err;
  1083. if (!ast->remaining) {
  1084. avi->stream_index = -1;
  1085. ast->packet_size = 0;
  1086. }
  1087. return 0;
  1088. }
  1089. if ((err = avi_sync(s, 0)) < 0)
  1090. return err;
  1091. goto resync;
  1092. }
  1093. /* XXX: We make the implicit supposition that the positions are sorted
  1094. * for each stream. */
  1095. static int avi_read_idx1(AVFormatContext *s, int size)
  1096. {
  1097. AVIContext *avi = s->priv_data;
  1098. AVIOContext *pb = s->pb;
  1099. int nb_index_entries, i;
  1100. AVStream *st;
  1101. AVIStream *ast;
  1102. unsigned int index, tag, flags, pos, len, first_packet = 1;
  1103. unsigned last_pos = -1;
  1104. int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
  1105. nb_index_entries = size / 16;
  1106. if (nb_index_entries <= 0)
  1107. return AVERROR_INVALIDDATA;
  1108. idx1_pos = avio_tell(pb);
  1109. avio_seek(pb, avi->movi_list + 4, SEEK_SET);
  1110. if (avi_sync(s, 1) == 0)
  1111. first_packet_pos = avio_tell(pb) - 8;
  1112. avi->stream_index = -1;
  1113. avio_seek(pb, idx1_pos, SEEK_SET);
  1114. /* Read the entries and sort them in each stream component. */
  1115. for (i = 0; i < nb_index_entries; i++) {
  1116. tag = avio_rl32(pb);
  1117. flags = avio_rl32(pb);
  1118. pos = avio_rl32(pb);
  1119. len = avio_rl32(pb);
  1120. av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
  1121. i, tag, flags, pos, len);
  1122. index = ((tag & 0xff) - '0') * 10;
  1123. index += (tag >> 8 & 0xff) - '0';
  1124. if (index >= s->nb_streams)
  1125. continue;
  1126. st = s->streams[index];
  1127. ast = st->priv_data;
  1128. if (first_packet && first_packet_pos && len) {
  1129. data_offset = first_packet_pos - pos;
  1130. first_packet = 0;
  1131. }
  1132. pos += data_offset;
  1133. av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  1134. if (pb->eof_reached)
  1135. return AVERROR_INVALIDDATA;
  1136. if (last_pos == pos)
  1137. avi->non_interleaved = 1;
  1138. else if (len || !ast->sample_size)
  1139. av_add_index_entry(st, pos, ast->cum_len, len, 0,
  1140. (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  1141. ast->cum_len += get_duration(ast, len);
  1142. last_pos = pos;
  1143. }
  1144. return 0;
  1145. }
  1146. static int guess_ni_flag(AVFormatContext *s)
  1147. {
  1148. int i;
  1149. int64_t last_start = 0;
  1150. int64_t first_end = INT64_MAX;
  1151. int64_t oldpos = avio_tell(s->pb);
  1152. for (i = 0; i < s->nb_streams; i++) {
  1153. AVStream *st = s->streams[i];
  1154. int n = st->nb_index_entries;
  1155. unsigned int size;
  1156. if (n <= 0)
  1157. continue;
  1158. if (n >= 2) {
  1159. int64_t pos = st->index_entries[0].pos;
  1160. avio_seek(s->pb, pos + 4, SEEK_SET);
  1161. size = avio_rl32(s->pb);
  1162. if (pos + size > st->index_entries[1].pos)
  1163. last_start = INT64_MAX;
  1164. }
  1165. if (st->index_entries[0].pos > last_start)
  1166. last_start = st->index_entries[0].pos;
  1167. if (st->index_entries[n - 1].pos < first_end)
  1168. first_end = st->index_entries[n - 1].pos;
  1169. }
  1170. avio_seek(s->pb, oldpos, SEEK_SET);
  1171. return last_start > first_end;
  1172. }
  1173. static int avi_load_index(AVFormatContext *s)
  1174. {
  1175. AVIContext *avi = s->priv_data;
  1176. AVIOContext *pb = s->pb;
  1177. uint32_t tag, size;
  1178. int64_t pos = avio_tell(pb);
  1179. int ret = -1;
  1180. if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
  1181. goto the_end; // maybe truncated file
  1182. av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
  1183. for (;;) {
  1184. if (pb->eof_reached)
  1185. break;
  1186. tag = avio_rl32(pb);
  1187. size = avio_rl32(pb);
  1188. av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
  1189. tag & 0xff,
  1190. (tag >> 8) & 0xff,
  1191. (tag >> 16) & 0xff,
  1192. (tag >> 24) & 0xff,
  1193. size);
  1194. if (tag == MKTAG('i', 'd', 'x', '1') &&
  1195. avi_read_idx1(s, size) >= 0) {
  1196. ret = 0;
  1197. break;
  1198. }
  1199. size += (size & 1);
  1200. if (avio_skip(pb, size) < 0)
  1201. break; // something is wrong here
  1202. }
  1203. the_end:
  1204. avio_seek(pb, pos, SEEK_SET);
  1205. return ret;
  1206. }
  1207. static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
  1208. {
  1209. AVIStream *ast2 = st2->priv_data;
  1210. int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
  1211. av_free_packet(&ast2->sub_pkt);
  1212. if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
  1213. avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
  1214. ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
  1215. }
  1216. static int avi_read_seek(AVFormatContext *s, int stream_index,
  1217. int64_t timestamp, int flags)
  1218. {
  1219. AVIContext *avi = s->priv_data;
  1220. AVStream *st;
  1221. int i, index;
  1222. int64_t pos;
  1223. AVIStream *ast;
  1224. /* Does not matter which stream is requested dv in avi has the
  1225. * stream information in the first video stream.
  1226. */
  1227. if (avi->dv_demux)
  1228. stream_index = 0;
  1229. if (!avi->index_loaded) {
  1230. /* we only load the index on demand */
  1231. avi_load_index(s);
  1232. avi->index_loaded = 1;
  1233. }
  1234. st = s->streams[stream_index];
  1235. ast = st->priv_data;
  1236. index = av_index_search_timestamp(st,
  1237. timestamp * FFMAX(ast->sample_size, 1),
  1238. flags);
  1239. if (index < 0)
  1240. return AVERROR_INVALIDDATA;
  1241. /* find the position */
  1242. pos = st->index_entries[index].pos;
  1243. timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
  1244. av_dlog(s, "XX %"PRId64" %d %"PRId64"\n",
  1245. timestamp, index, st->index_entries[index].timestamp);
  1246. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1247. /* One and only one real stream for DV in AVI, and it has video */
  1248. /* offsets. Calling with other stream indexes should have failed */
  1249. /* the av_index_search_timestamp call above. */
  1250. /* Feed the DV video stream version of the timestamp to the */
  1251. /* DV demux so it can synthesize correct timestamps. */
  1252. ff_dv_offset_reset(avi->dv_demux, timestamp);
  1253. avio_seek(s->pb, pos, SEEK_SET);
  1254. avi->stream_index = -1;
  1255. return 0;
  1256. }
  1257. for (i = 0; i < s->nb_streams; i++) {
  1258. AVStream *st2 = s->streams[i];
  1259. AVIStream *ast2 = st2->priv_data;
  1260. ast2->packet_size =
  1261. ast2->remaining = 0;
  1262. if (ast2->sub_ctx) {
  1263. seek_subtitle(st, st2, timestamp);
  1264. continue;
  1265. }
  1266. if (st2->nb_index_entries <= 0)
  1267. continue;
  1268. // assert(st2->codec->block_align);
  1269. assert((int64_t)st2->time_base.num * ast2->rate ==
  1270. (int64_t)st2->time_base.den * ast2->scale);
  1271. index = av_index_search_timestamp(st2,
  1272. av_rescale_q(timestamp,
  1273. st->time_base,
  1274. st2->time_base) *
  1275. FFMAX(ast2->sample_size, 1),
  1276. flags | AVSEEK_FLAG_BACKWARD);
  1277. if (index < 0)
  1278. index = 0;
  1279. if (!avi->non_interleaved) {
  1280. while (index > 0 && st2->index_entries[index].pos > pos)
  1281. index--;
  1282. while (index + 1 < st2->nb_index_entries &&
  1283. st2->index_entries[index].pos < pos)
  1284. index++;
  1285. }
  1286. av_dlog(s, "%"PRId64" %d %"PRId64"\n",
  1287. timestamp, index, st2->index_entries[index].timestamp);
  1288. /* extract the current frame number */
  1289. ast2->frame_offset = st2->index_entries[index].timestamp;
  1290. }
  1291. /* do the seek */
  1292. avio_seek(s->pb, pos, SEEK_SET);
  1293. avi->stream_index = -1;
  1294. return 0;
  1295. }
  1296. static int avi_read_close(AVFormatContext *s)
  1297. {
  1298. int i;
  1299. AVIContext *avi = s->priv_data;
  1300. for (i = 0; i < s->nb_streams; i++) {
  1301. AVStream *st = s->streams[i];
  1302. AVIStream *ast = st->priv_data;
  1303. if (ast) {
  1304. if (ast->sub_ctx) {
  1305. av_freep(&ast->sub_ctx->pb);
  1306. avformat_close_input(&ast->sub_ctx);
  1307. }
  1308. av_free(ast->sub_buffer);
  1309. av_free_packet(&ast->sub_pkt);
  1310. }
  1311. }
  1312. av_free(avi->dv_demux);
  1313. return 0;
  1314. }
  1315. static int avi_probe(AVProbeData *p)
  1316. {
  1317. int i;
  1318. /* check file header */
  1319. for (i = 0; avi_headers[i][0]; i++)
  1320. if (!memcmp(p->buf, avi_headers[i], 4) &&
  1321. !memcmp(p->buf + 8, avi_headers[i] + 4, 4))
  1322. return AVPROBE_SCORE_MAX;
  1323. return 0;
  1324. }
  1325. AVInputFormat ff_avi_demuxer = {
  1326. .name = "avi",
  1327. .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
  1328. .priv_data_size = sizeof(AVIContext),
  1329. .read_probe = avi_probe,
  1330. .read_header = avi_read_header,
  1331. .read_packet = avi_read_packet,
  1332. .read_close = avi_read_close,
  1333. .read_seek = avi_read_seek,
  1334. };