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.

1828 lines
62KB

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