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.

1591 lines
54KB

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