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
71 #define CHECK_VASTATUS(va_status, func) \
72 if (va_status != VA_STATUS_SUCCESS) { \
73 fprintf(stderr, "%s:%s (%d) failed, exit\n", __func__, func, __LINE__); \
77 static VAProfile mpeg2_va_profiles[] = {
82 struct mpeg2enc_context {
84 int rate_control_mode;
86 int mode; /* 0:I, 1:I/P, 2:I/P/B */
96 unsigned char *frame_data_buffer;
99 int bit_rate; /* in kbps */
100 VAEncPictureType next_type;
101 int next_display_order;
106 VAEncSequenceParameterBufferMPEG2 seq_param;
107 VAEncPictureParameterBufferMPEG2 pic_param;
108 VAEncSliceParameterBufferMPEG2 slice_param[MAX_SLICES];
109 VAContextID context_id;
110 VAConfigID config_id;
111 VABufferID seq_param_buf_id; /* Sequence level parameter */
112 VABufferID pic_param_buf_id; /* Picture level parameter */
113 VABufferID slice_param_buf_id[MAX_SLICES]; /* Slice level parameter, multil slices */
114 VABufferID codedbuf_buf_id; /* Output buffer, compressed data */
115 VABufferID packed_seq_header_param_buf_id;
116 VABufferID packed_seq_buf_id;
117 VABufferID packed_pic_header_param_buf_id;
118 VABufferID packed_pic_buf_id;
119 int num_slice_groups;
121 int codedbuf_pb_size;
124 pthread_t upload_thread_id;
125 int upload_thread_value;
126 int current_input_surface;
127 int current_upload_surface;
133 #define BITSTREAM_ALLOCATE_STEPPING 4096
136 unsigned int *buffer;
138 int max_size_in_dword;
141 typedef struct __bitstream bitstream;
144 swap32(unsigned int val)
146 unsigned char *pval = (unsigned char *)&val;
148 return ((pval[0] << 24) |
155 bitstream_start(bitstream *bs)
157 bs->max_size_in_dword = BITSTREAM_ALLOCATE_STEPPING;
158 bs->buffer = calloc(bs->max_size_in_dword * sizeof(int), 1);
163 bitstream_end(bitstream *bs)
165 int pos = (bs->bit_offset >> 5);
166 int bit_offset = (bs->bit_offset & 0x1f);
167 int bit_left = 32 - bit_offset;
170 bs->buffer[pos] = swap32((bs->buffer[pos] << bit_left));
175 bitstream_put_ui(bitstream *bs, unsigned int val, int size_in_bits)
177 int pos = (bs->bit_offset >> 5);
178 int bit_offset = (bs->bit_offset & 0x1f);
179 int bit_left = 32 - bit_offset;
184 if (size_in_bits < 32)
185 val &= ((1 << size_in_bits) - 1);
187 bs->bit_offset += size_in_bits;
189 if (bit_left > size_in_bits) {
190 bs->buffer[pos] = (bs->buffer[pos] << size_in_bits | val);
192 size_in_bits -= bit_left;
193 bs->buffer[pos] = (bs->buffer[pos] << bit_left) | (val >> size_in_bits);
194 bs->buffer[pos] = swap32(bs->buffer[pos]);
196 if (pos + 1 == bs->max_size_in_dword) {
197 bs->max_size_in_dword += BITSTREAM_ALLOCATE_STEPPING;
198 bs->buffer = realloc(bs->buffer, bs->max_size_in_dword * sizeof(unsigned int));
201 bs->buffer[pos + 1] = val;
206 bitstream_byte_aligning(bitstream *bs, int bit)
208 int bit_offset = (bs->bit_offset & 0x7);
209 int bit_left = 8 - bit_offset;
215 assert(bit == 0 || bit == 1);
218 new_val = (1 << bit_left) - 1;
222 bitstream_put_ui(bs, new_val, bit_left);
225 static struct mpeg2_frame_rate {
228 } frame_rate_tab[] = {
240 find_frame_rate_code(const VAEncSequenceParameterBufferMPEG2 *seq_param)
242 unsigned int delta = -1;
244 float frame_rate_value = seq_param->frame_rate *
245 (seq_param->sequence_extension.bits.frame_rate_extension_d + 1) /
246 (seq_param->sequence_extension.bits.frame_rate_extension_n + 1);
248 for (i = 0; i < sizeof(frame_rate_tab) / sizeof(frame_rate_tab[0]); i++) {
250 if (abs(1000 * frame_rate_tab[i].value - 1000 * frame_rate_value) < delta) {
251 code = frame_rate_tab[i].code;
252 delta = abs(1000 * frame_rate_tab[i].value - 1000 * frame_rate_value);
260 sps_rbsp(const VAEncSequenceParameterBufferMPEG2 *seq_param,
263 int frame_rate_code = find_frame_rate_code(seq_param);
265 bitstream_put_ui(bs, START_CODE_SEQ, 32);
266 bitstream_put_ui(bs, seq_param->picture_width, 12);
267 bitstream_put_ui(bs, seq_param->picture_height, 12);
268 bitstream_put_ui(bs, seq_param->aspect_ratio_information, 4);
269 bitstream_put_ui(bs, frame_rate_code, 4); /* frame_rate_code */
270 bitstream_put_ui(bs, (seq_param->bits_per_second + 399) / 400, 18); /* the low 18 bits of bit_rate */
271 bitstream_put_ui(bs, 1, 1); /* marker_bit */
272 bitstream_put_ui(bs, seq_param->vbv_buffer_size, 10);
273 bitstream_put_ui(bs, 0, 1); /* constraint_parameter_flag, always 0 for MPEG-2 */
274 bitstream_put_ui(bs, 0, 1); /* load_intra_quantiser_matrix */
275 bitstream_put_ui(bs, 0, 1); /* load_non_intra_quantiser_matrix */
277 bitstream_byte_aligning(bs, 0);
279 bitstream_put_ui(bs, START_CODE_EXT, 32);
280 bitstream_put_ui(bs, 1, 4); /* sequence_extension id */
281 bitstream_put_ui(bs, seq_param->sequence_extension.bits.profile_and_level_indication, 8);
282 bitstream_put_ui(bs, seq_param->sequence_extension.bits.progressive_sequence, 1);
283 bitstream_put_ui(bs, seq_param->sequence_extension.bits.chroma_format, 2);
284 bitstream_put_ui(bs, seq_param->picture_width >> 12, 2);
285 bitstream_put_ui(bs, seq_param->picture_height >> 12, 2);
286 bitstream_put_ui(bs, ((seq_param->bits_per_second + 399) / 400) >> 18, 12); /* bit_rate_extension */
287 bitstream_put_ui(bs, 1, 1); /* marker_bit */
288 bitstream_put_ui(bs, seq_param->vbv_buffer_size >> 10, 8);
289 bitstream_put_ui(bs, seq_param->sequence_extension.bits.low_delay, 1);
290 bitstream_put_ui(bs, seq_param->sequence_extension.bits.frame_rate_extension_n, 2);
291 bitstream_put_ui(bs, seq_param->sequence_extension.bits.frame_rate_extension_d, 5);
293 bitstream_byte_aligning(bs, 0);
297 pps_rbsp(const VAEncSequenceParameterBufferMPEG2 *seq_param,
298 const VAEncPictureParameterBufferMPEG2 *pic_param,
304 if (pic_param->temporal_reference == 0) {
305 bitstream_put_ui(bs, START_CODE_GOP, 32);
306 bitstream_put_ui(bs, seq_param->gop_header.bits.time_code, 25);
307 bitstream_put_ui(bs, seq_param->gop_header.bits.closed_gop, 1);
308 bitstream_put_ui(bs, seq_param->gop_header.bits.broken_link, 1);
310 bitstream_byte_aligning(bs, 0);
313 if (seq_param->sequence_extension.bits.chroma_format == CHROMA_FORMAT_420)
314 chroma_420_type = pic_param->picture_coding_extension.bits.progressive_frame;
318 bitstream_put_ui(bs, START_CODE_PICUTRE, 32);
319 bitstream_put_ui(bs, pic_param->temporal_reference, 10);
321 pic_param->picture_type == VAEncPictureTypeIntra ? 1 :
322 pic_param->picture_type == VAEncPictureTypePredictive ? 2 : 3,
324 bitstream_put_ui(bs, 0xFFFF, 16); /* vbv_delay, always 0xFFFF */
326 if (pic_param->picture_type == VAEncPictureTypePredictive) {
327 bitstream_put_ui(bs, 0, 1); /* full_pel_forward_vector, always 0 for MPEG-2 */
328 bitstream_put_ui(bs, 7, 3); /* forward_f_code, always 7 for MPEG-2 */
331 if (pic_param->picture_type == VAEncPictureTypeBidirectional) {
332 bitstream_put_ui(bs, 0, 1); /* full_pel_backward_vector, always 0 for MPEG-2 */
333 bitstream_put_ui(bs, 7, 3); /* backward_f_code, always 7 for MPEG-2 */
336 bitstream_put_ui(bs, 0, 1); /* extra_bit_picture, 0 */
338 bitstream_byte_aligning(bs, 0);
340 bitstream_put_ui(bs, START_CODE_EXT, 32);
341 bitstream_put_ui(bs, 8, 4); /* Picture Coding Extension ID: 8 */
342 bitstream_put_ui(bs, pic_param->f_code[0][0], 4);
343 bitstream_put_ui(bs, pic_param->f_code[0][1], 4);
344 bitstream_put_ui(bs, pic_param->f_code[1][0], 4);
345 bitstream_put_ui(bs, pic_param->f_code[1][1], 4);
347 bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.intra_dc_precision, 2);
348 bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.picture_structure, 2);
349 bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.top_field_first, 1);
350 bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.frame_pred_frame_dct, 1);
351 bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.concealment_motion_vectors, 1);
352 bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.q_scale_type, 1);
353 bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.intra_vlc_format, 1);
354 bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.alternate_scan, 1);
355 bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.repeat_first_field, 1);
356 bitstream_put_ui(bs, chroma_420_type, 1);
357 bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.progressive_frame, 1);
358 bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.composite_display_flag, 1);
360 bitstream_byte_aligning(bs, 0);
362 if (pic_param->user_data_length) {
363 bitstream_put_ui(bs, START_CODE_USER, 32);
365 for (i = 0; i < pic_param->user_data_length; i++) {
366 bitstream_put_ui(bs, pic_param->user_data[i], 8);
369 bitstream_byte_aligning(bs, 0);
374 build_packed_pic_buffer(const VAEncSequenceParameterBufferMPEG2 *seq_param,
375 const VAEncPictureParameterBufferMPEG2 *pic_param,
376 unsigned char **header_buffer)
380 bitstream_start(&bs);
381 pps_rbsp(seq_param, pic_param, &bs);
384 *header_buffer = (unsigned char *)bs.buffer;
385 return bs.bit_offset;
389 build_packed_seq_buffer(const VAEncSequenceParameterBufferMPEG2 *seq_param,
390 unsigned char **header_buffer)
394 bitstream_start(&bs);
395 sps_rbsp(seq_param, &bs);
398 *header_buffer = (unsigned char *)bs.buffer;
399 return bs.bit_offset;
405 #define SID_INPUT_PICTURE_0 0
406 #define SID_INPUT_PICTURE_1 1
407 #define SID_REFERENCE_PICTURE_L0 2
408 #define SID_REFERENCE_PICTURE_L1 3
409 #define SID_RECON_PICTURE 4
410 #define SID_NUMBER SID_RECON_PICTURE + 1
412 static VASurfaceID surface_ids[SID_NUMBER];
415 * upload thread function
418 upload_yuv_to_surface(void *data)
420 struct mpeg2enc_context *ctx = data;
421 VAImage surface_image;
423 void *surface_p = NULL;
424 unsigned char *y_src, *u_src, *v_src;
425 unsigned char *y_dst, *u_dst, *v_dst;
426 int y_size = ctx->width * ctx->height;
427 int u_size = (ctx->width >> 1) * (ctx->height >> 1);
432 n_items = fread(ctx->frame_data_buffer, ctx->frame_size, 1, ctx->ifp);
433 } while (n_items != 1);
435 va_status = vaDeriveImage(ctx->va_dpy, surface_ids[ctx->current_upload_surface], &surface_image);
436 CHECK_VASTATUS(va_status,"vaDeriveImage");
438 vaMapBuffer(ctx->va_dpy, surface_image.buf, &surface_p);
439 assert(VA_STATUS_SUCCESS == va_status);
441 y_src = ctx->frame_data_buffer;
442 u_src = ctx->frame_data_buffer + y_size; /* UV offset for NV12 */
443 v_src = ctx->frame_data_buffer + y_size + u_size;
445 y_dst = surface_p + surface_image.offsets[0];
446 u_dst = surface_p + surface_image.offsets[1]; /* UV offset for NV12 */
447 v_dst = surface_p + surface_image.offsets[2];
450 for (row = 0; row < surface_image.height; row++) {
451 memcpy(y_dst, y_src, surface_image.width);
452 y_dst += surface_image.pitches[0];
456 if (surface_image.format.fourcc == VA_FOURCC_NV12) { /* UV plane */
457 for (row = 0; row < surface_image.height / 2; row++) {
458 for (col = 0; col < surface_image.width / 2; col++) {
459 u_dst[col * 2] = u_src[col];
460 u_dst[col * 2 + 1] = v_src[col];
463 u_dst += surface_image.pitches[1];
464 u_src += (ctx->width / 2);
465 v_src += (ctx->width / 2);
468 for (row = 0; row < surface_image.height / 2; row++) {
469 for (col = 0; col < surface_image.width / 2; col++) {
470 u_dst[col] = u_src[col];
471 v_dst[col] = v_src[col];
474 u_dst += surface_image.pitches[1];
475 v_dst += surface_image.pitches[2];
476 u_src += (ctx->width / 2);
477 v_src += (ctx->width / 2);
481 vaUnmapBuffer(ctx->va_dpy, surface_image.buf);
482 vaDestroyImage(ctx->va_dpy, surface_image.image_id);
488 mpeg2enc_exit(struct mpeg2enc_context *ctx, int exit_code)
490 if (ctx->frame_data_buffer) {
491 free(ctx->frame_data_buffer);
492 ctx->frame_data_buffer = NULL;
511 fprintf(stderr, "Usage: %s --help\n", program);
512 fprintf(stderr, "\t--help print this message\n");
513 fprintf(stderr, "Usage: %s <width> <height> <ifile> <ofile> [options]\n", program);
514 fprintf(stderr, "\t<width> specifies the frame width\n");
515 fprintf(stderr, "\t<height> specifies the frame height\n");
516 fprintf(stderr, "\t<ifile> specifies the I420/IYUV YUV file\n");
517 fprintf(stderr, "\t<ofile> specifies the encoded MPEG-2 file\n");
518 fprintf(stderr, "where options include:\n");
519 fprintf(stderr, "\t--cqp <QP> const qp mode with specified <QP>\n");
520 fprintf(stderr, "\t--fps <FPS> specify the frame rate\n");
521 fprintf(stderr, "\t--mode <MODE> specify the mode 0 (I), 1 (I/P) and 2 (I/P/B)\n");
522 fprintf(stderr, "\t--profile <PROFILE> specify the profile 0(Simple), or 1(Main, default)\n");
523 fprintf(stderr, "\t--level <LEVEL> specify the level 0(Low), 1(Main, default) or 2(High)\n");
527 parse_args(struct mpeg2enc_context *ctx, int argc, char **argv)
530 int option_index = 0;
532 static struct option long_options[] = {
533 {"help", no_argument, 0, 'h'},
534 {"cqp", required_argument, 0, 'c'},
535 {"fps", required_argument, 0, 'f'},
536 {"mode", required_argument, 0, 'm'},
537 {"profile", required_argument, 0, 'p'},
538 {"level", required_argument, 0, 'l'},
542 if ((argc == 2 && strcmp(argv[1], "--help") == 0) ||
546 ctx->width = atoi(argv[1]);
547 ctx->height = atoi(argv[2]);
549 if (ctx->width <= 0 || ctx->height <= 0) {
550 fprintf(stderr, "<width> and <height> must be greater than 0\n");
554 ctx->ifp = fopen(argv[3], "rb");
556 if (ctx->ifp == NULL) {
557 fprintf(stderr, "Can't open the input file\n");
561 fseek(ctx->ifp, 0l, SEEK_END);
562 file_size = ftell(ctx->ifp);
563 ctx->frame_size = ctx->width * ctx->height * 3 / 2;
565 if ((file_size < ctx->frame_size) ||
566 (file_size % ctx->frame_size)) {
567 fprintf(stderr, "The input file size %ld isn't a multiple of the frame size %d\n", file_size, ctx->frame_size);
571 ctx->num_pictures = file_size / ctx->frame_size;
572 fseek(ctx->ifp, 0l, SEEK_SET);
574 ctx->ofp = fopen(argv[4], "wb");
576 if (ctx->ofp == NULL) {
577 fprintf(stderr, "Can't create the output file\n");
584 ctx->rate_control_mode = VA_RC_CQP;
585 ctx->mode = MPEG2_MODE_IP;
586 ctx->profile = VAProfileMPEG2Main;
587 ctx->level = MPEG2_LEVEL_MAIN;
591 while((c = getopt_long(argc, argv,
594 &option_index)) != -1) {
599 /* only support q_scale_type = 0 */
600 if (tmp > 62 || tmp < 2) {
601 fprintf(stderr, "Warning: QP must be in [2, 62]\n");
610 ctx->qp = tmp & 0xFE;
611 ctx->rate_control_mode = VA_RC_CQP;
619 fprintf(stderr, "Warning: FPS must be greater than 0\n");
623 ctx->rate_control_mode = VA_RC_CBR;
630 if (tmp < MPEG2_MODE_I || tmp > MPEG2_MODE_IPB)
631 fprintf(stderr, "Waning: MODE must be 0, 1, or 2\n");
640 if (tmp < 0 || tmp > 1)
641 fprintf(stderr, "Waning: PROFILE must be 0 or 1\n");
643 ctx->profile = mpeg2_va_profiles[tmp];
650 if (tmp < MPEG2_LEVEL_LOW || tmp > MPEG2_LEVEL_HIGH)
651 fprintf(stderr, "Waning: LEVEL must be 0, 1, or 2\n");
658 fprintf(stderr, "Error: unkown command options\n");
670 mpeg2enc_exit(ctx, 1);
677 mpeg2enc_init_sequence_parameter(struct mpeg2enc_context *ctx,
678 VAEncSequenceParameterBufferMPEG2 *seq_param)
680 int profile = 4, level = 8;
682 switch (ctx->profile) {
683 case VAProfileMPEG2Simple:
687 case VAProfileMPEG2Main:
696 switch (ctx->level) {
697 case MPEG2_LEVEL_LOW:
701 case MPEG2_LEVEL_MAIN:
705 case MPEG2_LEVEL_HIGH:
714 seq_param->intra_period = ctx->intra_period;
715 seq_param->ip_period = ctx->ip_period; /* FIXME: ??? */
716 seq_param->picture_width = ctx->width;
717 seq_param->picture_height = ctx->height;
719 if (ctx->bit_rate > 0)
720 seq_param->bits_per_second = 1024 * ctx->bit_rate; /* use kbps as input */
722 seq_param->bits_per_second = 0x3FFFF * 400;
724 seq_param->frame_rate = ctx->fps;
725 seq_param->aspect_ratio_information = 1;
726 seq_param->vbv_buffer_size = 3; /* B = 16 * 1024 * vbv_buffer_size */
728 seq_param->sequence_extension.bits.profile_and_level_indication = profile << 4 | level;
729 seq_param->sequence_extension.bits.progressive_sequence = 1; /* progressive frame-pictures */
730 seq_param->sequence_extension.bits.chroma_format = CHROMA_FORMAT_420; /* 4:2:0 */
731 seq_param->sequence_extension.bits.low_delay = 0; /* FIXME */
732 seq_param->sequence_extension.bits.frame_rate_extension_n = 0;
733 seq_param->sequence_extension.bits.frame_rate_extension_d = 0;
735 seq_param->gop_header.bits.time_code = (1 << 12); /* bit12: marker_bit */
736 seq_param->gop_header.bits.closed_gop = 0;
737 seq_param->gop_header.bits.broken_link = 0;
741 mpeg2enc_init_picture_parameter(struct mpeg2enc_context *ctx,
742 VAEncPictureParameterBufferMPEG2 *pic_param)
744 pic_param->forward_reference_picture = VA_INVALID_ID;
745 pic_param->backward_reference_picture = VA_INVALID_ID;
746 pic_param->reconstructed_picture = VA_INVALID_ID;
747 pic_param->coded_buf = VA_INVALID_ID;
748 pic_param->picture_type = VAEncPictureTypeIntra;
750 pic_param->temporal_reference = 0;
751 pic_param->f_code[0][0] = 0xf;
752 pic_param->f_code[0][1] = 0xf;
753 pic_param->f_code[1][0] = 0xf;
754 pic_param->f_code[1][1] = 0xf;
756 pic_param->picture_coding_extension.bits.intra_dc_precision = 0; /* 8bits */
757 pic_param->picture_coding_extension.bits.picture_structure = 3; /* frame picture */
758 pic_param->picture_coding_extension.bits.top_field_first = 0;
759 pic_param->picture_coding_extension.bits.frame_pred_frame_dct = 1; /* FIXME */
760 pic_param->picture_coding_extension.bits.concealment_motion_vectors = 0;
761 pic_param->picture_coding_extension.bits.q_scale_type = 0;
762 pic_param->picture_coding_extension.bits.intra_vlc_format = 0;
763 pic_param->picture_coding_extension.bits.alternate_scan = 0;
764 pic_param->picture_coding_extension.bits.repeat_first_field = 0;
765 pic_param->picture_coding_extension.bits.progressive_frame = 1;
766 pic_param->picture_coding_extension.bits.composite_display_flag = 0;
768 pic_param->user_data_length = 0;
772 mpeg2enc_alloc_va_resources(struct mpeg2enc_context *ctx)
774 VAEntrypoint *entrypoint_list;
775 VAConfigAttrib attrib_list[2];
777 int max_entrypoints, num_entrypoints, entrypoint;
778 int major_ver, minor_ver;
780 ctx->va_dpy = va_open_display();
781 va_status = vaInitialize(ctx->va_dpy,
784 CHECK_VASTATUS(va_status, "vaInitialize");
786 max_entrypoints = vaMaxNumEntrypoints(ctx->va_dpy);
787 entrypoint_list = malloc(max_entrypoints * sizeof(VAEntrypoint));
788 vaQueryConfigEntrypoints(ctx->va_dpy,
793 for (entrypoint = 0; entrypoint < num_entrypoints; entrypoint++) {
794 if (entrypoint_list[entrypoint] == VAEntrypointEncSlice)
798 free(entrypoint_list);
800 if (entrypoint == num_entrypoints) {
801 /* not find Slice entry point */
805 /* find out the format for the render target, and rate control mode */
806 attrib_list[0].type = VAConfigAttribRTFormat;
807 attrib_list[1].type = VAConfigAttribRateControl;
808 vaGetConfigAttributes(ctx->va_dpy,
810 VAEntrypointEncSlice,
814 if ((attrib_list[0].value & VA_RT_FORMAT_YUV420) == 0) {
815 /* not find desired YUV420 RT format */
819 if ((attrib_list[1].value & ctx->rate_control_mode) == 0) {
820 /* Can't find matched RC mode */
821 fprintf(stderr, "RC mode %d isn't found, exit\n", ctx->rate_control_mode);
825 attrib_list[0].value = VA_RT_FORMAT_YUV420; /* set to desired RT format */
826 attrib_list[1].value = ctx->rate_control_mode; /* set to desired RC mode */
828 va_status = vaCreateConfig(ctx->va_dpy,
830 VAEntrypointEncSlice,
834 CHECK_VASTATUS(va_status, "vaCreateConfig");
836 /* Create a context for this decode pipe */
837 va_status = vaCreateContext(ctx->va_dpy,
845 CHECK_VASTATUS(va_status, "vaCreateContext");
847 va_status = vaCreateSurfaces(ctx->va_dpy,
853 CHECK_VASTATUS(va_status, "vaCreateSurfaces");
857 mpeg2enc_init(struct mpeg2enc_context *ctx)
861 ctx->frame_data_buffer = (unsigned char *)malloc(ctx->frame_size);
862 ctx->seq_param_buf_id = VA_INVALID_ID;
863 ctx->pic_param_buf_id = VA_INVALID_ID;
864 ctx->packed_seq_header_param_buf_id = VA_INVALID_ID;
865 ctx->packed_seq_buf_id = VA_INVALID_ID;
866 ctx->packed_pic_header_param_buf_id = VA_INVALID_ID;
867 ctx->packed_pic_buf_id = VA_INVALID_ID;
868 ctx->codedbuf_buf_id = VA_INVALID_ID;
869 ctx->codedbuf_i_size = ctx->frame_size;
870 ctx->codedbuf_pb_size = 0;
871 ctx->next_display_order = 0;
872 ctx->next_type = VAEncPictureTypeIntra;
874 if (ctx->mode == MPEG2_MODE_I) {
875 ctx->intra_period = 1;
877 } else if (ctx->mode == MPEG2_MODE_IP) {
878 ctx->intra_period = 16;
881 ctx->intra_period = 16;
885 ctx->next_bframes = ctx->ip_period;
889 for (i = 0; i < MAX_SLICES; i++) {
890 ctx->slice_param_buf_id[i] = VA_INVALID_ID;
893 mpeg2enc_init_sequence_parameter(ctx, &ctx->seq_param);
894 mpeg2enc_init_picture_parameter(ctx, &ctx->pic_param);
895 mpeg2enc_alloc_va_resources(ctx);
898 ctx->current_input_surface = SID_INPUT_PICTURE_0;
899 ctx->current_upload_surface = SID_INPUT_PICTURE_1;
900 ctx->upload_thread_value = pthread_create(&ctx->upload_thread_id,
902 upload_yuv_to_surface,
907 mpeg2enc_time_code(VAEncSequenceParameterBufferMPEG2 *seq_param,
910 int fps = (int)(seq_param->frame_rate + 0.5);
912 int time_code_pictures, time_code_seconds, time_code_minutes, time_code_hours;
913 int drop_frame_flag = 0;
917 time_code_seconds = num_frames / fps;
918 time_code_pictures = num_frames % fps;
919 time_code |= time_code_pictures;
921 time_code_minutes = time_code_seconds / 60;
922 time_code_seconds = time_code_minutes % 60;
923 time_code |= (time_code_seconds << 6);
925 time_code_hours = time_code_minutes / 60;
926 time_code_minutes = time_code_minutes % 60;
928 time_code |= (1 << 12); /* marker_bit */
929 time_code |= (time_code_minutes << 13);
931 time_code_hours = time_code_hours % 24;
932 time_code |= (time_code_hours << 19);
934 time_code |= (drop_frame_flag << 24);
943 mpeg2enc_update_sequence_parameter(struct mpeg2enc_context *ctx,
944 VAEncPictureType picture_type,
948 VAEncSequenceParameterBufferMPEG2 *seq_param = &ctx->seq_param;
950 /* update the GOP info for the new GOP */
951 if (display_order % ctx->intra_period == 0) {
952 seq_param->gop_header.bits.time_code = mpeg2enc_time_code(seq_param, display_order);
957 mpeg2enc_update_picture_parameter(struct mpeg2enc_context *ctx,
958 VAEncPictureType picture_type,
962 VAEncPictureParameterBufferMPEG2 *pic_param = &ctx->pic_param;
964 pic_param->picture_type = picture_type;
965 pic_param->temporal_reference = display_order % ctx->intra_period;
966 pic_param->reconstructed_picture = surface_ids[SID_RECON_PICTURE];
967 pic_param->forward_reference_picture = surface_ids[SID_REFERENCE_PICTURE_L0];
968 pic_param->backward_reference_picture = surface_ids[SID_REFERENCE_PICTURE_L1];
970 if (pic_param->picture_type == VAEncPictureTypeIntra) {
971 pic_param->f_code[0][0] = 0xf;
972 pic_param->f_code[0][1] = 0xf;
973 pic_param->f_code[1][0] = 0xf;
974 pic_param->f_code[1][1] = 0xf;
975 pic_param->forward_reference_picture = VA_INVALID_SURFACE;
976 pic_param->backward_reference_picture = VA_INVALID_SURFACE;
978 } else if (pic_param->picture_type == VAEncPictureTypePredictive) {
979 pic_param->f_code[0][0] = 0x1;
980 pic_param->f_code[0][1] = 0x1;
981 pic_param->f_code[1][0] = 0xf;
982 pic_param->f_code[1][1] = 0xf;
983 pic_param->forward_reference_picture = surface_ids[SID_REFERENCE_PICTURE_L0];
984 pic_param->backward_reference_picture = VA_INVALID_SURFACE;
985 } else if (pic_param->picture_type == VAEncPictureTypeBidirectional) {
986 pic_param->f_code[0][0] = 0x1;
987 pic_param->f_code[0][1] = 0x1;
988 pic_param->f_code[1][0] = 0x1;
989 pic_param->f_code[1][1] = 0x1;
990 pic_param->forward_reference_picture = surface_ids[SID_REFERENCE_PICTURE_L0];
991 pic_param->backward_reference_picture = surface_ids[SID_REFERENCE_PICTURE_L1];
998 mpeg2enc_update_picture_parameter_buffer(struct mpeg2enc_context *ctx,
999 VAEncPictureType picture_type,
1003 VAEncPictureParameterBufferMPEG2 *pic_param = &ctx->pic_param;
1006 /* update the coded buffer id */
1007 pic_param->coded_buf = ctx->codedbuf_buf_id;
1008 va_status = vaCreateBuffer(ctx->va_dpy,
1010 VAEncPictureParameterBufferType,
1014 &ctx->pic_param_buf_id);
1015 CHECK_VASTATUS(va_status, "vaCreateBuffer");
1019 mpeg2enc_update_slice_parameter(struct mpeg2enc_context *ctx, VAEncPictureType picture_type)
1021 VAEncSequenceParameterBufferMPEG2 *seq_param;
1022 VAEncPictureParameterBufferMPEG2 *pic_param;
1023 VAEncSliceParameterBufferMPEG2 *slice_param;
1025 int i, width_in_mbs, height_in_mbs;
1027 pic_param = &ctx->pic_param;
1028 assert(pic_param->picture_coding_extension.bits.q_scale_type == 0);
1030 seq_param = &ctx->seq_param;
1031 width_in_mbs = (seq_param->picture_width + 15) / 16;
1032 height_in_mbs = (seq_param->picture_height + 15) / 16;
1033 ctx->num_slice_groups = 1;
1035 for (i = 0; i < height_in_mbs; i++) {
1036 slice_param = &ctx->slice_param[i];
1037 slice_param->macroblock_address = i * width_in_mbs;
1038 slice_param->num_macroblocks = width_in_mbs;
1039 slice_param->is_intra_slice = (picture_type == VAEncPictureTypeIntra);
1040 slice_param->quantiser_scale_code = ctx->qp / 2;
1043 va_status = vaCreateBuffer(ctx->va_dpy,
1045 VAEncSliceParameterBufferType,
1046 sizeof(*slice_param),
1049 ctx->slice_param_buf_id);
1050 CHECK_VASTATUS(va_status, "vaCreateBuffer");;
1054 begin_picture(struct mpeg2enc_context *ctx,
1057 VAEncPictureType picture_type)
1061 VAEncPackedHeaderParameterBuffer packed_header_param_buffer;
1062 unsigned int length_in_bits;
1063 unsigned char *packed_seq_buffer = NULL, *packed_pic_buffer = NULL;
1065 if (ctx->upload_thread_value != 0) {
1066 fprintf(stderr, "FATAL error!!!\n");
1070 pthread_join(ctx->upload_thread_id, NULL);
1072 ctx->upload_thread_value = -1;
1073 tmp = ctx->current_input_surface;
1074 ctx->current_input_surface = ctx->current_upload_surface;
1075 ctx->current_upload_surface = tmp;
1077 mpeg2enc_update_sequence_parameter(ctx, picture_type, coded_order, display_order);
1078 mpeg2enc_update_picture_parameter(ctx, picture_type, coded_order, display_order);
1080 if (coded_order == 0) {
1081 assert(picture_type == VAEncPictureTypeIntra);
1082 length_in_bits = build_packed_seq_buffer(&ctx->seq_param, &packed_seq_buffer);
1083 packed_header_param_buffer.type = VAEncPackedHeaderMPEG2_SPS;
1084 packed_header_param_buffer.has_emulation_bytes = 0;
1085 packed_header_param_buffer.bit_length = length_in_bits;
1086 va_status = vaCreateBuffer(ctx->va_dpy,
1088 VAEncPackedHeaderParameterBufferType,
1089 sizeof(packed_header_param_buffer), 1, &packed_header_param_buffer,
1090 &ctx->packed_seq_header_param_buf_id);
1091 CHECK_VASTATUS(va_status,"vaCreateBuffer");
1093 va_status = vaCreateBuffer(ctx->va_dpy,
1095 VAEncPackedHeaderDataBufferType,
1096 (length_in_bits + 7) / 8, 1, packed_seq_buffer,
1097 &ctx->packed_seq_buf_id);
1098 CHECK_VASTATUS(va_status,"vaCreateBuffer");
1100 free(packed_seq_buffer);
1103 length_in_bits = build_packed_pic_buffer(&ctx->seq_param, &ctx->pic_param, &packed_pic_buffer);
1104 packed_header_param_buffer.type = VAEncPackedHeaderMPEG2_PPS;
1105 packed_header_param_buffer.has_emulation_bytes = 0;
1106 packed_header_param_buffer.bit_length = length_in_bits;
1108 va_status = vaCreateBuffer(ctx->va_dpy,
1110 VAEncPackedHeaderParameterBufferType,
1111 sizeof(packed_header_param_buffer), 1, &packed_header_param_buffer,
1112 &ctx->packed_pic_header_param_buf_id);
1113 CHECK_VASTATUS(va_status,"vaCreateBuffer");
1115 va_status = vaCreateBuffer(ctx->va_dpy,
1117 VAEncPackedHeaderDataBufferType,
1118 (length_in_bits + 7) / 8, 1, packed_pic_buffer,
1119 &ctx->packed_pic_buf_id);
1120 CHECK_VASTATUS(va_status,"vaCreateBuffer");
1122 free(packed_pic_buffer);
1124 /* sequence parameter set */
1125 VAEncSequenceParameterBufferMPEG2 *seq_param = &ctx->seq_param;
1126 va_status = vaCreateBuffer(ctx->va_dpy,
1128 VAEncSequenceParameterBufferType,
1132 &ctx->seq_param_buf_id);
1133 CHECK_VASTATUS(va_status,"vaCreateBuffer");;
1135 /* slice parameter */
1136 mpeg2enc_update_slice_parameter(ctx, picture_type);
1142 mpeg2enc_render_picture(struct mpeg2enc_context *ctx)
1145 VABufferID va_buffers[16];
1146 unsigned int num_va_buffers = 0;
1148 va_buffers[num_va_buffers++] = ctx->seq_param_buf_id;
1149 va_buffers[num_va_buffers++] = ctx->pic_param_buf_id;
1151 if (ctx->packed_seq_header_param_buf_id != VA_INVALID_ID)
1152 va_buffers[num_va_buffers++] = ctx->packed_seq_header_param_buf_id;
1154 if (ctx->packed_seq_buf_id != VA_INVALID_ID)
1155 va_buffers[num_va_buffers++] = ctx->packed_seq_buf_id;
1157 if (ctx->packed_pic_header_param_buf_id != VA_INVALID_ID)
1158 va_buffers[num_va_buffers++] = ctx->packed_pic_header_param_buf_id;
1160 if (ctx->packed_pic_buf_id != VA_INVALID_ID)
1161 va_buffers[num_va_buffers++] = ctx->packed_pic_buf_id;
1163 va_status = vaBeginPicture(ctx->va_dpy,
1165 surface_ids[ctx->current_input_surface]);
1166 CHECK_VASTATUS(va_status,"vaBeginPicture");
1168 va_status = vaRenderPicture(ctx->va_dpy,
1172 CHECK_VASTATUS(va_status,"vaRenderPicture");
1174 va_status = vaRenderPicture(ctx->va_dpy,
1176 &ctx->slice_param_buf_id[0],
1177 ctx->num_slice_groups);
1178 CHECK_VASTATUS(va_status,"vaRenderPicture");
1180 va_status = vaEndPicture(ctx->va_dpy, ctx->context_id);
1181 CHECK_VASTATUS(va_status,"vaEndPicture");
1187 mpeg2enc_destroy_buffers(struct mpeg2enc_context *ctx, VABufferID *va_buffers, unsigned int num_va_buffers)
1192 for (i = 0; i < num_va_buffers; i++) {
1193 if (va_buffers[i] != VA_INVALID_ID) {
1194 va_status = vaDestroyBuffer(ctx->va_dpy, va_buffers[i]);
1195 CHECK_VASTATUS(va_status,"vaDestroyBuffer");
1196 va_buffers[i] = VA_INVALID_ID;
1204 end_picture(struct mpeg2enc_context *ctx, VAEncPictureType picture_type, int next_is_bpic)
1208 /* Prepare for next picture */
1209 tempID = surface_ids[SID_RECON_PICTURE];
1211 if (picture_type != VAEncPictureTypeBidirectional) {
1213 surface_ids[SID_RECON_PICTURE] = surface_ids[SID_REFERENCE_PICTURE_L1];
1214 surface_ids[SID_REFERENCE_PICTURE_L1] = tempID;
1216 surface_ids[SID_RECON_PICTURE] = surface_ids[SID_REFERENCE_PICTURE_L0];
1217 surface_ids[SID_REFERENCE_PICTURE_L0] = tempID;
1220 if (!next_is_bpic) {
1221 surface_ids[SID_RECON_PICTURE] = surface_ids[SID_REFERENCE_PICTURE_L0];
1222 surface_ids[SID_REFERENCE_PICTURE_L0] = surface_ids[SID_REFERENCE_PICTURE_L1];
1223 surface_ids[SID_REFERENCE_PICTURE_L1] = tempID;
1227 mpeg2enc_destroy_buffers(ctx, &ctx->seq_param_buf_id, 1);
1228 mpeg2enc_destroy_buffers(ctx, &ctx->pic_param_buf_id, 1);
1229 mpeg2enc_destroy_buffers(ctx, &ctx->packed_seq_header_param_buf_id, 1);
1230 mpeg2enc_destroy_buffers(ctx, &ctx->packed_seq_buf_id, 1);
1231 mpeg2enc_destroy_buffers(ctx, &ctx->packed_pic_header_param_buf_id, 1);
1232 mpeg2enc_destroy_buffers(ctx, &ctx->packed_pic_buf_id, 1);
1233 mpeg2enc_destroy_buffers(ctx, &ctx->slice_param_buf_id[0], ctx->num_slice_groups);
1234 mpeg2enc_destroy_buffers(ctx, &ctx->codedbuf_buf_id, 1);
1235 memset(ctx->slice_param, 0, sizeof(ctx->slice_param));
1236 ctx->num_slice_groups = 0;
1240 store_coded_buffer(struct mpeg2enc_context *ctx, VAEncPictureType picture_type)
1242 VACodedBufferSegment *coded_buffer_segment;
1243 unsigned char *coded_mem;
1244 int slice_data_length;
1246 VASurfaceStatus surface_status;
1249 va_status = vaSyncSurface(ctx->va_dpy, surface_ids[ctx->current_input_surface]);
1250 CHECK_VASTATUS(va_status,"vaSyncSurface");
1253 va_status = vaQuerySurfaceStatus(ctx->va_dpy, surface_ids[ctx->current_input_surface], &surface_status);
1254 CHECK_VASTATUS(va_status,"vaQuerySurfaceStatus");
1256 va_status = vaMapBuffer(ctx->va_dpy, ctx->codedbuf_buf_id, (void **)(&coded_buffer_segment));
1257 CHECK_VASTATUS(va_status,"vaMapBuffer");
1258 coded_mem = coded_buffer_segment->buf;
1260 if (coded_buffer_segment->status & VA_CODED_BUF_STATUS_SLICE_OVERFLOW_MASK) {
1261 if (picture_type == VAEncPictureTypeIntra)
1262 ctx->codedbuf_i_size *= 2;
1264 ctx->codedbuf_pb_size *= 2;
1266 vaUnmapBuffer(ctx->va_dpy, ctx->codedbuf_buf_id);
1270 slice_data_length = coded_buffer_segment->size;
1273 w_items = fwrite(coded_mem, slice_data_length, 1, ctx->ofp);
1274 } while (w_items != 1);
1276 if (picture_type == VAEncPictureTypeIntra) {
1277 if (ctx->codedbuf_i_size > slice_data_length * 3 / 2) {
1278 ctx->codedbuf_i_size = slice_data_length * 3 / 2;
1281 if (ctx->codedbuf_pb_size < slice_data_length) {
1282 ctx->codedbuf_pb_size = slice_data_length;
1285 if (ctx->codedbuf_pb_size > slice_data_length * 3 / 2) {
1286 ctx->codedbuf_pb_size = slice_data_length * 3 / 2;
1290 vaUnmapBuffer(ctx->va_dpy, ctx->codedbuf_buf_id);
1296 encode_picture(struct mpeg2enc_context *ctx,
1299 VAEncPictureType picture_type,
1301 int next_display_order)
1304 int ret = 0, codedbuf_size;
1306 begin_picture(ctx, coded_order, display_order, picture_type);
1309 /* upload YUV data to VA surface for next frame */
1310 if (next_display_order >= ctx->num_pictures)
1311 next_display_order = ctx->num_pictures - 1;
1313 fseek(ctx->ifp, ctx->frame_size * next_display_order, SEEK_SET);
1314 ctx->upload_thread_value = pthread_create(&ctx->upload_thread_id,
1316 upload_yuv_to_surface,
1321 mpeg2enc_destroy_buffers(ctx, &ctx->codedbuf_buf_id, 1);
1322 mpeg2enc_destroy_buffers(ctx, &ctx->pic_param_buf_id, 1);
1325 if (VAEncPictureTypeIntra == picture_type) {
1326 codedbuf_size = ctx->codedbuf_i_size;
1328 codedbuf_size = ctx->codedbuf_pb_size;
1332 va_status = vaCreateBuffer(ctx->va_dpy,
1334 VAEncCodedBufferType,
1335 codedbuf_size, 1, NULL,
1336 &ctx->codedbuf_buf_id);
1337 CHECK_VASTATUS(va_status,"vaCreateBuffer");
1339 /* picture parameter set */
1340 mpeg2enc_update_picture_parameter_buffer(ctx, picture_type, coded_order, display_order);
1342 mpeg2enc_render_picture(ctx);
1344 ret = store_coded_buffer(ctx, picture_type);
1347 end_picture(ctx, picture_type, next_is_bpic);
1351 update_next_frame_info(struct mpeg2enc_context *ctx,
1352 VAEncPictureType curr_type,
1353 int curr_coded_order,
1354 int curr_display_order)
1356 if (((curr_coded_order + 1) % ctx->intra_period) == 0) {
1357 ctx->next_type = VAEncPictureTypeIntra;
1358 ctx->next_display_order = curr_coded_order + 1;
1363 if (curr_type == VAEncPictureTypeIntra) {
1364 assert(curr_display_order == curr_coded_order);
1365 ctx->next_type = VAEncPictureTypePredictive;
1366 ctx->next_bframes = ctx->ip_period;
1367 ctx->next_display_order = curr_display_order + ctx->next_bframes + 1;
1368 } else if (curr_type == VAEncPictureTypePredictive) {
1369 if (ctx->ip_period == 0) {
1370 assert(curr_display_order == curr_coded_order);
1371 ctx->next_type = VAEncPictureTypePredictive;
1372 ctx->next_display_order = curr_display_order + 1;
1374 ctx->next_type = VAEncPictureTypeBidirectional;
1375 ctx->next_display_order = curr_display_order - ctx->next_bframes;
1376 ctx->next_bframes--;
1378 } else if (curr_type == VAEncPictureTypeBidirectional) {
1379 if (ctx->next_bframes == 0) {
1380 ctx->next_type = VAEncPictureTypePredictive;
1381 ctx->next_bframes = ctx->ip_period;
1382 ctx->next_display_order = curr_display_order + ctx->next_bframes + 2;
1384 ctx->next_type = VAEncPictureTypeBidirectional;
1385 ctx->next_display_order = curr_display_order + 1;
1386 ctx->next_bframes--;
1390 if (ctx->next_display_order >= ctx->num_pictures) {
1391 int rtmp = ctx->next_display_order - (ctx->num_pictures - 1);
1392 ctx->next_display_order = ctx->num_pictures - 1;
1393 ctx->next_bframes -= rtmp;
1397 mpeg2enc_run(struct mpeg2enc_context *ctx)
1399 int display_order = 0, coded_order = 0;
1400 VAEncPictureType type;
1402 while (coded_order < ctx->num_pictures) {
1403 type = ctx->next_type;
1404 display_order = ctx->next_display_order;
1405 /* follow the IPBxxBPBxxB mode */
1406 update_next_frame_info(ctx, type, coded_order, display_order);
1411 ctx->next_type == VAEncPictureTypeBidirectional,
1412 ctx->next_display_order);
1415 fprintf(stderr, "\r %d/%d ...", coded_order, ctx->num_pictures);
1424 mpeg2enc_release_va_resources(struct mpeg2enc_context *ctx)
1426 vaDestroySurfaces(ctx->va_dpy, surface_ids, SID_NUMBER);
1427 vaDestroyContext(ctx->va_dpy, ctx->context_id);
1428 vaDestroyConfig(ctx->va_dpy, ctx->config_id);
1429 vaTerminate(ctx->va_dpy);
1430 va_close_display(ctx->va_dpy);
1434 mpeg2enc_end(struct mpeg2enc_context *ctx)
1436 pthread_join(ctx->upload_thread_id, NULL);
1437 mpeg2enc_release_va_resources(ctx);
1441 main(int argc, char *argv[])
1443 struct mpeg2enc_context ctx;
1444 struct timeval tpstart, tpend;
1447 gettimeofday(&tpstart, NULL);
1449 memset(&ctx, 0, sizeof(ctx));
1450 parse_args(&ctx, argc, argv);
1451 mpeg2enc_init(&ctx);
1455 gettimeofday(&tpend, NULL);
1456 timeuse = 1000000 * (tpend.tv_sec - tpstart.tv_sec) + tpend.tv_usec - tpstart.tv_usec;
1458 fprintf(stderr, "\ndone!\n");
1459 fprintf(stderr, "encode %d frames in %f secondes, FPS is %.1f\n", ctx.num_pictures, timeuse, ctx.num_pictures / timeuse);
1461 mpeg2enc_exit(&ctx, 0);