Ticket #3900: 3byte_startcode_test.cpp

File 3byte_startcode_test.cpp, 9.6 KB (added by Lastique, 12 years ago)

A testcase to reproduce the problem

Line 
1// Compile with:
2// g++ -I <include dir> -o 3byte_startcode_test 3byte_startcode_test.cpp -L <lib dir> -lx264 -lavformat -lavcodec -lavutil
3// Add a -DDUMP_PACKETS to also see the encoded video packets
4
5#ifndef __STDC_CONSTANT_MACROS
6#define __STDC_CONSTANT_MACROS
7#endif
8
9extern "C" {
10
11#include <stdint.h>
12#include <x264.h>
13#include <libavcodec/avcodec.h>
14#include <libavformat/avformat.h>
15#include <libavutil/pixfmt.h>
16
17} // extern "C"
18
19#include <cstdio>
20#include <cstddef>
21#include <cstring>
22#include <vector>
23#include <iostream>
24#include <sstream>
25#include <stdexcept>
26
27const unsigned int width = 320;
28const unsigned int height = 240;
29const unsigned int frame_count = 25;
30const char filename[] = "test.avi";
31
32class x264_context :
33 public x264_param_t
34{
35public:
36 x264_t* ctx;
37
38 x264_context() : ctx(NULL)
39 {
40 x264_param_default_preset(this, "veryfast", "ssim");
41
42 this->i_csp = X264_CSP_I420;
43 this->vui.b_fullrange = 1;
44 this->i_width = width;
45 this->i_height = height;
46 this->i_keyint_min = 5;
47 this->i_keyint_max = 50;
48 this->b_repeat_headers = 0;
49 this->b_annexb = 1;
50
51 // time_base the base time unit in which we provide timestamps - 1 ms
52 this->i_timebase_num = 1;
53 this->i_timebase_den = 1000;
54 this->b_vfr_input = 1;
55
56 this->i_frame_reference = 3;
57
58 this->i_bframe = 0;
59 this->i_bframe_pyramid = 0;
60 this->b_cabac = 1;
61 this->analyse.b_transform_8x8 = 1;
62 this->analyse.i_weighted_pred = 1;
63
64 // Set rate control parameters
65 this->rc.i_rc_method = 1;
66 this->rc.f_rf_constant = 23.0f;
67
68 this->rc.f_qcompress = 0.7f;
69
70 // Do not use any lookahead to reduce latency
71 this->rc.i_lookahead = 0;
72 this->i_sync_lookahead = 0;
73
74 this->i_level_idc = -1;
75
76 this->b_intra_refresh = 0;
77 this->rc.b_mb_tree = 0;
78
79 this->i_slice_max_size = 0;
80
81 ctx = x264_encoder_open(this);
82 if (!ctx)
83 throw std::runtime_error("Failed to open libx264 encoder context");
84 }
85
86 ~x264_context()
87 {
88 x264_encoder_close(ctx);
89 }
90};
91
92class raw_image :
93 public x264_picture_t
94{
95public:
96 std::vector< uint8_t > data;
97
98 raw_image()
99 {
100 x264_picture_init(this);
101
102 this->i_type = X264_TYPE_AUTO;
103
104 this->img.i_csp = X264_CSP_I420;
105 this->img.i_plane = 3;
106
107 std::size_t luma_size = width * height;
108 std::size_t chroma_size = luma_size / 4;
109 data.resize(luma_size + 2 * chroma_size);
110
111 this->img.plane[0] = &data[0];
112 this->img.plane[1] = this->img.plane[0] + luma_size;
113 this->img.plane[2] = this->img.plane[1] + chroma_size;
114
115 this->img.i_stride[0] = width;
116 this->img.i_stride[1] = this->img.i_stride[2] = width / 2;
117 }
118};
119
120class av_format_context
121{
122public:
123 AVFormatContext* ctx;
124 bool file_header_written;
125
126 av_format_context() : ctx(avformat_alloc_context()), file_header_written(false)
127 {
128 if (!ctx)
129 throw std::runtime_error("Failed to allocate AVFormatContext");
130
131 ctx->oformat = av_guess_format("avi", filename, NULL);
132 if (!ctx->oformat)
133 throw std::runtime_error("Could not guess output format");
134
135 ctx->oformat->video_codec = CODEC_ID_NONE;
136 ctx->video_codec_id = CODEC_ID_NONE;
137 ctx->oformat->audio_codec = CODEC_ID_NONE;
138 ctx->audio_codec_id = CODEC_ID_NONE;
139 }
140
141 ~av_format_context()
142 {
143 if (ctx)
144 {
145 for (unsigned int i = 0; i < ctx->nb_streams; ++i)
146 {
147 if (ctx->streams[i]->codec->internal) // this field is only set when the codec is opened
148 avcodec_close(ctx->streams[i]->codec);
149 }
150
151 if (ctx->iformat)
152 {
153 // Close input stream
154 avformat_close_input(&ctx);
155 }
156 else
157 {
158 // Close output stream
159 if (ctx->oformat && (ctx->oformat->flags & AVFMT_NOFILE) == 0 && (ctx->oformat->flags & AVFMT_FLAG_CUSTOM_IO) == 0 && ctx->pb)
160 {
161 avio_close(ctx->pb);
162 ctx->pb = NULL;
163 }
164 avformat_free_context(ctx);
165 }
166 }
167 }
168
169 void open()
170 {
171 if (avio_open(&ctx->pb, filename, AVIO_FLAG_WRITE) < 0)
172 throw std::runtime_error("Failed to open output media file");
173 }
174
175 void close()
176 {
177 if (file_header_written)
178 av_write_trailer(ctx);
179 if (ctx->pb)
180 {
181 avio_close(ctx->pb);
182 ctx->pb = NULL;
183 }
184 file_header_written = false;
185 }
186
187 void write_file_header(const uint8_t* extradata, std::size_t extradata_size)
188 {
189 AVCodec* video_codec = avcodec_find_encoder(AV_CODEC_ID_H264);
190 if (!video_codec)
191 throw std::runtime_error("ffmpeg does not support h.264");
192
193 ctx->oformat->video_codec = AV_CODEC_ID_H264;
194 ctx->video_codec_id = AV_CODEC_ID_H264;
195
196 AVStream* av_stream = avformat_new_stream(ctx, NULL);
197 if (!av_stream)
198 throw std::runtime_error("av_new_stream failed");
199 av_stream->id = 0;
200
201 av_stream->r_frame_rate.num = av_stream->r_frame_rate.den = 0;
202 av_stream->time_base.num = 1;
203 av_stream->time_base.den = 1000;
204
205 AVCodecContext* av_video_codec_ctx = av_stream->codec;
206 av_video_codec_ctx->codec_id = AV_CODEC_ID_H264;
207 av_video_codec_ctx->width = width;
208 av_video_codec_ctx->height = height;
209 av_video_codec_ctx->pix_fmt = AV_PIX_FMT_YUV420P;
210
211 if (extradata_size > 0)
212 {
213 uint8_t* data = (uint8_t*)av_malloc(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
214 if (!data)
215 throw std::bad_alloc();
216 std::memcpy(data, extradata, extradata_size);
217 std::memset(data + extradata_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
218 av_video_codec_ctx->extradata = data;
219 av_video_codec_ctx->extradata_size = extradata_size;
220 }
221
222 av_video_codec_ctx->codec_type = AVMEDIA_TYPE_VIDEO;
223 av_video_codec_ctx->flags |= CODEC_FLAG_GLOBAL_HEADER;
224 av_video_codec_ctx->time_base.num = 1;
225 av_video_codec_ctx->time_base.den = 1000;
226
227 if (avformat_write_header(ctx, NULL) < 0)
228 throw std::runtime_error("error writing header");
229
230 file_header_written = true;
231 }
232
233 void write_frame(const uint8_t* payload, std::size_t size, bool is_keyframe, uint64_t pts, uint64_t dts)
234 {
235#if defined(DUMP_PACKETS)
236 std::printf("Frame pts %lu, dts: %lu:", (unsigned long)pts, (unsigned long)dts);
237 for (std::size_t i = 0; i < size; ++i)
238 {
239 std::printf(" %02x", (unsigned int)payload[i]);
240 }
241 std::printf("\n");
242#endif
243
244 AVPacket av_packet;
245 av_init_packet(&av_packet);
246 av_packet.stream_index = 0;
247
248 // Package the frame and stream it out
249 av_packet.flags &= ~AV_PKT_FLAG_KEY;
250 if (is_keyframe)
251 av_packet.flags |= AV_PKT_FLAG_KEY;
252
253 av_packet.data = const_cast< uint8_t* >(payload);
254 av_packet.size = size;
255
256 av_packet.pts = pts;
257 av_packet.dts = dts;
258
259 int res = av_interleaved_write_frame(ctx, &av_packet);
260 if (res != 0)
261 {
262 std::ostringstream strm;
263 strm << "Failed to write video frame, error: " << res;
264 throw std::runtime_error(strm.str());
265 }
266 }
267};
268
269int main(int, char*[])
270{
271 try
272 {
273 av_register_all();
274
275 x264_context x264_ctx;
276 raw_image picture_in;
277
278 x264_picture_t picture_out = {};
279 int nnal = 0;
280 x264_nal_t* nal = NULL;
281
282 if (x264_encoder_headers(x264_ctx.ctx, &nal, &nnal) < 0)
283 throw std::runtime_error("Failed to encode h.264 parameter sets");
284
285 std::vector< uint8_t > extradata, frame_buffer;
286 for (int i = 0; i < nnal; ++i)
287 {
288 if (nal[i].i_type == NAL_SEI)
289 {
290 /* only one SEI NAL is expected */
291 frame_buffer.insert(frame_buffer.end(), nal[i].p_payload, nal[i].p_payload + nal[i].i_payload);
292 }
293 else
294 {
295 extradata.insert(extradata.end(), nal[i].p_payload, nal[i].p_payload + nal[i].i_payload);
296 }
297 }
298
299 av_format_context file;
300
301 file.open();
302 file.write_file_header(&extradata[0], extradata.size());
303
304 uint64_t pts = 0;
305 for (unsigned int i = 0; i < frame_count; ++i, pts += 25)
306 {
307 picture_in.i_pts = picture_in.i_dts = pts;
308 picture_in.i_type = X264_TYPE_AUTO;
309
310 int result = x264_encoder_encode(x264_ctx.ctx, &nal, &nnal, &picture_in, &picture_out);
311 if (result < 0)
312 {
313 std::ostringstream strm;
314 strm << "Failed to encode frame, error code: " << result;
315 throw std::runtime_error(strm.str());
316 }
317 else if (result == 0)
318 {
319 continue;
320 }
321
322 // Append the first encoded frame to SEI, put the following frames to the start of the buffer
323 frame_buffer.insert(frame_buffer.end(), nal[0].p_payload, nal[nnal - 1].p_payload + nal[nnal - 1].i_payload);
324
325 file.write_frame(&frame_buffer[0], frame_buffer.size(), picture_out.b_keyframe != 0, picture_out.i_pts, picture_out.i_dts);
326
327 frame_buffer.clear();
328 }
329
330 file.close();
331 }
332 catch (std::exception& e)
333 {
334 std::cout << "Failure: " << e.what() << std::endl;
335 return 1;
336 }
337
338 return 0;
339}