FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
encode_video.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2001 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  * video encoding with libavcodec API example
26  *
27  * @example encode_video.c
28  */
29 
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 
34 #include <libavcodec/avcodec.h>
35 
36 #include <libavutil/opt.h>
37 #include <libavutil/imgutils.h>
38 
39 static void encode(AVCodecContext *enc_ctx, AVFrame *frame, AVPacket *pkt,
40  FILE *outfile)
41 {
42  int ret;
43 
44  /* send the frame to the encoder */
45  if (frame)
46  printf("Send frame %3"PRId64"\n", frame->pts);
47 
48  ret = avcodec_send_frame(enc_ctx, frame);
49  if (ret < 0) {
50  fprintf(stderr, "Error sending a frame for encoding\n");
51  exit(1);
52  }
53 
54  while (ret >= 0) {
55  ret = avcodec_receive_packet(enc_ctx, pkt);
56  if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
57  return;
58  else if (ret < 0) {
59  fprintf(stderr, "Error during encoding\n");
60  exit(1);
61  }
62 
63  printf("Write packet %3"PRId64" (size=%5d)\n", pkt->pts, pkt->size);
64  fwrite(pkt->data, 1, pkt->size, outfile);
65  av_packet_unref(pkt);
66  }
67 }
68 
69 int main(int argc, char **argv)
70 {
71  const char *filename, *codec_name;
72  const AVCodec *codec;
74  int i, ret, x, y;
75  FILE *f;
76  AVFrame *frame;
77  AVPacket *pkt;
78  uint8_t endcode[] = { 0, 0, 1, 0xb7 };
79 
80  if (argc <= 2) {
81  fprintf(stderr, "Usage: %s <output file> <codec name>\n", argv[0]);
82  exit(0);
83  }
84  filename = argv[1];
85  codec_name = argv[2];
86 
88 
89  /* find the mpeg1video encoder */
90  codec = avcodec_find_encoder_by_name(codec_name);
91  if (!codec) {
92  fprintf(stderr, "Codec '%s' not found\n", codec_name);
93  exit(1);
94  }
95 
96  c = avcodec_alloc_context3(codec);
97  if (!c) {
98  fprintf(stderr, "Could not allocate video codec context\n");
99  exit(1);
100  }
101 
102  pkt = av_packet_alloc();
103  if (!pkt)
104  exit(1);
105 
106  /* put sample parameters */
107  c->bit_rate = 400000;
108  /* resolution must be a multiple of two */
109  c->width = 352;
110  c->height = 288;
111  /* frames per second */
112  c->time_base = (AVRational){1, 25};
113  c->framerate = (AVRational){25, 1};
114 
115  /* emit one intra frame every ten frames
116  * check frame pict_type before passing frame
117  * to encoder, if frame->pict_type is AV_PICTURE_TYPE_I
118  * then gop_size is ignored and the output of encoder
119  * will always be I frame irrespective to gop_size
120  */
121  c->gop_size = 10;
122  c->max_b_frames = 1;
124 
125  if (codec->id == AV_CODEC_ID_H264)
126  av_opt_set(c->priv_data, "preset", "slow", 0);
127 
128  /* open it */
129  ret = avcodec_open2(c, codec, NULL);
130  if (ret < 0) {
131  fprintf(stderr, "Could not open codec: %s\n", av_err2str(ret));
132  exit(1);
133  }
134 
135  f = fopen(filename, "wb");
136  if (!f) {
137  fprintf(stderr, "Could not open %s\n", filename);
138  exit(1);
139  }
140 
141  frame = av_frame_alloc();
142  if (!frame) {
143  fprintf(stderr, "Could not allocate video frame\n");
144  exit(1);
145  }
146  frame->format = c->pix_fmt;
147  frame->width = c->width;
148  frame->height = c->height;
149 
150  ret = av_frame_get_buffer(frame, 32);
151  if (ret < 0) {
152  fprintf(stderr, "Could not allocate the video frame data\n");
153  exit(1);
154  }
155 
156  /* encode 1 second of video */
157  for (i = 0; i < 25; i++) {
158  fflush(stdout);
159 
160  /* make sure the frame data is writable */
161  ret = av_frame_make_writable(frame);
162  if (ret < 0)
163  exit(1);
164 
165  /* prepare a dummy image */
166  /* Y */
167  for (y = 0; y < c->height; y++) {
168  for (x = 0; x < c->width; x++) {
169  frame->data[0][y * frame->linesize[0] + x] = x + y + i * 3;
170  }
171  }
172 
173  /* Cb and Cr */
174  for (y = 0; y < c->height/2; y++) {
175  for (x = 0; x < c->width/2; x++) {
176  frame->data[1][y * frame->linesize[1] + x] = 128 + y + i * 2;
177  frame->data[2][y * frame->linesize[2] + x] = 64 + x + i * 5;
178  }
179  }
180 
181  frame->pts = i;
182 
183  /* encode the image */
184  encode(c, frame, pkt, f);
185  }
186 
187  /* flush the encoder */
188  encode(c, NULL, pkt, f);
189 
190  /* add sequence end code to have a real MPEG file */
191  fwrite(endcode, 1, sizeof(endcode), f);
192  fclose(f);
193 
195  av_frame_free(&frame);
196  av_packet_free(&pkt);
197 
198  return 0;
199 }
#define NULL
Definition: coverity.c:32
AVRational framerate
Definition: avcodec.h:3460
This structure describes decoded (raw) audio or video data.
Definition: frame.h:201
misc image utilities
int64_t bit_rate
the average bitrate
Definition: avcodec.h:1826
int max_b_frames
maximum number of B-frames between non-B-frames Note: The output will be delayed by max_b_frames+1 re...
Definition: avcodec.h:2047
int avcodec_receive_packet(AVCodecContext *avctx, AVPacket *avpkt)
Read encoded data from the encoder.
Definition: encode.c:430
int size
Definition: avcodec.h:1680
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:1989
static AVPacket pkt
void avcodec_register_all(void)
Register all the codecs, parsers and bitstream filters which were enabled at configuration time...
Definition: allcodecs.c:755
AVCodec.
Definition: avcodec.h:3739
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avcodec.h:1898
void av_packet_free(AVPacket **pkt)
Free the packet, if the packet is reference counted, it will be unreferenced first.
Definition: avpacket.c:62
uint8_t
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
Definition: frame.c:150
AVOptions.
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
Definition: frame.h:294
static AVFrame * frame
uint8_t * data
Definition: avcodec.h:1679
#define AVERROR_EOF
End of file.
Definition: error.h:55
AVCodec * avcodec_find_encoder_by_name(const char *name)
Find a registered encoder with the specified name.
Definition: utils.c:1261
enum AVCodecID id
Definition: avcodec.h:3753
int width
Definition: frame.h:259
#define AVERROR(e)
Definition: error.h:43
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:163
AVCodecContext * avcodec_alloc_context3(const AVCodec *codec)
Allocate an AVCodecContext and set its fields to default values.
Definition: options.c:157
int width
picture width / height.
Definition: avcodec.h:1948
int main(int argc, char **argv)
Definition: encode_video.c:69
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: error.h:119
int format
format of the frame, -1 if unknown or unset Values correspond to enum AVPixelFormat for video frames...
Definition: frame.h:274
Libavcodec external API header.
void avcodec_free_context(AVCodecContext **avctx)
Free the codec context and everything associated with it and write NULL to the provided pointer...
Definition: options.c:172
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
Definition: frame.h:232
main external API structure.
Definition: avcodec.h:1761
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:618
int avcodec_send_frame(AVCodecContext *avctx, const AVFrame *frame)
Supply a raw video or audio frame to the encoder.
Definition: encode.c:400
Rational number (pair of numerator and denominator).
Definition: rational.h:58
static void encode(AVCodecContext *enc_ctx, AVFrame *frame, AVPacket *pkt, FILE *outfile)
Definition: encode_video.c:39
int avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
Initialize the AVCodecContext to use the given AVCodec.
Definition: utils.c:627
int av_frame_get_buffer(AVFrame *frame, int align)
Allocate new buffer(s) for audio or video data.
Definition: frame.c:283
int av_frame_make_writable(AVFrame *frame)
Ensure that the frame data is writable, avoiding data copy if possible.
Definition: frame.c:560
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:215
int gop_size
the number of pictures in a group of pictures, or 0 for intra_only
Definition: avcodec.h:1974
planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
Definition: pixfmt.h:62
static double c[64]
void * priv_data
Definition: avcodec.h:1803
AVPacket * av_packet_alloc(void)
Allocate an AVPacket and set its fields to default values.
Definition: avpacket.c:51
int height
Definition: frame.h:259
This structure stores compressed data.
Definition: avcodec.h:1656
int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
Definition: opt.c:449
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1672
FILE * outfile
Definition: audiogen.c:96