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.

1488 lines
50KB

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