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.

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