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.

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