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.

561 lines
16KB

  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. * @example output.c
  27. * Output a media file in any supported libavformat format. The default
  28. * codecs are used.
  29. */
  30. #include <stdlib.h>
  31. #include <stdio.h>
  32. #include <string.h>
  33. #include <math.h>
  34. #include "libavutil/channel_layout.h"
  35. #include "libavutil/mathematics.h"
  36. #include "libavformat/avformat.h"
  37. #include "libswscale/swscale.h"
  38. /* 5 seconds stream duration */
  39. #define STREAM_DURATION 5.0
  40. #define STREAM_FRAME_RATE 25 /* 25 images/s */
  41. #define STREAM_NB_FRAMES ((int)(STREAM_DURATION * STREAM_FRAME_RATE))
  42. #define STREAM_PIX_FMT AV_PIX_FMT_YUV420P /* default pix_fmt */
  43. #define SCALE_FLAGS SWS_BICUBIC
  44. // a wrapper around a single output AVStream
  45. typedef struct OutputStream {
  46. AVStream *st;
  47. /* pts of the next frame that will be generated */
  48. int64_t next_pts;
  49. AVFrame *frame;
  50. AVFrame *tmp_frame;
  51. float t, tincr, tincr2;
  52. struct SwsContext *sws_ctx;
  53. } OutputStream;
  54. /**************************************************************/
  55. /* audio output */
  56. /*
  57. * add an audio output stream
  58. */
  59. static void add_audio_stream(OutputStream *ost, AVFormatContext *oc,
  60. enum AVCodecID codec_id)
  61. {
  62. AVCodecContext *c;
  63. AVCodec *codec;
  64. /* find the audio encoder */
  65. codec = avcodec_find_encoder(codec_id);
  66. if (!codec) {
  67. fprintf(stderr, "codec not found\n");
  68. exit(1);
  69. }
  70. ost->st = avformat_new_stream(oc, codec);
  71. if (!ost->st) {
  72. fprintf(stderr, "Could not alloc stream\n");
  73. exit(1);
  74. }
  75. c = ost->st->codec;
  76. /* put sample parameters */
  77. c->sample_fmt = AV_SAMPLE_FMT_S16;
  78. c->bit_rate = 64000;
  79. c->sample_rate = 44100;
  80. c->channels = 2;
  81. c->channel_layout = AV_CH_LAYOUT_STEREO;
  82. // some formats want stream headers to be separate
  83. if (oc->oformat->flags & AVFMT_GLOBALHEADER)
  84. c->flags |= CODEC_FLAG_GLOBAL_HEADER;
  85. }
  86. static void open_audio(AVFormatContext *oc, OutputStream *ost)
  87. {
  88. AVCodecContext *c;
  89. int ret;
  90. c = ost->st->codec;
  91. /* open it */
  92. if (avcodec_open2(c, NULL, NULL) < 0) {
  93. fprintf(stderr, "could not open codec\n");
  94. exit(1);
  95. }
  96. /* init signal generator */
  97. ost->t = 0;
  98. ost->tincr = 2 * M_PI * 110.0 / c->sample_rate;
  99. /* increment frequency by 110 Hz per second */
  100. ost->tincr2 = 2 * M_PI * 110.0 / c->sample_rate / c->sample_rate;
  101. ost->frame = av_frame_alloc();
  102. if (!ost->frame)
  103. exit(1);
  104. ost->frame->sample_rate = c->sample_rate;
  105. ost->frame->format = AV_SAMPLE_FMT_S16;
  106. ost->frame->channel_layout = c->channel_layout;
  107. if (c->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)
  108. ost->frame->nb_samples = 10000;
  109. else
  110. ost->frame->nb_samples = c->frame_size;
  111. ret = av_frame_get_buffer(ost->frame, 0);
  112. if (ret < 0) {
  113. fprintf(stderr, "Could not allocate an audio frame.\n");
  114. exit(1);
  115. }
  116. }
  117. /* Prepare a 16 bit dummy audio frame of 'frame_size' samples and
  118. * 'nb_channels' channels. */
  119. static AVFrame *get_audio_frame(OutputStream *ost)
  120. {
  121. int j, i, v, ret;
  122. int16_t *q = (int16_t*)ost->frame->data[0];
  123. /* check if we want to generate more frames */
  124. if (av_compare_ts(ost->next_pts, ost->st->codec->time_base,
  125. STREAM_DURATION, (AVRational){ 1, 1 }) >= 0)
  126. return NULL;
  127. /* when we pass a frame to the encoder, it may keep a reference to it
  128. * internally;
  129. * make sure we do not overwrite it here
  130. */
  131. ret = av_frame_make_writable(ost->frame);
  132. if (ret < 0)
  133. exit(1);
  134. for (j = 0; j < ost->frame->nb_samples; j++) {
  135. v = (int)(sin(ost->t) * 10000);
  136. for (i = 0; i < ost->st->codec->channels; i++)
  137. *q++ = v;
  138. ost->t += ost->tincr;
  139. ost->tincr += ost->tincr2;
  140. }
  141. ost->frame->pts = ost->next_pts;
  142. ost->next_pts += ost->frame->nb_samples;
  143. return ost->frame;
  144. }
  145. /*
  146. * encode one audio frame and send it to the muxer
  147. * return 1 when encoding is finished, 0 otherwise
  148. */
  149. static int write_audio_frame(AVFormatContext *oc, OutputStream *ost)
  150. {
  151. AVCodecContext *c;
  152. AVPacket pkt = { 0 }; // data and size must be 0;
  153. AVFrame *frame;
  154. int got_packet;
  155. av_init_packet(&pkt);
  156. c = ost->st->codec;
  157. frame = get_audio_frame(ost);
  158. avcodec_encode_audio2(c, &pkt, frame, &got_packet);
  159. if (got_packet) {
  160. pkt.stream_index = ost->st->index;
  161. /* Write the compressed frame to the media file. */
  162. if (av_interleaved_write_frame(oc, &pkt) != 0) {
  163. fprintf(stderr, "Error while writing audio frame\n");
  164. exit(1);
  165. }
  166. }
  167. return (frame || got_packet) ? 0 : 1;
  168. }
  169. /**************************************************************/
  170. /* video output */
  171. /* Add a video output stream. */
  172. static void add_video_stream(OutputStream *ost, AVFormatContext *oc,
  173. enum AVCodecID codec_id)
  174. {
  175. AVCodecContext *c;
  176. AVCodec *codec;
  177. /* find the video encoder */
  178. codec = avcodec_find_encoder(codec_id);
  179. if (!codec) {
  180. fprintf(stderr, "codec not found\n");
  181. exit(1);
  182. }
  183. ost->st = avformat_new_stream(oc, codec);
  184. if (!ost->st) {
  185. fprintf(stderr, "Could not alloc stream\n");
  186. exit(1);
  187. }
  188. c = ost->st->codec;
  189. /* Put sample parameters. */
  190. c->bit_rate = 400000;
  191. /* Resolution must be a multiple of two. */
  192. c->width = 352;
  193. c->height = 288;
  194. /* timebase: This is the fundamental unit of time (in seconds) in terms
  195. * of which frame timestamps are represented. For fixed-fps content,
  196. * timebase should be 1/framerate and timestamp increments should be
  197. * identical to 1. */
  198. c->time_base.den = STREAM_FRAME_RATE;
  199. c->time_base.num = 1;
  200. c->gop_size = 12; /* emit one intra frame every twelve frames at most */
  201. c->pix_fmt = STREAM_PIX_FMT;
  202. if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
  203. /* just for testing, we also add B frames */
  204. c->max_b_frames = 2;
  205. }
  206. if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
  207. /* Needed to avoid using macroblocks in which some coeffs overflow.
  208. * This does not happen with normal video, it just happens here as
  209. * the motion of the chroma plane does not match the luma plane. */
  210. c->mb_decision = 2;
  211. }
  212. /* Some formats want stream headers to be separate. */
  213. if (oc->oformat->flags & AVFMT_GLOBALHEADER)
  214. c->flags |= CODEC_FLAG_GLOBAL_HEADER;
  215. }
  216. static AVFrame *alloc_picture(enum AVPixelFormat pix_fmt, int width, int height)
  217. {
  218. AVFrame *picture;
  219. int ret;
  220. picture = av_frame_alloc();
  221. if (!picture)
  222. return NULL;
  223. picture->format = pix_fmt;
  224. picture->width = width;
  225. picture->height = height;
  226. /* allocate the buffers for the frame data */
  227. ret = av_frame_get_buffer(picture, 32);
  228. if (ret < 0) {
  229. fprintf(stderr, "Could not allocate frame data.\n");
  230. exit(1);
  231. }
  232. return picture;
  233. }
  234. static void open_video(AVFormatContext *oc, OutputStream *ost)
  235. {
  236. AVCodecContext *c;
  237. c = ost->st->codec;
  238. /* open the codec */
  239. if (avcodec_open2(c, NULL, NULL) < 0) {
  240. fprintf(stderr, "could not open codec\n");
  241. exit(1);
  242. }
  243. /* Allocate the encoded raw picture. */
  244. ost->frame = alloc_picture(c->pix_fmt, c->width, c->height);
  245. if (!ost->frame) {
  246. fprintf(stderr, "Could not allocate picture\n");
  247. exit(1);
  248. }
  249. /* If the output format is not YUV420P, then a temporary YUV420P
  250. * picture is needed too. It is then converted to the required
  251. * output format. */
  252. ost->tmp_frame = NULL;
  253. if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
  254. ost->tmp_frame = alloc_picture(AV_PIX_FMT_YUV420P, c->width, c->height);
  255. if (!ost->tmp_frame) {
  256. fprintf(stderr, "Could not allocate temporary picture\n");
  257. exit(1);
  258. }
  259. }
  260. }
  261. /* Prepare a dummy image. */
  262. static void fill_yuv_image(AVFrame *pict, int frame_index,
  263. int width, int height)
  264. {
  265. int x, y, i, ret;
  266. /* when we pass a frame to the encoder, it may keep a reference to it
  267. * internally;
  268. * make sure we do not overwrite it here
  269. */
  270. ret = av_frame_make_writable(pict);
  271. if (ret < 0)
  272. exit(1);
  273. i = frame_index;
  274. /* Y */
  275. for (y = 0; y < height; y++)
  276. for (x = 0; x < width; x++)
  277. pict->data[0][y * pict->linesize[0] + x] = x + y + i * 3;
  278. /* Cb and Cr */
  279. for (y = 0; y < height / 2; y++) {
  280. for (x = 0; x < width / 2; x++) {
  281. pict->data[1][y * pict->linesize[1] + x] = 128 + y + i * 2;
  282. pict->data[2][y * pict->linesize[2] + x] = 64 + x + i * 5;
  283. }
  284. }
  285. }
  286. static AVFrame *get_video_frame(OutputStream *ost)
  287. {
  288. AVCodecContext *c = ost->st->codec;
  289. /* check if we want to generate more frames */
  290. if (av_compare_ts(ost->next_pts, ost->st->codec->time_base,
  291. STREAM_DURATION, (AVRational){ 1, 1 }) >= 0)
  292. return NULL;
  293. if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
  294. /* as we only generate a YUV420P picture, we must convert it
  295. * to the codec pixel format if needed */
  296. if (!ost->sws_ctx) {
  297. ost->sws_ctx = sws_getContext(c->width, c->height,
  298. AV_PIX_FMT_YUV420P,
  299. c->width, c->height,
  300. c->pix_fmt,
  301. SCALE_FLAGS, NULL, NULL, NULL);
  302. if (!ost->sws_ctx) {
  303. fprintf(stderr,
  304. "Cannot initialize the conversion context\n");
  305. exit(1);
  306. }
  307. }
  308. fill_yuv_image(ost->tmp_frame, ost->next_pts, c->width, c->height);
  309. sws_scale(ost->sws_ctx, ost->tmp_frame->data, ost->tmp_frame->linesize,
  310. 0, c->height, ost->frame->data, ost->frame->linesize);
  311. } else {
  312. fill_yuv_image(ost->frame, ost->next_pts, c->width, c->height);
  313. }
  314. ost->frame->pts = ost->next_pts++;
  315. return ost->frame;
  316. }
  317. /*
  318. * encode one video frame and send it to the muxer
  319. * return 1 when encoding is finished, 0 otherwise
  320. */
  321. static int write_video_frame(AVFormatContext *oc, OutputStream *ost)
  322. {
  323. int ret;
  324. AVCodecContext *c;
  325. AVFrame *frame;
  326. int got_packet = 0;
  327. c = ost->st->codec;
  328. frame = get_video_frame(ost);
  329. if (oc->oformat->flags & AVFMT_RAWPICTURE) {
  330. /* a hack to avoid data copy with some raw video muxers */
  331. AVPacket pkt;
  332. av_init_packet(&pkt);
  333. if (!frame)
  334. return 1;
  335. pkt.flags |= AV_PKT_FLAG_KEY;
  336. pkt.stream_index = ost->st->index;
  337. pkt.data = (uint8_t *)frame;
  338. pkt.size = sizeof(AVPicture);
  339. pkt.pts = pkt.dts = frame->pts;
  340. av_packet_rescale_ts(&pkt, c->time_base, ost->st->time_base);
  341. ret = av_interleaved_write_frame(oc, &pkt);
  342. } else {
  343. AVPacket pkt = { 0 };
  344. av_init_packet(&pkt);
  345. /* encode the image */
  346. ret = avcodec_encode_video2(c, &pkt, frame, &got_packet);
  347. if (ret < 0) {
  348. fprintf(stderr, "Error encoding a video frame\n");
  349. exit(1);
  350. }
  351. if (got_packet) {
  352. av_packet_rescale_ts(&pkt, c->time_base, ost->st->time_base);
  353. pkt.stream_index = ost->st->index;
  354. /* Write the compressed frame to the media file. */
  355. ret = av_interleaved_write_frame(oc, &pkt);
  356. }
  357. }
  358. if (ret != 0) {
  359. fprintf(stderr, "Error while writing video frame\n");
  360. exit(1);
  361. }
  362. return (frame || got_packet) ? 0 : 1;
  363. }
  364. static void close_stream(AVFormatContext *oc, OutputStream *ost)
  365. {
  366. avcodec_close(ost->st->codec);
  367. av_frame_free(&ost->frame);
  368. av_frame_free(&ost->tmp_frame);
  369. sws_freeContext(ost->sws_ctx);
  370. }
  371. /**************************************************************/
  372. /* media file output */
  373. int main(int argc, char **argv)
  374. {
  375. OutputStream video_st = { 0 }, audio_st = { 0 };
  376. const char *filename;
  377. AVOutputFormat *fmt;
  378. AVFormatContext *oc;
  379. int have_video = 0, have_audio = 0;
  380. int encode_video = 0, encode_audio = 0;
  381. int i;
  382. /* Initialize libavcodec, and register all codecs and formats. */
  383. av_register_all();
  384. if (argc != 2) {
  385. printf("usage: %s output_file\n"
  386. "API example program to output a media file with libavformat.\n"
  387. "The output format is automatically guessed according to the file extension.\n"
  388. "Raw images can also be output by using '%%d' in the filename\n"
  389. "\n", argv[0]);
  390. return 1;
  391. }
  392. filename = argv[1];
  393. /* Autodetect the output format from the name. default is MPEG. */
  394. fmt = av_guess_format(NULL, filename, NULL);
  395. if (!fmt) {
  396. printf("Could not deduce output format from file extension: using MPEG.\n");
  397. fmt = av_guess_format("mpeg", NULL, NULL);
  398. }
  399. if (!fmt) {
  400. fprintf(stderr, "Could not find suitable output format\n");
  401. return 1;
  402. }
  403. /* Allocate the output media context. */
  404. oc = avformat_alloc_context();
  405. if (!oc) {
  406. fprintf(stderr, "Memory error\n");
  407. return 1;
  408. }
  409. oc->oformat = fmt;
  410. snprintf(oc->filename, sizeof(oc->filename), "%s", filename);
  411. /* Add the audio and video streams using the default format codecs
  412. * and initialize the codecs. */
  413. if (fmt->video_codec != AV_CODEC_ID_NONE) {
  414. add_video_stream(&video_st, oc, fmt->video_codec);
  415. have_video = 1;
  416. encode_video = 1;
  417. }
  418. if (fmt->audio_codec != AV_CODEC_ID_NONE) {
  419. add_audio_stream(&audio_st, oc, fmt->audio_codec);
  420. have_audio = 1;
  421. encode_audio = 1;
  422. }
  423. /* Now that all the parameters are set, we can open the audio and
  424. * video codecs and allocate the necessary encode buffers. */
  425. if (have_video)
  426. open_video(oc, &video_st);
  427. if (have_audio)
  428. open_audio(oc, &audio_st);
  429. av_dump_format(oc, 0, filename, 1);
  430. /* open the output file, if needed */
  431. if (!(fmt->flags & AVFMT_NOFILE)) {
  432. if (avio_open(&oc->pb, filename, AVIO_FLAG_WRITE) < 0) {
  433. fprintf(stderr, "Could not open '%s'\n", filename);
  434. return 1;
  435. }
  436. }
  437. /* Write the stream header, if any. */
  438. avformat_write_header(oc, NULL);
  439. while (encode_video || encode_audio) {
  440. /* select the stream to encode */
  441. if (encode_video &&
  442. (!encode_audio || av_compare_ts(video_st.next_pts, video_st.st->codec->time_base,
  443. audio_st.next_pts, audio_st.st->codec->time_base) <= 0)) {
  444. encode_video = !write_video_frame(oc, &video_st);
  445. } else {
  446. encode_audio = !write_audio_frame(oc, &audio_st);
  447. }
  448. }
  449. /* Write the trailer, if any. The trailer must be written before you
  450. * close the CodecContexts open when you wrote the header; otherwise
  451. * av_write_trailer() may try to use memory that was freed on
  452. * av_codec_close(). */
  453. av_write_trailer(oc);
  454. /* Close each codec. */
  455. if (have_video)
  456. close_stream(oc, &video_st);
  457. if (have_audio)
  458. close_stream(oc, &audio_st);
  459. if (!(fmt->flags & AVFMT_NOFILE))
  460. /* Close the output file. */
  461. avio_close(oc->pb);
  462. /* free the stream */
  463. avformat_free_context(oc);
  464. return 0;
  465. }