2 * Copyright (c) 2012 Intel Corporation. All Rights Reserved.
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sub license, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
12 * The above copyright notice and this permission notice (including the
13 * next paragraph) shall be included in all copies or substantial portions
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
19 * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR
20 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 * Simple MPEG-2 encoder based on libVA.
35 #include <sys/types.h>
41 #include <va/va_enc_mpeg2.h>
43 #include "va_display.h"
45 #define START_CODE_PICUTRE 0x00000100
46 #define START_CODE_SLICE 0x00000101
47 #define START_CODE_USER 0x000001B2
48 #define START_CODE_SEQ 0x000001B3
49 #define START_CODE_EXT 0x000001B5
50 #define START_CODE_GOP 0x000001B8
52 #define CHROMA_FORMAT_RESERVED 0
53 #define CHROMA_FORMAT_420 1
54 #define CHROMA_FORMAT_422 2
55 #define CHROMA_FORMAT_444 3
57 #define MAX_SLICES 128
59 #define CHECK_VASTATUS(va_status, func) \
60 if (va_status != VA_STATUS_SUCCESS) { \
61 fprintf(stderr, "%s:%s (%d) failed, exit\n", __func__, func, __LINE__); \
65 #define INTRA_PERIOD 30
67 static int const picture_type_patter[][2] = {{VAEncPictureTypeIntra, 1},
68 {VAEncPictureTypePredictive, 3}, {VAEncPictureTypePredictive, 3},{VAEncPictureTypePredictive, 3},
69 {VAEncPictureTypePredictive, 3}, {VAEncPictureTypePredictive, 3},{VAEncPictureTypePredictive, 3},
70 {VAEncPictureTypePredictive, 3}, {VAEncPictureTypePredictive, 3},{VAEncPictureTypePredictive, 3},
71 {VAEncPictureTypePredictive, 2}};
73 struct mpeg2enc_context {
75 int rate_control_mode;
84 unsigned char *frame_data_buffer;
86 int bit_rate; /* in kbps */
90 VAEncSequenceParameterBufferMPEG2 seq_param;
91 VAEncPictureParameterBufferMPEG2 pic_param;
92 VAEncSliceParameterBufferMPEG2 slice_param[MAX_SLICES];
93 VAContextID context_id;
95 VABufferID seq_param_buf_id; /* Sequence level parameter */
96 VABufferID pic_param_buf_id; /* Picture level parameter */
97 VABufferID slice_param_buf_id[MAX_SLICES]; /* Slice level parameter, multil slices */
98 VABufferID codedbuf_buf_id; /* Output buffer, compressed data */
99 VABufferID packed_seq_header_param_buf_id;
100 VABufferID packed_seq_buf_id;
101 VABufferID packed_pic_header_param_buf_id;
102 VABufferID packed_pic_buf_id;
103 int num_slice_groups;
105 int codedbuf_pb_size;
108 pthread_t upload_thread_id;
109 int upload_thread_value;
110 int current_input_surface;
111 int current_upload_surface;
117 #define BITSTREAM_ALLOCATE_STEPPING 4096
120 unsigned int *buffer;
122 int max_size_in_dword;
125 typedef struct __bitstream bitstream;
128 swap32(unsigned int val)
130 unsigned char *pval = (unsigned char *)&val;
132 return ((pval[0] << 24) |
139 bitstream_start(bitstream *bs)
141 bs->max_size_in_dword = BITSTREAM_ALLOCATE_STEPPING;
142 bs->buffer = calloc(bs->max_size_in_dword * sizeof(int), 1);
147 bitstream_end(bitstream *bs)
149 int pos = (bs->bit_offset >> 5);
150 int bit_offset = (bs->bit_offset & 0x1f);
151 int bit_left = 32 - bit_offset;
154 bs->buffer[pos] = swap32((bs->buffer[pos] << bit_left));
159 bitstream_put_ui(bitstream *bs, unsigned int val, int size_in_bits)
161 int pos = (bs->bit_offset >> 5);
162 int bit_offset = (bs->bit_offset & 0x1f);
163 int bit_left = 32 - bit_offset;
168 if (size_in_bits < 32)
169 val &= ((1 << size_in_bits) - 1);
171 bs->bit_offset += size_in_bits;
173 if (bit_left > size_in_bits) {
174 bs->buffer[pos] = (bs->buffer[pos] << size_in_bits | val);
176 size_in_bits -= bit_left;
177 bs->buffer[pos] = (bs->buffer[pos] << bit_left) | (val >> size_in_bits);
178 bs->buffer[pos] = swap32(bs->buffer[pos]);
180 if (pos + 1 == bs->max_size_in_dword) {
181 bs->max_size_in_dword += BITSTREAM_ALLOCATE_STEPPING;
182 bs->buffer = realloc(bs->buffer, bs->max_size_in_dword * sizeof(unsigned int));
185 bs->buffer[pos + 1] = val;
190 bitstream_byte_aligning(bitstream *bs, int bit)
192 int bit_offset = (bs->bit_offset & 0x7);
193 int bit_left = 8 - bit_offset;
199 assert(bit == 0 || bit == 1);
202 new_val = (1 << bit_left) - 1;
206 bitstream_put_ui(bs, new_val, bit_left);
209 static struct mpeg2_frame_rate {
212 } frame_rate_tab[] = {
224 find_frame_rate_code(const VAEncSequenceParameterBufferMPEG2 *seq_param)
226 unsigned int delta = -1;
228 float frame_rate_value = seq_param->frame_rate *
229 (seq_param->sequence_extension.bits.frame_rate_extension_d + 1) /
230 (seq_param->sequence_extension.bits.frame_rate_extension_n + 1);
232 for (i = 0; i < sizeof(frame_rate_tab) / sizeof(frame_rate_tab[0]); i++) {
234 if (abs(1000 * frame_rate_tab[i].value - 1000 * frame_rate_value) < delta) {
235 code = frame_rate_tab[i].code;
236 delta = abs(1000 * frame_rate_tab[i].value - 1000 * frame_rate_value);
244 sps_rbsp(const VAEncSequenceParameterBufferMPEG2 *seq_param,
247 int frame_rate_code = find_frame_rate_code(seq_param);
249 bitstream_put_ui(bs, START_CODE_SEQ, 32);
250 bitstream_put_ui(bs, seq_param->picture_width, 12);
251 bitstream_put_ui(bs, seq_param->picture_height, 12);
252 bitstream_put_ui(bs, seq_param->aspect_ratio_information, 4);
253 bitstream_put_ui(bs, frame_rate_code, 4); /* frame_rate_code */
254 bitstream_put_ui(bs, (seq_param->bits_per_second + 399) / 400, 18); /* the low 18 bits of bit_rate */
255 bitstream_put_ui(bs, 1, 1); /* marker_bit */
256 bitstream_put_ui(bs, seq_param->vbv_buffer_size, 10);
257 bitstream_put_ui(bs, 0, 1); /* constraint_parameter_flag, always 0 for MPEG-2 */
258 bitstream_put_ui(bs, 0, 1); /* load_intra_quantiser_matrix */
259 bitstream_put_ui(bs, 0, 1); /* load_non_intra_quantiser_matrix */
261 bitstream_byte_aligning(bs, 0);
263 bitstream_put_ui(bs, START_CODE_EXT, 32);
264 bitstream_put_ui(bs, 1, 4); /* sequence_extension id */
265 bitstream_put_ui(bs, seq_param->sequence_extension.bits.profile_and_level_indication, 8);
266 bitstream_put_ui(bs, seq_param->sequence_extension.bits.progressive_sequence, 1);
267 bitstream_put_ui(bs, seq_param->sequence_extension.bits.chroma_format, 2);
268 bitstream_put_ui(bs, seq_param->picture_width >> 12, 2);
269 bitstream_put_ui(bs, seq_param->picture_height >> 12, 2);
270 bitstream_put_ui(bs, ((seq_param->bits_per_second + 399) / 400) >> 18, 12); /* bit_rate_extension */
271 bitstream_put_ui(bs, 1, 1); /* marker_bit */
272 bitstream_put_ui(bs, seq_param->vbv_buffer_size >> 10, 8);
273 bitstream_put_ui(bs, seq_param->sequence_extension.bits.low_delay, 1);
274 bitstream_put_ui(bs, seq_param->sequence_extension.bits.frame_rate_extension_n, 2);
275 bitstream_put_ui(bs, seq_param->sequence_extension.bits.frame_rate_extension_d, 5);
277 bitstream_byte_aligning(bs, 0);
279 bitstream_put_ui(bs, START_CODE_GOP, 32);
280 bitstream_put_ui(bs, seq_param->gop_header.bits.time_code, 25);
281 bitstream_put_ui(bs, seq_param->gop_header.bits.closed_gop, 1);
282 bitstream_put_ui(bs, seq_param->gop_header.bits.broken_link, 1);
284 bitstream_byte_aligning(bs, 0);
288 pps_rbsp(const VAEncSequenceParameterBufferMPEG2 *seq_param,
289 const VAEncPictureParameterBufferMPEG2 *pic_param,
295 if (seq_param->sequence_extension.bits.chroma_format == CHROMA_FORMAT_420)
296 chroma_420_type = pic_param->picture_coding_extension.bits.progressive_frame;
300 bitstream_put_ui(bs, START_CODE_PICUTRE, 32);
301 bitstream_put_ui(bs, pic_param->temporal_reference, 10);
303 pic_param->picture_type == VAEncPictureTypeIntra ? 1 :
304 pic_param->picture_type == VAEncPictureTypePredictive ? 2 : 3,
306 bitstream_put_ui(bs, 0xFFFF, 16); /* vbv_delay, always 0xFFFF */
308 if (pic_param->picture_type == VAEncPictureTypePredictive) {
309 bitstream_put_ui(bs, 0, 1); /* full_pel_forward_vector, always 0 for MPEG-2 */
310 bitstream_put_ui(bs, 7, 3); /* forward_f_code, always 7 for MPEG-2 */
313 if (pic_param->picture_type == VAEncPictureTypeBidirectional) {
314 bitstream_put_ui(bs, 0, 1); /* full_pel_backward_vector, always 0 for MPEG-2 */
315 bitstream_put_ui(bs, 7, 3); /* backward_f_code, always 7 for MPEG-2 */
318 bitstream_put_ui(bs, 0, 1); /* extra_bit_picture, 0 */
320 bitstream_byte_aligning(bs, 0);
322 bitstream_put_ui(bs, START_CODE_EXT, 32);
323 bitstream_put_ui(bs, 8, 4); /* Picture Coding Extension ID: 8 */
324 bitstream_put_ui(bs, pic_param->f_code[0][0], 4);
325 bitstream_put_ui(bs, pic_param->f_code[0][1], 4);
326 bitstream_put_ui(bs, pic_param->f_code[1][0], 4);
327 bitstream_put_ui(bs, pic_param->f_code[1][1], 4);
329 bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.intra_dc_precision, 2);
330 bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.picture_structure, 2);
331 bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.top_field_first, 1);
332 bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.frame_pred_frame_dct, 1);
333 bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.concealment_motion_vectors, 1);
334 bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.q_scale_type, 1);
335 bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.intra_vlc_format, 1);
336 bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.alternate_scan, 1);
337 bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.repeat_first_field, 1);
338 bitstream_put_ui(bs, chroma_420_type, 1);
339 bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.progressive_frame, 1);
340 bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.composite_display_flag, 1);
342 bitstream_byte_aligning(bs, 0);
344 if (pic_param->user_data_length) {
345 bitstream_put_ui(bs, START_CODE_USER, 32);
347 for (i = 0; i < pic_param->user_data_length; i++) {
348 bitstream_put_ui(bs, pic_param->user_data[i], 8);
351 bitstream_byte_aligning(bs, 0);
356 build_packed_pic_buffer(const VAEncSequenceParameterBufferMPEG2 *seq_param,
357 const VAEncPictureParameterBufferMPEG2 *pic_param,
358 unsigned char **header_buffer)
362 bitstream_start(&bs);
363 pps_rbsp(seq_param, pic_param, &bs);
366 *header_buffer = (unsigned char *)bs.buffer;
367 return bs.bit_offset;
371 build_packed_seq_buffer(const VAEncSequenceParameterBufferMPEG2 *seq_param,
372 unsigned char **header_buffer)
376 bitstream_start(&bs);
377 sps_rbsp(seq_param, &bs);
380 *header_buffer = (unsigned char *)bs.buffer;
381 return bs.bit_offset;
387 #define SID_INPUT_PICTURE_0 0
388 #define SID_INPUT_PICTURE_1 1
389 #define SID_REFERENCE_PICTURE_L0 2
390 #define SID_REFERENCE_PICTURE_L1 3
391 #define SID_RECON_PICTURE 4
392 #define SID_NUMBER SID_RECON_PICTURE + 1
394 static VASurfaceID surface_ids[SID_NUMBER];
397 * upload thread function
400 upload_yuv_to_surface(void *data)
402 struct mpeg2enc_context *ctx = data;
403 VAImage surface_image;
405 void *surface_p = NULL;
406 unsigned char *y_src, *u_src, *v_src;
407 unsigned char *y_dst, *u_dst, *v_dst;
408 int y_size = ctx->width * ctx->height;
409 int u_size = (ctx->width >> 1) * (ctx->height >> 1);
414 n_items = fread(ctx->frame_data_buffer, ctx->frame_size, 1, ctx->ifp);
415 } while (n_items != 1);
417 va_status = vaDeriveImage(ctx->va_dpy, surface_ids[ctx->current_upload_surface], &surface_image);
418 CHECK_VASTATUS(va_status,"vaDeriveImage");
420 vaMapBuffer(ctx->va_dpy, surface_image.buf, &surface_p);
421 assert(VA_STATUS_SUCCESS == va_status);
423 y_src = ctx->frame_data_buffer;
424 u_src = ctx->frame_data_buffer + y_size; /* UV offset for NV12 */
425 v_src = ctx->frame_data_buffer + y_size + u_size;
427 y_dst = surface_p + surface_image.offsets[0];
428 u_dst = surface_p + surface_image.offsets[1]; /* UV offset for NV12 */
429 v_dst = surface_p + surface_image.offsets[2];
432 for (row = 0; row < surface_image.height; row++) {
433 memcpy(y_dst, y_src, surface_image.width);
434 y_dst += surface_image.pitches[0];
438 if (surface_image.format.fourcc == VA_FOURCC_NV12) { /* UV plane */
439 for (row = 0; row < surface_image.height / 2; row++) {
440 for (col = 0; col < surface_image.width / 2; col++) {
441 u_dst[col * 2] = u_src[col];
442 u_dst[col * 2 + 1] = v_src[col];
445 u_dst += surface_image.pitches[1];
446 u_src += (ctx->width / 2);
447 v_src += (ctx->width / 2);
450 for (row = 0; row < surface_image.height / 2; row++) {
451 for (col = 0; col < surface_image.width / 2; col++) {
452 u_dst[col] = u_src[col];
453 v_dst[col] = v_src[col];
456 u_dst += surface_image.pitches[1];
457 v_dst += surface_image.pitches[2];
458 u_src += (ctx->width / 2);
459 v_src += (ctx->width / 2);
463 vaUnmapBuffer(ctx->va_dpy, surface_image.buf);
464 vaDestroyImage(ctx->va_dpy, surface_image.image_id);
470 mpeg2enc_exit(struct mpeg2enc_context *ctx, int exit_code)
472 if (ctx->frame_data_buffer) {
473 free(ctx->frame_data_buffer);
474 ctx->frame_data_buffer = NULL;
493 fprintf(stderr, "Usage: %s --help\n", program);
494 fprintf(stderr, "\t--help print this message\n");
495 fprintf(stderr, "Usage: %s <width> <height> <ifile> <ofile> [options]\n", program);
496 fprintf(stderr, "\t<width> specifies the frame width\n");
497 fprintf(stderr, "\t<height> specifies the frame height\n");
498 fprintf(stderr, "\t<ifile> specifies the I420/IYUV YUV file\n");
499 fprintf(stderr, "\t<ofile> specifies the encoded MPEG-2 file\n");
500 fprintf(stderr, "where options include:\n");
501 fprintf(stderr, "\t--cqp <QP> const qp mode with specified <QP>\n");
502 fprintf(stderr, "\t--fps <FPS> specify the frame rate\n");
506 parse_args(struct mpeg2enc_context *ctx, int argc, char **argv)
509 int option_index = 0;
511 static struct option long_options[] = {
512 {"help", no_argument, 0, 'h'},
513 {"cqp", required_argument, 0, 'c'},
514 {"fps", required_argument, 0, 'f'},
518 if ((argc == 2 && strcmp(argv[1], "--help") == 0) ||
522 ctx->width = atoi(argv[1]);
523 ctx->height = atoi(argv[2]);
525 if (ctx->width <= 0 || ctx->height <= 0) {
526 fprintf(stderr, "<width> and <height> must be greater than 0\n");
530 ctx->ifp = fopen(argv[3], "rb");
532 if (ctx->ifp == NULL) {
533 fprintf(stderr, "Can't open the input file\n");
537 fseek(ctx->ifp, 0l, SEEK_END);
538 file_size = ftell(ctx->ifp);
539 ctx->frame_size = ctx->width * ctx->height * 3 / 2;
541 if ((file_size < ctx->frame_size) ||
542 (file_size % ctx->frame_size)) {
543 fprintf(stderr, "The input file size %ld isn't a multiple of the frame size %d\n", file_size, ctx->frame_size);
547 ctx->num_pictures = file_size / ctx->frame_size;
548 fseek(ctx->ifp, 0l, SEEK_SET);
550 ctx->ofp = fopen(argv[4], "wb");
552 if (ctx->ofp == NULL) {
553 fprintf(stderr, "Can't create the output file\n");
560 ctx->rate_control_mode = VA_RC_CQP;
564 while((c = getopt_long(argc, argv,
567 &option_index)) != -1) {
572 /* only support q_scale_type = 0 */
573 if (tmp > 62 || tmp < 2) {
574 fprintf(stderr, "Warning: QP must be in [2, 62]\n");
583 ctx->qp = tmp & 0xFE;
584 ctx->rate_control_mode = VA_RC_CQP;
592 fprintf(stderr, "Warning: FPS must be greater than 0\n");
596 ctx->rate_control_mode = VA_RC_CBR;
601 fprintf(stderr, "Error: unkown command options\n");
613 mpeg2enc_exit(ctx, 1);
620 mpeg2enc_init_sequence_parameter(struct mpeg2enc_context *ctx,
621 VAEncSequenceParameterBufferMPEG2 *seq_param)
623 seq_param->intra_period = ctx->intra_period;
624 seq_param->ip_period = 0; /* FIXME: ??? */
625 seq_param->picture_width = ctx->width;
626 seq_param->picture_height = ctx->height;
628 if (ctx->bit_rate > 0)
629 seq_param->bits_per_second = 1024 * ctx->bit_rate; /* use kbps as input */
631 seq_param->bits_per_second = 0x3FFFF * 400;
633 seq_param->frame_rate = ctx->fps;
634 seq_param->aspect_ratio_information = 1;
635 seq_param->vbv_buffer_size = 3; /* B = 16 * 1024 * vbv_buffer_size */
637 seq_param->sequence_extension.bits.profile_and_level_indication = 4 << 4 | 0x8; /* FIXME: Main/Main ??? */
638 seq_param->sequence_extension.bits.progressive_sequence = 1; /* progressive frame-pictures */
639 seq_param->sequence_extension.bits.chroma_format = CHROMA_FORMAT_420; /* 4:2:0 */
640 seq_param->sequence_extension.bits.low_delay = 0; /* FIXME */
641 seq_param->sequence_extension.bits.frame_rate_extension_n = 0;
642 seq_param->sequence_extension.bits.frame_rate_extension_d = 0;
644 seq_param->gop_header.bits.time_code = (1 << 12); /* bit12: marker_bit */
645 seq_param->gop_header.bits.closed_gop = 0;
646 seq_param->gop_header.bits.broken_link = 0;
650 mpeg2enc_init_picture_parameter(struct mpeg2enc_context *ctx,
651 VAEncPictureParameterBufferMPEG2 *pic_param)
653 pic_param->forward_reference_picture = VA_INVALID_ID;
654 pic_param->backward_reference_picture = VA_INVALID_ID;
655 pic_param->reconstructed_picture = VA_INVALID_ID;
656 pic_param->coded_buf = VA_INVALID_ID;
657 pic_param->picture_type = VAEncPictureTypeIntra;
659 pic_param->temporal_reference = 0;
660 pic_param->f_code[0][0] = 0xf;
661 pic_param->f_code[0][1] = 0xf;
662 pic_param->f_code[1][0] = 0xf;
663 pic_param->f_code[1][1] = 0xf;
665 pic_param->picture_coding_extension.bits.intra_dc_precision = 0; /* 8bits */
666 pic_param->picture_coding_extension.bits.picture_structure = 3; /* frame picture */
667 pic_param->picture_coding_extension.bits.top_field_first = 0;
668 pic_param->picture_coding_extension.bits.frame_pred_frame_dct = 1; /* FIXME */
669 pic_param->picture_coding_extension.bits.concealment_motion_vectors = 0;
670 pic_param->picture_coding_extension.bits.q_scale_type = 0;
671 pic_param->picture_coding_extension.bits.intra_vlc_format = 0;
672 pic_param->picture_coding_extension.bits.alternate_scan = 0;
673 pic_param->picture_coding_extension.bits.repeat_first_field = 0;
674 pic_param->picture_coding_extension.bits.progressive_frame = 1;
675 pic_param->picture_coding_extension.bits.composite_display_flag = 0;
677 pic_param->user_data_length = 0;
681 mpeg2enc_alloc_va_resources(struct mpeg2enc_context *ctx)
683 VAEntrypoint *entrypoint_list;
684 VAConfigAttrib attrib_list[2];
686 int max_entrypoints, num_entrypoints, entrypoint;
687 int major_ver, minor_ver;
689 ctx->va_dpy = va_open_display();
690 va_status = vaInitialize(ctx->va_dpy,
693 CHECK_VASTATUS(va_status, "vaInitialize");
695 max_entrypoints = vaMaxNumEntrypoints(ctx->va_dpy);
696 entrypoint_list = malloc(max_entrypoints * sizeof(VAEntrypoint));
697 vaQueryConfigEntrypoints(ctx->va_dpy,
698 VAProfileMPEG2Simple,
702 for (entrypoint = 0; entrypoint < num_entrypoints; entrypoint++) {
703 if (entrypoint_list[entrypoint] == VAEntrypointEncSlice)
707 free(entrypoint_list);
709 if (entrypoint == num_entrypoints) {
710 /* not find Slice entry point */
714 /* find out the format for the render target, and rate control mode */
715 attrib_list[0].type = VAConfigAttribRTFormat;
716 attrib_list[1].type = VAConfigAttribRateControl;
717 vaGetConfigAttributes(ctx->va_dpy,
718 VAProfileMPEG2Simple,
719 VAEntrypointEncSlice,
723 if ((attrib_list[0].value & VA_RT_FORMAT_YUV420) == 0) {
724 /* not find desired YUV420 RT format */
728 if ((attrib_list[1].value & ctx->rate_control_mode) == 0) {
729 /* Can't find matched RC mode */
730 fprintf(stderr, "RC mode %d isn't found, exit\n", ctx->rate_control_mode);
734 attrib_list[0].value = VA_RT_FORMAT_YUV420; /* set to desired RT format */
735 attrib_list[1].value = ctx->rate_control_mode; /* set to desired RC mode */
737 va_status = vaCreateConfig(ctx->va_dpy,
738 VAProfileMPEG2Simple,
739 VAEntrypointEncSlice,
743 CHECK_VASTATUS(va_status, "vaCreateConfig");
745 /* Create a context for this decode pipe */
746 va_status = vaCreateContext(ctx->va_dpy,
754 CHECK_VASTATUS(va_status, "vaCreateContext");
756 va_status = vaCreateSurfaces(ctx->va_dpy,
762 CHECK_VASTATUS(va_status, "vaCreateSurfaces");
766 mpeg2enc_init(struct mpeg2enc_context *ctx)
770 ctx->frame_data_buffer = (unsigned char *)malloc(ctx->frame_size);
771 ctx->seq_param_buf_id = VA_INVALID_ID;
772 ctx->pic_param_buf_id = VA_INVALID_ID;
773 ctx->packed_seq_header_param_buf_id = VA_INVALID_ID;
774 ctx->packed_seq_buf_id = VA_INVALID_ID;
775 ctx->packed_pic_header_param_buf_id = VA_INVALID_ID;
776 ctx->packed_pic_buf_id = VA_INVALID_ID;
777 ctx->codedbuf_buf_id = VA_INVALID_ID;
778 ctx->codedbuf_i_size = ctx->frame_size;
779 ctx->codedbuf_pb_size = 0;
780 ctx->intra_period = INTRA_PERIOD;
783 for (i = 0; i < MAX_SLICES; i++) {
784 ctx->slice_param_buf_id[i] = VA_INVALID_ID;
787 mpeg2enc_init_sequence_parameter(ctx, &ctx->seq_param);
788 mpeg2enc_init_picture_parameter(ctx, &ctx->pic_param);
789 mpeg2enc_alloc_va_resources(ctx);
792 ctx->current_input_surface = SID_INPUT_PICTURE_0;
793 ctx->current_upload_surface = SID_INPUT_PICTURE_1;
794 ctx->upload_thread_value = pthread_create(&ctx->upload_thread_id,
796 upload_yuv_to_surface,
804 mpeg2enc_update_picture_parameter(struct mpeg2enc_context *ctx,
805 VAEncPictureType picture_type,
809 VAEncPictureParameterBufferMPEG2 *pic_param;
813 pic_param = &ctx->pic_param;
814 pic_param->picture_type = picture_type;
815 pic_param->temporal_reference = display_order;
816 pic_param->reconstructed_picture = surface_ids[SID_RECON_PICTURE];
817 pic_param->forward_reference_picture = surface_ids[SID_REFERENCE_PICTURE_L0];
818 pic_param->backward_reference_picture = surface_ids[SID_REFERENCE_PICTURE_L1];
819 pic_param->coded_buf = ctx->codedbuf_buf_id;
821 va_status = vaCreateBuffer(ctx->va_dpy,
823 VAEncPictureParameterBufferType,
827 &ctx->pic_param_buf_id);
828 CHECK_VASTATUS(va_status, "vaCreateBuffer");
832 mpeg2enc_update_slice_parameter(struct mpeg2enc_context *ctx, VAEncPictureType picture_type)
834 VAEncSequenceParameterBufferMPEG2 *seq_param;
835 VAEncPictureParameterBufferMPEG2 *pic_param;
836 VAEncSliceParameterBufferMPEG2 *slice_param;
838 int i, width_in_mbs, height_in_mbs;
840 pic_param = &ctx->pic_param;
841 assert(pic_param->picture_coding_extension.bits.q_scale_type == 0);
843 seq_param = &ctx->seq_param;
844 width_in_mbs = (seq_param->picture_width + 15) / 16;
845 height_in_mbs = (seq_param->picture_height + 15) / 16;
846 ctx->num_slice_groups = 1;
848 for (i = 0; i < height_in_mbs; i++) {
849 slice_param = &ctx->slice_param[i];
850 slice_param->macroblock_address = i * width_in_mbs;
851 slice_param->num_macroblocks = width_in_mbs;
852 slice_param->is_intra_slice = (picture_type == VAEncPictureTypeIntra);
853 slice_param->quantiser_scale_code = ctx->qp / 2;
856 va_status = vaCreateBuffer(ctx->va_dpy,
858 VAEncSliceParameterBufferType,
859 sizeof(*slice_param),
862 ctx->slice_param_buf_id);
863 CHECK_VASTATUS(va_status, "vaCreateBuffer");;
867 begin_picture(struct mpeg2enc_context *ctx,
870 VAEncPictureType picture_type)
875 if (ctx->upload_thread_value != 0) {
876 fprintf(stderr, "FATAL error!!!\n");
880 pthread_join(ctx->upload_thread_id, NULL);
882 ctx->upload_thread_value = -1;
883 tmp = ctx->current_input_surface;
884 ctx->current_input_surface = ctx->current_upload_surface;
885 ctx->current_upload_surface = tmp;
887 if (coded_order == 0) {
888 VAEncPackedHeaderParameterBuffer packed_header_param_buffer;
889 unsigned int length_in_bits;
890 unsigned char *packed_seq_buffer = NULL, *packed_pic_buffer = NULL;
892 assert(picture_type == VAEncPictureTypeIntra);
893 length_in_bits = build_packed_seq_buffer(&ctx->seq_param, &packed_seq_buffer);
894 packed_header_param_buffer.type = VAEncPackedHeaderMPEG2_SPS;
895 packed_header_param_buffer.has_emulation_bytes = 0;
896 packed_header_param_buffer.bit_length = length_in_bits;
897 va_status = vaCreateBuffer(ctx->va_dpy,
899 VAEncPackedHeaderParameterBufferType,
900 sizeof(packed_header_param_buffer), 1, &packed_header_param_buffer,
901 &ctx->packed_seq_header_param_buf_id);
902 CHECK_VASTATUS(va_status,"vaCreateBuffer");
904 va_status = vaCreateBuffer(ctx->va_dpy,
906 VAEncPackedHeaderDataBufferType,
907 (length_in_bits + 7) / 8, 1, packed_seq_buffer,
908 &ctx->packed_seq_buf_id);
909 CHECK_VASTATUS(va_status,"vaCreateBuffer");
911 length_in_bits = build_packed_pic_buffer(&ctx->seq_param, &ctx->pic_param, &packed_pic_buffer);
912 packed_header_param_buffer.type = VAEncPackedHeaderMPEG2_PPS;
913 packed_header_param_buffer.has_emulation_bytes = 0;
914 packed_header_param_buffer.bit_length = length_in_bits;
916 va_status = vaCreateBuffer(ctx->va_dpy,
918 VAEncPackedHeaderParameterBufferType,
919 sizeof(packed_header_param_buffer), 1, &packed_header_param_buffer,
920 &ctx->packed_pic_header_param_buf_id);
921 CHECK_VASTATUS(va_status,"vaCreateBuffer");
923 va_status = vaCreateBuffer(ctx->va_dpy,
925 VAEncPackedHeaderDataBufferType,
926 (length_in_bits + 7) / 8, 1, packed_pic_buffer,
927 &ctx->packed_pic_buf_id);
928 CHECK_VASTATUS(va_status,"vaCreateBuffer");
930 free(packed_seq_buffer);
931 free(packed_pic_buffer);
934 /* sequence parameter set */
935 VAEncSequenceParameterBufferMPEG2 *seq_param = &ctx->seq_param;
936 va_status = vaCreateBuffer(ctx->va_dpy,
938 VAEncSequenceParameterBufferType,
942 &ctx->seq_param_buf_id);
943 CHECK_VASTATUS(va_status,"vaCreateBuffer");;
945 /* slice parameter */
946 mpeg2enc_update_slice_parameter(ctx, picture_type);
952 mpeg2enc_render_picture(struct mpeg2enc_context *ctx)
955 VABufferID va_buffers[16];
956 unsigned int num_va_buffers = 0;
958 va_buffers[num_va_buffers++] = ctx->seq_param_buf_id;
959 va_buffers[num_va_buffers++] = ctx->pic_param_buf_id;
961 if (ctx->packed_seq_header_param_buf_id != VA_INVALID_ID)
962 va_buffers[num_va_buffers++] = ctx->packed_seq_header_param_buf_id;
964 if (ctx->packed_seq_buf_id != VA_INVALID_ID)
965 va_buffers[num_va_buffers++] = ctx->packed_seq_buf_id;
967 if (ctx->packed_pic_header_param_buf_id != VA_INVALID_ID)
968 va_buffers[num_va_buffers++] = ctx->packed_pic_header_param_buf_id;
970 if (ctx->packed_pic_buf_id != VA_INVALID_ID)
971 va_buffers[num_va_buffers++] = ctx->packed_pic_buf_id;
973 va_status = vaBeginPicture(ctx->va_dpy,
975 surface_ids[ctx->current_input_surface]);
976 CHECK_VASTATUS(va_status,"vaBeginPicture");
978 va_status = vaRenderPicture(ctx->va_dpy,
982 CHECK_VASTATUS(va_status,"vaRenderPicture");
984 va_status = vaRenderPicture(ctx->va_dpy,
986 &ctx->slice_param_buf_id[0],
987 ctx->num_slice_groups);
988 CHECK_VASTATUS(va_status,"vaRenderPicture");
990 va_status = vaEndPicture(ctx->va_dpy, ctx->context_id);
991 CHECK_VASTATUS(va_status,"vaEndPicture");
997 mpeg2enc_destroy_buffers(struct mpeg2enc_context *ctx, VABufferID *va_buffers, unsigned int num_va_buffers)
1002 for (i = 0; i < num_va_buffers; i++) {
1003 if (va_buffers[i] != VA_INVALID_ID) {
1004 va_status = vaDestroyBuffer(ctx->va_dpy, va_buffers[i]);
1005 CHECK_VASTATUS(va_status,"vaDestroyBuffer");
1006 va_buffers[i] = VA_INVALID_ID;
1014 end_picture(struct mpeg2enc_context *ctx, VAEncPictureType picture_type, int next_is_bpic)
1018 /* Prepare for next picture */
1019 tempID = surface_ids[SID_RECON_PICTURE];
1021 if (picture_type != VAEncPictureTypeBidirectional) {
1023 surface_ids[SID_RECON_PICTURE] = surface_ids[SID_REFERENCE_PICTURE_L1];
1024 surface_ids[SID_REFERENCE_PICTURE_L1] = tempID;
1026 surface_ids[SID_RECON_PICTURE] = surface_ids[SID_REFERENCE_PICTURE_L0];
1027 surface_ids[SID_REFERENCE_PICTURE_L0] = tempID;
1030 if (!next_is_bpic) {
1031 surface_ids[SID_RECON_PICTURE] = surface_ids[SID_REFERENCE_PICTURE_L0];
1032 surface_ids[SID_REFERENCE_PICTURE_L0] = surface_ids[SID_REFERENCE_PICTURE_L1];
1033 surface_ids[SID_REFERENCE_PICTURE_L1] = tempID;
1037 mpeg2enc_destroy_buffers(ctx, &ctx->seq_param_buf_id, 1);
1038 mpeg2enc_destroy_buffers(ctx, &ctx->pic_param_buf_id, 1);
1039 mpeg2enc_destroy_buffers(ctx, &ctx->packed_seq_header_param_buf_id, 1);
1040 mpeg2enc_destroy_buffers(ctx, &ctx->packed_seq_buf_id, 1);
1041 mpeg2enc_destroy_buffers(ctx, &ctx->packed_pic_header_param_buf_id, 1);
1042 mpeg2enc_destroy_buffers(ctx, &ctx->packed_pic_buf_id, 1);
1043 mpeg2enc_destroy_buffers(ctx, &ctx->slice_param_buf_id[0], ctx->num_slice_groups);
1044 mpeg2enc_destroy_buffers(ctx, &ctx->codedbuf_buf_id, 1);
1045 memset(ctx->slice_param, 0, sizeof(ctx->slice_param));
1046 ctx->num_slice_groups = 0;
1050 store_coded_buffer(struct mpeg2enc_context *ctx, VAEncPictureType picture_type)
1052 VACodedBufferSegment *coded_buffer_segment;
1053 unsigned char *coded_mem;
1054 int slice_data_length;
1056 VASurfaceStatus surface_status;
1059 va_status = vaSyncSurface(ctx->va_dpy, surface_ids[ctx->current_input_surface]);
1060 CHECK_VASTATUS(va_status,"vaSyncSurface");
1063 va_status = vaQuerySurfaceStatus(ctx->va_dpy, surface_ids[ctx->current_input_surface], &surface_status);
1064 CHECK_VASTATUS(va_status,"vaQuerySurfaceStatus");
1066 va_status = vaMapBuffer(ctx->va_dpy, ctx->codedbuf_buf_id, (void **)(&coded_buffer_segment));
1067 CHECK_VASTATUS(va_status,"vaMapBuffer");
1068 coded_mem = coded_buffer_segment->buf;
1070 if (coded_buffer_segment->status & VA_CODED_BUF_STATUS_SLICE_OVERFLOW_MASK) {
1071 if (picture_type == VAEncPictureTypeIntra)
1072 ctx->codedbuf_i_size *= 2;
1074 ctx->codedbuf_pb_size *= 2;
1076 vaUnmapBuffer(ctx->va_dpy, ctx->codedbuf_buf_id);
1080 slice_data_length = coded_buffer_segment->size;
1083 w_items = fwrite(coded_mem, slice_data_length, 1, ctx->ofp);
1084 } while (w_items != 1);
1086 if (picture_type == VAEncPictureTypeIntra) {
1087 if (ctx->codedbuf_i_size > slice_data_length * 3 / 2) {
1088 ctx->codedbuf_i_size = slice_data_length * 3 / 2;
1091 if (ctx->codedbuf_pb_size < slice_data_length) {
1092 ctx->codedbuf_pb_size = slice_data_length;
1095 if (ctx->codedbuf_pb_size > slice_data_length * 3 / 2) {
1096 ctx->codedbuf_pb_size = slice_data_length * 3 / 2;
1100 vaUnmapBuffer(ctx->va_dpy, ctx->codedbuf_buf_id);
1106 encode_picture(struct mpeg2enc_context *ctx,
1109 VAEncPictureType picture_type,
1111 int next_display_order)
1114 int ret = 0, codedbuf_size;
1116 begin_picture(ctx, coded_order, display_order, picture_type);
1119 /* upload YUV data to VA surface for next frame */
1120 if (next_display_order >= ctx->num_pictures)
1121 next_display_order = ctx->num_pictures - 1;
1123 fseek(ctx->ifp, ctx->frame_size * next_display_order, SEEK_SET);
1124 ctx->upload_thread_value = pthread_create(&ctx->upload_thread_id,
1126 upload_yuv_to_surface,
1131 mpeg2enc_destroy_buffers(ctx, &ctx->codedbuf_buf_id, 1);
1132 mpeg2enc_destroy_buffers(ctx, &ctx->pic_param_buf_id, 1);
1135 if (VAEncPictureTypeIntra == picture_type) {
1136 codedbuf_size = ctx->codedbuf_i_size;
1138 codedbuf_size = ctx->codedbuf_pb_size;
1142 va_status = vaCreateBuffer(ctx->va_dpy,
1144 VAEncCodedBufferType,
1145 codedbuf_size, 1, NULL,
1146 &ctx->codedbuf_buf_id);
1147 CHECK_VASTATUS(va_status,"vaCreateBuffer");
1149 /* picture parameter set */
1150 mpeg2enc_update_picture_parameter(ctx, picture_type, coded_order, display_order);
1152 mpeg2enc_render_picture(ctx);
1154 ret = store_coded_buffer(ctx, picture_type);
1157 end_picture(ctx, picture_type, next_is_bpic);
1161 encode_pb_pictures(struct mpeg2enc_context *ctx,
1172 VAEncPictureTypePredictive,
1176 for( i = 0; i < nbframes - 1; i++) {
1180 VAEncPictureTypeBidirectional,
1188 VAEncPictureTypeBidirectional,
1194 mpeg2enc_run(struct mpeg2enc_context *ctx)
1196 int display_order = 0, coded_order = 0;
1197 int i_frame_only = 1, i_p_frame_only = 1;
1199 for (display_order = 0; display_order < ctx->num_pictures;) {
1204 VAEncPictureTypeIntra,
1209 } else if (i_p_frame_only) {
1210 if ((display_order % ctx->intra_period) == 0) {
1214 VAEncPictureTypeIntra,
1223 VAEncPictureTypePredictive,
1229 } else { // follow the i,p,b pattern
1230 static int fcurrent = 0;
1233 fcurrent = fcurrent % (sizeof(picture_type_patter)/sizeof(int[2]));
1234 fnext = (fcurrent+1) % (sizeof(picture_type_patter)/sizeof(int[2]));
1236 if ( picture_type_patter[fcurrent][0] == VAEncPictureTypeIntra ) {
1240 VAEncPictureTypeIntra,
1242 display_order + picture_type_patter[fnext][1]);
1246 encode_pb_pictures(ctx,
1249 picture_type_patter[fcurrent][1] - 1,
1250 display_order + picture_type_patter[fcurrent][1] + picture_type_patter[fnext][1] - 1);
1251 display_order += picture_type_patter[fcurrent][1];
1258 fprintf(stderr, "\r %d/%d ...", display_order + 1, ctx->num_pictures);
1267 mpeg2enc_release_va_resources(struct mpeg2enc_context *ctx)
1269 vaDestroySurfaces(ctx->va_dpy, surface_ids, SID_NUMBER);
1270 vaDestroyContext(ctx->va_dpy, ctx->context_id);
1271 vaDestroyConfig(ctx->va_dpy, ctx->config_id);
1272 vaTerminate(ctx->va_dpy);
1273 va_close_display(ctx->va_dpy);
1277 mpeg2enc_end(struct mpeg2enc_context *ctx)
1279 pthread_join(ctx->upload_thread_id, NULL);
1280 mpeg2enc_release_va_resources(ctx);
1284 main(int argc, char *argv[])
1286 struct mpeg2enc_context ctx;
1287 struct timeval tpstart, tpend;
1290 gettimeofday(&tpstart, NULL);
1292 memset(&ctx, 0, sizeof(ctx));
1293 parse_args(&ctx, argc, argv);
1294 mpeg2enc_init(&ctx);
1298 gettimeofday(&tpend, NULL);
1299 timeuse = 1000000 * (tpend.tv_sec - tpstart.tv_sec) + tpend.tv_usec - tpstart.tv_usec;
1301 fprintf(stderr, "\ndone!\n");
1302 fprintf(stderr, "encode %d frames in %f secondes, FPS is %.1f\n", ctx.num_pictures, timeuse, ctx.num_pictures / timeuse);
1304 mpeg2enc_exit(&ctx, 0);