muxing.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. /*
  2. * Copyright (c) 2003 Fabrice Bellard
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  17. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. /**
  23. * @file
  24. * libavformat API example.
  25. *
  26. * Output a media file in any supported libavformat format.
  27. * The default codecs are used.
  28. */
  29. #include <stdlib.h>
  30. #include <stdio.h>
  31. #include <string.h>
  32. #include <math.h>
  33. #include <libavutil/mathematics.h>
  34. #include <libavformat/avformat.h>
  35. #include <libswscale/swscale.h>
  36. /* 5 seconds stream duration */
  37. #define STREAM_DURATION 200.0
  38. #define STREAM_FRAME_RATE 25 /* 25 images/s */
  39. #define STREAM_NB_FRAMES ((int)(STREAM_DURATION * STREAM_FRAME_RATE))
  40. #define STREAM_PIX_FMT PIX_FMT_YUV420P /* default pix_fmt */
  41. static int sws_flags = SWS_BICUBIC;
  42. /**************************************************************/
  43. /* audio output */
  44. static float t, tincr, tincr2;
  45. static int16_t *samples;
  46. static int audio_input_frame_size;
  47. /*
  48. * add an audio output stream
  49. */
  50. static AVStream *add_audio_stream(AVFormatContext *oc, AVCodec **codec,
  51. enum AVCodecID codec_id)
  52. {
  53. AVCodecContext *c;
  54. AVStream *st;
  55. /* find the audio encoder */
  56. *codec = avcodec_find_encoder(codec_id);
  57. if (!(*codec)) {
  58. fprintf(stderr, "Could not find codec\n");
  59. exit(1);
  60. }
  61. st = avformat_new_stream(oc, *codec);
  62. if (!st) {
  63. fprintf(stderr, "Could not allocate stream\n");
  64. exit(1);
  65. }
  66. st->id = 1;
  67. c = st->codec;
  68. /* put sample parameters */
  69. c->sample_fmt = AV_SAMPLE_FMT_S16;
  70. c->bit_rate = 64000;
  71. c->sample_rate = 44100;
  72. c->channels = 2;
  73. // some formats want stream headers to be separate
  74. if (oc->oformat->flags & AVFMT_GLOBALHEADER)
  75. c->flags |= CODEC_FLAG_GLOBAL_HEADER;
  76. return st;
  77. }
  78. static void open_audio(AVFormatContext *oc, AVCodec *codec, AVStream *st)
  79. {
  80. AVCodecContext *c;
  81. c = st->codec;
  82. /* open it */
  83. if (avcodec_open2(c, codec, NULL) < 0) {
  84. fprintf(stderr, "could not open codec\n");
  85. exit(1);
  86. }
  87. /* init signal generator */
  88. t = 0;
  89. tincr = 2 * M_PI * 110.0 / c->sample_rate;
  90. /* increment frequency by 110 Hz per second */
  91. tincr2 = 2 * M_PI * 110.0 / c->sample_rate / c->sample_rate;
  92. if (c->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)
  93. audio_input_frame_size = 10000;
  94. else
  95. audio_input_frame_size = c->frame_size;
  96. samples = av_malloc(audio_input_frame_size *
  97. av_get_bytes_per_sample(c->sample_fmt) *
  98. c->channels);
  99. }
  100. /* Prepare a 16 bit dummy audio frame of 'frame_size' samples and
  101. * 'nb_channels' channels. */
  102. static void get_audio_frame(int16_t *samples, int frame_size, int nb_channels)
  103. {
  104. int j, i, v;
  105. int16_t *q;
  106. q = samples;
  107. for (j = 0; j < frame_size; j++) {
  108. v = (int)(sin(t) * 10000);
  109. for (i = 0; i < nb_channels; i++)
  110. *q++ = v;
  111. t += tincr;
  112. tincr += tincr2;
  113. }
  114. }
  115. static void write_audio_frame(AVFormatContext *oc, AVStream *st)
  116. {
  117. AVCodecContext *c;
  118. AVPacket pkt = { 0 }; // data and size must be 0;
  119. AVFrame *frame = avcodec_alloc_frame();
  120. int got_packet;
  121. av_init_packet(&pkt);
  122. c = st->codec;
  123. get_audio_frame(samples, audio_input_frame_size, c->channels);
  124. frame->nb_samples = audio_input_frame_size;
  125. avcodec_fill_audio_frame(frame, c->channels, c->sample_fmt,
  126. (uint8_t *)samples,
  127. audio_input_frame_size *
  128. av_get_bytes_per_sample(c->sample_fmt) *
  129. c->channels, 1);
  130. avcodec_encode_audio2(c, &pkt, frame, &got_packet);
  131. if (!got_packet)
  132. return;
  133. pkt.stream_index = st->index;
  134. /* Write the compressed frame to the media file. */
  135. if (av_interleaved_write_frame(oc, &pkt) != 0) {
  136. fprintf(stderr, "Error while writing audio frame\n");
  137. exit(1);
  138. }
  139. avcodec_free_frame(&frame);
  140. }
  141. static void close_audio(AVFormatContext *oc, AVStream *st)
  142. {
  143. avcodec_close(st->codec);
  144. av_free(samples);
  145. }
  146. /**************************************************************/
  147. /* video output */
  148. static AVFrame *frame;
  149. static AVPicture src_picture, dst_picture;
  150. static uint8_t *video_outbuf;
  151. static int frame_count, video_outbuf_size;
  152. /* Add a video output stream. */
  153. static AVStream *add_video_stream(AVFormatContext *oc, AVCodec **codec,
  154. enum AVCodecID codec_id)
  155. {
  156. AVCodecContext *c;
  157. AVStream *st;
  158. /* find the video encoder */
  159. *codec = avcodec_find_encoder(codec_id);
  160. if (!(*codec)) {
  161. fprintf(stderr, "codec not found\n");
  162. exit(1);
  163. }
  164. st = avformat_new_stream(oc, *codec);
  165. if (!st) {
  166. fprintf(stderr, "Could not alloc stream\n");
  167. exit(1);
  168. }
  169. c = st->codec;
  170. avcodec_get_context_defaults3(c, *codec);
  171. c->codec_id = codec_id;
  172. /* Put sample parameters. */
  173. c->bit_rate = 400000;
  174. /* Resolution must be a multiple of two. */
  175. c->width = 352;
  176. c->height = 288;
  177. /* timebase: This is the fundamental unit of time (in seconds) in terms
  178. * of which frame timestamps are represented. For fixed-fps content,
  179. * timebase should be 1/framerate and timestamp increments should be
  180. * identical to 1. */
  181. c->time_base.den = STREAM_FRAME_RATE;
  182. c->time_base.num = 1;
  183. c->gop_size = 12; /* emit one intra frame every twelve frames at most */
  184. c->pix_fmt = STREAM_PIX_FMT;
  185. if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
  186. /* just for testing, we also add B frames */
  187. c->max_b_frames = 2;
  188. }
  189. if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
  190. /* Needed to avoid using macroblocks in which some coeffs overflow.
  191. * This does not happen with normal video, it just happens here as
  192. * the motion of the chroma plane does not match the luma plane. */
  193. c->mb_decision = 2;
  194. }
  195. /* Some formats want stream headers to be separate. */
  196. if (oc->oformat->flags & AVFMT_GLOBALHEADER)
  197. c->flags |= CODEC_FLAG_GLOBAL_HEADER;
  198. return st;
  199. }
  200. static void open_video(AVFormatContext *oc, AVCodec *codec, AVStream *st)
  201. {
  202. int ret;
  203. AVCodecContext *c = st->codec;
  204. /* open the codec */
  205. if (avcodec_open2(c, codec, NULL) < 0) {
  206. fprintf(stderr, "Could not open codec\n");
  207. exit(1);
  208. }
  209. video_outbuf = NULL;
  210. if (!(oc->oformat->flags & AVFMT_RAWPICTURE)) {
  211. /* Allocate output buffer. */
  212. /* XXX: API change will be done. */
  213. /* Buffers passed into lav* can be allocated any way you prefer,
  214. * as long as they're aligned enough for the architecture, and
  215. * they're freed appropriately (such as using av_free for buffers
  216. * allocated with av_malloc). */
  217. video_outbuf_size = 200000;
  218. video_outbuf = av_malloc(video_outbuf_size);
  219. }
  220. /* allocate and init a re-usable frame */
  221. frame = avcodec_alloc_frame();
  222. if (!frame) {
  223. fprintf(stderr, "Could not allocate video frame\n");
  224. exit(1);
  225. }
  226. /* Allocate the encoded raw picture. */
  227. ret = avpicture_alloc(&dst_picture, c->pix_fmt, c->width, c->height);
  228. if (ret < 0) {
  229. fprintf(stderr, "Could not allocate picture\n");
  230. exit(1);
  231. }
  232. /* If the output format is not YUV420P, then a temporary YUV420P
  233. * picture is needed too. It is then converted to the required
  234. * output format. */
  235. if (c->pix_fmt != PIX_FMT_YUV420P) {
  236. ret = avpicture_alloc(&src_picture, PIX_FMT_YUV420P, c->width, c->height);
  237. if (ret < 0) {
  238. fprintf(stderr, "Could not allocate temporary picture\n");
  239. exit(1);
  240. }
  241. }
  242. /* copy data and linesize picture pointers to frame */
  243. *((AVPicture *)frame) = dst_picture;
  244. }
  245. /* Prepare a dummy image. */
  246. static void fill_yuv_image(AVPicture *pict, int frame_index,
  247. int width, int height)
  248. {
  249. int x, y, i;
  250. i = frame_index;
  251. /* Y */
  252. for (y = 0; y < height; y++)
  253. for (x = 0; x < width; x++)
  254. pict->data[0][y * pict->linesize[0] + x] = x + y + i * 3;
  255. /* Cb and Cr */
  256. for (y = 0; y < height / 2; y++) {
  257. for (x = 0; x < width / 2; x++) {
  258. pict->data[1][y * pict->linesize[1] + x] = 128 + y + i * 2;
  259. pict->data[2][y * pict->linesize[2] + x] = 64 + x + i * 5;
  260. }
  261. }
  262. }
  263. static void write_video_frame(AVFormatContext *oc, AVStream *st)
  264. {
  265. int ret;
  266. static struct SwsContext *sws_ctx;
  267. AVCodecContext *c = st->codec;
  268. if (frame_count >= STREAM_NB_FRAMES) {
  269. /* No more frames to compress. The codec has a latency of a few
  270. * frames if using B-frames, so we get the last frames by
  271. * passing the same picture again. */
  272. } else {
  273. if (c->pix_fmt != PIX_FMT_YUV420P) {
  274. /* as we only generate a YUV420P picture, we must convert it
  275. * to the codec pixel format if needed */
  276. if (!sws_ctx) {
  277. sws_ctx = sws_getContext(c->width, c->height, PIX_FMT_YUV420P,
  278. c->width, c->height, c->pix_fmt,
  279. sws_flags, NULL, NULL, NULL);
  280. if (!sws_ctx) {
  281. fprintf(stderr,
  282. "Could not initialize the conversion context\n");
  283. exit(1);
  284. }
  285. }
  286. fill_yuv_image(&src_picture, frame_count, c->width, c->height);
  287. sws_scale(sws_ctx,
  288. (const uint8_t * const *)src_picture.data, src_picture.linesize,
  289. 0, c->height, dst_picture.data, dst_picture.linesize);
  290. } else {
  291. fill_yuv_image(&dst_picture, frame_count, c->width, c->height);
  292. }
  293. }
  294. if (oc->oformat->flags & AVFMT_RAWPICTURE) {
  295. /* Raw video case - the API will change slightly in the near
  296. * future for that. */
  297. AVPacket pkt;
  298. av_init_packet(&pkt);
  299. pkt.flags |= AV_PKT_FLAG_KEY;
  300. pkt.stream_index = st->index;
  301. pkt.data = dst_picture.data[0];
  302. pkt.size = sizeof(AVPicture);
  303. ret = av_interleaved_write_frame(oc, &pkt);
  304. } else {
  305. /* encode the image */
  306. AVPacket pkt;
  307. int got_output;
  308. av_init_packet(&pkt);
  309. pkt.data = NULL; // packet data will be allocated by the encoder
  310. pkt.size = 0;
  311. ret = avcodec_encode_video2(c, &pkt, frame, &got_output);
  312. if (ret < 0) {
  313. fprintf(stderr, "Error encoding video frame\n");
  314. exit(1);
  315. }
  316. /* If size is zero, it means the image was buffered. */
  317. if (got_output) {
  318. if (c->coded_frame->pts != AV_NOPTS_VALUE)
  319. pkt.pts = av_rescale_q(c->coded_frame->pts,
  320. c->time_base, st->time_base);
  321. if (c->coded_frame->key_frame)
  322. pkt.flags |= AV_PKT_FLAG_KEY;
  323. pkt.stream_index = st->index;
  324. /* Write the compressed frame to the media file. */
  325. ret = av_interleaved_write_frame(oc, &pkt);
  326. } else {
  327. ret = 0;
  328. }
  329. }
  330. if (ret != 0) {
  331. fprintf(stderr, "Error while writing video frame\n");
  332. exit(1);
  333. }
  334. frame_count++;
  335. }
  336. static void close_video(AVFormatContext *oc, AVStream *st)
  337. {
  338. avcodec_close(st->codec);
  339. av_free(src_picture.data[0]);
  340. av_free(dst_picture.data[0]);
  341. av_free(frame);
  342. av_free(video_outbuf);
  343. }
  344. /**************************************************************/
  345. /* media file output */
  346. int main(int argc, char **argv)
  347. {
  348. const char *filename;
  349. AVOutputFormat *fmt;
  350. AVFormatContext *oc;
  351. AVStream *audio_st, *video_st;
  352. AVCodec *audio_codec, *video_codec;
  353. double audio_pts, video_pts;
  354. int i;
  355. /* Initialize libavcodec, and register all codecs and formats. */
  356. av_register_all();
  357. if (argc != 2) {
  358. printf("usage: %s output_file\n"
  359. "API example program to output a media file with libavformat.\n"
  360. "The output format is automatically guessed according to the file extension.\n"
  361. "Raw images can also be output by using '%%d' in the filename\n"
  362. "\n", argv[0]);
  363. return 1;
  364. }
  365. filename = argv[1];
  366. /* allocate the output media context */
  367. avformat_alloc_output_context2(&oc, NULL, NULL, filename);
  368. if (!oc) {
  369. printf("Could not deduce output format from file extension: using MPEG.\n");
  370. avformat_alloc_output_context2(&oc, NULL, "mpeg", filename);
  371. }
  372. if (!oc) {
  373. return 1;
  374. }
  375. fmt = oc->oformat;
  376. /* Add the audio and video streams using the default format codecs
  377. * and initialize the codecs. */
  378. video_st = NULL;
  379. audio_st = NULL;
  380. if (fmt->video_codec != AV_CODEC_ID_NONE) {
  381. video_st = add_video_stream(oc, &video_codec, fmt->video_codec);
  382. }
  383. if (fmt->audio_codec != AV_CODEC_ID_NONE) {
  384. audio_st = add_audio_stream(oc, &audio_codec, fmt->audio_codec);
  385. }
  386. /* Now that all the parameters are set, we can open the audio and
  387. * video codecs and allocate the necessary encode buffers. */
  388. if (video_st)
  389. open_video(oc, video_codec, video_st);
  390. if (audio_st)
  391. open_audio(oc, audio_codec, audio_st);
  392. av_dump_format(oc, 0, filename, 1);
  393. /* open the output file, if needed */
  394. if (!(fmt->flags & AVFMT_NOFILE)) {
  395. if (avio_open(&oc->pb, filename, AVIO_FLAG_WRITE) < 0) {
  396. fprintf(stderr, "Could not open '%s'\n", filename);
  397. return 1;
  398. }
  399. }
  400. /* Write the stream header, if any. */
  401. if (avformat_write_header(oc, NULL) < 0) {
  402. fprintf(stderr, "Error occurred when opening output file\n");
  403. return 1;
  404. }
  405. frame->pts = 0;
  406. for (;;) {
  407. /* Compute current audio and video time. */
  408. if (audio_st)
  409. audio_pts = (double)audio_st->pts.val * audio_st->time_base.num / audio_st->time_base.den;
  410. else
  411. audio_pts = 0.0;
  412. if (video_st)
  413. video_pts = (double)video_st->pts.val * video_st->time_base.num /
  414. video_st->time_base.den;
  415. else
  416. video_pts = 0.0;
  417. if ((!audio_st || audio_pts >= STREAM_DURATION) &&
  418. (!video_st || video_pts >= STREAM_DURATION))
  419. break;
  420. /* write interleaved audio and video frames */
  421. if (!video_st || (video_st && audio_st && audio_pts < video_pts)) {
  422. write_audio_frame(oc, audio_st);
  423. } else {
  424. write_video_frame(oc, video_st);
  425. frame->pts++;
  426. }
  427. }
  428. /* Write the trailer, if any. The trailer must be written before you
  429. * close the CodecContexts open when you wrote the header; otherwise
  430. * av_write_trailer() may try to use memory that was freed on
  431. * av_codec_close(). */
  432. av_write_trailer(oc);
  433. /* Close each codec. */
  434. if (video_st)
  435. close_video(oc, video_st);
  436. if (audio_st)
  437. close_audio(oc, audio_st);
  438. /* Free the streams. */
  439. for (i = 0; i < oc->nb_streams; i++) {
  440. av_freep(&oc->streams[i]->codec);
  441. av_freep(&oc->streams[i]);
  442. }
  443. if (!(fmt->flags & AVFMT_NOFILE))
  444. /* Close the output file. */
  445. avio_close(oc->pb);
  446. /* free the stream */
  447. av_free(oc);
  448. return 0;
  449. }