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.

1636 lines
55KB

  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);
  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. #if HAVE_BIGENDIAN
  572. for (i = 0; i < pal_size / 4; i++)
  573. ast->pal[i] = av_bswap32(((uint32_t *)pal_src)[i]);
  574. #else
  575. memcpy(ast->pal, pal_src, pal_size);
  576. #endif
  577. ast->has_pal = 1;
  578. }
  579. print_tag("video", tag1, 0);
  580. st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
  581. st->codecpar->codec_tag = tag1;
  582. st->codecpar->codec_id = ff_codec_get_id(ff_codec_bmp_tags,
  583. tag1);
  584. /* If codec is not found yet, try with the mov tags. */
  585. if (!st->codecpar->codec_id) {
  586. char tag_buf[32];
  587. av_get_codec_tag_string(tag_buf, sizeof(tag_buf), tag1);
  588. st->codecpar->codec_id =
  589. ff_codec_get_id(ff_codec_movvideo_tags, tag1);
  590. if (st->codecpar->codec_id)
  591. av_log(s, AV_LOG_WARNING,
  592. "mov tag found in avi (fourcc %s)\n",
  593. tag_buf);
  594. }
  595. /* This is needed to get the pict type which is necessary
  596. * for generating correct pts. */
  597. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  598. if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4 &&
  599. ast->handler == MKTAG('X', 'V', 'I', 'D'))
  600. st->codecpar->codec_tag = MKTAG('X', 'V', 'I', 'D');
  601. // Support "Resolution 1:1" for Avid AVI Codec
  602. if (tag1 == MKTAG('A', 'V', 'R', 'n') &&
  603. st->codecpar->extradata_size >= 31 &&
  604. !memcmp(&st->codecpar->extradata[28], "1:1", 3))
  605. st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
  606. if (st->codecpar->codec_tag == 0 && st->codecpar->height > 0 &&
  607. st->codecpar->extradata_size < 1U << 30) {
  608. st->codecpar->extradata_size += 9;
  609. if ((ret = av_reallocp(&st->codecpar->extradata,
  610. st->codecpar->extradata_size +
  611. AV_INPUT_BUFFER_PADDING_SIZE)) < 0) {
  612. st->codecpar->extradata_size = 0;
  613. return ret;
  614. } else
  615. memcpy(st->codecpar->extradata + st->codecpar->extradata_size - 9,
  616. "BottomUp", 9);
  617. }
  618. st->codecpar->height = FFABS(st->codecpar->height);
  619. // avio_skip(pb, size - 5 * 4);
  620. break;
  621. case AVMEDIA_TYPE_AUDIO:
  622. ret = ff_get_wav_header(s, pb, st->codecpar, size);
  623. if (ret < 0)
  624. return ret;
  625. ast->dshow_block_align = st->codecpar->block_align;
  626. if (ast->sample_size && st->codecpar->block_align &&
  627. ast->sample_size != st->codecpar->block_align) {
  628. av_log(s,
  629. AV_LOG_WARNING,
  630. "sample size (%d) != block align (%d)\n",
  631. ast->sample_size,
  632. st->codecpar->block_align);
  633. ast->sample_size = st->codecpar->block_align;
  634. }
  635. /* 2-aligned
  636. * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
  637. if (size & 1)
  638. avio_skip(pb, 1);
  639. /* Force parsing as several audio frames can be in
  640. * one packet and timestamps refer to packet start. */
  641. st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
  642. /* ADTS header is in extradata, AAC without header must be
  643. * stored as exact frames. Parser not needed and it will
  644. * fail. */
  645. if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
  646. st->codecpar->extradata_size)
  647. st->need_parsing = AVSTREAM_PARSE_NONE;
  648. /* AVI files with Xan DPCM audio (wrongly) declare PCM
  649. * audio in the header but have Axan as stream_code_tag. */
  650. if (ast->handler == AV_RL32("Axan")) {
  651. st->codecpar->codec_id = AV_CODEC_ID_XAN_DPCM;
  652. st->codecpar->codec_tag = 0;
  653. }
  654. if (amv_file_format) {
  655. st->codecpar->codec_id = AV_CODEC_ID_ADPCM_IMA_AMV;
  656. ast->dshow_block_align = 0;
  657. }
  658. break;
  659. case AVMEDIA_TYPE_SUBTITLE:
  660. st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
  661. st->codecpar->codec_id = AV_CODEC_ID_PROBE;
  662. break;
  663. default:
  664. st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  665. st->codecpar->codec_id = AV_CODEC_ID_NONE;
  666. st->codecpar->codec_tag = 0;
  667. avio_skip(pb, size);
  668. break;
  669. }
  670. }
  671. break;
  672. case MKTAG('i', 'n', 'd', 'x'):
  673. pos = avio_tell(pb);
  674. if (pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) &&
  675. read_braindead_odml_indx(s, 0) < 0 &&
  676. (s->error_recognition & AV_EF_EXPLODE))
  677. goto fail;
  678. avio_seek(pb, pos + size, SEEK_SET);
  679. break;
  680. case MKTAG('v', 'p', 'r', 'p'):
  681. if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) {
  682. AVRational active, active_aspect;
  683. st = s->streams[stream_index];
  684. avio_rl32(pb);
  685. avio_rl32(pb);
  686. avio_rl32(pb);
  687. avio_rl32(pb);
  688. avio_rl32(pb);
  689. active_aspect.den = avio_rl16(pb);
  690. active_aspect.num = avio_rl16(pb);
  691. active.num = avio_rl32(pb);
  692. active.den = avio_rl32(pb);
  693. avio_rl32(pb); // nbFieldsPerFrame
  694. if (active_aspect.num && active_aspect.den &&
  695. active.num && active.den) {
  696. st->sample_aspect_ratio = av_div_q(active_aspect, active);
  697. av_log(s, AV_LOG_TRACE, "vprp %d/%d %d/%d\n",
  698. active_aspect.num, active_aspect.den,
  699. active.num, active.den);
  700. }
  701. size -= 9 * 4;
  702. }
  703. avio_skip(pb, size);
  704. break;
  705. case MKTAG('s', 't', 'r', 'n'):
  706. if (s->nb_streams) {
  707. ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size);
  708. if (ret < 0)
  709. return ret;
  710. break;
  711. }
  712. default:
  713. if (size > 1000000) {
  714. av_log(s, AV_LOG_ERROR,
  715. "Something went wrong during header parsing, "
  716. "I will ignore it and try to continue anyway.\n");
  717. if (s->error_recognition & AV_EF_EXPLODE)
  718. goto fail;
  719. avi->movi_list = avio_tell(pb) - 4;
  720. avi->movi_end = avi->fsize;
  721. goto end_of_header;
  722. }
  723. /* skip tag */
  724. size += (size & 1);
  725. avio_skip(pb, size);
  726. break;
  727. }
  728. }
  729. end_of_header:
  730. /* check stream number */
  731. if (stream_index != s->nb_streams - 1) {
  732. fail:
  733. return AVERROR_INVALIDDATA;
  734. }
  735. if (!avi->index_loaded && pb->seekable)
  736. avi_load_index(s);
  737. avi->index_loaded = 1;
  738. if ((ret = guess_ni_flag(s)) < 0)
  739. return ret;
  740. avi->non_interleaved |= ret;
  741. for (i = 0; i < s->nb_streams; i++) {
  742. AVStream *st = s->streams[i];
  743. if (st->nb_index_entries)
  744. break;
  745. }
  746. if (i == s->nb_streams && avi->non_interleaved) {
  747. av_log(s, AV_LOG_WARNING,
  748. "Non-interleaved AVI without index, switching to interleaved\n");
  749. avi->non_interleaved = 0;
  750. }
  751. if (avi->non_interleaved) {
  752. av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
  753. clean_index(s);
  754. }
  755. ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
  756. ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
  757. return 0;
  758. }
  759. static int read_gab2_sub(AVStream *st, AVPacket *pkt)
  760. {
  761. if (pkt->size >= 7 &&
  762. !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
  763. uint8_t desc[256];
  764. int score = AVPROBE_SCORE_EXTENSION, ret;
  765. AVIStream *ast = st->priv_data;
  766. AVInputFormat *sub_demuxer;
  767. AVRational time_base;
  768. AVIOContext *pb = avio_alloc_context(pkt->data + 7,
  769. pkt->size - 7,
  770. 0, NULL, NULL, NULL, NULL);
  771. AVProbeData pd;
  772. unsigned int desc_len = avio_rl32(pb);
  773. if (desc_len > pb->buf_end - pb->buf_ptr)
  774. goto error;
  775. ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
  776. avio_skip(pb, desc_len - ret);
  777. if (*desc)
  778. av_dict_set(&st->metadata, "title", desc, 0);
  779. avio_rl16(pb); /* flags? */
  780. avio_rl32(pb); /* data size */
  781. pd = (AVProbeData) { .buf = pb->buf_ptr,
  782. .buf_size = pb->buf_end - pb->buf_ptr };
  783. if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
  784. goto error;
  785. if (!(ast->sub_ctx = avformat_alloc_context()))
  786. goto error;
  787. ast->sub_ctx->pb = pb;
  788. if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
  789. ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
  790. avcodec_parameters_copy(st->codecpar, ast->sub_ctx->streams[0]->codecpar);
  791. time_base = ast->sub_ctx->streams[0]->time_base;
  792. avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
  793. }
  794. ast->sub_buffer = pkt->data;
  795. memset(pkt, 0, sizeof(*pkt));
  796. return 1;
  797. error:
  798. av_freep(&pb);
  799. }
  800. return 0;
  801. }
  802. static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
  803. AVPacket *pkt)
  804. {
  805. AVIStream *ast, *next_ast = next_st->priv_data;
  806. int64_t ts, next_ts, ts_min = INT64_MAX;
  807. AVStream *st, *sub_st = NULL;
  808. int i;
  809. next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
  810. AV_TIME_BASE_Q);
  811. for (i = 0; i < s->nb_streams; i++) {
  812. st = s->streams[i];
  813. ast = st->priv_data;
  814. if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
  815. ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
  816. if (ts <= next_ts && ts < ts_min) {
  817. ts_min = ts;
  818. sub_st = st;
  819. }
  820. }
  821. }
  822. if (sub_st) {
  823. ast = sub_st->priv_data;
  824. *pkt = ast->sub_pkt;
  825. pkt->stream_index = sub_st->index;
  826. if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
  827. ast->sub_pkt.data = NULL;
  828. }
  829. return sub_st;
  830. }
  831. static int get_stream_idx(int *d)
  832. {
  833. if (d[0] >= '0' && d[0] <= '9' &&
  834. d[1] >= '0' && d[1] <= '9') {
  835. return (d[0] - '0') * 10 + (d[1] - '0');
  836. } else {
  837. return 100; // invalid stream ID
  838. }
  839. }
  840. static int avi_sync(AVFormatContext *s, int exit_early)
  841. {
  842. AVIContext *avi = s->priv_data;
  843. AVIOContext *pb = s->pb;
  844. int n;
  845. unsigned int d[8];
  846. unsigned int size;
  847. int64_t i, sync;
  848. start_sync:
  849. memset(d, -1, sizeof(d));
  850. for (i = sync = avio_tell(pb); !pb->eof_reached; i++) {
  851. int j;
  852. for (j = 0; j < 7; j++)
  853. d[j] = d[j + 1];
  854. d[7] = avio_r8(pb);
  855. size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24);
  856. n = get_stream_idx(d + 2);
  857. av_log(s, AV_LOG_TRACE, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
  858. d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
  859. if (i + (uint64_t)size > avi->fsize || d[0] > 127)
  860. continue;
  861. // parse ix##
  862. if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) ||
  863. // parse JUNK
  864. (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') ||
  865. (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')) {
  866. avio_skip(pb, size);
  867. goto start_sync;
  868. }
  869. // parse stray LIST
  870. if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') {
  871. avio_skip(pb, 4);
  872. goto start_sync;
  873. }
  874. n = get_stream_idx(d);
  875. if (!((i - avi->last_pkt_pos) & 1) &&
  876. get_stream_idx(d + 1) < s->nb_streams)
  877. continue;
  878. // detect ##ix chunk and skip
  879. if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) {
  880. avio_skip(pb, size);
  881. goto start_sync;
  882. }
  883. if (avi->dv_demux && n != 0)
  884. continue;
  885. // parse ##dc/##wb
  886. if (n < s->nb_streams) {
  887. AVStream *st;
  888. AVIStream *ast;
  889. st = s->streams[n];
  890. ast = st->priv_data;
  891. if (s->nb_streams >= 2) {
  892. AVStream *st1 = s->streams[1];
  893. AVIStream *ast1 = st1->priv_data;
  894. // workaround for broken small-file-bug402.avi
  895. if (d[2] == 'w' && d[3] == 'b' && n == 0 &&
  896. st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
  897. st1->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
  898. ast->prefix == 'd' * 256 + 'c' &&
  899. (d[2] * 256 + d[3] == ast1->prefix ||
  900. !ast1->prefix_count)) {
  901. n = 1;
  902. st = st1;
  903. ast = ast1;
  904. av_log(s, AV_LOG_WARNING,
  905. "Invalid stream + prefix combination, assuming audio.\n");
  906. }
  907. }
  908. if (!avi->dv_demux &&
  909. ((st->discard >= AVDISCARD_DEFAULT && size == 0) /* ||
  910. // FIXME: needs a little reordering
  911. (st->discard >= AVDISCARD_NONKEY &&
  912. !(pkt->flags & AV_PKT_FLAG_KEY)) */
  913. || st->discard >= AVDISCARD_ALL)) {
  914. if (!exit_early) {
  915. ast->frame_offset += get_duration(ast, size);
  916. }
  917. avio_skip(pb, size);
  918. goto start_sync;
  919. }
  920. if (d[2] == 'p' && d[3] == 'c' && size <= 4 * 256 + 4) {
  921. int k = avio_r8(pb);
  922. int last = (k + avio_r8(pb) - 1) & 0xFF;
  923. avio_rl16(pb); // flags
  924. // b + (g << 8) + (r << 16);
  925. for (; k <= last; k++)
  926. ast->pal[k] = avio_rb32(pb) >> 8;
  927. ast->has_pal = 1;
  928. goto start_sync;
  929. } else if (((ast->prefix_count < 5 || sync + 9 > i) &&
  930. d[2] < 128 && d[3] < 128) ||
  931. d[2] * 256 + d[3] == ast->prefix /* ||
  932. (d[2] == 'd' && d[3] == 'c') ||
  933. (d[2] == 'w' && d[3] == 'b') */) {
  934. if (exit_early)
  935. return 0;
  936. if (d[2] * 256 + d[3] == ast->prefix)
  937. ast->prefix_count++;
  938. else {
  939. ast->prefix = d[2] * 256 + d[3];
  940. ast->prefix_count = 0;
  941. }
  942. avi->stream_index = n;
  943. ast->packet_size = size + 8;
  944. ast->remaining = size;
  945. if (size || !ast->sample_size) {
  946. uint64_t pos = avio_tell(pb) - 8;
  947. if (!st->index_entries || !st->nb_index_entries ||
  948. st->index_entries[st->nb_index_entries - 1].pos < pos) {
  949. av_add_index_entry(st, pos, ast->frame_offset, size,
  950. 0, AVINDEX_KEYFRAME);
  951. }
  952. }
  953. return 0;
  954. }
  955. }
  956. }
  957. return AVERROR_EOF;
  958. }
  959. static int ni_prepare_read(AVFormatContext *s)
  960. {
  961. AVIContext *avi = s->priv_data;
  962. int best_stream_index = 0;
  963. AVStream *best_st = NULL;
  964. AVIStream *best_ast;
  965. int64_t best_ts = INT64_MAX;
  966. int i;
  967. for (i = 0; i < s->nb_streams; i++) {
  968. AVStream *st = s->streams[i];
  969. AVIStream *ast = st->priv_data;
  970. int64_t ts = ast->frame_offset;
  971. int64_t last_ts;
  972. if (!st->nb_index_entries)
  973. continue;
  974. last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
  975. if (!ast->remaining && ts > last_ts)
  976. continue;
  977. ts = av_rescale_q(ts, st->time_base,
  978. (AVRational) { FFMAX(1, ast->sample_size),
  979. AV_TIME_BASE });
  980. av_log(s, AV_LOG_TRACE, "%"PRId64" %d/%d %"PRId64"\n", ts,
  981. st->time_base.num, st->time_base.den, ast->frame_offset);
  982. if (ts < best_ts) {
  983. best_ts = ts;
  984. best_st = st;
  985. best_stream_index = i;
  986. }
  987. }
  988. if (!best_st)
  989. return AVERROR_EOF;
  990. best_ast = best_st->priv_data;
  991. best_ts = av_rescale_q(best_ts,
  992. (AVRational) { FFMAX(1, best_ast->sample_size),
  993. AV_TIME_BASE },
  994. best_st->time_base);
  995. if (best_ast->remaining) {
  996. i = av_index_search_timestamp(best_st,
  997. best_ts,
  998. AVSEEK_FLAG_ANY |
  999. AVSEEK_FLAG_BACKWARD);
  1000. } else {
  1001. i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
  1002. if (i >= 0)
  1003. best_ast->frame_offset = best_st->index_entries[i].timestamp;
  1004. }
  1005. if (i >= 0) {
  1006. int64_t pos = best_st->index_entries[i].pos;
  1007. pos += best_ast->packet_size - best_ast->remaining;
  1008. avio_seek(s->pb, pos + 8, SEEK_SET);
  1009. assert(best_ast->remaining <= best_ast->packet_size);
  1010. avi->stream_index = best_stream_index;
  1011. if (!best_ast->remaining)
  1012. best_ast->packet_size =
  1013. best_ast->remaining = best_st->index_entries[i].size;
  1014. }
  1015. return 0;
  1016. }
  1017. static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
  1018. {
  1019. AVIContext *avi = s->priv_data;
  1020. AVIOContext *pb = s->pb;
  1021. int err;
  1022. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1023. int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
  1024. if (size >= 0)
  1025. return size;
  1026. else
  1027. goto resync;
  1028. }
  1029. if (avi->non_interleaved) {
  1030. err = ni_prepare_read(s);
  1031. if (err < 0)
  1032. return err;
  1033. }
  1034. resync:
  1035. if (avi->stream_index >= 0) {
  1036. AVStream *st = s->streams[avi->stream_index];
  1037. AVIStream *ast = st->priv_data;
  1038. int size, err;
  1039. if (get_subtitle_pkt(s, st, pkt))
  1040. return 0;
  1041. // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  1042. if (ast->sample_size <= 1)
  1043. size = INT_MAX;
  1044. else if (ast->sample_size < 32)
  1045. // arbitrary multiplier to avoid tiny packets for raw PCM data
  1046. size = 1024 * ast->sample_size;
  1047. else
  1048. size = ast->sample_size;
  1049. if (size > ast->remaining)
  1050. size = ast->remaining;
  1051. avi->last_pkt_pos = avio_tell(pb);
  1052. err = av_get_packet(pb, pkt, size);
  1053. if (err < 0)
  1054. return err;
  1055. if (ast->has_pal && pkt->data && pkt->size < (unsigned)INT_MAX / 2) {
  1056. uint8_t *pal;
  1057. pal = av_packet_new_side_data(pkt,
  1058. AV_PKT_DATA_PALETTE,
  1059. AVPALETTE_SIZE);
  1060. if (!pal) {
  1061. av_log(s, AV_LOG_ERROR,
  1062. "Failed to allocate data for palette\n");
  1063. } else {
  1064. memcpy(pal, ast->pal, AVPALETTE_SIZE);
  1065. ast->has_pal = 0;
  1066. }
  1067. }
  1068. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1069. AVBufferRef *avbuf = pkt->buf;
  1070. size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
  1071. pkt->data, pkt->size);
  1072. pkt->buf = avbuf;
  1073. pkt->flags |= AV_PKT_FLAG_KEY;
  1074. if (size < 0)
  1075. av_packet_unref(pkt);
  1076. } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE &&
  1077. !st->codecpar->codec_tag && read_gab2_sub(st, pkt)) {
  1078. ast->frame_offset++;
  1079. avi->stream_index = -1;
  1080. ast->remaining = 0;
  1081. goto resync;
  1082. } else {
  1083. /* XXX: How to handle B-frames in AVI? */
  1084. pkt->dts = ast->frame_offset;
  1085. // pkt->dts += ast->start;
  1086. if (ast->sample_size)
  1087. pkt->dts /= ast->sample_size;
  1088. av_log(s, AV_LOG_TRACE,
  1089. "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d "
  1090. "base:%d st:%d size:%d\n",
  1091. pkt->dts,
  1092. ast->frame_offset,
  1093. ast->scale,
  1094. ast->rate,
  1095. ast->sample_size,
  1096. AV_TIME_BASE,
  1097. avi->stream_index,
  1098. size);
  1099. pkt->stream_index = avi->stream_index;
  1100. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  1101. AVIndexEntry *e;
  1102. int index;
  1103. assert(st->index_entries);
  1104. index = av_index_search_timestamp(st, ast->frame_offset, 0);
  1105. e = &st->index_entries[index];
  1106. if (index >= 0 && e->timestamp == ast->frame_offset)
  1107. if (e->flags & AVINDEX_KEYFRAME)
  1108. pkt->flags |= AV_PKT_FLAG_KEY;
  1109. } else {
  1110. pkt->flags |= AV_PKT_FLAG_KEY;
  1111. }
  1112. ast->frame_offset += get_duration(ast, pkt->size);
  1113. }
  1114. ast->remaining -= err;
  1115. if (!ast->remaining) {
  1116. avi->stream_index = -1;
  1117. ast->packet_size = 0;
  1118. }
  1119. return 0;
  1120. }
  1121. if ((err = avi_sync(s, 0)) < 0)
  1122. return err;
  1123. goto resync;
  1124. }
  1125. /* XXX: We make the implicit supposition that the positions are sorted
  1126. * for each stream. */
  1127. static int avi_read_idx1(AVFormatContext *s, int size)
  1128. {
  1129. AVIContext *avi = s->priv_data;
  1130. AVIOContext *pb = s->pb;
  1131. int nb_index_entries, i;
  1132. AVStream *st;
  1133. AVIStream *ast;
  1134. unsigned int index, tag, flags, pos, len, first_packet = 1;
  1135. unsigned last_pos = -1;
  1136. int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
  1137. nb_index_entries = size / 16;
  1138. if (nb_index_entries <= 0)
  1139. return AVERROR_INVALIDDATA;
  1140. idx1_pos = avio_tell(pb);
  1141. avio_seek(pb, avi->movi_list + 4, SEEK_SET);
  1142. if (avi_sync(s, 1) == 0)
  1143. first_packet_pos = avio_tell(pb) - 8;
  1144. avi->stream_index = -1;
  1145. avio_seek(pb, idx1_pos, SEEK_SET);
  1146. /* Read the entries and sort them in each stream component. */
  1147. for (i = 0; i < nb_index_entries; i++) {
  1148. tag = avio_rl32(pb);
  1149. flags = avio_rl32(pb);
  1150. pos = avio_rl32(pb);
  1151. len = avio_rl32(pb);
  1152. av_log(s, AV_LOG_TRACE, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
  1153. i, tag, flags, pos, len);
  1154. index = ((tag & 0xff) - '0') * 10;
  1155. index += (tag >> 8 & 0xff) - '0';
  1156. if (index >= s->nb_streams)
  1157. continue;
  1158. st = s->streams[index];
  1159. ast = st->priv_data;
  1160. if (first_packet && first_packet_pos && len) {
  1161. data_offset = first_packet_pos - pos;
  1162. first_packet = 0;
  1163. }
  1164. pos += data_offset;
  1165. av_log(s, AV_LOG_TRACE, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  1166. if (pb->eof_reached)
  1167. return AVERROR_INVALIDDATA;
  1168. if (last_pos == pos)
  1169. avi->non_interleaved = 1;
  1170. else if (len || !ast->sample_size)
  1171. av_add_index_entry(st, pos, ast->cum_len, len, 0,
  1172. (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  1173. ast->cum_len += get_duration(ast, len);
  1174. last_pos = pos;
  1175. }
  1176. return 0;
  1177. }
  1178. /* Scan the index and consider any file with streams more than
  1179. * 2 seconds or 64MB apart non-interleaved. */
  1180. static int check_stream_max_drift(AVFormatContext *s)
  1181. {
  1182. int64_t min_pos, pos;
  1183. int i;
  1184. int *idx = av_mallocz_array(s->nb_streams, sizeof(*idx));
  1185. if (!idx)
  1186. return AVERROR(ENOMEM);
  1187. for (min_pos = pos = 0; min_pos != INT64_MAX; pos = min_pos + 1LU) {
  1188. int64_t max_dts = INT64_MIN / 2;
  1189. int64_t min_dts = INT64_MAX / 2;
  1190. int64_t max_buffer = 0;
  1191. min_pos = INT64_MAX;
  1192. for (i = 0; i < s->nb_streams; i++) {
  1193. AVStream *st = s->streams[i];
  1194. AVIStream *ast = st->priv_data;
  1195. int n = st->nb_index_entries;
  1196. while (idx[i] < n && st->index_entries[idx[i]].pos < pos)
  1197. idx[i]++;
  1198. if (idx[i] < n) {
  1199. int64_t dts;
  1200. dts = av_rescale_q(st->index_entries[idx[i]].timestamp /
  1201. FFMAX(ast->sample_size, 1),
  1202. st->time_base, AV_TIME_BASE_Q);
  1203. min_dts = FFMIN(min_dts, dts);
  1204. min_pos = FFMIN(min_pos, st->index_entries[idx[i]].pos);
  1205. }
  1206. }
  1207. for (i = 0; i < s->nb_streams; i++) {
  1208. AVStream *st = s->streams[i];
  1209. AVIStream *ast = st->priv_data;
  1210. if (idx[i] && min_dts != INT64_MAX / 2) {
  1211. int64_t dts;
  1212. dts = av_rescale_q(st->index_entries[idx[i] - 1].timestamp /
  1213. FFMAX(ast->sample_size, 1),
  1214. st->time_base, AV_TIME_BASE_Q);
  1215. max_dts = FFMAX(max_dts, dts);
  1216. max_buffer = FFMAX(max_buffer,
  1217. av_rescale(dts - min_dts,
  1218. st->codecpar->bit_rate,
  1219. AV_TIME_BASE));
  1220. }
  1221. }
  1222. if (max_dts - min_dts > 2 * AV_TIME_BASE ||
  1223. max_buffer > 1024 * 1024 * 8 * 8) {
  1224. av_free(idx);
  1225. return 1;
  1226. }
  1227. }
  1228. av_free(idx);
  1229. return 0;
  1230. }
  1231. static int guess_ni_flag(AVFormatContext *s)
  1232. {
  1233. int i;
  1234. int64_t last_start = 0;
  1235. int64_t first_end = INT64_MAX;
  1236. int64_t oldpos = avio_tell(s->pb);
  1237. for (i = 0; i < s->nb_streams; i++) {
  1238. AVStream *st = s->streams[i];
  1239. int n = st->nb_index_entries;
  1240. unsigned int size;
  1241. if (n <= 0)
  1242. continue;
  1243. if (n >= 2) {
  1244. int64_t pos = st->index_entries[0].pos;
  1245. avio_seek(s->pb, pos + 4, SEEK_SET);
  1246. size = avio_rl32(s->pb);
  1247. if (pos + size > st->index_entries[1].pos)
  1248. last_start = INT64_MAX;
  1249. }
  1250. if (st->index_entries[0].pos > last_start)
  1251. last_start = st->index_entries[0].pos;
  1252. if (st->index_entries[n - 1].pos < first_end)
  1253. first_end = st->index_entries[n - 1].pos;
  1254. }
  1255. avio_seek(s->pb, oldpos, SEEK_SET);
  1256. if (last_start > first_end)
  1257. return 1;
  1258. return check_stream_max_drift(s);
  1259. }
  1260. static int avi_load_index(AVFormatContext *s)
  1261. {
  1262. AVIContext *avi = s->priv_data;
  1263. AVIOContext *pb = s->pb;
  1264. uint32_t tag, size;
  1265. int64_t pos = avio_tell(pb);
  1266. int ret = -1;
  1267. if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
  1268. goto the_end; // maybe truncated file
  1269. av_log(s, AV_LOG_TRACE, "movi_end=0x%"PRIx64"\n", avi->movi_end);
  1270. for (;;) {
  1271. if (pb->eof_reached)
  1272. break;
  1273. tag = avio_rl32(pb);
  1274. size = avio_rl32(pb);
  1275. av_log(s, AV_LOG_TRACE, "tag=%c%c%c%c size=0x%x\n",
  1276. tag & 0xff,
  1277. (tag >> 8) & 0xff,
  1278. (tag >> 16) & 0xff,
  1279. (tag >> 24) & 0xff,
  1280. size);
  1281. if (tag == MKTAG('i', 'd', 'x', '1') &&
  1282. avi_read_idx1(s, size) >= 0) {
  1283. ret = 0;
  1284. break;
  1285. }
  1286. size += (size & 1);
  1287. if (avio_skip(pb, size) < 0)
  1288. break; // something is wrong here
  1289. }
  1290. the_end:
  1291. avio_seek(pb, pos, SEEK_SET);
  1292. return ret;
  1293. }
  1294. static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
  1295. {
  1296. AVIStream *ast2 = st2->priv_data;
  1297. int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
  1298. av_packet_unref(&ast2->sub_pkt);
  1299. if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
  1300. avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
  1301. ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
  1302. }
  1303. static int avi_read_seek(AVFormatContext *s, int stream_index,
  1304. int64_t timestamp, int flags)
  1305. {
  1306. AVIContext *avi = s->priv_data;
  1307. AVStream *st;
  1308. int i, index;
  1309. int64_t pos;
  1310. AVIStream *ast;
  1311. /* Does not matter which stream is requested dv in avi has the
  1312. * stream information in the first video stream.
  1313. */
  1314. if (avi->dv_demux)
  1315. stream_index = 0;
  1316. if (!avi->index_loaded) {
  1317. /* we only load the index on demand */
  1318. avi_load_index(s);
  1319. avi->index_loaded = 1;
  1320. }
  1321. st = s->streams[stream_index];
  1322. ast = st->priv_data;
  1323. index = av_index_search_timestamp(st,
  1324. timestamp * FFMAX(ast->sample_size, 1),
  1325. flags);
  1326. if (index < 0)
  1327. return AVERROR_INVALIDDATA;
  1328. /* find the position */
  1329. pos = st->index_entries[index].pos;
  1330. timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
  1331. av_log(s, AV_LOG_TRACE, "XX %"PRId64" %d %"PRId64"\n",
  1332. timestamp, index, st->index_entries[index].timestamp);
  1333. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1334. /* One and only one real stream for DV in AVI, and it has video */
  1335. /* offsets. Calling with other stream indexes should have failed */
  1336. /* the av_index_search_timestamp call above. */
  1337. /* Feed the DV video stream version of the timestamp to the */
  1338. /* DV demux so it can synthesize correct timestamps. */
  1339. ff_dv_offset_reset(avi->dv_demux, timestamp);
  1340. avio_seek(s->pb, pos, SEEK_SET);
  1341. avi->stream_index = -1;
  1342. return 0;
  1343. }
  1344. for (i = 0; i < s->nb_streams; i++) {
  1345. AVStream *st2 = s->streams[i];
  1346. AVIStream *ast2 = st2->priv_data;
  1347. ast2->packet_size =
  1348. ast2->remaining = 0;
  1349. if (ast2->sub_ctx) {
  1350. seek_subtitle(st, st2, timestamp);
  1351. continue;
  1352. }
  1353. if (st2->nb_index_entries <= 0)
  1354. continue;
  1355. // assert(st2->codecpar->block_align);
  1356. assert((int64_t)st2->time_base.num * ast2->rate ==
  1357. (int64_t)st2->time_base.den * ast2->scale);
  1358. index = av_index_search_timestamp(st2,
  1359. av_rescale_q(timestamp,
  1360. st->time_base,
  1361. st2->time_base) *
  1362. FFMAX(ast2->sample_size, 1),
  1363. flags | AVSEEK_FLAG_BACKWARD);
  1364. if (index < 0)
  1365. index = 0;
  1366. if (!avi->non_interleaved) {
  1367. while (index > 0 && st2->index_entries[index].pos > pos)
  1368. index--;
  1369. while (index + 1 < st2->nb_index_entries &&
  1370. st2->index_entries[index].pos < pos)
  1371. index++;
  1372. }
  1373. av_log(s, AV_LOG_TRACE, "%"PRId64" %d %"PRId64"\n",
  1374. timestamp, index, st2->index_entries[index].timestamp);
  1375. /* extract the current frame number */
  1376. ast2->frame_offset = st2->index_entries[index].timestamp;
  1377. }
  1378. /* do the seek */
  1379. avio_seek(s->pb, pos, SEEK_SET);
  1380. avi->stream_index = -1;
  1381. return 0;
  1382. }
  1383. static int avi_read_close(AVFormatContext *s)
  1384. {
  1385. int i;
  1386. AVIContext *avi = s->priv_data;
  1387. for (i = 0; i < s->nb_streams; i++) {
  1388. AVStream *st = s->streams[i];
  1389. AVIStream *ast = st->priv_data;
  1390. if (ast) {
  1391. if (ast->sub_ctx) {
  1392. av_freep(&ast->sub_ctx->pb);
  1393. avformat_close_input(&ast->sub_ctx);
  1394. }
  1395. av_free(ast->sub_buffer);
  1396. av_packet_unref(&ast->sub_pkt);
  1397. }
  1398. }
  1399. av_free(avi->dv_demux);
  1400. return 0;
  1401. }
  1402. static int avi_probe(AVProbeData *p)
  1403. {
  1404. int i;
  1405. /* check file header */
  1406. for (i = 0; avi_headers[i][0]; i++)
  1407. if (!memcmp(p->buf, avi_headers[i], 4) &&
  1408. !memcmp(p->buf + 8, avi_headers[i] + 4, 4))
  1409. return AVPROBE_SCORE_MAX;
  1410. return 0;
  1411. }
  1412. AVInputFormat ff_avi_demuxer = {
  1413. .name = "avi",
  1414. .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
  1415. .priv_data_size = sizeof(AVIContext),
  1416. .extensions = "avi",
  1417. .read_probe = avi_probe,
  1418. .read_header = avi_read_header,
  1419. .read_packet = avi_read_packet,
  1420. .read_close = avi_read_close,
  1421. .read_seek = avi_read_seek,
  1422. };