FFmpeg
 All Data Structures Namespaces 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. The default
28  * codecs are used.
29  * @example muxing.c
30  */
31 
32 #include <stdlib.h>
33 #include <stdio.h>
34 #include <string.h>
35 #include <math.h>
36 
37 #include <libavutil/opt.h>
38 #include <libavutil/mathematics.h>
39 #include <libavutil/timestamp.h>
40 #include <libavformat/avformat.h>
41 #include <libswscale/swscale.h>
43 
45 
46 #define STREAM_DURATION 10.0
47 #define STREAM_FRAME_RATE 25 /* 25 images/s */
48 #define STREAM_PIX_FMT AV_PIX_FMT_YUV420P /* default pix_fmt */
49 
50 static int sws_flags = SWS_BICUBIC;
51 
52 static void log_packet(const AVFormatContext *fmt_ctx, const AVPacket *pkt)
53 {
54  AVRational *time_base = &fmt_ctx->streams[pkt->stream_index]->time_base;
55 
56  printf("pts:%s pts_time:%s dts:%s dts_time:%s duration:%s duration_time:%s stream_index:%d\n",
57  av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, time_base),
58  av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, time_base),
59  av_ts2str(pkt->duration), av_ts2timestr(pkt->duration, time_base),
60  pkt->stream_index);
61 }
62 
63 static int write_frame(AVFormatContext *fmt_ctx, const AVRational *time_base, AVStream *st, AVPacket *pkt)
64 {
65  /* rescale output packet timestamp values from codec to stream timebase */
68  pkt->duration = av_rescale_q(pkt->duration, *time_base, st->time_base);
69  pkt->stream_index = st->index;
70 
71  /* Write the compressed frame to the media file. */
72  log_packet(fmt_ctx, pkt);
73  return av_interleaved_write_frame(fmt_ctx, pkt);
74 }
75 
76 /* Add an output stream. */
78  enum AVCodecID codec_id)
79 {
81  AVStream *st;
82 
83  /* find the encoder */
84  *codec = avcodec_find_encoder(codec_id);
85  if (!(*codec)) {
86  fprintf(stderr, "Could not find encoder for '%s'\n",
87  avcodec_get_name(codec_id));
88  exit(1);
89  }
90 
91  st = avformat_new_stream(oc, *codec);
92  if (!st) {
93  fprintf(stderr, "Could not allocate stream\n");
94  exit(1);
95  }
96  st->id = oc->nb_streams-1;
97  c = st->codec;
98 
99  switch ((*codec)->type) {
100  case AVMEDIA_TYPE_AUDIO:
101  c->sample_fmt = (*codec)->sample_fmts ?
102  (*codec)->sample_fmts[0] : AV_SAMPLE_FMT_FLTP;
103  c->bit_rate = 64000;
104  c->sample_rate = 44100;
105  c->channels = 2;
106  break;
107 
108  case AVMEDIA_TYPE_VIDEO:
109  c->codec_id = codec_id;
110 
111  c->bit_rate = 400000;
112  /* Resolution must be a multiple of two. */
113  c->width = 352;
114  c->height = 288;
115  /* timebase: This is the fundamental unit of time (in seconds) in terms
116  * of which frame timestamps are represented. For fixed-fps content,
117  * timebase should be 1/framerate and timestamp increments should be
118  * identical to 1. */
120  c->time_base.num = 1;
121  c->gop_size = 12; /* emit one intra frame every twelve frames at most */
122  c->pix_fmt = STREAM_PIX_FMT;
123  if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
124  /* just for testing, we also add B frames */
125  c->max_b_frames = 2;
126  }
127  if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
128  /* Needed to avoid using macroblocks in which some coeffs overflow.
129  * This does not happen with normal video, it just happens here as
130  * the motion of the chroma plane does not match the luma plane. */
131  c->mb_decision = 2;
132  }
133  break;
134 
135  default:
136  break;
137  }
138 
139  /* Some formats want stream headers to be separate. */
140  if (oc->oformat->flags & AVFMT_GLOBALHEADER)
142 
143  return st;
144 }
145 
146 /**************************************************************/
147 /* audio output */
148 
149 static float t, tincr, tincr2;
150 
154 static int src_nb_samples;
155 
161 
162 struct SwrContext *swr_ctx = NULL;
163 
164 static void open_audio(AVFormatContext *oc, AVCodec *codec, AVStream *st)
165 {
166  AVCodecContext *c;
167  int ret;
168 
169  c = st->codec;
170 
171  /* allocate and init a re-usable frame */
172  audio_frame = av_frame_alloc();
173  if (!audio_frame) {
174  fprintf(stderr, "Could not allocate audio frame\n");
175  exit(1);
176  }
177 
178  /* open it */
179  ret = avcodec_open2(c, codec, NULL);
180  if (ret < 0) {
181  fprintf(stderr, "Could not open audio codec: %s\n", av_err2str(ret));
182  exit(1);
183  }
184 
185  /* init signal generator */
186  t = 0;
187  tincr = 2 * M_PI * 110.0 / c->sample_rate;
188  /* increment frequency by 110 Hz per second */
189  tincr2 = 2 * M_PI * 110.0 / c->sample_rate / c->sample_rate;
190 
192  10000 : c->frame_size;
193 
196  if (ret < 0) {
197  fprintf(stderr, "Could not allocate source samples\n");
198  exit(1);
199  }
200 
201  /* compute the number of converted samples: buffering is avoided
202  * ensuring that the output buffer will contain at least all the
203  * converted input samples */
205 
206  /* create resampler context */
207  if (c->sample_fmt != AV_SAMPLE_FMT_S16) {
208  swr_ctx = swr_alloc();
209  if (!swr_ctx) {
210  fprintf(stderr, "Could not allocate resampler context\n");
211  exit(1);
212  }
213 
214  /* set options */
215  av_opt_set_int (swr_ctx, "in_channel_count", c->channels, 0);
216  av_opt_set_int (swr_ctx, "in_sample_rate", c->sample_rate, 0);
217  av_opt_set_sample_fmt(swr_ctx, "in_sample_fmt", AV_SAMPLE_FMT_S16, 0);
218  av_opt_set_int (swr_ctx, "out_channel_count", c->channels, 0);
219  av_opt_set_int (swr_ctx, "out_sample_rate", c->sample_rate, 0);
220  av_opt_set_sample_fmt(swr_ctx, "out_sample_fmt", c->sample_fmt, 0);
221 
222  /* initialize the resampling context */
223  if ((ret = swr_init(swr_ctx)) < 0) {
224  fprintf(stderr, "Failed to initialize the resampling context\n");
225  exit(1);
226  }
227 
230  if (ret < 0) {
231  fprintf(stderr, "Could not allocate destination samples\n");
232  exit(1);
233  }
234  } else {
236  }
238  c->sample_fmt, 0);
239 }
240 
241 /* Prepare a 16 bit dummy audio frame of 'frame_size' samples and
242  * 'nb_channels' channels. */
243 static void get_audio_frame(int16_t *samples, int frame_size, int nb_channels)
244 {
245  int j, i, v;
246  int16_t *q;
247 
248  q = samples;
249  for (j = 0; j < frame_size; j++) {
250  v = (int)(sin(t) * 10000);
251  for (i = 0; i < nb_channels; i++)
252  *q++ = v;
253  t += tincr;
254  tincr += tincr2;
255  }
256 }
257 
259 {
260  AVCodecContext *c;
261  AVPacket pkt = { 0 }; // data and size must be 0;
262  int got_packet, ret, dst_nb_samples;
263 
264  av_init_packet(&pkt);
265  c = st->codec;
266 
267  if (!flush) {
269 
270  /* convert samples from native format to destination codec format, using the resampler */
271  if (swr_ctx) {
272  /* compute destination number of samples */
273  dst_nb_samples = av_rescale_rnd(swr_get_delay(swr_ctx, c->sample_rate) + src_nb_samples,
275  if (dst_nb_samples > max_dst_nb_samples) {
278  dst_nb_samples, c->sample_fmt, 0);
279  if (ret < 0)
280  exit(1);
281  max_dst_nb_samples = dst_nb_samples;
282  dst_samples_size = av_samples_get_buffer_size(NULL, c->channels, dst_nb_samples,
283  c->sample_fmt, 0);
284  }
285 
286  /* convert to destination format */
287  ret = swr_convert(swr_ctx,
288  dst_samples_data, dst_nb_samples,
290  if (ret < 0) {
291  fprintf(stderr, "Error while converting\n");
292  exit(1);
293  }
294  } else {
295  dst_nb_samples = src_nb_samples;
296  }
297 
298  audio_frame->nb_samples = dst_nb_samples;
299  audio_frame->pts = av_rescale_q(samples_count, (AVRational){1, c->sample_rate}, c->time_base);
300  avcodec_fill_audio_frame(audio_frame, c->channels, c->sample_fmt,
302  samples_count += dst_nb_samples;
303  }
304 
305  ret = avcodec_encode_audio2(c, &pkt, flush ? NULL : audio_frame, &got_packet);
306  if (ret < 0) {
307  fprintf(stderr, "Error encoding audio frame: %s\n", av_err2str(ret));
308  exit(1);
309  }
310 
311  if (!got_packet) {
312  if (flush)
313  audio_is_eof = 1;
314  return;
315  }
316 
317  ret = write_frame(oc, &c->time_base, st, &pkt);
318  if (ret < 0) {
319  fprintf(stderr, "Error while writing audio frame: %s\n",
320  av_err2str(ret));
321  exit(1);
322  }
323 }
324 
325 static void close_audio(AVFormatContext *oc, AVStream *st)
326 {
327  avcodec_close(st->codec);
331  }
334  av_frame_free(&audio_frame);
335 }
336 
337 /**************************************************************/
338 /* video output */
339 
340 static AVFrame *frame;
342 static int frame_count;
343 
344 static void open_video(AVFormatContext *oc, AVCodec *codec, AVStream *st)
345 {
346  int ret;
347  AVCodecContext *c = st->codec;
348 
349  /* open the codec */
350  ret = avcodec_open2(c, codec, NULL);
351  if (ret < 0) {
352  fprintf(stderr, "Could not open video codec: %s\n", av_err2str(ret));
353  exit(1);
354  }
355 
356  /* allocate and init a re-usable frame */
357  frame = av_frame_alloc();
358  if (!frame) {
359  fprintf(stderr, "Could not allocate video frame\n");
360  exit(1);
361  }
362  frame->format = c->pix_fmt;
363  frame->width = c->width;
364  frame->height = c->height;
365 
366  /* Allocate the encoded raw picture. */
367  ret = avpicture_alloc(&dst_picture, c->pix_fmt, c->width, c->height);
368  if (ret < 0) {
369  fprintf(stderr, "Could not allocate picture: %s\n", av_err2str(ret));
370  exit(1);
371  }
372 
373  /* If the output format is not YUV420P, then a temporary YUV420P
374  * picture is needed too. It is then converted to the required
375  * output format. */
376  if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
377  ret = avpicture_alloc(&src_picture, AV_PIX_FMT_YUV420P, c->width, c->height);
378  if (ret < 0) {
379  fprintf(stderr, "Could not allocate temporary picture: %s\n",
380  av_err2str(ret));
381  exit(1);
382  }
383  }
384 
385  /* copy data and linesize picture pointers to frame */
386  *((AVPicture *)frame) = dst_picture;
387 }
388 
389 /* Prepare a dummy image. */
390 static void fill_yuv_image(AVPicture *pict, int frame_index,
391  int width, int height)
392 {
393  int x, y, i;
394 
395  i = frame_index;
396 
397  /* Y */
398  for (y = 0; y < height; y++)
399  for (x = 0; x < width; x++)
400  pict->data[0][y * pict->linesize[0] + x] = x + y + i * 3;
401 
402  /* Cb and Cr */
403  for (y = 0; y < height / 2; y++) {
404  for (x = 0; x < width / 2; x++) {
405  pict->data[1][y * pict->linesize[1] + x] = 128 + y + i * 2;
406  pict->data[2][y * pict->linesize[2] + x] = 64 + x + i * 5;
407  }
408  }
409 }
410 
412 {
413  int ret;
414  static struct SwsContext *sws_ctx;
415  AVCodecContext *c = st->codec;
416 
417  if (!flush) {
418  if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
419  /* as we only generate a YUV420P picture, we must convert it
420  * to the codec pixel format if needed */
421  if (!sws_ctx) {
422  sws_ctx = sws_getContext(c->width, c->height, AV_PIX_FMT_YUV420P,
423  c->width, c->height, c->pix_fmt,
424  sws_flags, NULL, NULL, NULL);
425  if (!sws_ctx) {
426  fprintf(stderr,
427  "Could not initialize the conversion context\n");
428  exit(1);
429  }
430  }
431  fill_yuv_image(&src_picture, frame_count, c->width, c->height);
432  sws_scale(sws_ctx,
433  (const uint8_t * const *)src_picture.data, src_picture.linesize,
434  0, c->height, dst_picture.data, dst_picture.linesize);
435  } else {
436  fill_yuv_image(&dst_picture, frame_count, c->width, c->height);
437  }
438  }
439 
440  if (oc->oformat->flags & AVFMT_RAWPICTURE && !flush) {
441  /* Raw video case - directly store the picture in the packet */
442  AVPacket pkt;
443  av_init_packet(&pkt);
444 
445  pkt.flags |= AV_PKT_FLAG_KEY;
446  pkt.stream_index = st->index;
447  pkt.data = dst_picture.data[0];
448  pkt.size = sizeof(AVPicture);
449 
450  ret = av_interleaved_write_frame(oc, &pkt);
451  } else {
452  AVPacket pkt = { 0 };
453  int got_packet;
454  av_init_packet(&pkt);
455 
456  /* encode the image */
457  frame->pts = frame_count;
458  ret = avcodec_encode_video2(c, &pkt, flush ? NULL : frame, &got_packet);
459  if (ret < 0) {
460  fprintf(stderr, "Error encoding video frame: %s\n", av_err2str(ret));
461  exit(1);
462  }
463  /* If size is zero, it means the image was buffered. */
464 
465  if (got_packet) {
466  ret = write_frame(oc, &c->time_base, st, &pkt);
467  } else {
468  if (flush)
469  video_is_eof = 1;
470  ret = 0;
471  }
472  }
473 
474  if (ret < 0) {
475  fprintf(stderr, "Error while writing video frame: %s\n", av_err2str(ret));
476  exit(1);
477  }
478  frame_count++;
479 }
480 
481 static void close_video(AVFormatContext *oc, AVStream *st)
482 {
483  avcodec_close(st->codec);
484  av_free(src_picture.data[0]);
485  av_free(dst_picture.data[0]);
486  av_frame_free(&frame);
487 }
488 
489 /**************************************************************/
490 /* media file output */
491 
492 int main(int argc, char **argv)
493 {
494  const char *filename;
496  AVFormatContext *oc;
497  AVStream *audio_st, *video_st;
498  AVCodec *audio_codec, *video_codec;
499  double audio_time, video_time;
500  int flush, ret;
501 
502  /* Initialize libavcodec, and register all codecs and formats. */
503  av_register_all();
504 
505  if (argc != 2) {
506  printf("usage: %s output_file\n"
507  "API example program to output a media file with libavformat.\n"
508  "This program generates a synthetic audio and video stream, encodes and\n"
509  "muxes them into a file named output_file.\n"
510  "The output format is automatically guessed according to the file extension.\n"
511  "Raw images can also be output by using '%%d' in the filename.\n"
512  "\n", argv[0]);
513  return 1;
514  }
515 
516  filename = argv[1];
517 
518  /* allocate the output media context */
519  avformat_alloc_output_context2(&oc, NULL, NULL, filename);
520  if (!oc) {
521  printf("Could not deduce output format from file extension: using MPEG.\n");
522  avformat_alloc_output_context2(&oc, NULL, "mpeg", filename);
523  }
524  if (!oc)
525  return 1;
526 
527  fmt = oc->oformat;
528 
529  /* Add the audio and video streams using the default format codecs
530  * and initialize the codecs. */
531  video_st = NULL;
532  audio_st = NULL;
533 
534  if (fmt->video_codec != AV_CODEC_ID_NONE)
535  video_st = add_stream(oc, &video_codec, fmt->video_codec);
536  if (fmt->audio_codec != AV_CODEC_ID_NONE)
537  audio_st = add_stream(oc, &audio_codec, fmt->audio_codec);
538 
539  /* Now that all the parameters are set, we can open the audio and
540  * video codecs and allocate the necessary encode buffers. */
541  if (video_st)
542  open_video(oc, video_codec, video_st);
543  if (audio_st)
544  open_audio(oc, audio_codec, audio_st);
545 
546  av_dump_format(oc, 0, filename, 1);
547 
548  /* open the output file, if needed */
549  if (!(fmt->flags & AVFMT_NOFILE)) {
550  ret = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE);
551  if (ret < 0) {
552  fprintf(stderr, "Could not open '%s': %s\n", filename,
553  av_err2str(ret));
554  return 1;
555  }
556  }
557 
558  /* Write the stream header, if any. */
559  ret = avformat_write_header(oc, NULL);
560  if (ret < 0) {
561  fprintf(stderr, "Error occurred when opening output file: %s\n",
562  av_err2str(ret));
563  return 1;
564  }
565 
566  flush = 0;
567  while ((video_st && !video_is_eof) || (audio_st && !audio_is_eof)) {
568  /* Compute current audio and video time. */
569  audio_time = (audio_st && !audio_is_eof) ? audio_st->pts.val * av_q2d(audio_st->time_base) : INFINITY;
570  video_time = (video_st && !video_is_eof) ? video_st->pts.val * av_q2d(video_st->time_base) : INFINITY;
571 
572  if (!flush &&
573  (!audio_st || audio_time >= STREAM_DURATION) &&
574  (!video_st || video_time >= STREAM_DURATION)) {
575  flush = 1;
576  }
577 
578  /* write interleaved audio and video frames */
579  if (audio_st && !audio_is_eof && audio_time <= video_time) {
580  write_audio_frame(oc, audio_st, flush);
581  } else if (video_st && !video_is_eof && video_time < audio_time) {
582  write_video_frame(oc, video_st, flush);
583  }
584  }
585 
586  /* Write the trailer, if any. The trailer must be written before you
587  * close the CodecContexts open when you wrote the header; otherwise
588  * av_write_trailer() may try to use memory that was freed on
589  * av_codec_close(). */
590  av_write_trailer(oc);
591 
592  /* Close each codec. */
593  if (video_st)
594  close_video(oc, video_st);
595  if (audio_st)
596  close_audio(oc, audio_st);
597 
598  if (!(fmt->flags & AVFMT_NOFILE))
599  /* Close the output file. */
600  avio_close(oc->pb);
601 
602  /* free the stream */
604 
605  return 0;
606 }