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.

1616 lines
54KB

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