FFmpeg
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
muxing.c
Go to the documentation of this file.
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 /**
24  * @file
25  * libavformat API example.
26  *
27  * Output a media file in any supported libavformat format.
28  * The default codecs are used.
29  * @example doc/examples/muxing.c
30  */
31 
32 #include <stdlib.h>
33 #include <stdio.h>
34 #include <string.h>
35 #include <math.h>
36 
37 #include <libavutil/mathematics.h>
38 #include <libavformat/avformat.h>
39 #include <libswscale/swscale.h>
40 
41 /* 5 seconds stream duration */
42 #define STREAM_DURATION 200.0
43 #define STREAM_FRAME_RATE 25 /* 25 images/s */
44 #define STREAM_NB_FRAMES ((int)(STREAM_DURATION * STREAM_FRAME_RATE))
45 #define STREAM_PIX_FMT AV_PIX_FMT_YUV420P /* default pix_fmt */
46 
47 static int sws_flags = SWS_BICUBIC;
48 
49 /**************************************************************/
50 /* audio output */
51 
52 static float t, tincr, tincr2;
53 static int16_t *samples;
55 
56 /* Add an output stream. */
58  enum AVCodecID codec_id)
59 {
61  AVStream *st;
62 
63  /* find the encoder */
64  *codec = avcodec_find_encoder(codec_id);
65  if (!(*codec)) {
66  fprintf(stderr, "Could not find encoder for '%s'\n",
67  avcodec_get_name(codec_id));
68  exit(1);
69  }
70 
71  st = avformat_new_stream(oc, *codec);
72  if (!st) {
73  fprintf(stderr, "Could not allocate stream\n");
74  exit(1);
75  }
76  st->id = oc->nb_streams-1;
77  c = st->codec;
78 
79  switch ((*codec)->type) {
80  case AVMEDIA_TYPE_AUDIO:
81  st->id = 1;
83  c->bit_rate = 64000;
84  c->sample_rate = 44100;
85  c->channels = 2;
86  break;
87 
88  case AVMEDIA_TYPE_VIDEO:
89  c->codec_id = codec_id;
90 
91  c->bit_rate = 400000;
92  /* Resolution must be a multiple of two. */
93  c->width = 352;
94  c->height = 288;
95  /* timebase: This is the fundamental unit of time (in seconds) in terms
96  * of which frame timestamps are represented. For fixed-fps content,
97  * timebase should be 1/framerate and timestamp increments should be
98  * identical to 1. */
100  c->time_base.num = 1;
101  c->gop_size = 12; /* emit one intra frame every twelve frames at most */
102  c->pix_fmt = STREAM_PIX_FMT;
103  if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
104  /* just for testing, we also add B frames */
105  c->max_b_frames = 2;
106  }
107  if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
108  /* Needed to avoid using macroblocks in which some coeffs overflow.
109  * This does not happen with normal video, it just happens here as
110  * the motion of the chroma plane does not match the luma plane. */
111  c->mb_decision = 2;
112  }
113  break;
114 
115  default:
116  break;
117  }
118 
119  /* Some formats want stream headers to be separate. */
120  if (oc->oformat->flags & AVFMT_GLOBALHEADER)
122 
123  return st;
124 }
125 
126 /**************************************************************/
127 /* audio output */
128 
129 static float t, tincr, tincr2;
130 static int16_t *samples;
131 static int audio_input_frame_size;
132 
133 static void open_audio(AVFormatContext *oc, AVCodec *codec, AVStream *st)
134 {
135  AVCodecContext *c;
136  int ret;
137 
138  c = st->codec;
139 
140  /* open it */
141  ret = avcodec_open2(c, codec, NULL);
142  if (ret < 0) {
143  fprintf(stderr, "Could not open audio codec: %s\n", av_err2str(ret));
144  exit(1);
145  }
146 
147  /* init signal generator */
148  t = 0;
149  tincr = 2 * M_PI * 110.0 / c->sample_rate;
150  /* increment frequency by 110 Hz per second */
151  tincr2 = 2 * M_PI * 110.0 / c->sample_rate / c->sample_rate;
152 
154  audio_input_frame_size = 10000;
155  else
159  c->channels);
160  if (!samples) {
161  fprintf(stderr, "Could not allocate audio samples buffer\n");
162  exit(1);
163  }
164 }
165 
166 /* Prepare a 16 bit dummy audio frame of 'frame_size' samples and
167  * 'nb_channels' channels. */
168 static void get_audio_frame(int16_t *samples, int frame_size, int nb_channels)
169 {
170  int j, i, v;
171  int16_t *q;
172 
173  q = samples;
174  for (j = 0; j < frame_size; j++) {
175  v = (int)(sin(t) * 10000);
176  for (i = 0; i < nb_channels; i++)
177  *q++ = v;
178  t += tincr;
179  tincr += tincr2;
180  }
181 }
182 
184 {
185  AVCodecContext *c;
186  AVPacket pkt = { 0 }; // data and size must be 0;
188  int got_packet, ret;
189 
190  av_init_packet(&pkt);
191  c = st->codec;
192 
196  (uint8_t *)samples,
199  c->channels, 1);
200 
201  ret = avcodec_encode_audio2(c, &pkt, frame, &got_packet);
202  if (ret < 0) {
203  fprintf(stderr, "Error encoding audio frame: %s\n", av_err2str(ret));
204  exit(1);
205  }
206 
207  if (!got_packet)
208  return;
209 
210  pkt.stream_index = st->index;
211 
212  /* Write the compressed frame to the media file. */
213  ret = av_interleaved_write_frame(oc, &pkt);
214  if (ret != 0) {
215  fprintf(stderr, "Error while writing audio frame: %s\n",
216  av_err2str(ret));
217  exit(1);
218  }
219  avcodec_free_frame(&frame);
220 }
221 
222 static void close_audio(AVFormatContext *oc, AVStream *st)
223 {
224  avcodec_close(st->codec);
225 
226  av_free(samples);
227 }
228 
229 /**************************************************************/
230 /* video output */
231 
232 static AVFrame *frame;
234 static int frame_count;
235 
236 static void open_video(AVFormatContext *oc, AVCodec *codec, AVStream *st)
237 {
238  int ret;
239  AVCodecContext *c = st->codec;
240 
241  /* open the codec */
242  ret = avcodec_open2(c, codec, NULL);
243  if (ret < 0) {
244  fprintf(stderr, "Could not open video codec: %s\n", av_err2str(ret));
245  exit(1);
246  }
247 
248  /* allocate and init a re-usable frame */
249  frame = avcodec_alloc_frame();
250  if (!frame) {
251  fprintf(stderr, "Could not allocate video frame\n");
252  exit(1);
253  }
254 
255  /* Allocate the encoded raw picture. */
256  ret = avpicture_alloc(&dst_picture, c->pix_fmt, c->width, c->height);
257  if (ret < 0) {
258  fprintf(stderr, "Could not allocate picture: %s\n", av_err2str(ret));
259  exit(1);
260  }
261 
262  /* If the output format is not YUV420P, then a temporary YUV420P
263  * picture is needed too. It is then converted to the required
264  * output format. */
265  if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
266  ret = avpicture_alloc(&src_picture, AV_PIX_FMT_YUV420P, c->width, c->height);
267  if (ret < 0) {
268  fprintf(stderr, "Could not allocate temporary picture: %s\n",
269  av_err2str(ret));
270  exit(1);
271  }
272  }
273 
274  /* copy data and linesize picture pointers to frame */
275  *((AVPicture *)frame) = dst_picture;
276 }
277 
278 /* Prepare a dummy image. */
279 static void fill_yuv_image(AVPicture *pict, int frame_index,
280  int width, int height)
281 {
282  int x, y, i;
283 
284  i = frame_index;
285 
286  /* Y */
287  for (y = 0; y < height; y++)
288  for (x = 0; x < width; x++)
289  pict->data[0][y * pict->linesize[0] + x] = x + y + i * 3;
290 
291  /* Cb and Cr */
292  for (y = 0; y < height / 2; y++) {
293  for (x = 0; x < width / 2; x++) {
294  pict->data[1][y * pict->linesize[1] + x] = 128 + y + i * 2;
295  pict->data[2][y * pict->linesize[2] + x] = 64 + x + i * 5;
296  }
297  }
298 }
299 
301 {
302  int ret;
303  static struct SwsContext *sws_ctx;
304  AVCodecContext *c = st->codec;
305 
306  if (frame_count >= STREAM_NB_FRAMES) {
307  /* No more frames to compress. The codec has a latency of a few
308  * frames if using B-frames, so we get the last frames by
309  * passing the same picture again. */
310  } else {
311  if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
312  /* as we only generate a YUV420P picture, we must convert it
313  * to the codec pixel format if needed */
314  if (!sws_ctx) {
315  sws_ctx = sws_getContext(c->width, c->height, AV_PIX_FMT_YUV420P,
316  c->width, c->height, c->pix_fmt,
317  sws_flags, NULL, NULL, NULL);
318  if (!sws_ctx) {
319  fprintf(stderr,
320  "Could not initialize the conversion context\n");
321  exit(1);
322  }
323  }
324  fill_yuv_image(&src_picture, frame_count, c->width, c->height);
325  sws_scale(sws_ctx,
326  (const uint8_t * const *)src_picture.data, src_picture.linesize,
327  0, c->height, dst_picture.data, dst_picture.linesize);
328  } else {
329  fill_yuv_image(&dst_picture, frame_count, c->width, c->height);
330  }
331  }
332 
333  if (oc->oformat->flags & AVFMT_RAWPICTURE) {
334  /* Raw video case - directly store the picture in the packet */
335  AVPacket pkt;
336  av_init_packet(&pkt);
337 
338  pkt.flags |= AV_PKT_FLAG_KEY;
339  pkt.stream_index = st->index;
340  pkt.data = dst_picture.data[0];
341  pkt.size = sizeof(AVPicture);
342 
343  ret = av_interleaved_write_frame(oc, &pkt);
344  } else {
345  /* encode the image */
346  AVPacket pkt;
347  int got_output;
348 
349  av_init_packet(&pkt);
350  pkt.data = NULL; // packet data will be allocated by the encoder
351  pkt.size = 0;
352 
353  ret = avcodec_encode_video2(c, &pkt, frame, &got_output);
354  if (ret < 0) {
355  fprintf(stderr, "Error encoding video frame: %s\n", av_err2str(ret));
356  exit(1);
357  }
358 
359  /* If size is zero, it means the image was buffered. */
360  if (got_output) {
361  if (c->coded_frame->key_frame)
362  pkt.flags |= AV_PKT_FLAG_KEY;
363 
364  pkt.stream_index = st->index;
365 
366  /* Write the compressed frame to the media file. */
367  ret = av_interleaved_write_frame(oc, &pkt);
368  } else {
369  ret = 0;
370  }
371  }
372  if (ret != 0) {
373  fprintf(stderr, "Error while writing video frame: %s\n", av_err2str(ret));
374  exit(1);
375  }
376  frame_count++;
377 }
378 
379 static void close_video(AVFormatContext *oc, AVStream *st)
380 {
381  avcodec_close(st->codec);
382  av_free(src_picture.data[0]);
383  av_free(dst_picture.data[0]);
384  av_free(frame);
385 }
386 
387 /**************************************************************/
388 /* media file output */
389 
390 int main(int argc, char **argv)
391 {
392  const char *filename;
394  AVFormatContext *oc;
395  AVStream *audio_st, *video_st;
396  AVCodec *audio_codec, *video_codec;
397  double audio_pts, video_pts;
398  int ret;
399 
400  /* Initialize libavcodec, and register all codecs and formats. */
401  av_register_all();
402 
403  if (argc != 2) {
404  printf("usage: %s output_file\n"
405  "API example program to output a media file with libavformat.\n"
406  "This program generates a synthetic audio and video stream, encodes and\n"
407  "muxes them into a file named output_file.\n"
408  "The output format is automatically guessed according to the file extension.\n"
409  "Raw images can also be output by using '%%d' in the filename.\n"
410  "\n", argv[0]);
411  return 1;
412  }
413 
414  filename = argv[1];
415 
416  /* allocate the output media context */
417  avformat_alloc_output_context2(&oc, NULL, NULL, filename);
418  if (!oc) {
419  printf("Could not deduce output format from file extension: using MPEG.\n");
420  avformat_alloc_output_context2(&oc, NULL, "mpeg", filename);
421  }
422  if (!oc) {
423  return 1;
424  }
425  fmt = oc->oformat;
426 
427  /* Add the audio and video streams using the default format codecs
428  * and initialize the codecs. */
429  video_st = NULL;
430  audio_st = NULL;
431 
432  if (fmt->video_codec != AV_CODEC_ID_NONE) {
433  video_st = add_stream(oc, &video_codec, fmt->video_codec);
434  }
435  if (fmt->audio_codec != AV_CODEC_ID_NONE) {
436  audio_st = add_stream(oc, &audio_codec, fmt->audio_codec);
437  }
438 
439  /* Now that all the parameters are set, we can open the audio and
440  * video codecs and allocate the necessary encode buffers. */
441  if (video_st)
442  open_video(oc, video_codec, video_st);
443  if (audio_st)
444  open_audio(oc, audio_codec, audio_st);
445 
446  av_dump_format(oc, 0, filename, 1);
447 
448  /* open the output file, if needed */
449  if (!(fmt->flags & AVFMT_NOFILE)) {
450  ret = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE);
451  if (ret < 0) {
452  fprintf(stderr, "Could not open '%s': %s\n", filename,
453  av_err2str(ret));
454  return 1;
455  }
456  }
457 
458  /* Write the stream header, if any. */
459  ret = avformat_write_header(oc, NULL);
460  if (ret < 0) {
461  fprintf(stderr, "Error occurred when opening output file: %s\n",
462  av_err2str(ret));
463  return 1;
464  }
465 
466  if (frame)
467  frame->pts = 0;
468  for (;;) {
469  /* Compute current audio and video time. */
470  if (audio_st)
471  audio_pts = (double)audio_st->pts.val * audio_st->time_base.num / audio_st->time_base.den;
472  else
473  audio_pts = 0.0;
474 
475  if (video_st)
476  video_pts = (double)video_st->pts.val * video_st->time_base.num /
477  video_st->time_base.den;
478  else
479  video_pts = 0.0;
480 
481  if ((!audio_st || audio_pts >= STREAM_DURATION) &&
482  (!video_st || video_pts >= STREAM_DURATION))
483  break;
484 
485  /* write interleaved audio and video frames */
486  if (!video_st || (video_st && audio_st && audio_pts < video_pts)) {
487  write_audio_frame(oc, audio_st);
488  } else {
489  write_video_frame(oc, video_st);
490  frame->pts += av_rescale_q(1, video_st->codec->time_base, video_st->time_base);
491  }
492  }
493 
494  /* Write the trailer, if any. The trailer must be written before you
495  * close the CodecContexts open when you wrote the header; otherwise
496  * av_write_trailer() may try to use memory that was freed on
497  * av_codec_close(). */
498  av_write_trailer(oc);
499 
500  /* Close each codec. */
501  if (video_st)
502  close_video(oc, video_st);
503  if (audio_st)
504  close_audio(oc, audio_st);
505 
506  if (!(fmt->flags & AVFMT_NOFILE))
507  /* Close the output file. */
508  avio_close(oc->pb);
509 
510  /* free the stream */
512 
513  return 0;
514 }