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.

1024 lines
37KB

  1. /*
  2. * AVI muxer
  3. * Copyright (c) 2000 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 <math.h>
  22. #include "avformat.h"
  23. #include "internal.h"
  24. #include "avi.h"
  25. #include "avio_internal.h"
  26. #include "riff.h"
  27. #include "mpegts.h"
  28. #include "libavformat/avlanguage.h"
  29. #include "libavutil/avstring.h"
  30. #include "libavutil/avutil.h"
  31. #include "libavutil/internal.h"
  32. #include "libavutil/dict.h"
  33. #include "libavutil/avassert.h"
  34. #include "libavutil/timestamp.h"
  35. #include "libavutil/opt.h"
  36. #include "libavutil/pixdesc.h"
  37. #include "libavcodec/raw.h"
  38. /*
  39. * TODO:
  40. * - fill all fields if non streamed (nb_frames for example)
  41. */
  42. typedef struct AVIIentry {
  43. char tag[4];
  44. unsigned int flags;
  45. unsigned int pos;
  46. unsigned int len;
  47. } AVIIentry;
  48. #define AVI_INDEX_CLUSTER_SIZE 16384
  49. #define AVI_MASTER_INDEX_PREFIX_SIZE (8+2+1+1+4+8+4+4)
  50. #define AVI_MASTER_INDEX_ENTRY_SIZE 16 /* bytes per entry */
  51. #define AVI_MASTER_INDEX_SIZE_DEFAULT 256 /* number of entries */
  52. typedef struct AVIIndex {
  53. int64_t indx_start;
  54. int64_t audio_strm_offset;
  55. int entry;
  56. int ents_allocated;
  57. int master_odml_riff_id_base;
  58. AVIIentry** cluster;
  59. } AVIIndex;
  60. typedef struct AVIContext {
  61. const AVClass *class;
  62. int64_t riff_start, movi_list, odml_list;
  63. int64_t frames_hdr_all;
  64. int riff_id;
  65. int reserve_index_space;
  66. int master_index_max_size;
  67. int write_channel_mask;
  68. } AVIContext;
  69. typedef struct AVIStream {
  70. int64_t frames_hdr_strm;
  71. int64_t audio_strm_length;
  72. int packet_count;
  73. int entry;
  74. int max_size;
  75. int sample_requested;
  76. int64_t last_dts;
  77. AVIIndex indexes;
  78. int64_t strh_flags_offset;
  79. uint32_t palette[AVPALETTE_COUNT];
  80. uint32_t old_palette[AVPALETTE_COUNT];
  81. int64_t pal_offset;
  82. } AVIStream;
  83. static int avi_write_packet_internal(AVFormatContext *s, AVPacket *pkt);
  84. static inline AVIIentry *avi_get_ientry(const AVIIndex *idx, int ent_id)
  85. {
  86. int cl = ent_id / AVI_INDEX_CLUSTER_SIZE;
  87. int id = ent_id % AVI_INDEX_CLUSTER_SIZE;
  88. return &idx->cluster[cl][id];
  89. }
  90. static int avi_add_ientry(AVFormatContext *s, int stream_index, char *tag,
  91. unsigned int flags, unsigned int size)
  92. {
  93. AVIContext *avi = s->priv_data;
  94. AVIOContext *pb = s->pb;
  95. AVIStream *avist = s->streams[stream_index]->priv_data;
  96. AVIIndex *idx = &avist->indexes;
  97. int cl = idx->entry / AVI_INDEX_CLUSTER_SIZE;
  98. int id = idx->entry % AVI_INDEX_CLUSTER_SIZE;
  99. if (idx->ents_allocated <= idx->entry) {
  100. idx->cluster = av_realloc_f(idx->cluster, sizeof(void*), cl+1);
  101. if (!idx->cluster) {
  102. idx->ents_allocated = 0;
  103. idx->entry = 0;
  104. return AVERROR(ENOMEM);
  105. }
  106. idx->cluster[cl] =
  107. av_malloc(AVI_INDEX_CLUSTER_SIZE * sizeof(AVIIentry));
  108. if (!idx->cluster[cl])
  109. return AVERROR(ENOMEM);
  110. idx->ents_allocated += AVI_INDEX_CLUSTER_SIZE;
  111. }
  112. if (tag)
  113. memcpy(idx->cluster[cl][id].tag, tag, 4);
  114. else
  115. memset(idx->cluster[cl][id].tag, 0, 4);
  116. idx->cluster[cl][id].flags = flags;
  117. idx->cluster[cl][id].pos = avio_tell(pb) - avi->movi_list;
  118. idx->cluster[cl][id].len = size;
  119. avist->max_size = FFMAX(avist->max_size, size);
  120. idx->entry++;
  121. return 0;
  122. }
  123. static av_cold int avi_init(struct AVFormatContext *s)
  124. {
  125. AVIContext *avi = s->priv_data;
  126. if (avi->reserve_index_space > 0) {
  127. avi->master_index_max_size = (avi->reserve_index_space - AVI_MASTER_INDEX_PREFIX_SIZE) / AVI_MASTER_INDEX_ENTRY_SIZE;
  128. avi->master_index_max_size = FFMAX(avi->master_index_max_size, 16);
  129. } else
  130. avi->master_index_max_size = AVI_MASTER_INDEX_SIZE_DEFAULT;
  131. av_log(s, AV_LOG_DEBUG, "reserve_index_space:%d master_index_max_size:%d\n",
  132. avi->reserve_index_space, avi->master_index_max_size);
  133. return 1; /* stream initialization continues in avi_write_header */
  134. }
  135. static int64_t avi_start_new_riff(AVFormatContext *s, AVIOContext *pb,
  136. const char *riff_tag, const char *list_tag)
  137. {
  138. AVIContext *avi = s->priv_data;
  139. int64_t loff;
  140. int i;
  141. avi->riff_id++;
  142. for (i = 0; i < s->nb_streams; i++) {
  143. AVIStream *avist = s->streams[i]->priv_data;
  144. avist->indexes.audio_strm_offset = avist->audio_strm_length;
  145. avist->indexes.entry = 0;
  146. }
  147. avi->riff_start = ff_start_tag(pb, "RIFF");
  148. ffio_wfourcc(pb, riff_tag);
  149. loff = ff_start_tag(pb, "LIST");
  150. ffio_wfourcc(pb, list_tag);
  151. return loff;
  152. }
  153. static char *avi_stream2fourcc(char *tag, int index, enum AVMediaType type)
  154. {
  155. tag[0] = '0' + index / 10;
  156. tag[1] = '0' + index % 10;
  157. if (type == AVMEDIA_TYPE_VIDEO) {
  158. tag[2] = 'd';
  159. tag[3] = 'c';
  160. } else if (type == AVMEDIA_TYPE_SUBTITLE) {
  161. // note: this is not an official code
  162. tag[2] = 's';
  163. tag[3] = 'b';
  164. } else {
  165. tag[2] = 'w';
  166. tag[3] = 'b';
  167. }
  168. tag[4] = '\0';
  169. return tag;
  170. }
  171. static int avi_write_counters(AVFormatContext *s, int riff_id)
  172. {
  173. AVIOContext *pb = s->pb;
  174. AVIContext *avi = s->priv_data;
  175. int n, au_byterate, au_ssize, au_scale, nb_frames = 0;
  176. int64_t file_size;
  177. AVCodecParameters *par;
  178. file_size = avio_tell(pb);
  179. for (n = 0; n < s->nb_streams; n++) {
  180. AVIStream *avist = s->streams[n]->priv_data;
  181. av_assert0(avist->frames_hdr_strm);
  182. par = s->streams[n]->codecpar;
  183. avio_seek(pb, avist->frames_hdr_strm, SEEK_SET);
  184. ff_parse_specific_params(s->streams[n], &au_byterate, &au_ssize, &au_scale);
  185. if (au_ssize == 0)
  186. avio_wl32(pb, avist->packet_count);
  187. else
  188. avio_wl32(pb, avist->audio_strm_length / au_ssize);
  189. if (par->codec_type == AVMEDIA_TYPE_VIDEO)
  190. nb_frames = FFMAX(nb_frames, avist->packet_count);
  191. }
  192. if (riff_id == 1) {
  193. av_assert0(avi->frames_hdr_all);
  194. avio_seek(pb, avi->frames_hdr_all, SEEK_SET);
  195. avio_wl32(pb, nb_frames);
  196. }
  197. avio_seek(pb, file_size, SEEK_SET);
  198. return 0;
  199. }
  200. static void write_odml_master(AVFormatContext *s, int stream_index)
  201. {
  202. AVIOContext *pb = s->pb;
  203. AVIContext *avi = s->priv_data;
  204. AVStream *st = s->streams[stream_index];
  205. AVCodecParameters *par = st->codecpar;
  206. AVIStream *avist = st->priv_data;
  207. unsigned char tag[5];
  208. int j;
  209. /* Starting to lay out AVI OpenDML master index.
  210. * We want to make it JUNK entry for now, since we'd
  211. * like to get away without making AVI an OpenDML one
  212. * for compatibility reasons. */
  213. avist->indexes.indx_start = ff_start_tag(pb, "JUNK");
  214. avio_wl16(pb, 4); /* wLongsPerEntry */
  215. avio_w8(pb, 0); /* bIndexSubType (0 == frame index) */
  216. avio_w8(pb, 0); /* bIndexType (0 == AVI_INDEX_OF_INDEXES) */
  217. avio_wl32(pb, 0); /* nEntriesInUse (will fill out later on) */
  218. ffio_wfourcc(pb, avi_stream2fourcc(tag, stream_index, par->codec_type));
  219. /* dwChunkId */
  220. avio_wl64(pb, 0); /* dwReserved[3] */
  221. avio_wl32(pb, 0); /* Must be 0. */
  222. for (j = 0; j < avi->master_index_max_size * 2; j++)
  223. avio_wl64(pb, 0);
  224. ff_end_tag(pb, avist->indexes.indx_start);
  225. }
  226. static int avi_write_header(AVFormatContext *s)
  227. {
  228. AVIContext *avi = s->priv_data;
  229. AVIOContext *pb = s->pb;
  230. int bitrate, n, i, nb_frames, au_byterate, au_ssize, au_scale;
  231. int64_t max_stream_duration = 0;
  232. AVCodecParameters *video_par;
  233. AVStream *video_st = NULL;
  234. int64_t list1, list2, strh, strf;
  235. AVDictionaryEntry *t = NULL;
  236. int padding;
  237. if (s->nb_streams > AVI_MAX_STREAM_COUNT) {
  238. av_log(s, AV_LOG_ERROR, "AVI does not support "
  239. ">"AV_STRINGIFY(AVI_MAX_STREAM_COUNT)" streams\n");
  240. return AVERROR(EINVAL);
  241. }
  242. for (n = 0; n < s->nb_streams; n++) {
  243. s->streams[n]->priv_data = av_mallocz(sizeof(AVIStream));
  244. if (!s->streams[n]->priv_data)
  245. return AVERROR(ENOMEM);
  246. }
  247. /* header list */
  248. avi->riff_id = 0;
  249. list1 = avi_start_new_riff(s, pb, "AVI ", "hdrl");
  250. /* avi header */
  251. ffio_wfourcc(pb, "avih");
  252. avio_wl32(pb, 14 * 4);
  253. bitrate = 0;
  254. video_par = NULL;
  255. for (n = 0; n < s->nb_streams; n++) {
  256. AVCodecParameters *par = s->streams[n]->codecpar;
  257. AVStream *st = s->streams[n];
  258. bitrate = FFMIN(bitrate + par->bit_rate, INT32_MAX);
  259. if (st->duration > 0) {
  260. int64_t stream_duration = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
  261. max_stream_duration = FFMAX(stream_duration, max_stream_duration);
  262. }
  263. if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
  264. video_par = par;
  265. video_st = st;
  266. }
  267. }
  268. /* guess master index size based on bitrate and duration */
  269. if (!avi->reserve_index_space) {
  270. double duration_est, filesize_est;
  271. if (s->duration > 0)
  272. duration_est = (double)s->duration / AV_TIME_BASE;
  273. else if (max_stream_duration > 0)
  274. duration_est = (double)max_stream_duration / AV_TIME_BASE;
  275. else
  276. duration_est = 10 * 60 * 60; /* default to 10 hours */
  277. filesize_est = duration_est * (bitrate / 8) * 1.10; /* add 10% safety margin for muxer+bitrate */
  278. avi->master_index_max_size = FFMAX((int)ceil(filesize_est / AVI_MAX_RIFF_SIZE) + 1,
  279. avi->master_index_max_size);
  280. av_log(s, AV_LOG_DEBUG, "duration_est:%0.3f, filesize_est:%0.1fGiB, master_index_max_size:%d\n",
  281. duration_est, filesize_est / (1024*1024*1024), avi->master_index_max_size);
  282. }
  283. nb_frames = 0;
  284. // TODO: should be avg_frame_rate
  285. if (video_st)
  286. avio_wl32(pb, (uint32_t) (INT64_C(1000000) * video_st->time_base.num /
  287. video_st->time_base.den));
  288. else
  289. avio_wl32(pb, 0);
  290. avio_wl32(pb, bitrate / 8); /* XXX: not quite exact */
  291. avio_wl32(pb, 0); /* padding */
  292. if (!(pb->seekable & AVIO_SEEKABLE_NORMAL))
  293. avio_wl32(pb, AVIF_TRUSTCKTYPE | AVIF_ISINTERLEAVED); /* flags */
  294. else
  295. avio_wl32(pb, AVIF_TRUSTCKTYPE | AVIF_HASINDEX | AVIF_ISINTERLEAVED); /* flags */
  296. avi->frames_hdr_all = avio_tell(pb); /* remember this offset to fill later */
  297. avio_wl32(pb, nb_frames); /* nb frames, filled later */
  298. avio_wl32(pb, 0); /* initial frame */
  299. avio_wl32(pb, s->nb_streams); /* nb streams */
  300. avio_wl32(pb, 1024 * 1024); /* suggested buffer size */
  301. if (video_par) {
  302. avio_wl32(pb, video_par->width);
  303. avio_wl32(pb, video_par->height);
  304. } else {
  305. avio_wl32(pb, 0);
  306. avio_wl32(pb, 0);
  307. }
  308. avio_wl32(pb, 0); /* reserved */
  309. avio_wl32(pb, 0); /* reserved */
  310. avio_wl32(pb, 0); /* reserved */
  311. avio_wl32(pb, 0); /* reserved */
  312. /* stream list */
  313. for (i = 0; i < n; i++) {
  314. AVStream *st = s->streams[i];
  315. AVCodecParameters *par = st->codecpar;
  316. AVIStream *avist = st->priv_data;
  317. list2 = ff_start_tag(pb, "LIST");
  318. ffio_wfourcc(pb, "strl");
  319. /* stream generic header */
  320. strh = ff_start_tag(pb, "strh");
  321. switch (par->codec_type) {
  322. case AVMEDIA_TYPE_SUBTITLE:
  323. // XSUB subtitles behave like video tracks, other subtitles
  324. // are not (yet) supported.
  325. if (par->codec_id != AV_CODEC_ID_XSUB) {
  326. avpriv_report_missing_feature(s, "Subtitle streams other than DivX XSUB");
  327. return AVERROR_PATCHWELCOME;
  328. }
  329. case AVMEDIA_TYPE_VIDEO:
  330. ffio_wfourcc(pb, "vids");
  331. break;
  332. case AVMEDIA_TYPE_AUDIO:
  333. ffio_wfourcc(pb, "auds");
  334. break;
  335. // case AVMEDIA_TYPE_TEXT:
  336. // ffio_wfourcc(pb, "txts");
  337. // break;
  338. case AVMEDIA_TYPE_DATA:
  339. ffio_wfourcc(pb, "dats");
  340. break;
  341. }
  342. if (par->codec_type == AVMEDIA_TYPE_VIDEO ||
  343. par->codec_id == AV_CODEC_ID_XSUB)
  344. avio_wl32(pb, par->codec_tag);
  345. else
  346. avio_wl32(pb, 1);
  347. avist->strh_flags_offset = avio_tell(pb);
  348. avio_wl32(pb, 0); /* flags */
  349. avio_wl16(pb, 0); /* priority */
  350. avio_wl16(pb, 0); /* language */
  351. avio_wl32(pb, 0); /* initial frame */
  352. ff_parse_specific_params(st, &au_byterate, &au_ssize, &au_scale);
  353. if ( par->codec_type == AVMEDIA_TYPE_VIDEO
  354. && par->codec_id != AV_CODEC_ID_XSUB
  355. && au_byterate > 1000LL*au_scale) {
  356. au_byterate = 600;
  357. au_scale = 1;
  358. }
  359. avpriv_set_pts_info(st, 64, au_scale, au_byterate);
  360. if (par->codec_id == AV_CODEC_ID_XSUB)
  361. au_scale = au_byterate = 0;
  362. avio_wl32(pb, au_scale); /* scale */
  363. avio_wl32(pb, au_byterate); /* rate */
  364. avio_wl32(pb, 0); /* start */
  365. /* remember this offset to fill later */
  366. avist->frames_hdr_strm = avio_tell(pb);
  367. if (!(pb->seekable & AVIO_SEEKABLE_NORMAL))
  368. /* FIXME: this may be broken, but who cares */
  369. avio_wl32(pb, AVI_MAX_RIFF_SIZE);
  370. else
  371. avio_wl32(pb, 0); /* length, XXX: filled later */
  372. /* suggested buffer size, is set to largest chunk size in avi_write_trailer */
  373. if (par->codec_type == AVMEDIA_TYPE_VIDEO)
  374. avio_wl32(pb, 1024 * 1024);
  375. else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
  376. avio_wl32(pb, 12 * 1024);
  377. else
  378. avio_wl32(pb, 0);
  379. avio_wl32(pb, -1); /* quality */
  380. avio_wl32(pb, au_ssize); /* sample size */
  381. avio_wl32(pb, 0);
  382. avio_wl16(pb, par->width);
  383. avio_wl16(pb, par->height);
  384. ff_end_tag(pb, strh);
  385. if (par->codec_type != AVMEDIA_TYPE_DATA) {
  386. int ret, flags;
  387. enum AVPixelFormat pix_fmt;
  388. strf = ff_start_tag(pb, "strf");
  389. switch (par->codec_type) {
  390. case AVMEDIA_TYPE_SUBTITLE:
  391. /* XSUB subtitles behave like video tracks, other subtitles
  392. * are not (yet) supported. */
  393. if (par->codec_id != AV_CODEC_ID_XSUB)
  394. break;
  395. case AVMEDIA_TYPE_VIDEO:
  396. /* WMP expects RGB 5:5:5 rawvideo in avi to have bpp set to 16. */
  397. if ( !par->codec_tag
  398. && par->codec_id == AV_CODEC_ID_RAWVIDEO
  399. && par->format == AV_PIX_FMT_RGB555LE
  400. && par->bits_per_coded_sample == 15)
  401. par->bits_per_coded_sample = 16;
  402. avist->pal_offset = avio_tell(pb) + 40;
  403. ff_put_bmp_header(pb, par, 0, 0);
  404. pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_avi,
  405. par->bits_per_coded_sample);
  406. if ( !par->codec_tag
  407. && par->codec_id == AV_CODEC_ID_RAWVIDEO
  408. && par->format != pix_fmt
  409. && par->format != AV_PIX_FMT_NONE)
  410. av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to avi, output file will be unreadable\n",
  411. av_get_pix_fmt_name(par->format));
  412. if (par->format == AV_PIX_FMT_PAL8) {
  413. if (par->bits_per_coded_sample < 0 || par->bits_per_coded_sample > 8) {
  414. av_log(s, AV_LOG_ERROR, "PAL8 with %d bps is not allowed\n", par->bits_per_coded_sample);
  415. return AVERROR(EINVAL);
  416. }
  417. }
  418. break;
  419. case AVMEDIA_TYPE_AUDIO:
  420. flags = (avi->write_channel_mask == 0) ? FF_PUT_WAV_HEADER_SKIP_CHANNELMASK : 0;
  421. if ((ret = ff_put_wav_header(s, pb, par, flags)) < 0)
  422. return ret;
  423. break;
  424. default:
  425. av_log(s, AV_LOG_ERROR,
  426. "Invalid or not supported codec type '%s' found in the input\n",
  427. (char *)av_x_if_null(av_get_media_type_string(par->codec_type), "?"));
  428. return AVERROR(EINVAL);
  429. }
  430. ff_end_tag(pb, strf);
  431. if ((t = av_dict_get(st->metadata, "title", NULL, 0))) {
  432. ff_riff_write_info_tag(s->pb, "strn", t->value);
  433. t = NULL;
  434. }
  435. if (par->codec_id == AV_CODEC_ID_XSUB
  436. && (t = av_dict_get(s->streams[i]->metadata, "language", NULL, 0))) {
  437. const char* langstr = ff_convert_lang_to(t->value, AV_LANG_ISO639_1);
  438. t = NULL;
  439. if (langstr) {
  440. char* str = av_asprintf("Subtitle - %s-xx;02", langstr);
  441. if (!str)
  442. return AVERROR(ENOMEM);
  443. ff_riff_write_info_tag(s->pb, "strn", str);
  444. av_free(str);
  445. }
  446. }
  447. }
  448. if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
  449. write_odml_master(s, i);
  450. }
  451. if (par->codec_type == AVMEDIA_TYPE_VIDEO &&
  452. st->sample_aspect_ratio.num > 0 &&
  453. st->sample_aspect_ratio.den > 0) {
  454. int vprp = ff_start_tag(pb, "vprp");
  455. AVRational dar = av_mul_q(st->sample_aspect_ratio,
  456. (AVRational) { par->width,
  457. par->height });
  458. int num, den, fields, i;
  459. av_reduce(&num, &den, dar.num, dar.den, 0xFFFF);
  460. if (par->field_order == AV_FIELD_TT || par->field_order == AV_FIELD_BB ||
  461. par->field_order == AV_FIELD_TB || par->field_order == AV_FIELD_BT) {
  462. fields = 2; // interlaced
  463. } else {
  464. fields = 1; // progressive
  465. }
  466. avio_wl32(pb, 0); // video format = unknown
  467. avio_wl32(pb, 0); // video standard = unknown
  468. // TODO: should be avg_frame_rate
  469. avio_wl32(pb, (2LL*st->time_base.den + st->time_base.num - 1) / (2LL * st->time_base.num));
  470. avio_wl32(pb, par->width);
  471. avio_wl32(pb, par->height);
  472. avio_wl16(pb, den);
  473. avio_wl16(pb, num);
  474. avio_wl32(pb, par->width);
  475. avio_wl32(pb, par->height);
  476. avio_wl32(pb, fields); // fields per frame
  477. for (i = 0; i < fields; i++) {
  478. int start_line;
  479. // OpenDML v1.02 is not very specific on what value to use for
  480. // start_line when frame data is not coming from a capturing device,
  481. // so just use 0/1 depending on the field order for interlaced frames
  482. if (par->field_order == AV_FIELD_TT || par->field_order == AV_FIELD_TB) {
  483. start_line = (i == 0) ? 0 : 1;
  484. } else if (par->field_order == AV_FIELD_BB || par->field_order == AV_FIELD_BT) {
  485. start_line = (i == 0) ? 1 : 0;
  486. } else {
  487. start_line = 0;
  488. }
  489. avio_wl32(pb, par->height / fields); // compressed bitmap height
  490. avio_wl32(pb, par->width); // compressed bitmap width
  491. avio_wl32(pb, par->height / fields); // valid bitmap height
  492. avio_wl32(pb, par->width); // valid bitmap width
  493. avio_wl32(pb, 0); // valid bitmap X offset
  494. avio_wl32(pb, 0); // valid bitmap Y offset
  495. avio_wl32(pb, 0); // valid X offset in T
  496. avio_wl32(pb, start_line); // valid Y start line
  497. }
  498. ff_end_tag(pb, vprp);
  499. }
  500. ff_end_tag(pb, list2);
  501. }
  502. if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
  503. /* AVI could become an OpenDML one, if it grows beyond 2Gb range */
  504. avi->odml_list = ff_start_tag(pb, "JUNK");
  505. ffio_wfourcc(pb, "odml");
  506. ffio_wfourcc(pb, "dmlh");
  507. avio_wl32(pb, 248);
  508. for (i = 0; i < 248; i += 4)
  509. avio_wl32(pb, 0);
  510. ff_end_tag(pb, avi->odml_list);
  511. }
  512. ff_end_tag(pb, list1);
  513. ff_riff_write_info(s);
  514. padding = s->metadata_header_padding;
  515. if (padding < 0)
  516. padding = 1016;
  517. /* some padding for easier tag editing */
  518. if (padding) {
  519. list2 = ff_start_tag(pb, "JUNK");
  520. for (i = padding; i > 0; i -= 4)
  521. avio_wl32(pb, 0);
  522. ff_end_tag(pb, list2);
  523. }
  524. avi->movi_list = ff_start_tag(pb, "LIST");
  525. ffio_wfourcc(pb, "movi");
  526. return 0;
  527. }
  528. static void update_odml_entry(AVFormatContext *s, int stream_index, int64_t ix, int size)
  529. {
  530. AVIOContext *pb = s->pb;
  531. AVIContext *avi = s->priv_data;
  532. AVIStream *avist = s->streams[stream_index]->priv_data;
  533. int64_t pos;
  534. int au_byterate, au_ssize, au_scale;
  535. pos = avio_tell(pb);
  536. /* Updating one entry in the AVI OpenDML master index */
  537. avio_seek(pb, avist->indexes.indx_start - 8, SEEK_SET);
  538. ffio_wfourcc(pb, "indx"); /* enabling this entry */
  539. avio_skip(pb, 8);
  540. avio_wl32(pb, avi->riff_id - avist->indexes.master_odml_riff_id_base); /* nEntriesInUse */
  541. avio_skip(pb, 16 * (avi->riff_id - avist->indexes.master_odml_riff_id_base));
  542. avio_wl64(pb, ix); /* qwOffset */
  543. avio_wl32(pb, size); /* dwSize */
  544. ff_parse_specific_params(s->streams[stream_index], &au_byterate, &au_ssize, &au_scale);
  545. if (s->streams[stream_index]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && au_ssize > 0) {
  546. uint32_t audio_segm_size = (avist->audio_strm_length - avist->indexes.audio_strm_offset);
  547. if ((audio_segm_size % au_ssize > 0) && !avist->sample_requested) {
  548. avpriv_request_sample(s, "OpenDML index duration for audio packets with partial frames");
  549. avist->sample_requested = 1;
  550. }
  551. avio_wl32(pb, audio_segm_size / au_ssize); /* dwDuration (sample count) */
  552. } else
  553. avio_wl32(pb, avist->indexes.entry); /* dwDuration (packet count) */
  554. avio_seek(pb, pos, SEEK_SET);
  555. }
  556. static int avi_write_ix(AVFormatContext *s)
  557. {
  558. AVIOContext *pb = s->pb;
  559. AVIContext *avi = s->priv_data;
  560. char tag[5];
  561. char ix_tag[] = "ix00";
  562. int i, j;
  563. av_assert0(pb->seekable & AVIO_SEEKABLE_NORMAL);
  564. for (i = 0; i < s->nb_streams; i++) {
  565. AVIStream *avist = s->streams[i]->priv_data;
  566. if (avi->riff_id - avist->indexes.master_odml_riff_id_base == avi->master_index_max_size) {
  567. int64_t pos;
  568. int size = AVI_MASTER_INDEX_PREFIX_SIZE + AVI_MASTER_INDEX_ENTRY_SIZE * avi->master_index_max_size;
  569. pos = avio_tell(pb);
  570. update_odml_entry(s, i, pos, size);
  571. write_odml_master(s, i);
  572. av_assert1(avio_tell(pb) - pos == size);
  573. avist->indexes.master_odml_riff_id_base = avi->riff_id - 1;
  574. }
  575. av_assert0(avi->riff_id - avist->indexes.master_odml_riff_id_base < avi->master_index_max_size);
  576. }
  577. for (i = 0; i < s->nb_streams; i++) {
  578. AVIStream *avist = s->streams[i]->priv_data;
  579. int64_t ix;
  580. avi_stream2fourcc(tag, i, s->streams[i]->codecpar->codec_type);
  581. ix_tag[3] = '0' + i;
  582. /* Writing AVI OpenDML leaf index chunk */
  583. ix = avio_tell(pb);
  584. ffio_wfourcc(pb, ix_tag); /* ix?? */
  585. avio_wl32(pb, avist->indexes.entry * 8 + 24);
  586. /* chunk size */
  587. avio_wl16(pb, 2); /* wLongsPerEntry */
  588. avio_w8(pb, 0); /* bIndexSubType (0 == frame index) */
  589. avio_w8(pb, 1); /* bIndexType (1 == AVI_INDEX_OF_CHUNKS) */
  590. avio_wl32(pb, avist->indexes.entry);
  591. /* nEntriesInUse */
  592. ffio_wfourcc(pb, tag); /* dwChunkId */
  593. avio_wl64(pb, avi->movi_list); /* qwBaseOffset */
  594. avio_wl32(pb, 0); /* dwReserved_3 (must be 0) */
  595. for (j = 0; j < avist->indexes.entry; j++) {
  596. AVIIentry *ie = avi_get_ientry(&avist->indexes, j);
  597. avio_wl32(pb, ie->pos + 8);
  598. avio_wl32(pb, ((uint32_t) ie->len & ~0x80000000) |
  599. (ie->flags & 0x10 ? 0 : 0x80000000));
  600. }
  601. update_odml_entry(s, i, ix, avio_tell(pb) - ix);
  602. }
  603. return 0;
  604. }
  605. static int avi_write_idx1(AVFormatContext *s)
  606. {
  607. AVIOContext *pb = s->pb;
  608. AVIContext *avi = s->priv_data;
  609. int64_t idx_chunk;
  610. int i;
  611. char tag[5];
  612. if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
  613. AVIStream *avist;
  614. AVIIentry *ie = 0, *tie;
  615. int empty, stream_id = -1;
  616. idx_chunk = ff_start_tag(pb, "idx1");
  617. for (i = 0; i < s->nb_streams; i++) {
  618. avist = s->streams[i]->priv_data;
  619. avist->entry = 0;
  620. }
  621. do {
  622. empty = 1;
  623. for (i = 0; i < s->nb_streams; i++) {
  624. avist = s->streams[i]->priv_data;
  625. if (avist->indexes.entry <= avist->entry)
  626. continue;
  627. tie = avi_get_ientry(&avist->indexes, avist->entry);
  628. if (empty || tie->pos < ie->pos) {
  629. ie = tie;
  630. stream_id = i;
  631. }
  632. empty = 0;
  633. }
  634. if (!empty) {
  635. avist = s->streams[stream_id]->priv_data;
  636. if (*ie->tag)
  637. ffio_wfourcc(pb, ie->tag);
  638. else {
  639. avi_stream2fourcc(tag, stream_id,
  640. s->streams[stream_id]->codecpar->codec_type);
  641. ffio_wfourcc(pb, tag);
  642. }
  643. avio_wl32(pb, ie->flags);
  644. avio_wl32(pb, ie->pos);
  645. avio_wl32(pb, ie->len);
  646. avist->entry++;
  647. }
  648. } while (!empty);
  649. ff_end_tag(pb, idx_chunk);
  650. avi_write_counters(s, avi->riff_id);
  651. }
  652. return 0;
  653. }
  654. static int write_skip_frames(AVFormatContext *s, int stream_index, int64_t dts)
  655. {
  656. AVIStream *avist = s->streams[stream_index]->priv_data;
  657. AVCodecParameters *par = s->streams[stream_index]->codecpar;
  658. ff_dlog(s, "dts:%s packet_count:%d stream_index:%d\n", av_ts2str(dts), avist->packet_count, stream_index);
  659. while (par->block_align == 0 && dts != AV_NOPTS_VALUE &&
  660. dts > avist->packet_count && par->codec_id != AV_CODEC_ID_XSUB && avist->packet_count) {
  661. AVPacket empty_packet;
  662. if (dts - avist->packet_count > 60000) {
  663. av_log(s, AV_LOG_ERROR, "Too large number of skipped frames %"PRId64" > 60000\n", dts - avist->packet_count);
  664. return AVERROR(EINVAL);
  665. }
  666. av_init_packet(&empty_packet);
  667. empty_packet.size = 0;
  668. empty_packet.data = NULL;
  669. empty_packet.stream_index = stream_index;
  670. avi_write_packet_internal(s, &empty_packet);
  671. ff_dlog(s, "dup dts:%s packet_count:%d\n", av_ts2str(dts), avist->packet_count);
  672. }
  673. return 0;
  674. }
  675. static int avi_write_packet(AVFormatContext *s, AVPacket *pkt)
  676. {
  677. const int stream_index = pkt->stream_index;
  678. AVCodecParameters *par = s->streams[stream_index]->codecpar;
  679. int ret;
  680. if (par->codec_id == AV_CODEC_ID_H264 && par->codec_tag == MKTAG('H','2','6','4') && pkt->size) {
  681. ret = ff_check_h264_startcode(s, s->streams[stream_index], pkt);
  682. if (ret < 0)
  683. return ret;
  684. }
  685. if ((ret = write_skip_frames(s, stream_index, pkt->dts)) < 0)
  686. return ret;
  687. if (!pkt->size)
  688. return avi_write_packet_internal(s, pkt); /* Passthrough */
  689. if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
  690. AVIStream *avist = s->streams[stream_index]->priv_data;
  691. AVIOContext *pb = s->pb;
  692. AVPacket *opkt = pkt;
  693. int reshuffle_ret;
  694. if (par->codec_id == AV_CODEC_ID_RAWVIDEO && par->codec_tag == 0) {
  695. int64_t bpc = par->bits_per_coded_sample != 15 ? par->bits_per_coded_sample : 16;
  696. int expected_stride = ((par->width * bpc + 31) >> 5)*4;
  697. reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, par, expected_stride);
  698. if (reshuffle_ret < 0)
  699. return reshuffle_ret;
  700. } else
  701. reshuffle_ret = 0;
  702. if (par->format == AV_PIX_FMT_PAL8) {
  703. ret = ff_get_packet_palette(s, opkt, reshuffle_ret, avist->palette);
  704. if (ret < 0)
  705. goto fail;
  706. if (ret) {
  707. int pal_size = 1 << par->bits_per_coded_sample;
  708. int pc_tag, i;
  709. av_assert0(par->bits_per_coded_sample >= 0 && par->bits_per_coded_sample <= 8);
  710. if ((pb->seekable & AVIO_SEEKABLE_NORMAL) && avist->pal_offset) {
  711. int64_t cur_offset = avio_tell(pb);
  712. avio_seek(pb, avist->pal_offset, SEEK_SET);
  713. for (i = 0; i < pal_size; i++) {
  714. uint32_t v = avist->palette[i];
  715. avio_wl32(pb, v & 0xffffff);
  716. }
  717. avio_seek(pb, cur_offset, SEEK_SET);
  718. memcpy(avist->old_palette, avist->palette, pal_size * 4);
  719. avist->pal_offset = 0;
  720. }
  721. if (memcmp(avist->palette, avist->old_palette, pal_size * 4)) {
  722. unsigned char tag[5];
  723. avi_stream2fourcc(tag, stream_index, par->codec_type);
  724. tag[2] = 'p'; tag[3] = 'c';
  725. if (s->pb->seekable & AVIO_SEEKABLE_NORMAL) {
  726. if (avist->strh_flags_offset) {
  727. int64_t cur_offset = avio_tell(pb);
  728. avio_seek(pb, avist->strh_flags_offset, SEEK_SET);
  729. avio_wl32(pb, AVISF_VIDEO_PALCHANGES);
  730. avio_seek(pb, cur_offset, SEEK_SET);
  731. avist->strh_flags_offset = 0;
  732. }
  733. ret = avi_add_ientry(s, stream_index, tag, AVIIF_NO_TIME,
  734. pal_size * 4 + 4);
  735. if (ret < 0)
  736. goto fail;
  737. }
  738. pc_tag = ff_start_tag(pb, tag);
  739. avio_w8(pb, 0);
  740. avio_w8(pb, pal_size & 0xFF);
  741. avio_wl16(pb, 0); // reserved
  742. for (i = 0; i < pal_size; i++) {
  743. uint32_t v = avist->palette[i];
  744. avio_wb32(pb, v<<8);
  745. }
  746. ff_end_tag(pb, pc_tag);
  747. memcpy(avist->old_palette, avist->palette, pal_size * 4);
  748. }
  749. }
  750. }
  751. if (reshuffle_ret) {
  752. ret = avi_write_packet_internal(s, pkt);
  753. fail:
  754. if (reshuffle_ret)
  755. av_packet_free(&pkt);
  756. return ret;
  757. }
  758. }
  759. return avi_write_packet_internal(s, pkt);
  760. }
  761. static int avi_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
  762. {
  763. unsigned char tag[5];
  764. unsigned int flags = 0;
  765. const int stream_index = pkt->stream_index;
  766. int size = pkt->size;
  767. AVIContext *avi = s->priv_data;
  768. AVIOContext *pb = s->pb;
  769. AVIStream *avist = s->streams[stream_index]->priv_data;
  770. AVCodecParameters *par = s->streams[stream_index]->codecpar;
  771. if (pkt->dts != AV_NOPTS_VALUE)
  772. avist->last_dts = pkt->dts + pkt->duration;
  773. avist->packet_count++;
  774. // Make sure to put an OpenDML chunk when the file size exceeds the limits
  775. if ((pb->seekable & AVIO_SEEKABLE_NORMAL) &&
  776. (avio_tell(pb) - avi->riff_start > AVI_MAX_RIFF_SIZE)) {
  777. avi_write_ix(s);
  778. ff_end_tag(pb, avi->movi_list);
  779. if (avi->riff_id == 1)
  780. avi_write_idx1(s);
  781. ff_end_tag(pb, avi->riff_start);
  782. avi->movi_list = avi_start_new_riff(s, pb, "AVIX", "movi");
  783. }
  784. avi_stream2fourcc(tag, stream_index, par->codec_type);
  785. if (pkt->flags & AV_PKT_FLAG_KEY)
  786. flags = 0x10;
  787. if (par->codec_type == AVMEDIA_TYPE_AUDIO)
  788. avist->audio_strm_length += size;
  789. if (s->pb->seekable & AVIO_SEEKABLE_NORMAL) {
  790. int ret;
  791. ret = avi_add_ientry(s, stream_index, NULL, flags, size);
  792. if (ret < 0)
  793. return ret;
  794. }
  795. avio_write(pb, tag, 4);
  796. avio_wl32(pb, size);
  797. avio_write(pb, pkt->data, size);
  798. if (size & 1)
  799. avio_w8(pb, 0);
  800. return 0;
  801. }
  802. static int avi_write_trailer(AVFormatContext *s)
  803. {
  804. AVIContext *avi = s->priv_data;
  805. AVIOContext *pb = s->pb;
  806. int res = 0;
  807. int i, n, nb_frames;
  808. int64_t file_size;
  809. for (i = 0; i < s->nb_streams; i++) {
  810. AVIStream *avist = s->streams[i]->priv_data;
  811. write_skip_frames(s, i, avist->last_dts);
  812. }
  813. if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
  814. if (avi->riff_id == 1) {
  815. ff_end_tag(pb, avi->movi_list);
  816. res = avi_write_idx1(s);
  817. ff_end_tag(pb, avi->riff_start);
  818. } else {
  819. avi_write_ix(s);
  820. ff_end_tag(pb, avi->movi_list);
  821. ff_end_tag(pb, avi->riff_start);
  822. file_size = avio_tell(pb);
  823. avio_seek(pb, avi->odml_list - 8, SEEK_SET);
  824. ffio_wfourcc(pb, "LIST"); /* Making this AVI OpenDML one */
  825. avio_skip(pb, 16);
  826. for (n = nb_frames = 0; n < s->nb_streams; n++) {
  827. AVCodecParameters *par = s->streams[n]->codecpar;
  828. AVIStream *avist = s->streams[n]->priv_data;
  829. if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
  830. if (nb_frames < avist->packet_count)
  831. nb_frames = avist->packet_count;
  832. } else {
  833. if (par->codec_id == AV_CODEC_ID_MP2 ||
  834. par->codec_id == AV_CODEC_ID_MP3)
  835. nb_frames += avist->packet_count;
  836. }
  837. }
  838. avio_wl32(pb, nb_frames);
  839. avio_seek(pb, file_size, SEEK_SET);
  840. avi_write_counters(s, avi->riff_id);
  841. }
  842. }
  843. if (avi->riff_id >= avi->master_index_max_size) {
  844. int index_space = AVI_MASTER_INDEX_PREFIX_SIZE +
  845. AVI_MASTER_INDEX_ENTRY_SIZE * avi->riff_id;
  846. av_log(s, AV_LOG_WARNING, "Output file not strictly OpenDML compliant, "
  847. "consider re-muxing with 'reserve_index_space' option value >= %d\n",
  848. index_space);
  849. }
  850. for (i = 0; i < s->nb_streams; i++) {
  851. AVIStream *avist = s->streams[i]->priv_data;
  852. if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
  853. avio_seek(pb, avist->frames_hdr_strm + 4, SEEK_SET);
  854. avio_wl32(pb, avist->max_size);
  855. }
  856. }
  857. return res;
  858. }
  859. static void avi_deinit(AVFormatContext *s)
  860. {
  861. for (int i = 0; i < s->nb_streams; i++) {
  862. AVIStream *avist = s->streams[i]->priv_data;
  863. if (!avist)
  864. continue;
  865. for (int j = 0; j < avist->indexes.ents_allocated / AVI_INDEX_CLUSTER_SIZE; j++)
  866. av_freep(&avist->indexes.cluster[j]);
  867. av_freep(&avist->indexes.cluster);
  868. avist->indexes.ents_allocated = avist->indexes.entry = 0;
  869. }
  870. }
  871. #define OFFSET(x) offsetof(AVIContext, x)
  872. #define ENC AV_OPT_FLAG_ENCODING_PARAM
  873. static const AVOption options[] = {
  874. { "reserve_index_space", "reserve space (in bytes) at the beginning of the file for each stream index", OFFSET(reserve_index_space), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, ENC },
  875. { "write_channel_mask", "write channel mask into wave format header", OFFSET(write_channel_mask), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, ENC },
  876. { NULL },
  877. };
  878. static const AVClass avi_muxer_class = {
  879. .class_name = "AVI muxer",
  880. .item_name = av_default_item_name,
  881. .option = options,
  882. .version = LIBAVUTIL_VERSION_INT,
  883. };
  884. AVOutputFormat ff_avi_muxer = {
  885. .name = "avi",
  886. .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
  887. .mime_type = "video/x-msvideo",
  888. .extensions = "avi",
  889. .priv_data_size = sizeof(AVIContext),
  890. .audio_codec = CONFIG_LIBMP3LAME ? AV_CODEC_ID_MP3 : AV_CODEC_ID_AC3,
  891. .video_codec = AV_CODEC_ID_MPEG4,
  892. .init = avi_init,
  893. .deinit = avi_deinit,
  894. .write_header = avi_write_header,
  895. .write_packet = avi_write_packet,
  896. .write_trailer = avi_write_trailer,
  897. .codec_tag = (const AVCodecTag * const []) {
  898. ff_codec_bmp_tags, ff_codec_wav_tags, 0
  899. },
  900. .priv_class = &avi_muxer_class,
  901. };