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.

1743 lines
59KB

  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 <stdint.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 avi_read_header(AVFormatContext *s)
  329. {
  330. AVIContext *avi = s->priv_data;
  331. AVIOContext *pb = s->pb;
  332. unsigned int tag, tag1, handler;
  333. int codec_type, stream_index, frame_period;
  334. unsigned int size;
  335. int i;
  336. AVStream *st;
  337. AVIStream *ast = NULL;
  338. int avih_width = 0, avih_height = 0;
  339. int amv_file_format = 0;
  340. uint64_t list_end = 0;
  341. int ret;
  342. AVDictionaryEntry *dict_entry;
  343. avi->stream_index = -1;
  344. ret = get_riff(s, pb);
  345. if (ret < 0)
  346. return ret;
  347. av_log(avi, AV_LOG_DEBUG, "use odml:%d\n", avi->use_odml);
  348. avi->io_fsize = avi->fsize = avio_size(pb);
  349. if (avi->fsize <= 0 || avi->fsize < avi->riff_end)
  350. avi->fsize = avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
  351. /* first list tag */
  352. stream_index = -1;
  353. codec_type = -1;
  354. frame_period = 0;
  355. for (;;) {
  356. if (url_feof(pb))
  357. goto fail;
  358. tag = avio_rl32(pb);
  359. size = avio_rl32(pb);
  360. print_tag("tag", tag, size);
  361. switch (tag) {
  362. case MKTAG('L', 'I', 'S', 'T'):
  363. list_end = avio_tell(pb) + size;
  364. /* Ignored, except at start of video packets. */
  365. tag1 = avio_rl32(pb);
  366. print_tag("list", tag1, 0);
  367. if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
  368. avi->movi_list = avio_tell(pb) - 4;
  369. if (size)
  370. avi->movi_end = avi->movi_list + size + (size & 1);
  371. else
  372. avi->movi_end = avi->fsize;
  373. av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
  374. goto end_of_header;
  375. } else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
  376. ff_read_riff_info(s, size - 4);
  377. else if (tag1 == MKTAG('n', 'c', 'd', 't'))
  378. avi_read_nikon(s, list_end);
  379. break;
  380. case MKTAG('I', 'D', 'I', 'T'):
  381. {
  382. unsigned char date[64] = { 0 };
  383. size += (size & 1);
  384. size -= avio_read(pb, date, FFMIN(size, sizeof(date) - 1));
  385. avio_skip(pb, size);
  386. avi_metadata_creation_time(&s->metadata, date);
  387. break;
  388. }
  389. case MKTAG('d', 'm', 'l', 'h'):
  390. avi->is_odml = 1;
  391. avio_skip(pb, size + (size & 1));
  392. break;
  393. case MKTAG('a', 'm', 'v', 'h'):
  394. amv_file_format = 1;
  395. case MKTAG('a', 'v', 'i', 'h'):
  396. /* AVI header */
  397. /* using frame_period is bad idea */
  398. frame_period = avio_rl32(pb);
  399. avio_rl32(pb); /* max. bytes per second */
  400. avio_rl32(pb);
  401. avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
  402. avio_skip(pb, 2 * 4);
  403. avio_rl32(pb);
  404. avio_rl32(pb);
  405. avih_width = avio_rl32(pb);
  406. avih_height = avio_rl32(pb);
  407. avio_skip(pb, size - 10 * 4);
  408. break;
  409. case MKTAG('s', 't', 'r', 'h'):
  410. /* stream header */
  411. tag1 = avio_rl32(pb);
  412. handler = avio_rl32(pb); /* codec tag */
  413. if (tag1 == MKTAG('p', 'a', 'd', 's')) {
  414. avio_skip(pb, size - 8);
  415. break;
  416. } else {
  417. stream_index++;
  418. st = avformat_new_stream(s, NULL);
  419. if (!st)
  420. goto fail;
  421. st->id = stream_index;
  422. ast = av_mallocz(sizeof(AVIStream));
  423. if (!ast)
  424. goto fail;
  425. st->priv_data = ast;
  426. }
  427. if (amv_file_format)
  428. tag1 = stream_index ? MKTAG('a', 'u', 'd', 's')
  429. : MKTAG('v', 'i', 'd', 's');
  430. print_tag("strh", tag1, -1);
  431. if (tag1 == MKTAG('i', 'a', 'v', 's') ||
  432. tag1 == MKTAG('i', 'v', 'a', 's')) {
  433. int64_t dv_dur;
  434. /* After some consideration -- I don't think we
  435. * have to support anything but DV in type1 AVIs. */
  436. if (s->nb_streams != 1)
  437. goto fail;
  438. if (handler != MKTAG('d', 'v', 's', 'd') &&
  439. handler != MKTAG('d', 'v', 'h', 'd') &&
  440. handler != MKTAG('d', 'v', 's', 'l'))
  441. goto fail;
  442. ast = s->streams[0]->priv_data;
  443. av_freep(&s->streams[0]->codec->extradata);
  444. av_freep(&s->streams[0]->codec);
  445. if (s->streams[0]->info)
  446. av_freep(&s->streams[0]->info->duration_error);
  447. av_freep(&s->streams[0]->info);
  448. av_freep(&s->streams[0]);
  449. s->nb_streams = 0;
  450. if (CONFIG_DV_DEMUXER) {
  451. avi->dv_demux = avpriv_dv_init_demux(s);
  452. if (!avi->dv_demux)
  453. goto fail;
  454. } else
  455. goto fail;
  456. s->streams[0]->priv_data = ast;
  457. avio_skip(pb, 3 * 4);
  458. ast->scale = avio_rl32(pb);
  459. ast->rate = avio_rl32(pb);
  460. avio_skip(pb, 4); /* start time */
  461. dv_dur = avio_rl32(pb);
  462. if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
  463. dv_dur *= AV_TIME_BASE;
  464. s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
  465. }
  466. /* else, leave duration alone; timing estimation in utils.c
  467. * will make a guess based on bitrate. */
  468. stream_index = s->nb_streams - 1;
  469. avio_skip(pb, size - 9 * 4);
  470. break;
  471. }
  472. av_assert0(stream_index < s->nb_streams);
  473. st->codec->stream_codec_tag = handler;
  474. avio_rl32(pb); /* flags */
  475. avio_rl16(pb); /* priority */
  476. avio_rl16(pb); /* language */
  477. avio_rl32(pb); /* initial frame */
  478. ast->scale = avio_rl32(pb);
  479. ast->rate = avio_rl32(pb);
  480. if (!(ast->scale && ast->rate)) {
  481. av_log(s, AV_LOG_WARNING,
  482. "scale/rate is %u/%u which is invalid. "
  483. "(This file has been generated by broken software.)\n",
  484. ast->scale,
  485. ast->rate);
  486. if (frame_period) {
  487. ast->rate = 1000000;
  488. ast->scale = frame_period;
  489. } else {
  490. ast->rate = 25;
  491. ast->scale = 1;
  492. }
  493. }
  494. avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
  495. ast->cum_len = avio_rl32(pb); /* start */
  496. st->nb_frames = avio_rl32(pb);
  497. st->start_time = 0;
  498. avio_rl32(pb); /* buffer size */
  499. avio_rl32(pb); /* quality */
  500. if (ast->cum_len*ast->scale/ast->rate > 3600) {
  501. av_log(s, AV_LOG_ERROR, "crazy start time, iam scared, giving up\n");
  502. return AVERROR_INVALIDDATA;
  503. }
  504. ast->sample_size = avio_rl32(pb); /* sample ssize */
  505. ast->cum_len *= FFMAX(1, ast->sample_size);
  506. av_dlog(s, "%"PRIu32" %"PRIu32" %d\n",
  507. ast->rate, ast->scale, ast->sample_size);
  508. switch (tag1) {
  509. case MKTAG('v', 'i', 'd', 's'):
  510. codec_type = AVMEDIA_TYPE_VIDEO;
  511. ast->sample_size = 0;
  512. break;
  513. case MKTAG('a', 'u', 'd', 's'):
  514. codec_type = AVMEDIA_TYPE_AUDIO;
  515. break;
  516. case MKTAG('t', 'x', 't', 's'):
  517. codec_type = AVMEDIA_TYPE_SUBTITLE;
  518. break;
  519. case MKTAG('d', 'a', 't', 's'):
  520. codec_type = AVMEDIA_TYPE_DATA;
  521. break;
  522. default:
  523. av_log(s, AV_LOG_INFO, "unknown stream type %X\n", tag1);
  524. }
  525. if (ast->sample_size == 0) {
  526. st->duration = st->nb_frames;
  527. if (st->duration > 0 && avi->io_fsize > 0 && avi->riff_end > avi->io_fsize) {
  528. av_log(s, AV_LOG_DEBUG, "File is truncated adjusting duration\n");
  529. st->duration = av_rescale(st->duration, avi->io_fsize, avi->riff_end);
  530. }
  531. }
  532. ast->frame_offset = ast->cum_len;
  533. avio_skip(pb, size - 12 * 4);
  534. break;
  535. case MKTAG('s', 't', 'r', 'f'):
  536. /* stream header */
  537. if (!size)
  538. break;
  539. if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
  540. avio_skip(pb, size);
  541. } else {
  542. uint64_t cur_pos = avio_tell(pb);
  543. unsigned esize;
  544. if (cur_pos < list_end)
  545. size = FFMIN(size, list_end - cur_pos);
  546. st = s->streams[stream_index];
  547. if (st->codec->codec_type != AVMEDIA_TYPE_UNKNOWN) {
  548. avio_skip(pb, size);
  549. break;
  550. }
  551. switch (codec_type) {
  552. case AVMEDIA_TYPE_VIDEO:
  553. if (amv_file_format) {
  554. st->codec->width = avih_width;
  555. st->codec->height = avih_height;
  556. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  557. st->codec->codec_id = AV_CODEC_ID_AMV;
  558. avio_skip(pb, size);
  559. break;
  560. }
  561. tag1 = ff_get_bmp_header(pb, st, &esize);
  562. if (tag1 == MKTAG('D', 'X', 'S', 'B') ||
  563. tag1 == MKTAG('D', 'X', 'S', 'A')) {
  564. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  565. st->codec->codec_tag = tag1;
  566. st->codec->codec_id = AV_CODEC_ID_XSUB;
  567. break;
  568. }
  569. if (size > 10 * 4 && size < (1 << 30) && size < avi->fsize) {
  570. if (esize == size-1 && (esize&1)) {
  571. st->codec->extradata_size = esize - 10 * 4;
  572. } else
  573. st->codec->extradata_size = size - 10 * 4;
  574. if (ff_get_extradata(st->codec, pb, st->codec->extradata_size) < 0)
  575. return AVERROR(ENOMEM);
  576. }
  577. // FIXME: check if the encoder really did this correctly
  578. if (st->codec->extradata_size & 1)
  579. avio_r8(pb);
  580. /* Extract palette from extradata if bpp <= 8.
  581. * This code assumes that extradata contains only palette.
  582. * This is true for all paletted codecs implemented in
  583. * FFmpeg. */
  584. if (st->codec->extradata_size &&
  585. (st->codec->bits_per_coded_sample <= 8)) {
  586. int pal_size = (1 << st->codec->bits_per_coded_sample) << 2;
  587. const uint8_t *pal_src;
  588. pal_size = FFMIN(pal_size, st->codec->extradata_size);
  589. pal_src = st->codec->extradata +
  590. st->codec->extradata_size - pal_size;
  591. for (i = 0; i < pal_size / 4; i++)
  592. ast->pal[i] = 0xFFU<<24 | AV_RL32(pal_src+4*i);
  593. ast->has_pal = 1;
  594. }
  595. print_tag("video", tag1, 0);
  596. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  597. st->codec->codec_tag = tag1;
  598. st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags,
  599. tag1);
  600. /* This is needed to get the pict type which is necessary
  601. * for generating correct pts. */
  602. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  603. if (st->codec->codec_tag == MKTAG('V', 'S', 'S', 'H'))
  604. st->need_parsing = AVSTREAM_PARSE_FULL;
  605. if (st->codec->codec_tag == 0 && st->codec->height > 0 &&
  606. st->codec->extradata_size < 1U << 30) {
  607. st->codec->extradata_size += 9;
  608. if ((ret = av_reallocp(&st->codec->extradata,
  609. st->codec->extradata_size +
  610. FF_INPUT_BUFFER_PADDING_SIZE)) < 0) {
  611. st->codec->extradata_size = 0;
  612. return ret;
  613. } else
  614. memcpy(st->codec->extradata + st->codec->extradata_size - 9,
  615. "BottomUp", 9);
  616. }
  617. st->codec->height = FFABS(st->codec->height);
  618. // avio_skip(pb, size - 5 * 4);
  619. break;
  620. case AVMEDIA_TYPE_AUDIO:
  621. ret = ff_get_wav_header(pb, st->codec, size);
  622. if (ret < 0)
  623. return ret;
  624. ast->dshow_block_align = st->codec->block_align;
  625. if (ast->sample_size && st->codec->block_align &&
  626. ast->sample_size != st->codec->block_align) {
  627. av_log(s,
  628. AV_LOG_WARNING,
  629. "sample size (%d) != block align (%d)\n",
  630. ast->sample_size,
  631. st->codec->block_align);
  632. ast->sample_size = st->codec->block_align;
  633. }
  634. /* 2-aligned
  635. * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
  636. if (size & 1)
  637. avio_skip(pb, 1);
  638. /* Force parsing as several audio frames can be in
  639. * one packet and timestamps refer to packet start. */
  640. st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
  641. /* ADTS header is in extradata, AAC without header must be
  642. * stored as exact frames. Parser not needed and it will
  643. * fail. */
  644. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  645. st->codec->extradata_size)
  646. st->need_parsing = AVSTREAM_PARSE_NONE;
  647. /* AVI files with Xan DPCM audio (wrongly) declare PCM
  648. * audio in the header but have Axan as stream_code_tag. */
  649. if (st->codec->stream_codec_tag == AV_RL32("Axan")) {
  650. st->codec->codec_id = AV_CODEC_ID_XAN_DPCM;
  651. st->codec->codec_tag = 0;
  652. ast->dshow_block_align = 0;
  653. }
  654. if (amv_file_format) {
  655. st->codec->codec_id = AV_CODEC_ID_ADPCM_IMA_AMV;
  656. ast->dshow_block_align = 0;
  657. }
  658. if (st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align <= 4 && ast->dshow_block_align) {
  659. av_log(s, AV_LOG_DEBUG, "overriding invalid dshow_block_align of %d\n", ast->dshow_block_align);
  660. ast->dshow_block_align = 0;
  661. }
  662. if (st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 1024 && ast->sample_size == 1024 ||
  663. st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 4096 && ast->sample_size == 4096 ||
  664. st->codec->codec_id == AV_CODEC_ID_MP3 && ast->dshow_block_align == 1152 && ast->sample_size == 1152) {
  665. av_log(s, AV_LOG_DEBUG, "overriding sample_size\n");
  666. ast->sample_size = 0;
  667. }
  668. break;
  669. case AVMEDIA_TYPE_SUBTITLE:
  670. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  671. st->request_probe= 1;
  672. avio_skip(pb, size);
  673. break;
  674. default:
  675. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  676. st->codec->codec_id = AV_CODEC_ID_NONE;
  677. st->codec->codec_tag = 0;
  678. avio_skip(pb, size);
  679. break;
  680. }
  681. }
  682. break;
  683. case MKTAG('s', 't', 'r', 'd'):
  684. if (stream_index >= (unsigned)s->nb_streams
  685. || s->streams[stream_index]->codec->extradata_size
  686. || s->streams[stream_index]->codec->codec_tag == MKTAG('H','2','6','4')) {
  687. avio_skip(pb, size);
  688. } else {
  689. uint64_t cur_pos = avio_tell(pb);
  690. if (cur_pos < list_end)
  691. size = FFMIN(size, list_end - cur_pos);
  692. st = s->streams[stream_index];
  693. if (size<(1<<30)) {
  694. if (ff_get_extradata(st->codec, pb, size) < 0)
  695. return AVERROR(ENOMEM);
  696. }
  697. if (st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
  698. avio_r8(pb);
  699. }
  700. break;
  701. case MKTAG('i', 'n', 'd', 'x'):
  702. i = avio_tell(pb);
  703. if (pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) &&
  704. avi->use_odml &&
  705. read_braindead_odml_indx(s, 0) < 0 &&
  706. (s->error_recognition & AV_EF_EXPLODE))
  707. goto fail;
  708. avio_seek(pb, i + size, SEEK_SET);
  709. break;
  710. case MKTAG('v', 'p', 'r', 'p'):
  711. if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) {
  712. AVRational active, active_aspect;
  713. st = s->streams[stream_index];
  714. avio_rl32(pb);
  715. avio_rl32(pb);
  716. avio_rl32(pb);
  717. avio_rl32(pb);
  718. avio_rl32(pb);
  719. active_aspect.den = avio_rl16(pb);
  720. active_aspect.num = avio_rl16(pb);
  721. active.num = avio_rl32(pb);
  722. active.den = avio_rl32(pb);
  723. avio_rl32(pb); // nbFieldsPerFrame
  724. if (active_aspect.num && active_aspect.den &&
  725. active.num && active.den) {
  726. st->sample_aspect_ratio = av_div_q(active_aspect, active);
  727. av_dlog(s, "vprp %d/%d %d/%d\n",
  728. active_aspect.num, active_aspect.den,
  729. active.num, active.den);
  730. }
  731. size -= 9 * 4;
  732. }
  733. avio_skip(pb, size);
  734. break;
  735. case MKTAG('s', 't', 'r', 'n'):
  736. if (s->nb_streams) {
  737. ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size);
  738. if (ret < 0)
  739. return ret;
  740. break;
  741. }
  742. default:
  743. if (size > 1000000) {
  744. av_log(s, AV_LOG_ERROR,
  745. "Something went wrong during header parsing, "
  746. "I will ignore it and try to continue anyway.\n");
  747. if (s->error_recognition & AV_EF_EXPLODE)
  748. goto fail;
  749. avi->movi_list = avio_tell(pb) - 4;
  750. avi->movi_end = avi->fsize;
  751. goto end_of_header;
  752. }
  753. /* skip tag */
  754. size += (size & 1);
  755. avio_skip(pb, size);
  756. break;
  757. }
  758. }
  759. end_of_header:
  760. /* check stream number */
  761. if (stream_index != s->nb_streams - 1) {
  762. fail:
  763. return AVERROR_INVALIDDATA;
  764. }
  765. if (!avi->index_loaded && pb->seekable)
  766. avi_load_index(s);
  767. avi->index_loaded |= 1;
  768. avi->non_interleaved |= guess_ni_flag(s) | (s->flags & AVFMT_FLAG_SORT_DTS);
  769. dict_entry = av_dict_get(s->metadata, "ISFT", NULL, 0);
  770. if (dict_entry && !strcmp(dict_entry->value, "PotEncoder"))
  771. for (i = 0; i < s->nb_streams; i++) {
  772. AVStream *st = s->streams[i];
  773. if ( st->codec->codec_id == AV_CODEC_ID_MPEG1VIDEO
  774. || st->codec->codec_id == AV_CODEC_ID_MPEG2VIDEO)
  775. st->need_parsing = AVSTREAM_PARSE_FULL;
  776. }
  777. for (i = 0; i < s->nb_streams; i++) {
  778. AVStream *st = s->streams[i];
  779. if (st->nb_index_entries)
  780. break;
  781. }
  782. // DV-in-AVI cannot be non-interleaved, if set this must be
  783. // a mis-detection.
  784. if (avi->dv_demux)
  785. avi->non_interleaved = 0;
  786. if (i == s->nb_streams && avi->non_interleaved) {
  787. av_log(s, AV_LOG_WARNING,
  788. "Non-interleaved AVI without index, switching to interleaved\n");
  789. avi->non_interleaved = 0;
  790. }
  791. if (avi->non_interleaved) {
  792. av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
  793. clean_index(s);
  794. }
  795. ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
  796. ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
  797. return 0;
  798. }
  799. static int read_gab2_sub(AVStream *st, AVPacket *pkt)
  800. {
  801. if (pkt->size >= 7 &&
  802. !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
  803. uint8_t desc[256];
  804. int score = AVPROBE_SCORE_EXTENSION, ret;
  805. AVIStream *ast = st->priv_data;
  806. AVInputFormat *sub_demuxer;
  807. AVRational time_base;
  808. AVIOContext *pb = avio_alloc_context(pkt->data + 7,
  809. pkt->size - 7,
  810. 0, NULL, NULL, NULL, NULL);
  811. AVProbeData pd;
  812. unsigned int desc_len = avio_rl32(pb);
  813. if (desc_len > pb->buf_end - pb->buf_ptr)
  814. goto error;
  815. ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
  816. avio_skip(pb, desc_len - ret);
  817. if (*desc)
  818. av_dict_set(&st->metadata, "title", desc, 0);
  819. avio_rl16(pb); /* flags? */
  820. avio_rl32(pb); /* data size */
  821. pd = (AVProbeData) { .buf = pb->buf_ptr,
  822. .buf_size = pb->buf_end - pb->buf_ptr };
  823. if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
  824. goto error;
  825. if (!(ast->sub_ctx = avformat_alloc_context()))
  826. goto error;
  827. ast->sub_ctx->pb = pb;
  828. if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
  829. ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
  830. *st->codec = *ast->sub_ctx->streams[0]->codec;
  831. ast->sub_ctx->streams[0]->codec->extradata = NULL;
  832. time_base = ast->sub_ctx->streams[0]->time_base;
  833. avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
  834. }
  835. ast->sub_buffer = pkt->data;
  836. memset(pkt, 0, sizeof(*pkt));
  837. return 1;
  838. error:
  839. av_freep(&pb);
  840. }
  841. return 0;
  842. }
  843. static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
  844. AVPacket *pkt)
  845. {
  846. AVIStream *ast, *next_ast = next_st->priv_data;
  847. int64_t ts, next_ts, ts_min = INT64_MAX;
  848. AVStream *st, *sub_st = NULL;
  849. int i;
  850. next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
  851. AV_TIME_BASE_Q);
  852. for (i = 0; i < s->nb_streams; i++) {
  853. st = s->streams[i];
  854. ast = st->priv_data;
  855. if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
  856. ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
  857. if (ts <= next_ts && ts < ts_min) {
  858. ts_min = ts;
  859. sub_st = st;
  860. }
  861. }
  862. }
  863. if (sub_st) {
  864. ast = sub_st->priv_data;
  865. *pkt = ast->sub_pkt;
  866. pkt->stream_index = sub_st->index;
  867. if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
  868. ast->sub_pkt.data = NULL;
  869. }
  870. return sub_st;
  871. }
  872. static int get_stream_idx(unsigned *d)
  873. {
  874. if (d[0] >= '0' && d[0] <= '9' &&
  875. d[1] >= '0' && d[1] <= '9') {
  876. return (d[0] - '0') * 10 + (d[1] - '0');
  877. } else {
  878. return 100; // invalid stream ID
  879. }
  880. }
  881. /**
  882. *
  883. * @param exit_early set to 1 to just gather packet position without making the changes needed to actually read & return the packet
  884. */
  885. static int avi_sync(AVFormatContext *s, int exit_early)
  886. {
  887. AVIContext *avi = s->priv_data;
  888. AVIOContext *pb = s->pb;
  889. int n;
  890. unsigned int d[8];
  891. unsigned int size;
  892. int64_t i, sync;
  893. start_sync:
  894. memset(d, -1, sizeof(d));
  895. for (i = sync = avio_tell(pb); !url_feof(pb); i++) {
  896. int j;
  897. for (j = 0; j < 7; j++)
  898. d[j] = d[j + 1];
  899. d[7] = avio_r8(pb);
  900. size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24);
  901. n = get_stream_idx(d + 2);
  902. av_dlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
  903. d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
  904. if (i*(avi->io_fsize>0) + (uint64_t)size > avi->fsize || d[0] > 127)
  905. continue;
  906. // parse ix##
  907. if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) ||
  908. // parse JUNK
  909. (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') ||
  910. (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')) {
  911. avio_skip(pb, size);
  912. goto start_sync;
  913. }
  914. // parse stray LIST
  915. if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') {
  916. avio_skip(pb, 4);
  917. goto start_sync;
  918. }
  919. n = avi->dv_demux ? 0 : get_stream_idx(d);
  920. if (!((i - avi->last_pkt_pos) & 1) &&
  921. get_stream_idx(d + 1) < s->nb_streams)
  922. continue;
  923. // detect ##ix chunk and skip
  924. if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) {
  925. avio_skip(pb, size);
  926. goto start_sync;
  927. }
  928. // parse ##dc/##wb
  929. if (n < s->nb_streams) {
  930. AVStream *st;
  931. AVIStream *ast;
  932. st = s->streams[n];
  933. ast = st->priv_data;
  934. if (!ast) {
  935. av_log(s, AV_LOG_WARNING, "Skiping foreign stream %d packet\n", n);
  936. continue;
  937. }
  938. if (s->nb_streams >= 2) {
  939. AVStream *st1 = s->streams[1];
  940. AVIStream *ast1 = st1->priv_data;
  941. // workaround for broken small-file-bug402.avi
  942. if ( d[2] == 'w' && d[3] == 'b'
  943. && n == 0
  944. && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
  945. && st1->codec->codec_type == AVMEDIA_TYPE_AUDIO
  946. && ast->prefix == 'd'*256+'c'
  947. && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
  948. ) {
  949. n = 1;
  950. st = st1;
  951. ast = ast1;
  952. av_log(s, AV_LOG_WARNING,
  953. "Invalid stream + prefix combination, assuming audio.\n");
  954. }
  955. }
  956. if (!avi->dv_demux &&
  957. ((st->discard >= AVDISCARD_DEFAULT && size == 0) /* ||
  958. // FIXME: needs a little reordering
  959. (st->discard >= AVDISCARD_NONKEY &&
  960. !(pkt->flags & AV_PKT_FLAG_KEY)) */
  961. || st->discard >= AVDISCARD_ALL)) {
  962. if (!exit_early) {
  963. ast->frame_offset += get_duration(ast, size);
  964. avio_skip(pb, size);
  965. goto start_sync;
  966. }
  967. }
  968. if (d[2] == 'p' && d[3] == 'c' && size <= 4 * 256 + 4) {
  969. int k = avio_r8(pb);
  970. int last = (k + avio_r8(pb) - 1) & 0xFF;
  971. avio_rl16(pb); // flags
  972. // b + (g << 8) + (r << 16);
  973. for (; k <= last; k++)
  974. ast->pal[k] = 0xFFU<<24 | avio_rb32(pb)>>8;
  975. ast->has_pal = 1;
  976. goto start_sync;
  977. } else if (((ast->prefix_count < 5 || sync + 9 > i) &&
  978. d[2] < 128 && d[3] < 128) ||
  979. d[2] * 256 + d[3] == ast->prefix /* ||
  980. (d[2] == 'd' && d[3] == 'c') ||
  981. (d[2] == 'w' && d[3] == 'b') */) {
  982. if (exit_early)
  983. return 0;
  984. if (d[2] * 256 + d[3] == ast->prefix)
  985. ast->prefix_count++;
  986. else {
  987. ast->prefix = d[2] * 256 + d[3];
  988. ast->prefix_count = 0;
  989. }
  990. avi->stream_index = n;
  991. ast->packet_size = size + 8;
  992. ast->remaining = size;
  993. if (size || !ast->sample_size) {
  994. uint64_t pos = avio_tell(pb) - 8;
  995. if (!st->index_entries || !st->nb_index_entries ||
  996. st->index_entries[st->nb_index_entries - 1].pos < pos) {
  997. av_add_index_entry(st, pos, ast->frame_offset, size,
  998. 0, AVINDEX_KEYFRAME);
  999. }
  1000. }
  1001. return 0;
  1002. }
  1003. }
  1004. }
  1005. if (pb->error)
  1006. return pb->error;
  1007. return AVERROR_EOF;
  1008. }
  1009. static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
  1010. {
  1011. AVIContext *avi = s->priv_data;
  1012. AVIOContext *pb = s->pb;
  1013. int err;
  1014. #if FF_API_DESTRUCT_PACKET
  1015. void *dstr;
  1016. #endif
  1017. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1018. int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
  1019. if (size >= 0)
  1020. return size;
  1021. else
  1022. goto resync;
  1023. }
  1024. if (avi->non_interleaved) {
  1025. int best_stream_index = 0;
  1026. AVStream *best_st = NULL;
  1027. AVIStream *best_ast;
  1028. int64_t best_ts = INT64_MAX;
  1029. int i;
  1030. for (i = 0; i < s->nb_streams; i++) {
  1031. AVStream *st = s->streams[i];
  1032. AVIStream *ast = st->priv_data;
  1033. int64_t ts = ast->frame_offset;
  1034. int64_t last_ts;
  1035. if (!st->nb_index_entries)
  1036. continue;
  1037. last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
  1038. if (!ast->remaining && ts > last_ts)
  1039. continue;
  1040. ts = av_rescale_q(ts, st->time_base,
  1041. (AVRational) { FFMAX(1, ast->sample_size),
  1042. AV_TIME_BASE });
  1043. av_dlog(s, "%"PRId64" %d/%d %"PRId64"\n", ts,
  1044. st->time_base.num, st->time_base.den, ast->frame_offset);
  1045. if (ts < best_ts) {
  1046. best_ts = ts;
  1047. best_st = st;
  1048. best_stream_index = i;
  1049. }
  1050. }
  1051. if (!best_st)
  1052. return AVERROR_EOF;
  1053. best_ast = best_st->priv_data;
  1054. best_ts = best_ast->frame_offset;
  1055. if (best_ast->remaining) {
  1056. i = av_index_search_timestamp(best_st,
  1057. best_ts,
  1058. AVSEEK_FLAG_ANY |
  1059. AVSEEK_FLAG_BACKWARD);
  1060. } else {
  1061. i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
  1062. if (i >= 0)
  1063. best_ast->frame_offset = best_st->index_entries[i].timestamp;
  1064. }
  1065. if (i >= 0) {
  1066. int64_t pos = best_st->index_entries[i].pos;
  1067. pos += best_ast->packet_size - best_ast->remaining;
  1068. if (avio_seek(s->pb, pos + 8, SEEK_SET) < 0)
  1069. return AVERROR_EOF;
  1070. av_assert0(best_ast->remaining <= best_ast->packet_size);
  1071. avi->stream_index = best_stream_index;
  1072. if (!best_ast->remaining)
  1073. best_ast->packet_size =
  1074. best_ast->remaining = best_st->index_entries[i].size;
  1075. }
  1076. else
  1077. return AVERROR_EOF;
  1078. }
  1079. resync:
  1080. if (avi->stream_index >= 0) {
  1081. AVStream *st = s->streams[avi->stream_index];
  1082. AVIStream *ast = st->priv_data;
  1083. int size, err;
  1084. if (get_subtitle_pkt(s, st, pkt))
  1085. return 0;
  1086. // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  1087. if (ast->sample_size <= 1)
  1088. size = INT_MAX;
  1089. else if (ast->sample_size < 32)
  1090. // arbitrary multiplier to avoid tiny packets for raw PCM data
  1091. size = 1024 * ast->sample_size;
  1092. else
  1093. size = ast->sample_size;
  1094. if (size > ast->remaining)
  1095. size = ast->remaining;
  1096. avi->last_pkt_pos = avio_tell(pb);
  1097. err = av_get_packet(pb, pkt, size);
  1098. if (err < 0)
  1099. return err;
  1100. size = err;
  1101. if (ast->has_pal && pkt->size < (unsigned)INT_MAX / 2) {
  1102. uint8_t *pal;
  1103. pal = av_packet_new_side_data(pkt,
  1104. AV_PKT_DATA_PALETTE,
  1105. AVPALETTE_SIZE);
  1106. if (!pal) {
  1107. av_log(s, AV_LOG_ERROR,
  1108. "Failed to allocate data for palette\n");
  1109. } else {
  1110. memcpy(pal, ast->pal, AVPALETTE_SIZE);
  1111. ast->has_pal = 0;
  1112. }
  1113. }
  1114. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1115. AVBufferRef *avbuf = pkt->buf;
  1116. #if FF_API_DESTRUCT_PACKET
  1117. FF_DISABLE_DEPRECATION_WARNINGS
  1118. dstr = pkt->destruct;
  1119. FF_ENABLE_DEPRECATION_WARNINGS
  1120. #endif
  1121. size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
  1122. pkt->data, pkt->size, pkt->pos);
  1123. #if FF_API_DESTRUCT_PACKET
  1124. FF_DISABLE_DEPRECATION_WARNINGS
  1125. pkt->destruct = dstr;
  1126. FF_ENABLE_DEPRECATION_WARNINGS
  1127. #endif
  1128. pkt->buf = avbuf;
  1129. pkt->flags |= AV_PKT_FLAG_KEY;
  1130. if (size < 0)
  1131. av_free_packet(pkt);
  1132. } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
  1133. !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
  1134. ast->frame_offset++;
  1135. avi->stream_index = -1;
  1136. ast->remaining = 0;
  1137. goto resync;
  1138. } else {
  1139. /* XXX: How to handle B-frames in AVI? */
  1140. pkt->dts = ast->frame_offset;
  1141. // pkt->dts += ast->start;
  1142. if (ast->sample_size)
  1143. pkt->dts /= ast->sample_size;
  1144. av_dlog(s,
  1145. "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d "
  1146. "base:%d st:%d size:%d\n",
  1147. pkt->dts,
  1148. ast->frame_offset,
  1149. ast->scale,
  1150. ast->rate,
  1151. ast->sample_size,
  1152. AV_TIME_BASE,
  1153. avi->stream_index,
  1154. size);
  1155. pkt->stream_index = avi->stream_index;
  1156. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->index_entries) {
  1157. AVIndexEntry *e;
  1158. int index;
  1159. index = av_index_search_timestamp(st, ast->frame_offset, 0);
  1160. e = &st->index_entries[index];
  1161. if (index >= 0 && e->timestamp == ast->frame_offset) {
  1162. if (index == st->nb_index_entries-1) {
  1163. int key=1;
  1164. int i;
  1165. uint32_t state=-1;
  1166. for (i=0; i<FFMIN(size,256); i++) {
  1167. if (st->codec->codec_id == AV_CODEC_ID_MPEG4) {
  1168. if (state == 0x1B6) {
  1169. key= !(pkt->data[i]&0xC0);
  1170. break;
  1171. }
  1172. }else
  1173. break;
  1174. state= (state<<8) + pkt->data[i];
  1175. }
  1176. if (!key)
  1177. e->flags &= ~AVINDEX_KEYFRAME;
  1178. }
  1179. if (e->flags & AVINDEX_KEYFRAME)
  1180. pkt->flags |= AV_PKT_FLAG_KEY;
  1181. }
  1182. } else {
  1183. pkt->flags |= AV_PKT_FLAG_KEY;
  1184. }
  1185. ast->frame_offset += get_duration(ast, pkt->size);
  1186. }
  1187. ast->remaining -= err;
  1188. if (!ast->remaining) {
  1189. avi->stream_index = -1;
  1190. ast->packet_size = 0;
  1191. }
  1192. if (!avi->non_interleaved && pkt->pos >= 0 && ast->seek_pos > pkt->pos) {
  1193. av_free_packet(pkt);
  1194. goto resync;
  1195. }
  1196. ast->seek_pos= 0;
  1197. if (!avi->non_interleaved && st->nb_index_entries>1 && avi->index_loaded>1) {
  1198. int64_t dts= av_rescale_q(pkt->dts, st->time_base, AV_TIME_BASE_Q);
  1199. if (avi->dts_max - dts > 2*AV_TIME_BASE) {
  1200. avi->non_interleaved= 1;
  1201. av_log(s, AV_LOG_INFO, "Switching to NI mode, due to poor interleaving\n");
  1202. }else if (avi->dts_max < dts)
  1203. avi->dts_max = dts;
  1204. }
  1205. return 0;
  1206. }
  1207. if ((err = avi_sync(s, 0)) < 0)
  1208. return err;
  1209. goto resync;
  1210. }
  1211. /* XXX: We make the implicit supposition that the positions are sorted
  1212. * for each stream. */
  1213. static int avi_read_idx1(AVFormatContext *s, int size)
  1214. {
  1215. AVIContext *avi = s->priv_data;
  1216. AVIOContext *pb = s->pb;
  1217. int nb_index_entries, i;
  1218. AVStream *st;
  1219. AVIStream *ast;
  1220. unsigned int index, tag, flags, pos, len, first_packet = 1;
  1221. unsigned last_pos = -1;
  1222. unsigned last_idx = -1;
  1223. int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
  1224. int anykey = 0;
  1225. nb_index_entries = size / 16;
  1226. if (nb_index_entries <= 0)
  1227. return AVERROR_INVALIDDATA;
  1228. idx1_pos = avio_tell(pb);
  1229. avio_seek(pb, avi->movi_list + 4, SEEK_SET);
  1230. if (avi_sync(s, 1) == 0)
  1231. first_packet_pos = avio_tell(pb) - 8;
  1232. avi->stream_index = -1;
  1233. avio_seek(pb, idx1_pos, SEEK_SET);
  1234. if (s->nb_streams == 1 && s->streams[0]->codec->codec_tag == AV_RL32("MMES")) {
  1235. first_packet_pos = 0;
  1236. data_offset = avi->movi_list;
  1237. }
  1238. /* Read the entries and sort them in each stream component. */
  1239. for (i = 0; i < nb_index_entries; i++) {
  1240. if (url_feof(pb))
  1241. return -1;
  1242. tag = avio_rl32(pb);
  1243. flags = avio_rl32(pb);
  1244. pos = avio_rl32(pb);
  1245. len = avio_rl32(pb);
  1246. av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
  1247. i, tag, flags, pos, len);
  1248. index = ((tag & 0xff) - '0') * 10;
  1249. index += (tag >> 8 & 0xff) - '0';
  1250. if (index >= s->nb_streams)
  1251. continue;
  1252. st = s->streams[index];
  1253. ast = st->priv_data;
  1254. if (first_packet && first_packet_pos) {
  1255. data_offset = first_packet_pos - pos;
  1256. first_packet = 0;
  1257. }
  1258. pos += data_offset;
  1259. av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  1260. // even if we have only a single stream, we should
  1261. // switch to non-interleaved to get correct timestamps
  1262. if (last_pos == pos)
  1263. avi->non_interleaved = 1;
  1264. if (last_idx != pos && len) {
  1265. av_add_index_entry(st, pos, ast->cum_len, len, 0,
  1266. (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  1267. last_idx= pos;
  1268. }
  1269. ast->cum_len += get_duration(ast, len);
  1270. last_pos = pos;
  1271. anykey |= flags&AVIIF_INDEX;
  1272. }
  1273. if (!anykey) {
  1274. for (index = 0; index < s->nb_streams; index++) {
  1275. st = s->streams[index];
  1276. if (st->nb_index_entries)
  1277. st->index_entries[0].flags |= AVINDEX_KEYFRAME;
  1278. }
  1279. }
  1280. return 0;
  1281. }
  1282. static int guess_ni_flag(AVFormatContext *s)
  1283. {
  1284. int i;
  1285. int64_t last_start = 0;
  1286. int64_t first_end = INT64_MAX;
  1287. int64_t oldpos = avio_tell(s->pb);
  1288. int *idx;
  1289. int64_t min_pos, pos;
  1290. for (i = 0; i < s->nb_streams; i++) {
  1291. AVStream *st = s->streams[i];
  1292. int n = st->nb_index_entries;
  1293. unsigned int size;
  1294. if (n <= 0)
  1295. continue;
  1296. if (n >= 2) {
  1297. int64_t pos = st->index_entries[0].pos;
  1298. avio_seek(s->pb, pos + 4, SEEK_SET);
  1299. size = avio_rl32(s->pb);
  1300. if (pos + size > st->index_entries[1].pos)
  1301. last_start = INT64_MAX;
  1302. }
  1303. if (st->index_entries[0].pos > last_start)
  1304. last_start = st->index_entries[0].pos;
  1305. if (st->index_entries[n - 1].pos < first_end)
  1306. first_end = st->index_entries[n - 1].pos;
  1307. }
  1308. avio_seek(s->pb, oldpos, SEEK_SET);
  1309. if (last_start > first_end)
  1310. return 1;
  1311. idx= av_calloc(s->nb_streams, sizeof(*idx));
  1312. if (!idx)
  1313. return 0;
  1314. for (min_pos=pos=0; min_pos!=INT64_MAX; pos= min_pos+1LU) {
  1315. int64_t max_dts = INT64_MIN/2, min_dts= INT64_MAX/2;
  1316. min_pos = INT64_MAX;
  1317. for (i=0; i<s->nb_streams; i++) {
  1318. AVStream *st = s->streams[i];
  1319. AVIStream *ast = st->priv_data;
  1320. int n= st->nb_index_entries;
  1321. while (idx[i]<n && st->index_entries[idx[i]].pos < pos)
  1322. idx[i]++;
  1323. if (idx[i] < n) {
  1324. min_dts = FFMIN(min_dts, av_rescale_q(st->index_entries[idx[i]].timestamp/FFMAX(ast->sample_size, 1), st->time_base, AV_TIME_BASE_Q));
  1325. min_pos = FFMIN(min_pos, st->index_entries[idx[i]].pos);
  1326. }
  1327. if (idx[i])
  1328. max_dts = FFMAX(max_dts, av_rescale_q(st->index_entries[idx[i]-1].timestamp/FFMAX(ast->sample_size, 1), st->time_base, AV_TIME_BASE_Q));
  1329. }
  1330. if (max_dts - min_dts > 2*AV_TIME_BASE) {
  1331. av_free(idx);
  1332. return 1;
  1333. }
  1334. }
  1335. av_free(idx);
  1336. return 0;
  1337. }
  1338. static int avi_load_index(AVFormatContext *s)
  1339. {
  1340. AVIContext *avi = s->priv_data;
  1341. AVIOContext *pb = s->pb;
  1342. uint32_t tag, size;
  1343. int64_t pos = avio_tell(pb);
  1344. int64_t next;
  1345. int ret = -1;
  1346. if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
  1347. goto the_end; // maybe truncated file
  1348. av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
  1349. for (;;) {
  1350. tag = avio_rl32(pb);
  1351. size = avio_rl32(pb);
  1352. if (url_feof(pb))
  1353. break;
  1354. next = avio_tell(pb) + size + (size & 1);
  1355. av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
  1356. tag & 0xff,
  1357. (tag >> 8) & 0xff,
  1358. (tag >> 16) & 0xff,
  1359. (tag >> 24) & 0xff,
  1360. size);
  1361. if (tag == MKTAG('i', 'd', 'x', '1') &&
  1362. avi_read_idx1(s, size) >= 0) {
  1363. avi->index_loaded=2;
  1364. ret = 0;
  1365. }else if (tag == MKTAG('L', 'I', 'S', 'T')) {
  1366. uint32_t tag1 = avio_rl32(pb);
  1367. if (tag1 == MKTAG('I', 'N', 'F', 'O'))
  1368. ff_read_riff_info(s, size - 4);
  1369. }else if (!ret)
  1370. break;
  1371. if (avio_seek(pb, next, SEEK_SET) < 0)
  1372. break; // something is wrong here
  1373. }
  1374. the_end:
  1375. avio_seek(pb, pos, SEEK_SET);
  1376. return ret;
  1377. }
  1378. static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
  1379. {
  1380. AVIStream *ast2 = st2->priv_data;
  1381. int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
  1382. av_free_packet(&ast2->sub_pkt);
  1383. if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
  1384. avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
  1385. ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
  1386. }
  1387. static int avi_read_seek(AVFormatContext *s, int stream_index,
  1388. int64_t timestamp, int flags)
  1389. {
  1390. AVIContext *avi = s->priv_data;
  1391. AVStream *st;
  1392. int i, index;
  1393. int64_t pos, pos_min;
  1394. AVIStream *ast;
  1395. /* Does not matter which stream is requested dv in avi has the
  1396. * stream information in the first video stream.
  1397. */
  1398. if (avi->dv_demux)
  1399. stream_index = 0;
  1400. if (!avi->index_loaded) {
  1401. /* we only load the index on demand */
  1402. avi_load_index(s);
  1403. avi->index_loaded |= 1;
  1404. }
  1405. av_assert0(stream_index >= 0);
  1406. st = s->streams[stream_index];
  1407. ast = st->priv_data;
  1408. index = av_index_search_timestamp(st,
  1409. timestamp * FFMAX(ast->sample_size, 1),
  1410. flags);
  1411. if (index < 0) {
  1412. if (st->nb_index_entries > 0)
  1413. av_log(s, AV_LOG_DEBUG, "Failed to find timestamp %"PRId64 " in index %"PRId64 " .. %"PRId64 "\n",
  1414. timestamp * FFMAX(ast->sample_size, 1),
  1415. st->index_entries[0].timestamp,
  1416. st->index_entries[st->nb_index_entries - 1].timestamp);
  1417. return AVERROR_INVALIDDATA;
  1418. }
  1419. /* find the position */
  1420. pos = st->index_entries[index].pos;
  1421. timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
  1422. av_dlog(s, "XX %"PRId64" %d %"PRId64"\n",
  1423. timestamp, index, st->index_entries[index].timestamp);
  1424. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1425. /* One and only one real stream for DV in AVI, and it has video */
  1426. /* offsets. Calling with other stream indexes should have failed */
  1427. /* the av_index_search_timestamp call above. */
  1428. if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  1429. return -1;
  1430. /* Feed the DV video stream version of the timestamp to the */
  1431. /* DV demux so it can synthesize correct timestamps. */
  1432. ff_dv_offset_reset(avi->dv_demux, timestamp);
  1433. avi->stream_index = -1;
  1434. return 0;
  1435. }
  1436. pos_min = pos;
  1437. for (i = 0; i < s->nb_streams; i++) {
  1438. AVStream *st2 = s->streams[i];
  1439. AVIStream *ast2 = st2->priv_data;
  1440. ast2->packet_size =
  1441. ast2->remaining = 0;
  1442. if (ast2->sub_ctx) {
  1443. seek_subtitle(st, st2, timestamp);
  1444. continue;
  1445. }
  1446. if (st2->nb_index_entries <= 0)
  1447. continue;
  1448. // av_assert1(st2->codec->block_align);
  1449. av_assert0((int64_t)st2->time_base.num * ast2->rate ==
  1450. (int64_t)st2->time_base.den * ast2->scale);
  1451. index = av_index_search_timestamp(st2,
  1452. av_rescale_q(timestamp,
  1453. st->time_base,
  1454. st2->time_base) *
  1455. FFMAX(ast2->sample_size, 1),
  1456. flags |
  1457. AVSEEK_FLAG_BACKWARD |
  1458. (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
  1459. if (index < 0)
  1460. index = 0;
  1461. ast2->seek_pos = st2->index_entries[index].pos;
  1462. pos_min = FFMIN(pos_min,ast2->seek_pos);
  1463. }
  1464. for (i = 0; i < s->nb_streams; i++) {
  1465. AVStream *st2 = s->streams[i];
  1466. AVIStream *ast2 = st2->priv_data;
  1467. if (ast2->sub_ctx || st2->nb_index_entries <= 0)
  1468. continue;
  1469. index = av_index_search_timestamp(
  1470. st2,
  1471. av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
  1472. flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
  1473. if (index < 0)
  1474. index = 0;
  1475. while (!avi->non_interleaved && index>0 && st2->index_entries[index-1].pos >= pos_min)
  1476. index--;
  1477. ast2->frame_offset = st2->index_entries[index].timestamp;
  1478. }
  1479. /* do the seek */
  1480. if (avio_seek(s->pb, pos_min, SEEK_SET) < 0) {
  1481. av_log(s, AV_LOG_ERROR, "Seek failed\n");
  1482. return -1;
  1483. }
  1484. avi->stream_index = -1;
  1485. avi->dts_max = INT_MIN;
  1486. return 0;
  1487. }
  1488. static int avi_read_close(AVFormatContext *s)
  1489. {
  1490. int i;
  1491. AVIContext *avi = s->priv_data;
  1492. for (i = 0; i < s->nb_streams; i++) {
  1493. AVStream *st = s->streams[i];
  1494. AVIStream *ast = st->priv_data;
  1495. if (ast) {
  1496. if (ast->sub_ctx) {
  1497. av_freep(&ast->sub_ctx->pb);
  1498. avformat_close_input(&ast->sub_ctx);
  1499. }
  1500. av_free(ast->sub_buffer);
  1501. av_free_packet(&ast->sub_pkt);
  1502. }
  1503. }
  1504. av_free(avi->dv_demux);
  1505. return 0;
  1506. }
  1507. static int avi_probe(AVProbeData *p)
  1508. {
  1509. int i;
  1510. /* check file header */
  1511. for (i = 0; avi_headers[i][0]; i++)
  1512. if (!memcmp(p->buf, avi_headers[i], 4) &&
  1513. !memcmp(p->buf + 8, avi_headers[i] + 4, 4))
  1514. return AVPROBE_SCORE_MAX;
  1515. return 0;
  1516. }
  1517. AVInputFormat ff_avi_demuxer = {
  1518. .name = "avi",
  1519. .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
  1520. .priv_data_size = sizeof(AVIContext),
  1521. .read_probe = avi_probe,
  1522. .read_header = avi_read_header,
  1523. .read_packet = avi_read_packet,
  1524. .read_close = avi_read_close,
  1525. .read_seek = avi_read_seek,
  1526. .priv_class = &demuxer_class,
  1527. };