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.

1404 lines
47KB

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