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.

1183 lines
39KB

  1. /*
  2. * AVI demuxer
  3. * Copyright (c) 2001 Fabrice Bellard
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. //#define DEBUG
  22. //#define DEBUG_SEEK
  23. #include "libavutil/intreadwrite.h"
  24. #include "libavutil/bswap.h"
  25. #include "avformat.h"
  26. #include "avi.h"
  27. #include "dv.h"
  28. #include "riff.h"
  29. #undef NDEBUG
  30. #include <assert.h>
  31. typedef struct AVIStream {
  32. int64_t frame_offset; /* current frame (video) or byte (audio) counter
  33. (used to compute the pts) */
  34. int remaining;
  35. int packet_size;
  36. int scale;
  37. int rate;
  38. int sample_size; /* size of one sample (or packet) (in the rate/scale sense) in bytes */
  39. int64_t cum_len; /* temporary storage (used during seek) */
  40. int prefix; ///< normally 'd'<<8 + 'c' or 'w'<<8 + 'b'
  41. int prefix_count;
  42. uint32_t pal[256];
  43. int has_pal;
  44. } AVIStream;
  45. typedef struct {
  46. int64_t riff_end;
  47. int64_t movi_end;
  48. int64_t fsize;
  49. int64_t movi_list;
  50. int64_t last_pkt_pos;
  51. int index_loaded;
  52. int is_odml;
  53. int non_interleaved;
  54. int stream_index;
  55. DVDemuxContext* dv_demux;
  56. } AVIContext;
  57. static const char avi_headers[][8] = {
  58. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
  59. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
  60. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19},
  61. { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
  62. { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
  63. { 0 }
  64. };
  65. static int avi_load_index(AVFormatContext *s);
  66. static int guess_ni_flag(AVFormatContext *s);
  67. #ifdef DEBUG
  68. static void print_tag(const char *str, unsigned int tag, int size)
  69. {
  70. dprintf(NULL, "%s: tag=%c%c%c%c size=0x%x\n",
  71. str, tag & 0xff,
  72. (tag >> 8) & 0xff,
  73. (tag >> 16) & 0xff,
  74. (tag >> 24) & 0xff,
  75. size);
  76. }
  77. #endif
  78. static int get_riff(AVFormatContext *s, ByteIOContext *pb)
  79. {
  80. AVIContext *avi = s->priv_data;
  81. char header[8];
  82. int i;
  83. /* check RIFF header */
  84. get_buffer(pb, header, 4);
  85. avi->riff_end = get_le32(pb); /* RIFF chunk size */
  86. avi->riff_end += url_ftell(pb); /* RIFF chunk end */
  87. get_buffer(pb, header+4, 4);
  88. for(i=0; avi_headers[i][0]; i++)
  89. if(!memcmp(header, avi_headers[i], 8))
  90. break;
  91. if(!avi_headers[i][0])
  92. return -1;
  93. if(header[7] == 0x19)
  94. av_log(s, AV_LOG_INFO, "This file has been generated by a totally broken muxer.\n");
  95. return 0;
  96. }
  97. static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
  98. AVIContext *avi = s->priv_data;
  99. ByteIOContext *pb = s->pb;
  100. int longs_pre_entry= get_le16(pb);
  101. int index_sub_type = get_byte(pb);
  102. int index_type = get_byte(pb);
  103. int entries_in_use = get_le32(pb);
  104. int chunk_id = get_le32(pb);
  105. int64_t base = get_le64(pb);
  106. int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');
  107. AVStream *st;
  108. AVIStream *ast;
  109. int i;
  110. int64_t last_pos= -1;
  111. int64_t filesize= url_fsize(s->pb);
  112. #ifdef DEBUG_SEEK
  113. av_log(s, AV_LOG_ERROR, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",
  114. longs_pre_entry,index_type, entries_in_use, chunk_id, base);
  115. #endif
  116. if(stream_id > s->nb_streams || stream_id < 0)
  117. return -1;
  118. st= s->streams[stream_id];
  119. ast = st->priv_data;
  120. if(index_sub_type)
  121. return -1;
  122. get_le32(pb);
  123. if(index_type && longs_pre_entry != 2)
  124. return -1;
  125. if(index_type>1)
  126. return -1;
  127. if(filesize > 0 && base >= filesize){
  128. av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
  129. if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF)
  130. base &= 0xFFFFFFFF;
  131. else
  132. return -1;
  133. }
  134. for(i=0; i<entries_in_use; i++){
  135. if(index_type){
  136. int64_t pos= get_le32(pb) + base - 8;
  137. int len = get_le32(pb);
  138. int key= len >= 0;
  139. len &= 0x7FFFFFFF;
  140. #ifdef DEBUG_SEEK
  141. av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
  142. #endif
  143. if(url_feof(pb))
  144. return -1;
  145. if(last_pos == pos || pos == base - 8)
  146. avi->non_interleaved= 1;
  147. if(last_pos != pos && (len || !ast->sample_size))
  148. av_add_index_entry(st, pos, ast->cum_len, len, 0, key ? AVINDEX_KEYFRAME : 0);
  149. if(ast->sample_size)
  150. ast->cum_len += len;
  151. else
  152. ast->cum_len ++;
  153. last_pos= pos;
  154. }else{
  155. int64_t offset, pos;
  156. int duration;
  157. offset = get_le64(pb);
  158. get_le32(pb); /* size */
  159. duration = get_le32(pb);
  160. if(url_feof(pb))
  161. return -1;
  162. pos = url_ftell(pb);
  163. url_fseek(pb, offset+8, SEEK_SET);
  164. read_braindead_odml_indx(s, frame_num);
  165. frame_num += duration;
  166. url_fseek(pb, pos, SEEK_SET);
  167. }
  168. }
  169. avi->index_loaded=1;
  170. return 0;
  171. }
  172. static void clean_index(AVFormatContext *s){
  173. int i;
  174. int64_t j;
  175. for(i=0; i<s->nb_streams; i++){
  176. AVStream *st = s->streams[i];
  177. AVIStream *ast = st->priv_data;
  178. int n= st->nb_index_entries;
  179. int max= ast->sample_size;
  180. int64_t pos, size, ts;
  181. if(n != 1 || ast->sample_size==0)
  182. continue;
  183. while(max < 1024) max+=max;
  184. pos= st->index_entries[0].pos;
  185. size= st->index_entries[0].size;
  186. ts= st->index_entries[0].timestamp;
  187. for(j=0; j<size; j+=max){
  188. av_add_index_entry(st, pos+j, ts+j, FFMIN(max, size-j), 0, AVINDEX_KEYFRAME);
  189. }
  190. }
  191. }
  192. static int avi_read_tag(AVFormatContext *s, const char *key, unsigned int size)
  193. {
  194. ByteIOContext *pb = s->pb;
  195. char *value;
  196. size += (size & 1);
  197. if (size == UINT_MAX)
  198. return -1;
  199. value = av_malloc(size+1);
  200. if (!value)
  201. return -1;
  202. get_strz(pb, value, size);
  203. return av_metadata_set2(&s->metadata, key, value,
  204. AV_METADATA_DONT_STRDUP_VAL);
  205. }
  206. static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
  207. {
  208. AVIContext *avi = s->priv_data;
  209. ByteIOContext *pb = s->pb;
  210. unsigned int tag, tag1, handler;
  211. int codec_type, stream_index, frame_period, bit_rate;
  212. unsigned int size, nb_frames;
  213. int i;
  214. AVStream *st;
  215. AVIStream *ast = NULL;
  216. int avih_width=0, avih_height=0;
  217. int amv_file_format=0;
  218. uint64_t list_end = 0;
  219. avi->stream_index= -1;
  220. if (get_riff(s, pb) < 0)
  221. return -1;
  222. avi->fsize = url_fsize(pb);
  223. if(avi->fsize<=0)
  224. avi->fsize= avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
  225. /* first list tag */
  226. stream_index = -1;
  227. codec_type = -1;
  228. frame_period = 0;
  229. for(;;) {
  230. if (url_feof(pb))
  231. goto fail;
  232. tag = get_le32(pb);
  233. size = get_le32(pb);
  234. #ifdef DEBUG
  235. print_tag("tag", tag, size);
  236. #endif
  237. switch(tag) {
  238. case MKTAG('L', 'I', 'S', 'T'):
  239. list_end = url_ftell(pb) + size;
  240. /* Ignored, except at start of video packets. */
  241. tag1 = get_le32(pb);
  242. #ifdef DEBUG
  243. print_tag("list", tag1, 0);
  244. #endif
  245. if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
  246. avi->movi_list = url_ftell(pb) - 4;
  247. if(size) avi->movi_end = avi->movi_list + size + (size & 1);
  248. else avi->movi_end = url_fsize(pb);
  249. dprintf(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
  250. goto end_of_header;
  251. }
  252. break;
  253. case MKTAG('d', 'm', 'l', 'h'):
  254. avi->is_odml = 1;
  255. url_fskip(pb, size + (size & 1));
  256. break;
  257. case MKTAG('a', 'm', 'v', 'h'):
  258. amv_file_format=1;
  259. case MKTAG('a', 'v', 'i', 'h'):
  260. /* AVI header */
  261. /* using frame_period is bad idea */
  262. frame_period = get_le32(pb);
  263. bit_rate = get_le32(pb) * 8;
  264. get_le32(pb);
  265. avi->non_interleaved |= get_le32(pb) & AVIF_MUSTUSEINDEX;
  266. url_fskip(pb, 2 * 4);
  267. get_le32(pb);
  268. get_le32(pb);
  269. avih_width=get_le32(pb);
  270. avih_height=get_le32(pb);
  271. url_fskip(pb, size - 10 * 4);
  272. break;
  273. case MKTAG('s', 't', 'r', 'h'):
  274. /* stream header */
  275. tag1 = get_le32(pb);
  276. handler = get_le32(pb); /* codec tag */
  277. if(tag1 == MKTAG('p', 'a', 'd', 's')){
  278. url_fskip(pb, size - 8);
  279. break;
  280. }else{
  281. stream_index++;
  282. st = av_new_stream(s, stream_index);
  283. if (!st)
  284. goto fail;
  285. ast = av_mallocz(sizeof(AVIStream));
  286. if (!ast)
  287. goto fail;
  288. st->priv_data = ast;
  289. }
  290. if(amv_file_format)
  291. tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
  292. #ifdef DEBUG
  293. print_tag("strh", tag1, -1);
  294. #endif
  295. if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
  296. int64_t dv_dur;
  297. /*
  298. * After some consideration -- I don't think we
  299. * have to support anything but DV in type1 AVIs.
  300. */
  301. if (s->nb_streams != 1)
  302. goto fail;
  303. if (handler != MKTAG('d', 'v', 's', 'd') &&
  304. handler != MKTAG('d', 'v', 'h', 'd') &&
  305. handler != MKTAG('d', 'v', 's', 'l'))
  306. goto fail;
  307. ast = s->streams[0]->priv_data;
  308. av_freep(&s->streams[0]->codec->extradata);
  309. av_freep(&s->streams[0]);
  310. s->nb_streams = 0;
  311. if (CONFIG_DV_DEMUXER) {
  312. avi->dv_demux = dv_init_demux(s);
  313. if (!avi->dv_demux)
  314. goto fail;
  315. }
  316. s->streams[0]->priv_data = ast;
  317. url_fskip(pb, 3 * 4);
  318. ast->scale = get_le32(pb);
  319. ast->rate = get_le32(pb);
  320. url_fskip(pb, 4); /* start time */
  321. dv_dur = get_le32(pb);
  322. if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
  323. dv_dur *= AV_TIME_BASE;
  324. s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
  325. }
  326. /*
  327. * else, leave duration alone; timing estimation in utils.c
  328. * will make a guess based on bitrate.
  329. */
  330. stream_index = s->nb_streams - 1;
  331. url_fskip(pb, size - 9*4);
  332. break;
  333. }
  334. assert(stream_index < s->nb_streams);
  335. st->codec->stream_codec_tag= handler;
  336. get_le32(pb); /* flags */
  337. get_le16(pb); /* priority */
  338. get_le16(pb); /* language */
  339. get_le32(pb); /* initial frame */
  340. ast->scale = get_le32(pb);
  341. ast->rate = get_le32(pb);
  342. if(!(ast->scale && ast->rate)){
  343. 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);
  344. if(frame_period){
  345. ast->rate = 1000000;
  346. ast->scale = frame_period;
  347. }else{
  348. ast->rate = 25;
  349. ast->scale = 1;
  350. }
  351. }
  352. av_set_pts_info(st, 64, ast->scale, ast->rate);
  353. ast->cum_len=get_le32(pb); /* start */
  354. nb_frames = get_le32(pb);
  355. st->start_time = 0;
  356. st->duration = nb_frames;
  357. get_le32(pb); /* buffer size */
  358. get_le32(pb); /* quality */
  359. ast->sample_size = get_le32(pb); /* sample ssize */
  360. ast->cum_len *= FFMAX(1, ast->sample_size);
  361. // av_log(s, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);
  362. switch(tag1) {
  363. case MKTAG('v', 'i', 'd', 's'):
  364. codec_type = CODEC_TYPE_VIDEO;
  365. ast->sample_size = 0;
  366. break;
  367. case MKTAG('a', 'u', 'd', 's'):
  368. codec_type = CODEC_TYPE_AUDIO;
  369. break;
  370. case MKTAG('t', 'x', 't', 's'):
  371. //FIXME
  372. codec_type = CODEC_TYPE_DATA; //CODEC_TYPE_SUB ? FIXME
  373. break;
  374. case MKTAG('d', 'a', 't', 's'):
  375. codec_type = CODEC_TYPE_DATA;
  376. break;
  377. default:
  378. av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
  379. goto fail;
  380. }
  381. ast->frame_offset= ast->cum_len;
  382. url_fskip(pb, size - 12 * 4);
  383. break;
  384. case MKTAG('s', 't', 'r', 'f'):
  385. /* stream header */
  386. if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
  387. url_fskip(pb, size);
  388. } else {
  389. uint64_t cur_pos = url_ftell(pb);
  390. if (cur_pos < list_end)
  391. size = FFMIN(size, list_end - cur_pos);
  392. st = s->streams[stream_index];
  393. switch(codec_type) {
  394. case CODEC_TYPE_VIDEO:
  395. if(amv_file_format){
  396. st->codec->width=avih_width;
  397. st->codec->height=avih_height;
  398. st->codec->codec_type = CODEC_TYPE_VIDEO;
  399. st->codec->codec_id = CODEC_ID_AMV;
  400. url_fskip(pb, size);
  401. break;
  402. }
  403. get_le32(pb); /* size */
  404. st->codec->width = get_le32(pb);
  405. st->codec->height = (int32_t)get_le32(pb);
  406. get_le16(pb); /* panes */
  407. st->codec->bits_per_coded_sample= get_le16(pb); /* depth */
  408. tag1 = get_le32(pb);
  409. get_le32(pb); /* ImageSize */
  410. get_le32(pb); /* XPelsPerMeter */
  411. get_le32(pb); /* YPelsPerMeter */
  412. get_le32(pb); /* ClrUsed */
  413. get_le32(pb); /* ClrImportant */
  414. if (tag1 == MKTAG('D', 'X', 'S', 'B')) {
  415. st->codec->codec_type = CODEC_TYPE_SUBTITLE;
  416. st->codec->codec_tag = tag1;
  417. st->codec->codec_id = CODEC_ID_XSUB;
  418. break;
  419. }
  420. if(size > 10*4 && size<(1<<30)){
  421. st->codec->extradata_size= size - 10*4;
  422. st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  423. if (!st->codec->extradata) {
  424. st->codec->extradata_size= 0;
  425. return AVERROR(ENOMEM);
  426. }
  427. get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
  428. }
  429. if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
  430. get_byte(pb);
  431. /* Extract palette from extradata if bpp <= 8. */
  432. /* This code assumes that extradata contains only palette. */
  433. /* This is true for all paletted codecs implemented in FFmpeg. */
  434. if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
  435. st->codec->palctrl = av_mallocz(sizeof(AVPaletteControl));
  436. #if HAVE_BIGENDIAN
  437. for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
  438. st->codec->palctrl->palette[i] = bswap_32(((uint32_t*)st->codec->extradata)[i]);
  439. #else
  440. memcpy(st->codec->palctrl->palette, st->codec->extradata,
  441. FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
  442. #endif
  443. st->codec->palctrl->palette_changed = 1;
  444. }
  445. #ifdef DEBUG
  446. print_tag("video", tag1, 0);
  447. #endif
  448. st->codec->codec_type = CODEC_TYPE_VIDEO;
  449. st->codec->codec_tag = tag1;
  450. st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1);
  451. st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
  452. // Support "Resolution 1:1" for Avid AVI Codec
  453. if(tag1 == MKTAG('A', 'V', 'R', 'n') &&
  454. st->codec->extradata_size >= 31 &&
  455. !memcmp(&st->codec->extradata[28], "1:1", 3))
  456. st->codec->codec_id = CODEC_ID_RAWVIDEO;
  457. if(st->codec->codec_tag==0 && st->codec->height > 0 && st->codec->extradata_size < 1U<<30){
  458. st->codec->extradata_size+= 9;
  459. st->codec->extradata= av_realloc(st->codec->extradata, st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  460. if(st->codec->extradata)
  461. memcpy(st->codec->extradata + st->codec->extradata_size - 9, "BottomUp", 9);
  462. }
  463. st->codec->height= FFABS(st->codec->height);
  464. // url_fskip(pb, size - 5 * 4);
  465. break;
  466. case CODEC_TYPE_AUDIO:
  467. ff_get_wav_header(pb, st->codec, size);
  468. if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
  469. av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
  470. ast->sample_size= st->codec->block_align;
  471. }
  472. if (size%2) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
  473. url_fskip(pb, 1);
  474. /* Force parsing as several audio frames can be in
  475. * one packet and timestamps refer to packet start. */
  476. st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
  477. /* ADTS header is in extradata, AAC without header must be
  478. * stored as exact frames. Parser not needed and it will
  479. * fail. */
  480. if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)
  481. st->need_parsing = AVSTREAM_PARSE_NONE;
  482. /* AVI files with Xan DPCM audio (wrongly) declare PCM
  483. * audio in the header but have Axan as stream_code_tag. */
  484. if (st->codec->stream_codec_tag == AV_RL32("Axan")){
  485. st->codec->codec_id = CODEC_ID_XAN_DPCM;
  486. st->codec->codec_tag = 0;
  487. }
  488. if (amv_file_format)
  489. st->codec->codec_id = CODEC_ID_ADPCM_IMA_AMV;
  490. break;
  491. default:
  492. st->codec->codec_type = CODEC_TYPE_DATA;
  493. st->codec->codec_id= CODEC_ID_NONE;
  494. st->codec->codec_tag= 0;
  495. url_fskip(pb, size);
  496. break;
  497. }
  498. }
  499. break;
  500. case MKTAG('i', 'n', 'd', 'x'):
  501. i= url_ftell(pb);
  502. if(!url_is_streamed(pb) && !(s->flags & AVFMT_FLAG_IGNIDX)){
  503. read_braindead_odml_indx(s, 0);
  504. }
  505. url_fseek(pb, i+size, SEEK_SET);
  506. break;
  507. case MKTAG('v', 'p', 'r', 'p'):
  508. if(stream_index < (unsigned)s->nb_streams && size > 9*4){
  509. AVRational active, active_aspect;
  510. st = s->streams[stream_index];
  511. get_le32(pb);
  512. get_le32(pb);
  513. get_le32(pb);
  514. get_le32(pb);
  515. get_le32(pb);
  516. active_aspect.den= get_le16(pb);
  517. active_aspect.num= get_le16(pb);
  518. active.num = get_le32(pb);
  519. active.den = get_le32(pb);
  520. get_le32(pb); //nbFieldsPerFrame
  521. if(active_aspect.num && active_aspect.den && active.num && active.den){
  522. st->sample_aspect_ratio= av_div_q(active_aspect, active);
  523. //av_log(s, AV_LOG_ERROR, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den);
  524. }
  525. size -= 9*4;
  526. }
  527. url_fseek(pb, size, SEEK_CUR);
  528. break;
  529. case MKTAG('I', 'N', 'A', 'M'):
  530. avi_read_tag(s, "Title", size);
  531. break;
  532. case MKTAG('I', 'A', 'R', 'T'):
  533. avi_read_tag(s, "Artist", size);
  534. break;
  535. case MKTAG('I', 'C', 'O', 'P'):
  536. avi_read_tag(s, "Copyright", size);
  537. break;
  538. case MKTAG('I', 'C', 'M', 'T'):
  539. avi_read_tag(s, "Comment", size);
  540. break;
  541. case MKTAG('I', 'G', 'N', 'R'):
  542. avi_read_tag(s, "Genre", size);
  543. break;
  544. case MKTAG('I', 'P', 'R', 'D'):
  545. avi_read_tag(s, "Album", size);
  546. break;
  547. case MKTAG('I', 'P', 'R', 'T'):
  548. avi_read_tag(s, "Track", size);
  549. break;
  550. default:
  551. if(size > 1000000){
  552. av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
  553. "I will ignore it and try to continue anyway.\n");
  554. avi->movi_list = url_ftell(pb) - 4;
  555. avi->movi_end = url_fsize(pb);
  556. goto end_of_header;
  557. }
  558. /* skip tag */
  559. size += (size & 1);
  560. url_fskip(pb, size);
  561. break;
  562. }
  563. }
  564. end_of_header:
  565. /* check stream number */
  566. if (stream_index != s->nb_streams - 1) {
  567. fail:
  568. return -1;
  569. }
  570. if(!avi->index_loaded && !url_is_streamed(pb))
  571. avi_load_index(s);
  572. avi->index_loaded = 1;
  573. avi->non_interleaved |= guess_ni_flag(s);
  574. if(avi->non_interleaved) {
  575. av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
  576. clean_index(s);
  577. }
  578. return 0;
  579. }
  580. static int get_stream_idx(int *d){
  581. if( d[0] >= '0' && d[0] <= '9'
  582. && d[1] >= '0' && d[1] <= '9'){
  583. return (d[0] - '0') * 10 + (d[1] - '0');
  584. }else{
  585. return 100; //invalid stream ID
  586. }
  587. }
  588. static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
  589. {
  590. AVIContext *avi = s->priv_data;
  591. ByteIOContext *pb = s->pb;
  592. int n, d[8];
  593. unsigned int size;
  594. int64_t i, sync;
  595. void* dstr;
  596. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  597. int size = dv_get_packet(avi->dv_demux, pkt);
  598. if (size >= 0)
  599. return size;
  600. }
  601. if(avi->non_interleaved){
  602. int best_stream_index = 0;
  603. AVStream *best_st= NULL;
  604. AVIStream *best_ast;
  605. int64_t best_ts= INT64_MAX;
  606. int i;
  607. for(i=0; i<s->nb_streams; i++){
  608. AVStream *st = s->streams[i];
  609. AVIStream *ast = st->priv_data;
  610. int64_t ts= ast->frame_offset;
  611. int64_t last_ts;
  612. if(!st->nb_index_entries)
  613. continue;
  614. last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
  615. if(!ast->remaining && ts > last_ts)
  616. continue;
  617. ts = av_rescale_q(ts, st->time_base, (AVRational){FFMAX(1, ast->sample_size), AV_TIME_BASE});
  618. // av_log(s, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
  619. if(ts < best_ts){
  620. best_ts= ts;
  621. best_st= st;
  622. best_stream_index= i;
  623. }
  624. }
  625. if(!best_st)
  626. return -1;
  627. best_ast = best_st->priv_data;
  628. best_ts = av_rescale_q(best_ts, (AVRational){FFMAX(1, best_ast->sample_size), AV_TIME_BASE}, best_st->time_base);
  629. if(best_ast->remaining)
  630. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
  631. else{
  632. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
  633. if(i>=0)
  634. best_ast->frame_offset= best_st->index_entries[i].timestamp;
  635. }
  636. // av_log(s, AV_LOG_DEBUG, "%d\n", i);
  637. if(i>=0){
  638. int64_t pos= best_st->index_entries[i].pos;
  639. pos += best_ast->packet_size - best_ast->remaining;
  640. url_fseek(s->pb, pos + 8, SEEK_SET);
  641. // av_log(s, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
  642. assert(best_ast->remaining <= best_ast->packet_size);
  643. avi->stream_index= best_stream_index;
  644. if(!best_ast->remaining)
  645. best_ast->packet_size=
  646. best_ast->remaining= best_st->index_entries[i].size;
  647. }
  648. }
  649. resync:
  650. if(avi->stream_index >= 0){
  651. AVStream *st= s->streams[ avi->stream_index ];
  652. AVIStream *ast= st->priv_data;
  653. int size, err;
  654. if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  655. size= INT_MAX;
  656. else if(ast->sample_size < 32)
  657. size= 64*ast->sample_size;
  658. else
  659. size= ast->sample_size;
  660. if(size > ast->remaining)
  661. size= ast->remaining;
  662. avi->last_pkt_pos= url_ftell(pb);
  663. err= av_get_packet(pb, pkt, size);
  664. if(err<0)
  665. return err;
  666. if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
  667. void *ptr= av_realloc(pkt->data, pkt->size + 4*256 + FF_INPUT_BUFFER_PADDING_SIZE);
  668. if(ptr){
  669. ast->has_pal=0;
  670. pkt->size += 4*256;
  671. pkt->data= ptr;
  672. memcpy(pkt->data + pkt->size - 4*256, ast->pal, 4*256);
  673. }else
  674. av_log(s, AV_LOG_ERROR, "Failed to append palette\n");
  675. }
  676. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  677. dstr = pkt->destruct;
  678. size = dv_produce_packet(avi->dv_demux, pkt,
  679. pkt->data, pkt->size);
  680. pkt->destruct = dstr;
  681. pkt->flags |= PKT_FLAG_KEY;
  682. } else {
  683. /* XXX: How to handle B-frames in AVI? */
  684. pkt->dts = ast->frame_offset;
  685. // pkt->dts += ast->start;
  686. if(ast->sample_size)
  687. pkt->dts /= ast->sample_size;
  688. //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);
  689. pkt->stream_index = avi->stream_index;
  690. if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
  691. AVIndexEntry *e;
  692. int index;
  693. assert(st->index_entries);
  694. index= av_index_search_timestamp(st, ast->frame_offset, 0);
  695. e= &st->index_entries[index];
  696. if(index >= 0 && e->timestamp == ast->frame_offset){
  697. if (e->flags & AVINDEX_KEYFRAME)
  698. pkt->flags |= PKT_FLAG_KEY;
  699. }
  700. } else {
  701. pkt->flags |= PKT_FLAG_KEY;
  702. }
  703. if(ast->sample_size)
  704. ast->frame_offset += pkt->size;
  705. else
  706. ast->frame_offset++;
  707. }
  708. ast->remaining -= size;
  709. if(!ast->remaining){
  710. avi->stream_index= -1;
  711. ast->packet_size= 0;
  712. }
  713. return size;
  714. }
  715. memset(d, -1, sizeof(int)*8);
  716. for(i=sync=url_ftell(pb); !url_feof(pb); i++) {
  717. int j;
  718. for(j=0; j<7; j++)
  719. d[j]= d[j+1];
  720. d[7]= get_byte(pb);
  721. size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
  722. n= get_stream_idx(d+2);
  723. //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);
  724. if(i + (uint64_t)size > avi->fsize || d[0]<0)
  725. continue;
  726. //parse ix##
  727. if( (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
  728. //parse JUNK
  729. ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
  730. ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
  731. url_fskip(pb, size);
  732. //av_log(s, AV_LOG_DEBUG, "SKIP\n");
  733. goto resync;
  734. }
  735. //parse stray LIST
  736. if(d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T'){
  737. url_fskip(pb, 4);
  738. goto resync;
  739. }
  740. n= get_stream_idx(d);
  741. if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
  742. continue;
  743. //detect ##ix chunk and skip
  744. if(d[2] == 'i' && d[3] == 'x' && n < s->nb_streams){
  745. url_fskip(pb, size);
  746. goto resync;
  747. }
  748. //parse ##dc/##wb
  749. if(n < s->nb_streams){
  750. AVStream *st;
  751. AVIStream *ast;
  752. st = s->streams[n];
  753. ast = st->priv_data;
  754. if(s->nb_streams>=2){
  755. AVStream *st1 = s->streams[1];
  756. AVIStream *ast1= st1->priv_data;
  757. //workaround for broken small-file-bug402.avi
  758. if( d[2] == 'w' && d[3] == 'b'
  759. && n==0
  760. && st ->codec->codec_type == CODEC_TYPE_VIDEO
  761. && st1->codec->codec_type == CODEC_TYPE_AUDIO
  762. && ast->prefix == 'd'*256+'c'
  763. && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
  764. ){
  765. n=1;
  766. st = st1;
  767. ast = ast1;
  768. av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
  769. }
  770. }
  771. if( (st->discard >= AVDISCARD_DEFAULT && size==0)
  772. /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & PKT_FLAG_KEY))*/ //FIXME needs a little reordering
  773. || st->discard >= AVDISCARD_ALL){
  774. if(ast->sample_size) ast->frame_offset += pkt->size;
  775. else ast->frame_offset++;
  776. url_fskip(pb, size);
  777. goto resync;
  778. }
  779. if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
  780. int k = get_byte(pb);
  781. int last = (k + get_byte(pb) - 1) & 0xFF;
  782. get_le16(pb); //flags
  783. for (; k <= last; k++)
  784. ast->pal[k] = get_be32(pb)>>8;// b + (g << 8) + (r << 16);
  785. ast->has_pal= 1;
  786. goto resync;
  787. } else if( ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
  788. d[2]*256+d[3] == ast->prefix /*||
  789. (d[2] == 'd' && d[3] == 'c') ||
  790. (d[2] == 'w' && d[3] == 'b')*/) {
  791. //av_log(s, AV_LOG_DEBUG, "OK\n");
  792. if(d[2]*256+d[3] == ast->prefix)
  793. ast->prefix_count++;
  794. else{
  795. ast->prefix= d[2]*256+d[3];
  796. ast->prefix_count= 0;
  797. }
  798. avi->stream_index= n;
  799. ast->packet_size= size + 8;
  800. ast->remaining= size;
  801. if(size || !ast->sample_size){
  802. uint64_t pos= url_ftell(pb) - 8;
  803. if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
  804. av_add_index_entry(st, pos, ast->frame_offset, size, 0, AVINDEX_KEYFRAME);
  805. }
  806. }
  807. goto resync;
  808. }
  809. }
  810. }
  811. return AVERROR_EOF;
  812. }
  813. /* XXX: We make the implicit supposition that the positions are sorted
  814. for each stream. */
  815. static int avi_read_idx1(AVFormatContext *s, int size)
  816. {
  817. AVIContext *avi = s->priv_data;
  818. ByteIOContext *pb = s->pb;
  819. int nb_index_entries, i;
  820. AVStream *st;
  821. AVIStream *ast;
  822. unsigned int index, tag, flags, pos, len;
  823. unsigned last_pos= -1;
  824. nb_index_entries = size / 16;
  825. if (nb_index_entries <= 0)
  826. return -1;
  827. /* Read the entries and sort them in each stream component. */
  828. for(i = 0; i < nb_index_entries; i++) {
  829. tag = get_le32(pb);
  830. flags = get_le32(pb);
  831. pos = get_le32(pb);
  832. len = get_le32(pb);
  833. #if defined(DEBUG_SEEK)
  834. av_log(s, AV_LOG_DEBUG, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
  835. i, tag, flags, pos, len);
  836. #endif
  837. if(i==0 && pos > avi->movi_list)
  838. avi->movi_list= 0; //FIXME better check
  839. pos += avi->movi_list;
  840. index = ((tag & 0xff) - '0') * 10;
  841. index += ((tag >> 8) & 0xff) - '0';
  842. if (index >= s->nb_streams)
  843. continue;
  844. st = s->streams[index];
  845. ast = st->priv_data;
  846. #if defined(DEBUG_SEEK)
  847. av_log(s, AV_LOG_DEBUG, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  848. #endif
  849. if(url_feof(pb))
  850. return -1;
  851. if(last_pos == pos)
  852. avi->non_interleaved= 1;
  853. else if(len || !ast->sample_size)
  854. av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  855. if(ast->sample_size)
  856. ast->cum_len += len;
  857. else
  858. ast->cum_len ++;
  859. last_pos= pos;
  860. }
  861. return 0;
  862. }
  863. static int guess_ni_flag(AVFormatContext *s){
  864. int i;
  865. int64_t last_start=0;
  866. int64_t first_end= INT64_MAX;
  867. int64_t oldpos= url_ftell(s->pb);
  868. for(i=0; i<s->nb_streams; i++){
  869. AVStream *st = s->streams[i];
  870. int n= st->nb_index_entries;
  871. unsigned int size;
  872. if(n <= 0)
  873. continue;
  874. if(n >= 2){
  875. int64_t pos= st->index_entries[0].pos;
  876. url_fseek(s->pb, pos + 4, SEEK_SET);
  877. size= get_le32(s->pb);
  878. if(pos + size > st->index_entries[1].pos)
  879. last_start= INT64_MAX;
  880. }
  881. if(st->index_entries[0].pos > last_start)
  882. last_start= st->index_entries[0].pos;
  883. if(st->index_entries[n-1].pos < first_end)
  884. first_end= st->index_entries[n-1].pos;
  885. }
  886. url_fseek(s->pb, oldpos, SEEK_SET);
  887. return last_start > first_end;
  888. }
  889. static int avi_load_index(AVFormatContext *s)
  890. {
  891. AVIContext *avi = s->priv_data;
  892. ByteIOContext *pb = s->pb;
  893. uint32_t tag, size;
  894. int64_t pos= url_ftell(pb);
  895. int ret = -1;
  896. if (url_fseek(pb, avi->movi_end, SEEK_SET) < 0)
  897. goto the_end; // maybe truncated file
  898. #ifdef DEBUG_SEEK
  899. printf("movi_end=0x%"PRIx64"\n", avi->movi_end);
  900. #endif
  901. for(;;) {
  902. if (url_feof(pb))
  903. break;
  904. tag = get_le32(pb);
  905. size = get_le32(pb);
  906. #ifdef DEBUG_SEEK
  907. printf("tag=%c%c%c%c size=0x%x\n",
  908. tag & 0xff,
  909. (tag >> 8) & 0xff,
  910. (tag >> 16) & 0xff,
  911. (tag >> 24) & 0xff,
  912. size);
  913. #endif
  914. switch(tag) {
  915. case MKTAG('i', 'd', 'x', '1'):
  916. if (avi_read_idx1(s, size) < 0)
  917. goto skip;
  918. ret = 0;
  919. goto the_end;
  920. break;
  921. default:
  922. skip:
  923. size += (size & 1);
  924. if (url_fseek(pb, size, SEEK_CUR) < 0)
  925. goto the_end; // something is wrong here
  926. break;
  927. }
  928. }
  929. the_end:
  930. url_fseek(pb, pos, SEEK_SET);
  931. return ret;
  932. }
  933. static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  934. {
  935. AVIContext *avi = s->priv_data;
  936. AVStream *st;
  937. int i, index;
  938. int64_t pos;
  939. AVIStream *ast;
  940. if (!avi->index_loaded) {
  941. /* we only load the index on demand */
  942. avi_load_index(s);
  943. avi->index_loaded = 1;
  944. }
  945. assert(stream_index>= 0);
  946. st = s->streams[stream_index];
  947. ast= st->priv_data;
  948. index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags);
  949. if(index<0)
  950. return -1;
  951. /* find the position */
  952. pos = st->index_entries[index].pos;
  953. timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
  954. // av_log(s, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
  955. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  956. /* One and only one real stream for DV in AVI, and it has video */
  957. /* offsets. Calling with other stream indexes should have failed */
  958. /* the av_index_search_timestamp call above. */
  959. assert(stream_index == 0);
  960. /* Feed the DV video stream version of the timestamp to the */
  961. /* DV demux so it can synthesize correct timestamps. */
  962. dv_offset_reset(avi->dv_demux, timestamp);
  963. url_fseek(s->pb, pos, SEEK_SET);
  964. avi->stream_index= -1;
  965. return 0;
  966. }
  967. for(i = 0; i < s->nb_streams; i++) {
  968. AVStream *st2 = s->streams[i];
  969. AVIStream *ast2 = st2->priv_data;
  970. ast2->packet_size=
  971. ast2->remaining= 0;
  972. if (st2->nb_index_entries <= 0)
  973. continue;
  974. // assert(st2->codec->block_align);
  975. assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
  976. index = av_index_search_timestamp(
  977. st2,
  978. av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
  979. flags | AVSEEK_FLAG_BACKWARD);
  980. if(index<0)
  981. index=0;
  982. if(!avi->non_interleaved){
  983. while(index>0 && st2->index_entries[index].pos > pos)
  984. index--;
  985. while(index+1 < st2->nb_index_entries && st2->index_entries[index].pos < pos)
  986. index++;
  987. }
  988. // av_log(s, AV_LOG_DEBUG, "%"PRId64" %d %"PRId64"\n", timestamp, index, st2->index_entries[index].timestamp);
  989. /* extract the current frame number */
  990. ast2->frame_offset = st2->index_entries[index].timestamp;
  991. }
  992. /* do the seek */
  993. url_fseek(s->pb, pos, SEEK_SET);
  994. avi->stream_index= -1;
  995. return 0;
  996. }
  997. static int avi_read_close(AVFormatContext *s)
  998. {
  999. int i;
  1000. AVIContext *avi = s->priv_data;
  1001. for(i=0;i<s->nb_streams;i++) {
  1002. AVStream *st = s->streams[i];
  1003. av_free(st->codec->palctrl);
  1004. }
  1005. if (avi->dv_demux)
  1006. av_free(avi->dv_demux);
  1007. return 0;
  1008. }
  1009. static int avi_probe(AVProbeData *p)
  1010. {
  1011. int i;
  1012. /* check file header */
  1013. for(i=0; avi_headers[i][0]; i++)
  1014. if(!memcmp(p->buf , avi_headers[i] , 4) &&
  1015. !memcmp(p->buf+8, avi_headers[i]+4, 4))
  1016. return AVPROBE_SCORE_MAX;
  1017. return 0;
  1018. }
  1019. AVInputFormat avi_demuxer = {
  1020. "avi",
  1021. NULL_IF_CONFIG_SMALL("AVI format"),
  1022. sizeof(AVIContext),
  1023. avi_probe,
  1024. avi_read_header,
  1025. avi_read_packet,
  1026. avi_read_close,
  1027. avi_read_seek,
  1028. };