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.

1020 lines
36KB

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