2 #include "h264encode.h"
4 #include <EGL/eglplatform.h>
9 #include <libavcodec/avcodec.h>
10 #include <libavformat/avio.h>
11 #include <libavutil/mathematics.h>
12 #include <libavutil/rational.h>
13 #include <libdrm/drm_fourcc.h>
19 #include <va/va_drmcommon.h>
20 #include <va/va_enc_h264.h>
21 #include <va/va_x11.h>
22 #include <condition_variable>
33 #define CHECK_VASTATUS(va_status, func) \
34 if (va_status != VA_STATUS_SUCCESS) { \
35 fprintf(stderr, "%s:%d (%s) failed with %d\n", __func__, __LINE__, func, va_status); \
39 //#include "loadsurface.h"
41 #define NAL_REF_IDC_NONE 0
42 #define NAL_REF_IDC_LOW 1
43 #define NAL_REF_IDC_MEDIUM 2
44 #define NAL_REF_IDC_HIGH 3
52 #define SLICE_TYPE_P 0
53 #define SLICE_TYPE_B 1
54 #define SLICE_TYPE_I 2
55 #define IS_P_SLICE(type) (SLICE_TYPE_P == (type))
56 #define IS_B_SLICE(type) (SLICE_TYPE_B == (type))
57 #define IS_I_SLICE(type) (SLICE_TYPE_I == (type))
60 #define ENTROPY_MODE_CAVLC 0
61 #define ENTROPY_MODE_CABAC 1
63 #define PROFILE_IDC_BASELINE 66
64 #define PROFILE_IDC_MAIN 77
65 #define PROFILE_IDC_HIGH 100
67 #define BITSTREAM_ALLOCATE_STEPPING 4096
69 #define SURFACE_NUM 16 /* 16 surfaces for source YUV */
70 static VADisplay va_dpy;
71 static VAProfile h264_profile = (VAProfile)~0;
72 static VAConfigAttrib config_attrib[VAConfigAttribTypeMax];
73 static int config_attrib_num = 0, enc_packed_header_idx;
76 VASurfaceID src_surface, ref_surface;
79 VAImage surface_image;
80 GLuint y_tex, cbcr_tex;
81 EGLImage y_egl_image, cbcr_egl_image;
83 GLSurface gl_surfaces[SURFACE_NUM];
85 static VAConfigID config_id;
86 static VAContextID context_id;
87 static VAEncSequenceParameterBufferH264 seq_param;
88 static VAEncPictureParameterBufferH264 pic_param;
89 static VAEncSliceParameterBufferH264 slice_param;
90 static VAPictureH264 CurrentCurrPic;
91 static VAPictureH264 ReferenceFrames[16], RefPicList0_P[32], RefPicList0_B[32], RefPicList1_B[32];
93 static unsigned int MaxFrameNum = (2<<16);
94 static unsigned int MaxPicOrderCntLsb = (2<<8);
95 static unsigned int Log2MaxFrameNum = 16;
96 static unsigned int Log2MaxPicOrderCntLsb = 8;
98 static unsigned int num_ref_frames = 2;
99 static unsigned int numShortTerm = 0;
100 static int constraint_set_flag = 0;
101 static int h264_packedheader = 0; /* support pack header? */
102 static int h264_maxref = (1<<16|1);
103 static int h264_entropy_mode = 1; /* cabac */
105 static char *coded_fn = NULL;
106 static FILE *coded_fp = NULL;
108 static int frame_width = 176;
109 static int frame_height = 144;
110 static int frame_width_mbaligned;
111 static int frame_height_mbaligned;
112 static int frame_rate = 60;
113 static unsigned int frame_bitrate = 0;
114 static unsigned int frame_slices = 1;
115 static double frame_size = 0;
116 static int initial_qp = 15;
117 //static int initial_qp = 28;
118 static int minimal_qp = 0;
119 static int intra_period = 30;
120 static int intra_idr_period = 60;
121 static int ip_period = 1;
122 static int rc_mode = -1;
123 static int rc_default_modes[] = {
126 VA_RC_VBR_CONSTRAINED,
131 static unsigned long long current_frame_encoding = 0;
132 static unsigned long long current_frame_display = 0;
133 static unsigned long long current_IDR_display = 0;
134 static unsigned int current_frame_num = 0;
135 static int current_frame_type;
137 static int misc_priv_type = 0;
138 static int misc_priv_value = 0;
140 /* thread to save coded data */
141 #define SRC_SURFACE_FREE 0
142 #define SRC_SURFACE_IN_ENCODING 1
145 unsigned int *buffer;
147 int max_size_in_dword;
149 typedef struct __bitstream bitstream;
154 va_swap32(unsigned int val)
156 unsigned char *pval = (unsigned char *)&val;
158 return ((pval[0] << 24) |
165 bitstream_start(bitstream *bs)
167 bs->max_size_in_dword = BITSTREAM_ALLOCATE_STEPPING;
168 bs->buffer = (unsigned int *)calloc(bs->max_size_in_dword * sizeof(int), 1);
173 bitstream_end(bitstream *bs)
175 int pos = (bs->bit_offset >> 5);
176 int bit_offset = (bs->bit_offset & 0x1f);
177 int bit_left = 32 - bit_offset;
180 bs->buffer[pos] = va_swap32((bs->buffer[pos] << bit_left));
185 bitstream_put_ui(bitstream *bs, unsigned int val, int size_in_bits)
187 int pos = (bs->bit_offset >> 5);
188 int bit_offset = (bs->bit_offset & 0x1f);
189 int bit_left = 32 - bit_offset;
194 bs->bit_offset += size_in_bits;
196 if (bit_left > size_in_bits) {
197 bs->buffer[pos] = (bs->buffer[pos] << size_in_bits | val);
199 size_in_bits -= bit_left;
200 bs->buffer[pos] = (bs->buffer[pos] << bit_left) | (val >> size_in_bits);
201 bs->buffer[pos] = va_swap32(bs->buffer[pos]);
203 if (pos + 1 == bs->max_size_in_dword) {
204 bs->max_size_in_dword += BITSTREAM_ALLOCATE_STEPPING;
205 bs->buffer = (unsigned int *)realloc(bs->buffer, bs->max_size_in_dword * sizeof(unsigned int));
208 bs->buffer[pos + 1] = val;
213 bitstream_put_ue(bitstream *bs, unsigned int val)
215 int size_in_bits = 0;
223 bitstream_put_ui(bs, 0, size_in_bits - 1); // leading zero
224 bitstream_put_ui(bs, val, size_in_bits);
228 bitstream_put_se(bitstream *bs, int val)
230 unsigned int new_val;
235 new_val = 2 * val - 1;
237 bitstream_put_ue(bs, new_val);
241 bitstream_byte_aligning(bitstream *bs, int bit)
243 int bit_offset = (bs->bit_offset & 0x7);
244 int bit_left = 8 - bit_offset;
250 assert(bit == 0 || bit == 1);
253 new_val = (1 << bit_left) - 1;
257 bitstream_put_ui(bs, new_val, bit_left);
261 rbsp_trailing_bits(bitstream *bs)
263 bitstream_put_ui(bs, 1, 1);
264 bitstream_byte_aligning(bs, 0);
267 static void nal_start_code_prefix(bitstream *bs)
269 bitstream_put_ui(bs, 0x00000001, 32);
272 static void nal_header(bitstream *bs, int nal_ref_idc, int nal_unit_type)
274 bitstream_put_ui(bs, 0, 1); /* forbidden_zero_bit: 0 */
275 bitstream_put_ui(bs, nal_ref_idc, 2);
276 bitstream_put_ui(bs, nal_unit_type, 5);
279 static void sps_rbsp(bitstream *bs)
281 int profile_idc = PROFILE_IDC_BASELINE;
283 if (h264_profile == VAProfileH264High)
284 profile_idc = PROFILE_IDC_HIGH;
285 else if (h264_profile == VAProfileH264Main)
286 profile_idc = PROFILE_IDC_MAIN;
288 bitstream_put_ui(bs, profile_idc, 8); /* profile_idc */
289 bitstream_put_ui(bs, !!(constraint_set_flag & 1), 1); /* constraint_set0_flag */
290 bitstream_put_ui(bs, !!(constraint_set_flag & 2), 1); /* constraint_set1_flag */
291 bitstream_put_ui(bs, !!(constraint_set_flag & 4), 1); /* constraint_set2_flag */
292 bitstream_put_ui(bs, !!(constraint_set_flag & 8), 1); /* constraint_set3_flag */
293 bitstream_put_ui(bs, 0, 4); /* reserved_zero_4bits */
294 bitstream_put_ui(bs, seq_param.level_idc, 8); /* level_idc */
295 bitstream_put_ue(bs, seq_param.seq_parameter_set_id); /* seq_parameter_set_id */
297 if ( profile_idc == PROFILE_IDC_HIGH) {
298 bitstream_put_ue(bs, 1); /* chroma_format_idc = 1, 4:2:0 */
299 bitstream_put_ue(bs, 0); /* bit_depth_luma_minus8 */
300 bitstream_put_ue(bs, 0); /* bit_depth_chroma_minus8 */
301 bitstream_put_ui(bs, 0, 1); /* qpprime_y_zero_transform_bypass_flag */
302 bitstream_put_ui(bs, 0, 1); /* seq_scaling_matrix_present_flag */
305 bitstream_put_ue(bs, seq_param.seq_fields.bits.log2_max_frame_num_minus4); /* log2_max_frame_num_minus4 */
306 bitstream_put_ue(bs, seq_param.seq_fields.bits.pic_order_cnt_type); /* pic_order_cnt_type */
308 if (seq_param.seq_fields.bits.pic_order_cnt_type == 0)
309 bitstream_put_ue(bs, seq_param.seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4); /* log2_max_pic_order_cnt_lsb_minus4 */
314 bitstream_put_ue(bs, seq_param.max_num_ref_frames); /* num_ref_frames */
315 bitstream_put_ui(bs, 0, 1); /* gaps_in_frame_num_value_allowed_flag */
317 bitstream_put_ue(bs, seq_param.picture_width_in_mbs - 1); /* pic_width_in_mbs_minus1 */
318 bitstream_put_ue(bs, seq_param.picture_height_in_mbs - 1); /* pic_height_in_map_units_minus1 */
319 bitstream_put_ui(bs, seq_param.seq_fields.bits.frame_mbs_only_flag, 1); /* frame_mbs_only_flag */
321 if (!seq_param.seq_fields.bits.frame_mbs_only_flag) {
325 bitstream_put_ui(bs, seq_param.seq_fields.bits.direct_8x8_inference_flag, 1); /* direct_8x8_inference_flag */
326 bitstream_put_ui(bs, seq_param.frame_cropping_flag, 1); /* frame_cropping_flag */
328 if (seq_param.frame_cropping_flag) {
329 bitstream_put_ue(bs, seq_param.frame_crop_left_offset); /* frame_crop_left_offset */
330 bitstream_put_ue(bs, seq_param.frame_crop_right_offset); /* frame_crop_right_offset */
331 bitstream_put_ue(bs, seq_param.frame_crop_top_offset); /* frame_crop_top_offset */
332 bitstream_put_ue(bs, seq_param.frame_crop_bottom_offset); /* frame_crop_bottom_offset */
335 //if ( frame_bit_rate < 0 ) { //TODO EW: the vui header isn't correct
337 bitstream_put_ui(bs, 0, 1); /* vui_parameters_present_flag */
339 bitstream_put_ui(bs, 1, 1); /* vui_parameters_present_flag */
340 bitstream_put_ui(bs, 0, 1); /* aspect_ratio_info_present_flag */
341 bitstream_put_ui(bs, 0, 1); /* overscan_info_present_flag */
342 bitstream_put_ui(bs, 0, 1); /* video_signal_type_present_flag */
343 bitstream_put_ui(bs, 0, 1); /* chroma_loc_info_present_flag */
344 bitstream_put_ui(bs, 1, 1); /* timing_info_present_flag */
346 bitstream_put_ui(bs, 1, 32); // FPS
347 bitstream_put_ui(bs, frame_rate * 2, 32); // FPS
348 bitstream_put_ui(bs, 1, 1);
350 bitstream_put_ui(bs, 1, 1); /* nal_hrd_parameters_present_flag */
353 bitstream_put_ue(bs, 0); /* cpb_cnt_minus1 */
354 bitstream_put_ui(bs, 4, 4); /* bit_rate_scale */
355 bitstream_put_ui(bs, 6, 4); /* cpb_size_scale */
357 bitstream_put_ue(bs, frame_bitrate - 1); /* bit_rate_value_minus1[0] */
358 bitstream_put_ue(bs, frame_bitrate*8 - 1); /* cpb_size_value_minus1[0] */
359 bitstream_put_ui(bs, 1, 1); /* cbr_flag[0] */
361 bitstream_put_ui(bs, 23, 5); /* initial_cpb_removal_delay_length_minus1 */
362 bitstream_put_ui(bs, 23, 5); /* cpb_removal_delay_length_minus1 */
363 bitstream_put_ui(bs, 23, 5); /* dpb_output_delay_length_minus1 */
364 bitstream_put_ui(bs, 23, 5); /* time_offset_length */
366 bitstream_put_ui(bs, 0, 1); /* vcl_hrd_parameters_present_flag */
367 bitstream_put_ui(bs, 0, 1); /* low_delay_hrd_flag */
369 bitstream_put_ui(bs, 0, 1); /* pic_struct_present_flag */
370 bitstream_put_ui(bs, 0, 1); /* bitstream_restriction_flag */
373 rbsp_trailing_bits(bs); /* rbsp_trailing_bits */
377 static void pps_rbsp(bitstream *bs)
379 bitstream_put_ue(bs, pic_param.pic_parameter_set_id); /* pic_parameter_set_id */
380 bitstream_put_ue(bs, pic_param.seq_parameter_set_id); /* seq_parameter_set_id */
382 bitstream_put_ui(bs, pic_param.pic_fields.bits.entropy_coding_mode_flag, 1); /* entropy_coding_mode_flag */
384 bitstream_put_ui(bs, 0, 1); /* pic_order_present_flag: 0 */
386 bitstream_put_ue(bs, 0); /* num_slice_groups_minus1 */
388 bitstream_put_ue(bs, pic_param.num_ref_idx_l0_active_minus1); /* num_ref_idx_l0_active_minus1 */
389 bitstream_put_ue(bs, pic_param.num_ref_idx_l1_active_minus1); /* num_ref_idx_l1_active_minus1 1 */
391 bitstream_put_ui(bs, pic_param.pic_fields.bits.weighted_pred_flag, 1); /* weighted_pred_flag: 0 */
392 bitstream_put_ui(bs, pic_param.pic_fields.bits.weighted_bipred_idc, 2); /* weighted_bipred_idc: 0 */
394 bitstream_put_se(bs, pic_param.pic_init_qp - 26); /* pic_init_qp_minus26 */
395 bitstream_put_se(bs, 0); /* pic_init_qs_minus26 */
396 bitstream_put_se(bs, 0); /* chroma_qp_index_offset */
398 bitstream_put_ui(bs, pic_param.pic_fields.bits.deblocking_filter_control_present_flag, 1); /* deblocking_filter_control_present_flag */
399 bitstream_put_ui(bs, 0, 1); /* constrained_intra_pred_flag */
400 bitstream_put_ui(bs, 0, 1); /* redundant_pic_cnt_present_flag */
403 bitstream_put_ui(bs, pic_param.pic_fields.bits.transform_8x8_mode_flag, 1); /*transform_8x8_mode_flag */
404 bitstream_put_ui(bs, 0, 1); /* pic_scaling_matrix_present_flag */
405 bitstream_put_se(bs, pic_param.second_chroma_qp_index_offset ); /*second_chroma_qp_index_offset */
407 rbsp_trailing_bits(bs);
410 static void slice_header(bitstream *bs)
412 int first_mb_in_slice = slice_param.macroblock_address;
414 bitstream_put_ue(bs, first_mb_in_slice); /* first_mb_in_slice: 0 */
415 bitstream_put_ue(bs, slice_param.slice_type); /* slice_type */
416 bitstream_put_ue(bs, slice_param.pic_parameter_set_id); /* pic_parameter_set_id: 0 */
417 bitstream_put_ui(bs, pic_param.frame_num, seq_param.seq_fields.bits.log2_max_frame_num_minus4 + 4); /* frame_num */
419 /* frame_mbs_only_flag == 1 */
420 if (!seq_param.seq_fields.bits.frame_mbs_only_flag) {
425 if (pic_param.pic_fields.bits.idr_pic_flag)
426 bitstream_put_ue(bs, slice_param.idr_pic_id); /* idr_pic_id: 0 */
428 if (seq_param.seq_fields.bits.pic_order_cnt_type == 0) {
429 bitstream_put_ui(bs, pic_param.CurrPic.TopFieldOrderCnt, seq_param.seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4 + 4);
430 /* pic_order_present_flag == 0 */
436 /* redundant_pic_cnt_present_flag == 0 */
438 if (IS_P_SLICE(slice_param.slice_type)) {
439 bitstream_put_ui(bs, slice_param.num_ref_idx_active_override_flag, 1); /* num_ref_idx_active_override_flag: */
441 if (slice_param.num_ref_idx_active_override_flag)
442 bitstream_put_ue(bs, slice_param.num_ref_idx_l0_active_minus1);
444 /* ref_pic_list_reordering */
445 bitstream_put_ui(bs, 0, 1); /* ref_pic_list_reordering_flag_l0: 0 */
446 } else if (IS_B_SLICE(slice_param.slice_type)) {
447 bitstream_put_ui(bs, slice_param.direct_spatial_mv_pred_flag, 1); /* direct_spatial_mv_pred: 1 */
449 bitstream_put_ui(bs, slice_param.num_ref_idx_active_override_flag, 1); /* num_ref_idx_active_override_flag: */
451 if (slice_param.num_ref_idx_active_override_flag) {
452 bitstream_put_ue(bs, slice_param.num_ref_idx_l0_active_minus1);
453 bitstream_put_ue(bs, slice_param.num_ref_idx_l1_active_minus1);
456 /* ref_pic_list_reordering */
457 bitstream_put_ui(bs, 0, 1); /* ref_pic_list_reordering_flag_l0: 0 */
458 bitstream_put_ui(bs, 0, 1); /* ref_pic_list_reordering_flag_l1: 0 */
461 if ((pic_param.pic_fields.bits.weighted_pred_flag &&
462 IS_P_SLICE(slice_param.slice_type)) ||
463 ((pic_param.pic_fields.bits.weighted_bipred_idc == 1) &&
464 IS_B_SLICE(slice_param.slice_type))) {
465 /* FIXME: fill weight/offset table */
469 /* dec_ref_pic_marking */
470 if (pic_param.pic_fields.bits.reference_pic_flag) { /* nal_ref_idc != 0 */
471 unsigned char no_output_of_prior_pics_flag = 0;
472 unsigned char long_term_reference_flag = 0;
473 unsigned char adaptive_ref_pic_marking_mode_flag = 0;
475 if (pic_param.pic_fields.bits.idr_pic_flag) {
476 bitstream_put_ui(bs, no_output_of_prior_pics_flag, 1); /* no_output_of_prior_pics_flag: 0 */
477 bitstream_put_ui(bs, long_term_reference_flag, 1); /* long_term_reference_flag: 0 */
479 bitstream_put_ui(bs, adaptive_ref_pic_marking_mode_flag, 1); /* adaptive_ref_pic_marking_mode_flag: 0 */
483 if (pic_param.pic_fields.bits.entropy_coding_mode_flag &&
484 !IS_I_SLICE(slice_param.slice_type))
485 bitstream_put_ue(bs, slice_param.cabac_init_idc); /* cabac_init_idc: 0 */
487 bitstream_put_se(bs, slice_param.slice_qp_delta); /* slice_qp_delta: 0 */
489 /* ignore for SP/SI */
491 if (pic_param.pic_fields.bits.deblocking_filter_control_present_flag) {
492 bitstream_put_ue(bs, slice_param.disable_deblocking_filter_idc); /* disable_deblocking_filter_idc: 0 */
494 if (slice_param.disable_deblocking_filter_idc != 1) {
495 bitstream_put_se(bs, slice_param.slice_alpha_c0_offset_div2); /* slice_alpha_c0_offset_div2: 2 */
496 bitstream_put_se(bs, slice_param.slice_beta_offset_div2); /* slice_beta_offset_div2: 2 */
500 if (pic_param.pic_fields.bits.entropy_coding_mode_flag) {
501 bitstream_byte_aligning(bs, 1);
506 build_packed_pic_buffer(unsigned char **header_buffer)
510 bitstream_start(&bs);
511 nal_start_code_prefix(&bs);
512 nal_header(&bs, NAL_REF_IDC_HIGH, NAL_PPS);
516 *header_buffer = (unsigned char *)bs.buffer;
517 return bs.bit_offset;
521 build_packed_seq_buffer(unsigned char **header_buffer)
525 bitstream_start(&bs);
526 nal_start_code_prefix(&bs);
527 nal_header(&bs, NAL_REF_IDC_HIGH, NAL_SPS);
531 *header_buffer = (unsigned char *)bs.buffer;
532 return bs.bit_offset;
535 static int build_packed_slice_buffer(unsigned char **header_buffer)
538 int is_idr = !!pic_param.pic_fields.bits.idr_pic_flag;
539 int is_ref = !!pic_param.pic_fields.bits.reference_pic_flag;
541 bitstream_start(&bs);
542 nal_start_code_prefix(&bs);
544 if (IS_I_SLICE(slice_param.slice_type)) {
545 nal_header(&bs, NAL_REF_IDC_HIGH, is_idr ? NAL_IDR : NAL_NON_IDR);
546 } else if (IS_P_SLICE(slice_param.slice_type)) {
547 nal_header(&bs, NAL_REF_IDC_MEDIUM, NAL_NON_IDR);
549 assert(IS_B_SLICE(slice_param.slice_type));
550 nal_header(&bs, is_ref ? NAL_REF_IDC_LOW : NAL_REF_IDC_NONE, NAL_NON_IDR);
556 *header_buffer = (unsigned char *)bs.buffer;
557 return bs.bit_offset;
562 Assume frame sequence is: Frame#0, #1, #2, ..., #M, ..., #X, ... (encoding order)
563 1) period between Frame #X and Frame #N = #X - #N
564 2) 0 means infinite for intra_period/intra_idr_period, and 0 is invalid for ip_period
565 3) intra_idr_period % intra_period (intra_period > 0) and intra_period % ip_period must be 0
566 4) intra_period and intra_idr_period take precedence over ip_period
567 5) if ip_period > 1, intra_period and intra_idr_period are not the strict periods
568 of I/IDR frames, see bellow examples
569 -------------------------------------------------------------------
570 intra_period intra_idr_period ip_period frame sequence (intra_period/intra_idr_period/ip_period)
571 0 ignored 1 IDRPPPPPPP ... (No IDR/I any more)
572 0 ignored >=2 IDR(PBB)(PBB)... (No IDR/I any more)
573 1 0 ignored IDRIIIIIII... (No IDR any more)
574 1 1 ignored IDR IDR IDR IDR...
575 1 >=2 ignored IDRII IDRII IDR... (1/3/ignore)
576 >=2 0 1 IDRPPP IPPP I... (3/0/1)
577 >=2 0 >=2 IDR(PBB)(PBB)(IBB) (6/0/3)
578 (PBB)(IBB)(PBB)(IBB)...
579 >=2 >=2 1 IDRPPPPP IPPPPP IPPPPP (6/18/1)
580 IDRPPPPP IPPPPP IPPPPP...
581 >=2 >=2 >=2 {IDR(PBB)(PBB)(IBB)(PBB)(IBB)(PBB)} (6/18/3)
582 {IDR(PBB)(PBB)(IBB)(PBB)(IBB)(PBB)}...
583 {IDR(PBB)(PBB)(IBB)(PBB)} (6/12/3)
584 {IDR(PBB)(PBB)(IBB)(PBB)}...
585 {IDR(PBB)(PBB)} (6/6/3)
590 * Return displaying order with specified periods and encoding order
591 * displaying_order: displaying order
592 * frame_type: frame type
598 void encoding2display_order(
599 unsigned long long encoding_order, int intra_period,
600 int intra_idr_period, int ip_period,
601 unsigned long long *displaying_order,
604 int encoding_order_gop = 0;
606 if (intra_period == 1) { /* all are I/IDR frames */
607 *displaying_order = encoding_order;
608 if (intra_idr_period == 0)
609 *frame_type = (encoding_order == 0)?FRAME_IDR:FRAME_I;
611 *frame_type = (encoding_order % intra_idr_period == 0)?FRAME_IDR:FRAME_I;
615 if (intra_period == 0)
616 intra_idr_period = 0;
620 * IDR (PBB)(PBB)(IBB)(PBB)
622 encoding_order_gop = (intra_idr_period == 0)? encoding_order:
623 (encoding_order % (intra_idr_period + ((ip_period == 1)?0:1)));
625 if (encoding_order_gop == 0) { /* the first frame */
626 *frame_type = FRAME_IDR;
627 *displaying_order = encoding_order;
628 } else if (((encoding_order_gop - 1) % ip_period) != 0) { /* B frames */
629 *frame_type = FRAME_B;
630 *displaying_order = encoding_order - 1;
631 } else if ((intra_period != 0) && /* have I frames */
632 (encoding_order_gop >= 2) &&
633 ((ip_period == 1 && encoding_order_gop % intra_period == 0) || /* for IDR PPPPP IPPPP */
634 /* for IDR (PBB)(PBB)(IBB) */
635 (ip_period >= 2 && ((encoding_order_gop - 1) / ip_period % (intra_period / ip_period)) == 0))) {
636 *frame_type = FRAME_I;
637 *displaying_order = encoding_order + ip_period - 1;
639 *frame_type = FRAME_P;
640 *displaying_order = encoding_order + ip_period - 1;
645 static const char *rc_to_string(int rcmode)
658 case VA_RC_VBR_CONSTRAINED:
659 return "VBR_CONSTRAINED";
666 static int process_cmdline(int argc, char *argv[])
669 const struct option long_opts[] = {
670 {"help", no_argument, NULL, 0 },
671 {"bitrate", required_argument, NULL, 1 },
672 {"minqp", required_argument, NULL, 2 },
673 {"initialqp", required_argument, NULL, 3 },
674 {"intra_period", required_argument, NULL, 4 },
675 {"idr_period", required_argument, NULL, 5 },
676 {"ip_period", required_argument, NULL, 6 },
677 {"rcmode", required_argument, NULL, 7 },
678 {"srcyuv", required_argument, NULL, 9 },
679 {"recyuv", required_argument, NULL, 10 },
680 {"fourcc", required_argument, NULL, 11 },
681 {"syncmode", no_argument, NULL, 12 },
682 {"enablePSNR", no_argument, NULL, 13 },
683 {"prit", required_argument, NULL, 14 },
684 {"priv", required_argument, NULL, 15 },
685 {"framecount", required_argument, NULL, 16 },
686 {"entropy", required_argument, NULL, 17 },
687 {"profile", required_argument, NULL, 18 },
688 {NULL, no_argument, NULL, 0 }};
691 while ((c =getopt_long_only(argc, argv, "w:h:n:f:o:?", long_opts, &long_index)) != EOF) {
694 frame_width = atoi(optarg);
697 frame_height = atoi(optarg);
701 frame_rate = atoi(optarg);
704 coded_fn = strdup(optarg);
710 frame_bitrate = atoi(optarg);
713 minimal_qp = atoi(optarg);
716 initial_qp = atoi(optarg);
719 intra_period = atoi(optarg);
722 intra_idr_period = atoi(optarg);
725 ip_period = atoi(optarg);
728 rc_mode = string_to_rc(optarg);
735 srcyuv_fn = strdup(optarg);
738 srcyuv_fourcc = string_to_fourcc(optarg);
739 if (srcyuv_fourcc <= 0) {
748 misc_priv_type = strtol(optarg, NULL, 0);
751 misc_priv_value = strtol(optarg, NULL, 0);
754 h264_entropy_mode = atoi(optarg) ? 1: 0;
757 if (strncmp(optarg, "BP", 2) == 0)
758 h264_profile = VAProfileH264Baseline;
759 else if (strncmp(optarg, "MP", 2) == 0)
760 h264_profile = VAProfileH264Main;
761 else if (strncmp(optarg, "HP", 2) == 0)
762 h264_profile = VAProfileH264High;
764 h264_profile = (VAProfile)0;
774 printf(" ip_period must be greater than 0\n");
777 if (intra_period != 1 && intra_period % ip_period != 0) {
778 printf(" intra_period must be a multiplier of ip_period\n");
781 if (intra_period != 0 && intra_idr_period % intra_period != 0) {
782 printf(" intra_idr_period must be a multiplier of intra_period\n");
786 if (frame_bitrate == 0)
787 frame_bitrate = frame_width * frame_height * 12 * frame_rate / 50;
789 if (coded_fn == NULL) {
791 if (stat("/tmp", &buf) == 0)
792 coded_fn = strdup("/tmp/test.264");
793 else if (stat("/sdcard", &buf) == 0)
794 coded_fn = strdup("/sdcard/test.264");
796 coded_fn = strdup("./test.264");
799 /* store coded data into a file */
800 coded_fp = fopen(coded_fn, "w+");
801 if (coded_fp == NULL) {
802 printf("Open file %s failed, exit\n", coded_fn);
806 frame_width_mbaligned = (frame_width + 15) & (~15);
807 frame_height_mbaligned = (frame_height + 15) & (~15);
808 if (frame_width != frame_width_mbaligned ||
809 frame_height != frame_height_mbaligned) {
810 printf("Source frame is %dx%d and will code clip to %dx%d with crop\n",
811 frame_width, frame_height,
812 frame_width_mbaligned, frame_height_mbaligned
820 static Display *x11_display;
821 static Window x11_window;
824 va_open_display(void)
826 x11_display = XOpenDisplay(NULL);
828 fprintf(stderr, "error: can't connect to X server!\n");
831 return vaGetDisplay(x11_display);
835 va_close_display(VADisplay va_dpy)
841 XUnmapWindow(x11_display, x11_window);
842 XDestroyWindow(x11_display, x11_window);
845 XCloseDisplay(x11_display);
849 static int init_va(void)
851 VAProfile profile_list[]={VAProfileH264High, VAProfileH264Main, VAProfileH264Baseline, VAProfileH264ConstrainedBaseline};
852 VAEntrypoint *entrypoints;
853 int num_entrypoints, slice_entrypoint;
854 int support_encode = 0;
855 int major_ver, minor_ver;
859 va_dpy = va_open_display();
860 va_status = vaInitialize(va_dpy, &major_ver, &minor_ver);
861 CHECK_VASTATUS(va_status, "vaInitialize");
863 num_entrypoints = vaMaxNumEntrypoints(va_dpy);
864 entrypoints = (VAEntrypoint *)malloc(num_entrypoints * sizeof(*entrypoints));
866 fprintf(stderr, "error: failed to initialize VA entrypoints array\n");
870 /* use the highest profile */
871 for (i = 0; i < sizeof(profile_list)/sizeof(profile_list[0]); i++) {
872 if ((h264_profile != ~0) && h264_profile != profile_list[i])
875 h264_profile = profile_list[i];
876 vaQueryConfigEntrypoints(va_dpy, h264_profile, entrypoints, &num_entrypoints);
877 for (slice_entrypoint = 0; slice_entrypoint < num_entrypoints; slice_entrypoint++) {
878 if (entrypoints[slice_entrypoint] == VAEntrypointEncSlice) {
883 if (support_encode == 1)
887 if (support_encode == 0) {
888 printf("Can't find VAEntrypointEncSlice for H264 profiles\n");
891 switch (h264_profile) {
892 case VAProfileH264Baseline:
893 printf("Use profile VAProfileH264Baseline\n");
895 constraint_set_flag |= (1 << 0); /* Annex A.2.1 */
896 h264_entropy_mode = 0;
898 case VAProfileH264ConstrainedBaseline:
899 printf("Use profile VAProfileH264ConstrainedBaseline\n");
900 constraint_set_flag |= (1 << 0 | 1 << 1); /* Annex A.2.2 */
904 case VAProfileH264Main:
905 printf("Use profile VAProfileH264Main\n");
906 constraint_set_flag |= (1 << 1); /* Annex A.2.2 */
909 case VAProfileH264High:
910 constraint_set_flag |= (1 << 3); /* Annex A.2.4 */
911 printf("Use profile VAProfileH264High\n");
914 printf("unknow profile. Set to Baseline");
915 h264_profile = VAProfileH264Baseline;
917 constraint_set_flag |= (1 << 0); /* Annex A.2.1 */
922 VAConfigAttrib attrib[VAConfigAttribTypeMax];
924 /* find out the format for the render target, and rate control mode */
925 for (i = 0; i < VAConfigAttribTypeMax; i++)
926 attrib[i].type = (VAConfigAttribType)i;
928 va_status = vaGetConfigAttributes(va_dpy, h264_profile, VAEntrypointEncSlice,
929 &attrib[0], VAConfigAttribTypeMax);
930 CHECK_VASTATUS(va_status, "vaGetConfigAttributes");
931 /* check the interested configattrib */
932 if ((attrib[VAConfigAttribRTFormat].value & VA_RT_FORMAT_YUV420) == 0) {
933 printf("Not find desired YUV420 RT format\n");
936 config_attrib[config_attrib_num].type = VAConfigAttribRTFormat;
937 config_attrib[config_attrib_num].value = VA_RT_FORMAT_YUV420;
941 if (attrib[VAConfigAttribRateControl].value != VA_ATTRIB_NOT_SUPPORTED) {
942 int tmp = attrib[VAConfigAttribRateControl].value;
944 printf("Support rate control mode (0x%x):", tmp);
946 if (tmp & VA_RC_NONE)
956 if (tmp & VA_RC_VBR_CONSTRAINED)
957 printf("VBR_CONSTRAINED ");
961 if (rc_mode == -1 || !(rc_mode & tmp)) {
963 printf("Warning: Don't support the specified RateControl mode: %s!!!, switch to ", rc_to_string(rc_mode));
966 for (i = 0; i < sizeof(rc_default_modes) / sizeof(rc_default_modes[0]); i++) {
967 if (rc_default_modes[i] & tmp) {
968 rc_mode = rc_default_modes[i];
973 printf("RateControl mode: %s\n", rc_to_string(rc_mode));
976 config_attrib[config_attrib_num].type = VAConfigAttribRateControl;
977 config_attrib[config_attrib_num].value = rc_mode;
982 if (attrib[VAConfigAttribEncPackedHeaders].value != VA_ATTRIB_NOT_SUPPORTED) {
983 int tmp = attrib[VAConfigAttribEncPackedHeaders].value;
985 printf("Support VAConfigAttribEncPackedHeaders\n");
987 h264_packedheader = 1;
988 config_attrib[config_attrib_num].type = VAConfigAttribEncPackedHeaders;
989 config_attrib[config_attrib_num].value = VA_ENC_PACKED_HEADER_NONE;
991 if (tmp & VA_ENC_PACKED_HEADER_SEQUENCE) {
992 printf("Support packed sequence headers\n");
993 config_attrib[config_attrib_num].value |= VA_ENC_PACKED_HEADER_SEQUENCE;
996 if (tmp & VA_ENC_PACKED_HEADER_PICTURE) {
997 printf("Support packed picture headers\n");
998 config_attrib[config_attrib_num].value |= VA_ENC_PACKED_HEADER_PICTURE;
1001 if (tmp & VA_ENC_PACKED_HEADER_SLICE) {
1002 printf("Support packed slice headers\n");
1003 config_attrib[config_attrib_num].value |= VA_ENC_PACKED_HEADER_SLICE;
1006 if (tmp & VA_ENC_PACKED_HEADER_MISC) {
1007 printf("Support packed misc headers\n");
1008 config_attrib[config_attrib_num].value |= VA_ENC_PACKED_HEADER_MISC;
1011 enc_packed_header_idx = config_attrib_num;
1012 config_attrib_num++;
1015 if (attrib[VAConfigAttribEncInterlaced].value != VA_ATTRIB_NOT_SUPPORTED) {
1016 int tmp = attrib[VAConfigAttribEncInterlaced].value;
1018 printf("Support VAConfigAttribEncInterlaced\n");
1020 if (tmp & VA_ENC_INTERLACED_FRAME)
1021 printf("support VA_ENC_INTERLACED_FRAME\n");
1022 if (tmp & VA_ENC_INTERLACED_FIELD)
1023 printf("Support VA_ENC_INTERLACED_FIELD\n");
1024 if (tmp & VA_ENC_INTERLACED_MBAFF)
1025 printf("Support VA_ENC_INTERLACED_MBAFF\n");
1026 if (tmp & VA_ENC_INTERLACED_PAFF)
1027 printf("Support VA_ENC_INTERLACED_PAFF\n");
1029 config_attrib[config_attrib_num].type = VAConfigAttribEncInterlaced;
1030 config_attrib[config_attrib_num].value = VA_ENC_PACKED_HEADER_NONE;
1031 config_attrib_num++;
1034 if (attrib[VAConfigAttribEncMaxRefFrames].value != VA_ATTRIB_NOT_SUPPORTED) {
1035 h264_maxref = attrib[VAConfigAttribEncMaxRefFrames].value;
1037 printf("Support %d RefPicList0 and %d RefPicList1\n",
1038 h264_maxref & 0xffff, (h264_maxref >> 16) & 0xffff );
1041 if (attrib[VAConfigAttribEncMaxSlices].value != VA_ATTRIB_NOT_SUPPORTED)
1042 printf("Support %d slices\n", attrib[VAConfigAttribEncMaxSlices].value);
1044 if (attrib[VAConfigAttribEncSliceStructure].value != VA_ATTRIB_NOT_SUPPORTED) {
1045 int tmp = attrib[VAConfigAttribEncSliceStructure].value;
1047 printf("Support VAConfigAttribEncSliceStructure\n");
1049 if (tmp & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS)
1050 printf("Support VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS\n");
1051 if (tmp & VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS)
1052 printf("Support VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS\n");
1053 if (tmp & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS)
1054 printf("Support VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS\n");
1056 if (attrib[VAConfigAttribEncMacroblockInfo].value != VA_ATTRIB_NOT_SUPPORTED) {
1057 printf("Support VAConfigAttribEncMacroblockInfo\n");
1064 static int setup_encode()
1067 VASurfaceID *tmp_surfaceid;
1068 int codedbuf_size, i;
1069 static VASurfaceID src_surface[SURFACE_NUM];
1070 static VASurfaceID ref_surface[SURFACE_NUM];
1072 va_status = vaCreateConfig(va_dpy, h264_profile, VAEntrypointEncSlice,
1073 &config_attrib[0], config_attrib_num, &config_id);
1074 CHECK_VASTATUS(va_status, "vaCreateConfig");
1076 /* create source surfaces */
1077 va_status = vaCreateSurfaces(va_dpy,
1078 VA_RT_FORMAT_YUV420, frame_width_mbaligned, frame_height_mbaligned,
1079 &src_surface[0], SURFACE_NUM,
1081 CHECK_VASTATUS(va_status, "vaCreateSurfaces");
1083 /* create reference surfaces */
1084 va_status = vaCreateSurfaces(va_dpy,
1085 VA_RT_FORMAT_YUV420, frame_width_mbaligned, frame_height_mbaligned,
1086 &ref_surface[0], SURFACE_NUM,
1088 CHECK_VASTATUS(va_status, "vaCreateSurfaces");
1090 tmp_surfaceid = (VASurfaceID *)calloc(2 * SURFACE_NUM, sizeof(VASurfaceID));
1091 memcpy(tmp_surfaceid, src_surface, SURFACE_NUM * sizeof(VASurfaceID));
1092 memcpy(tmp_surfaceid + SURFACE_NUM, ref_surface, SURFACE_NUM * sizeof(VASurfaceID));
1094 /* Create a context for this encode pipe */
1095 va_status = vaCreateContext(va_dpy, config_id,
1096 frame_width_mbaligned, frame_height_mbaligned,
1098 tmp_surfaceid, 2 * SURFACE_NUM,
1100 CHECK_VASTATUS(va_status, "vaCreateContext");
1101 free(tmp_surfaceid);
1103 codedbuf_size = (frame_width_mbaligned * frame_height_mbaligned * 400) / (16*16);
1105 for (i = 0; i < SURFACE_NUM; i++) {
1106 /* create coded buffer once for all
1107 * other VA buffers which won't be used again after vaRenderPicture.
1108 * so APP can always vaCreateBuffer for every frame
1109 * but coded buffer need to be mapped and accessed after vaRenderPicture/vaEndPicture
1110 * so VA won't maintain the coded buffer
1112 va_status = vaCreateBuffer(va_dpy, context_id, VAEncCodedBufferType,
1113 codedbuf_size, 1, NULL, &gl_surfaces[i].coded_buf);
1114 CHECK_VASTATUS(va_status, "vaCreateBuffer");
1117 /* create OpenGL objects */
1118 //glGenFramebuffers(SURFACE_NUM, fbos);
1120 for (i = 0; i < SURFACE_NUM; i++) {
1121 glGenTextures(1, &gl_surfaces[i].y_tex);
1122 glGenTextures(1, &gl_surfaces[i].cbcr_tex);
1125 for (i = 0; i < SURFACE_NUM; i++) {
1126 gl_surfaces[i].src_surface = src_surface[i];
1127 gl_surfaces[i].ref_surface = ref_surface[i];
1135 #define partition(ref, field, key, ascending) \
1138 while (ref[i].field < key) \
1140 while (ref[j].field > key) \
1143 while (ref[i].field > key) \
1145 while (ref[j].field < key) \
1157 static void sort_one(VAPictureH264 ref[], int left, int right,
1158 int ascending, int frame_idx)
1160 int i = left, j = right;
1165 key = ref[(left + right) / 2].frame_idx;
1166 partition(ref, frame_idx, key, ascending);
1168 key = ref[(left + right) / 2].TopFieldOrderCnt;
1169 partition(ref, TopFieldOrderCnt, (signed int)key, ascending);
1174 sort_one(ref, left, j, ascending, frame_idx);
1177 sort_one(ref, i, right, ascending, frame_idx);
1180 static void sort_two(VAPictureH264 ref[], int left, int right, unsigned int key, unsigned int frame_idx,
1181 int partition_ascending, int list0_ascending, int list1_ascending)
1183 int i = left, j = right;
1187 partition(ref, frame_idx, key, partition_ascending);
1189 partition(ref, TopFieldOrderCnt, (signed int)key, partition_ascending);
1193 sort_one(ref, left, i-1, list0_ascending, frame_idx);
1194 sort_one(ref, j+1, right, list1_ascending, frame_idx);
1197 static int update_ReferenceFrames(void)
1201 if (current_frame_type == FRAME_B)
1204 CurrentCurrPic.flags = VA_PICTURE_H264_SHORT_TERM_REFERENCE;
1206 if (numShortTerm > num_ref_frames)
1207 numShortTerm = num_ref_frames;
1208 for (i=numShortTerm-1; i>0; i--)
1209 ReferenceFrames[i] = ReferenceFrames[i-1];
1210 ReferenceFrames[0] = CurrentCurrPic;
1212 if (current_frame_type != FRAME_B)
1213 current_frame_num++;
1214 if (current_frame_num > MaxFrameNum)
1215 current_frame_num = 0;
1221 static int update_RefPicList(void)
1223 unsigned int current_poc = CurrentCurrPic.TopFieldOrderCnt;
1225 if (current_frame_type == FRAME_P) {
1226 memcpy(RefPicList0_P, ReferenceFrames, numShortTerm * sizeof(VAPictureH264));
1227 sort_one(RefPicList0_P, 0, numShortTerm-1, 0, 1);
1230 if (current_frame_type == FRAME_B) {
1231 memcpy(RefPicList0_B, ReferenceFrames, numShortTerm * sizeof(VAPictureH264));
1232 sort_two(RefPicList0_B, 0, numShortTerm-1, current_poc, 0,
1235 memcpy(RefPicList1_B, ReferenceFrames, numShortTerm * sizeof(VAPictureH264));
1236 sort_two(RefPicList1_B, 0, numShortTerm-1, current_poc, 0,
1244 static int render_sequence(void)
1246 VABufferID seq_param_buf, rc_param_buf, misc_param_tmpbuf, render_id[2];
1248 VAEncMiscParameterBuffer *misc_param, *misc_param_tmp;
1249 VAEncMiscParameterRateControl *misc_rate_ctrl;
1251 seq_param.level_idc = 41 /*SH_LEVEL_3*/;
1252 seq_param.picture_width_in_mbs = frame_width_mbaligned / 16;
1253 seq_param.picture_height_in_mbs = frame_height_mbaligned / 16;
1254 seq_param.bits_per_second = frame_bitrate;
1256 seq_param.intra_period = intra_period;
1257 seq_param.intra_idr_period = intra_idr_period;
1258 seq_param.ip_period = ip_period;
1260 seq_param.max_num_ref_frames = num_ref_frames;
1261 seq_param.seq_fields.bits.frame_mbs_only_flag = 1;
1262 seq_param.time_scale = frame_rate * 2;
1263 seq_param.num_units_in_tick = 1; /* Tc = num_units_in_tick / scale */
1264 seq_param.seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4 = Log2MaxPicOrderCntLsb - 4;
1265 seq_param.seq_fields.bits.log2_max_frame_num_minus4 = Log2MaxFrameNum - 4;;
1266 seq_param.seq_fields.bits.frame_mbs_only_flag = 1;
1267 seq_param.seq_fields.bits.chroma_format_idc = 1;
1268 seq_param.seq_fields.bits.direct_8x8_inference_flag = 1;
1270 if (frame_width != frame_width_mbaligned ||
1271 frame_height != frame_height_mbaligned) {
1272 seq_param.frame_cropping_flag = 1;
1273 seq_param.frame_crop_left_offset = 0;
1274 seq_param.frame_crop_right_offset = (frame_width_mbaligned - frame_width)/2;
1275 seq_param.frame_crop_top_offset = 0;
1276 seq_param.frame_crop_bottom_offset = (frame_height_mbaligned - frame_height)/2;
1279 va_status = vaCreateBuffer(va_dpy, context_id,
1280 VAEncSequenceParameterBufferType,
1281 sizeof(seq_param), 1, &seq_param, &seq_param_buf);
1282 CHECK_VASTATUS(va_status, "vaCreateBuffer");
1284 va_status = vaCreateBuffer(va_dpy, context_id,
1285 VAEncMiscParameterBufferType,
1286 sizeof(VAEncMiscParameterBuffer) + sizeof(VAEncMiscParameterRateControl),
1287 1, NULL, &rc_param_buf);
1288 CHECK_VASTATUS(va_status, "vaCreateBuffer");
1290 vaMapBuffer(va_dpy, rc_param_buf, (void **)&misc_param);
1291 misc_param->type = VAEncMiscParameterTypeRateControl;
1292 misc_rate_ctrl = (VAEncMiscParameterRateControl *)misc_param->data;
1293 memset(misc_rate_ctrl, 0, sizeof(*misc_rate_ctrl));
1294 misc_rate_ctrl->bits_per_second = frame_bitrate;
1295 misc_rate_ctrl->target_percentage = 66;
1296 misc_rate_ctrl->window_size = 1000;
1297 misc_rate_ctrl->initial_qp = initial_qp;
1298 misc_rate_ctrl->min_qp = minimal_qp;
1299 misc_rate_ctrl->basic_unit_size = 0;
1300 vaUnmapBuffer(va_dpy, rc_param_buf);
1302 render_id[0] = seq_param_buf;
1303 render_id[1] = rc_param_buf;
1305 va_status = vaRenderPicture(va_dpy, context_id, &render_id[0], 2);
1306 CHECK_VASTATUS(va_status, "vaRenderPicture");;
1308 if (misc_priv_type != 0) {
1309 va_status = vaCreateBuffer(va_dpy, context_id,
1310 VAEncMiscParameterBufferType,
1311 sizeof(VAEncMiscParameterBuffer),
1312 1, NULL, &misc_param_tmpbuf);
1313 CHECK_VASTATUS(va_status, "vaCreateBuffer");
1314 vaMapBuffer(va_dpy, misc_param_tmpbuf, (void **)&misc_param_tmp);
1315 misc_param_tmp->type = (VAEncMiscParameterType)misc_priv_type;
1316 misc_param_tmp->data[0] = misc_priv_value;
1317 vaUnmapBuffer(va_dpy, misc_param_tmpbuf);
1319 va_status = vaRenderPicture(va_dpy, context_id, &misc_param_tmpbuf, 1);
1325 static int calc_poc(int pic_order_cnt_lsb)
1327 static int PicOrderCntMsb_ref = 0, pic_order_cnt_lsb_ref = 0;
1328 int prevPicOrderCntMsb, prevPicOrderCntLsb;
1329 int PicOrderCntMsb, TopFieldOrderCnt;
1331 if (current_frame_type == FRAME_IDR)
1332 prevPicOrderCntMsb = prevPicOrderCntLsb = 0;
1334 prevPicOrderCntMsb = PicOrderCntMsb_ref;
1335 prevPicOrderCntLsb = pic_order_cnt_lsb_ref;
1338 if ((pic_order_cnt_lsb < prevPicOrderCntLsb) &&
1339 ((prevPicOrderCntLsb - pic_order_cnt_lsb) >= (int)(MaxPicOrderCntLsb / 2)))
1340 PicOrderCntMsb = prevPicOrderCntMsb + MaxPicOrderCntLsb;
1341 else if ((pic_order_cnt_lsb > prevPicOrderCntLsb) &&
1342 ((pic_order_cnt_lsb - prevPicOrderCntLsb) > (int)(MaxPicOrderCntLsb / 2)))
1343 PicOrderCntMsb = prevPicOrderCntMsb - MaxPicOrderCntLsb;
1345 PicOrderCntMsb = prevPicOrderCntMsb;
1347 TopFieldOrderCnt = PicOrderCntMsb + pic_order_cnt_lsb;
1349 if (current_frame_type != FRAME_B) {
1350 PicOrderCntMsb_ref = PicOrderCntMsb;
1351 pic_order_cnt_lsb_ref = pic_order_cnt_lsb;
1354 return TopFieldOrderCnt;
1357 static int render_picture(void)
1359 VABufferID pic_param_buf;
1363 pic_param.CurrPic.picture_id = gl_surfaces[current_frame_display % SURFACE_NUM].ref_surface;
1364 pic_param.CurrPic.frame_idx = current_frame_num;
1365 pic_param.CurrPic.flags = 0;
1366 pic_param.CurrPic.TopFieldOrderCnt = calc_poc((current_frame_display - current_IDR_display) % MaxPicOrderCntLsb);
1367 pic_param.CurrPic.BottomFieldOrderCnt = pic_param.CurrPic.TopFieldOrderCnt;
1368 CurrentCurrPic = pic_param.CurrPic;
1370 if (getenv("TO_DEL")) { /* set RefPicList into ReferenceFrames */
1371 update_RefPicList(); /* calc RefPicList */
1372 memset(pic_param.ReferenceFrames, 0xff, 16 * sizeof(VAPictureH264)); /* invalid all */
1373 if (current_frame_type == FRAME_P) {
1374 pic_param.ReferenceFrames[0] = RefPicList0_P[0];
1375 } else if (current_frame_type == FRAME_B) {
1376 pic_param.ReferenceFrames[0] = RefPicList0_B[0];
1377 pic_param.ReferenceFrames[1] = RefPicList1_B[0];
1380 memcpy(pic_param.ReferenceFrames, ReferenceFrames, numShortTerm*sizeof(VAPictureH264));
1381 for (i = numShortTerm; i < SURFACE_NUM; i++) {
1382 pic_param.ReferenceFrames[i].picture_id = VA_INVALID_SURFACE;
1383 pic_param.ReferenceFrames[i].flags = VA_PICTURE_H264_INVALID;
1387 pic_param.pic_fields.bits.idr_pic_flag = (current_frame_type == FRAME_IDR);
1388 pic_param.pic_fields.bits.reference_pic_flag = (current_frame_type != FRAME_B);
1389 pic_param.pic_fields.bits.entropy_coding_mode_flag = h264_entropy_mode;
1390 pic_param.pic_fields.bits.deblocking_filter_control_present_flag = 1;
1391 pic_param.frame_num = current_frame_num;
1392 pic_param.coded_buf = gl_surfaces[current_frame_display % SURFACE_NUM].coded_buf;
1393 pic_param.last_picture = false; // FIXME
1394 pic_param.pic_init_qp = initial_qp;
1396 va_status = vaCreateBuffer(va_dpy, context_id, VAEncPictureParameterBufferType,
1397 sizeof(pic_param), 1, &pic_param, &pic_param_buf);
1398 CHECK_VASTATUS(va_status, "vaCreateBuffer");;
1400 va_status = vaRenderPicture(va_dpy, context_id, &pic_param_buf, 1);
1401 CHECK_VASTATUS(va_status, "vaRenderPicture");
1406 static int render_packedsequence(void)
1408 VAEncPackedHeaderParameterBuffer packedheader_param_buffer;
1409 VABufferID packedseq_para_bufid, packedseq_data_bufid, render_id[2];
1410 unsigned int length_in_bits;
1411 unsigned char *packedseq_buffer = NULL;
1414 length_in_bits = build_packed_seq_buffer(&packedseq_buffer);
1416 packedheader_param_buffer.type = VAEncPackedHeaderSequence;
1418 packedheader_param_buffer.bit_length = length_in_bits; /*length_in_bits*/
1419 packedheader_param_buffer.has_emulation_bytes = 0;
1420 va_status = vaCreateBuffer(va_dpy,
1422 VAEncPackedHeaderParameterBufferType,
1423 sizeof(packedheader_param_buffer), 1, &packedheader_param_buffer,
1424 &packedseq_para_bufid);
1425 CHECK_VASTATUS(va_status, "vaCreateBuffer");
1427 va_status = vaCreateBuffer(va_dpy,
1429 VAEncPackedHeaderDataBufferType,
1430 (length_in_bits + 7) / 8, 1, packedseq_buffer,
1431 &packedseq_data_bufid);
1432 CHECK_VASTATUS(va_status, "vaCreateBuffer");
1434 render_id[0] = packedseq_para_bufid;
1435 render_id[1] = packedseq_data_bufid;
1436 va_status = vaRenderPicture(va_dpy, context_id, render_id, 2);
1437 CHECK_VASTATUS(va_status, "vaRenderPicture");
1439 free(packedseq_buffer);
1445 static int render_packedpicture(void)
1447 VAEncPackedHeaderParameterBuffer packedheader_param_buffer;
1448 VABufferID packedpic_para_bufid, packedpic_data_bufid, render_id[2];
1449 unsigned int length_in_bits;
1450 unsigned char *packedpic_buffer = NULL;
1453 length_in_bits = build_packed_pic_buffer(&packedpic_buffer);
1454 packedheader_param_buffer.type = VAEncPackedHeaderPicture;
1455 packedheader_param_buffer.bit_length = length_in_bits;
1456 packedheader_param_buffer.has_emulation_bytes = 0;
1458 va_status = vaCreateBuffer(va_dpy,
1460 VAEncPackedHeaderParameterBufferType,
1461 sizeof(packedheader_param_buffer), 1, &packedheader_param_buffer,
1462 &packedpic_para_bufid);
1463 CHECK_VASTATUS(va_status, "vaCreateBuffer");
1465 va_status = vaCreateBuffer(va_dpy,
1467 VAEncPackedHeaderDataBufferType,
1468 (length_in_bits + 7) / 8, 1, packedpic_buffer,
1469 &packedpic_data_bufid);
1470 CHECK_VASTATUS(va_status, "vaCreateBuffer");
1472 render_id[0] = packedpic_para_bufid;
1473 render_id[1] = packedpic_data_bufid;
1474 va_status = vaRenderPicture(va_dpy, context_id, render_id, 2);
1475 CHECK_VASTATUS(va_status, "vaRenderPicture");
1477 free(packedpic_buffer);
1482 static void render_packedslice()
1484 VAEncPackedHeaderParameterBuffer packedheader_param_buffer;
1485 VABufferID packedslice_para_bufid, packedslice_data_bufid, render_id[2];
1486 unsigned int length_in_bits;
1487 unsigned char *packedslice_buffer = NULL;
1490 length_in_bits = build_packed_slice_buffer(&packedslice_buffer);
1491 packedheader_param_buffer.type = VAEncPackedHeaderSlice;
1492 packedheader_param_buffer.bit_length = length_in_bits;
1493 packedheader_param_buffer.has_emulation_bytes = 0;
1495 va_status = vaCreateBuffer(va_dpy,
1497 VAEncPackedHeaderParameterBufferType,
1498 sizeof(packedheader_param_buffer), 1, &packedheader_param_buffer,
1499 &packedslice_para_bufid);
1500 CHECK_VASTATUS(va_status, "vaCreateBuffer");
1502 va_status = vaCreateBuffer(va_dpy,
1504 VAEncPackedHeaderDataBufferType,
1505 (length_in_bits + 7) / 8, 1, packedslice_buffer,
1506 &packedslice_data_bufid);
1507 CHECK_VASTATUS(va_status, "vaCreateBuffer");
1509 render_id[0] = packedslice_para_bufid;
1510 render_id[1] = packedslice_data_bufid;
1511 va_status = vaRenderPicture(va_dpy, context_id, render_id, 2);
1512 CHECK_VASTATUS(va_status, "vaRenderPicture");
1514 free(packedslice_buffer);
1517 static int render_slice(void)
1519 VABufferID slice_param_buf;
1523 update_RefPicList();
1525 /* one frame, one slice */
1526 slice_param.macroblock_address = 0;
1527 slice_param.num_macroblocks = frame_width_mbaligned * frame_height_mbaligned/(16*16); /* Measured by MB */
1528 slice_param.slice_type = (current_frame_type == FRAME_IDR)?2:current_frame_type;
1529 if (current_frame_type == FRAME_IDR) {
1530 if (current_frame_encoding != 0)
1531 ++slice_param.idr_pic_id;
1532 } else if (current_frame_type == FRAME_P) {
1533 int refpiclist0_max = h264_maxref & 0xffff;
1534 memcpy(slice_param.RefPicList0, RefPicList0_P, refpiclist0_max*sizeof(VAPictureH264));
1536 for (i = refpiclist0_max; i < 32; i++) {
1537 slice_param.RefPicList0[i].picture_id = VA_INVALID_SURFACE;
1538 slice_param.RefPicList0[i].flags = VA_PICTURE_H264_INVALID;
1540 } else if (current_frame_type == FRAME_B) {
1541 int refpiclist0_max = h264_maxref & 0xffff;
1542 int refpiclist1_max = (h264_maxref >> 16) & 0xffff;
1544 memcpy(slice_param.RefPicList0, RefPicList0_B, refpiclist0_max*sizeof(VAPictureH264));
1545 for (i = refpiclist0_max; i < 32; i++) {
1546 slice_param.RefPicList0[i].picture_id = VA_INVALID_SURFACE;
1547 slice_param.RefPicList0[i].flags = VA_PICTURE_H264_INVALID;
1550 memcpy(slice_param.RefPicList1, RefPicList1_B, refpiclist1_max*sizeof(VAPictureH264));
1551 for (i = refpiclist1_max; i < 32; i++) {
1552 slice_param.RefPicList1[i].picture_id = VA_INVALID_SURFACE;
1553 slice_param.RefPicList1[i].flags = VA_PICTURE_H264_INVALID;
1557 slice_param.slice_alpha_c0_offset_div2 = 0;
1558 slice_param.slice_beta_offset_div2 = 0;
1559 slice_param.direct_spatial_mv_pred_flag = 1;
1560 slice_param.pic_order_cnt_lsb = (current_frame_display - current_IDR_display) % MaxPicOrderCntLsb;
1563 if (h264_packedheader &&
1564 config_attrib[enc_packed_header_idx].value & VA_ENC_PACKED_HEADER_SLICE)
1565 render_packedslice();
1567 va_status = vaCreateBuffer(va_dpy, context_id, VAEncSliceParameterBufferType,
1568 sizeof(slice_param), 1, &slice_param, &slice_param_buf);
1569 CHECK_VASTATUS(va_status, "vaCreateBuffer");;
1571 va_status = vaRenderPicture(va_dpy, context_id, &slice_param_buf, 1);
1572 CHECK_VASTATUS(va_status, "vaRenderPicture");
1579 int H264Encoder::save_codeddata(unsigned long long display_order, unsigned long long encode_order, int frame_type)
1581 VACodedBufferSegment *buf_list = NULL;
1583 unsigned int coded_size = 0;
1587 va_status = vaMapBuffer(va_dpy, gl_surfaces[display_order % SURFACE_NUM].coded_buf, (void **)(&buf_list));
1588 CHECK_VASTATUS(va_status, "vaMapBuffer");
1589 while (buf_list != NULL) {
1590 data.append(reinterpret_cast<const char *>(buf_list->buf), buf_list->size);
1591 if (coded_fp != nullptr)
1592 coded_size += fwrite(buf_list->buf, 1, buf_list->size, coded_fp);
1593 buf_list = (VACodedBufferSegment *) buf_list->next;
1595 frame_size += coded_size;
1597 vaUnmapBuffer(va_dpy, gl_surfaces[display_order % SURFACE_NUM].coded_buf);
1600 memset(&pkt, 0, sizeof(pkt));
1602 pkt.pts = av_rescale_q(display_order, AVRational{1, frame_rate}, avstream->time_base);
1603 pkt.dts = av_rescale_q(encode_order, AVRational{1, frame_rate}, avstream->time_base);
1604 pkt.data = reinterpret_cast<uint8_t *>(&data[0]);
1605 pkt.size = data.size();
1606 pkt.stream_index = 0;
1607 if (frame_type == FRAME_IDR || frame_type == FRAME_I) {
1608 pkt.flags = AV_PKT_FLAG_KEY;
1613 av_interleaved_write_frame(avctx, &pkt);
1616 printf("\r "); /* return back to startpoint */
1617 switch (encode_order % 4) {
1631 printf("%08lld", encode_order);
1632 printf("(%06d bytes coded)", coded_size);
1639 // this is weird. but it seems to put a new frame onto the queue
1640 void H264Encoder::storage_task_enqueue(unsigned long long display_order, unsigned long long encode_order, int frame_type)
1642 std::unique_lock<std::mutex> lock(storage_task_queue_mutex);
1645 tmp.display_order = display_order;
1646 tmp.encode_order = encode_order;
1647 tmp.frame_type = frame_type;
1648 storage_task_queue.push(tmp);
1649 srcsurface_status[display_order % SURFACE_NUM] = SRC_SURFACE_IN_ENCODING;
1651 storage_task_queue_changed.notify_all();
1654 void H264Encoder::storage_task_thread()
1657 storage_task current;
1659 // wait until there's an encoded frame
1660 std::unique_lock<std::mutex> lock(storage_task_queue_mutex);
1661 storage_task_queue_changed.wait(lock, [this]{ return storage_thread_should_quit || !storage_task_queue.empty(); });
1662 if (storage_thread_should_quit) return;
1663 current = storage_task_queue.front();
1664 storage_task_queue.pop();
1669 // waits for data, then saves it to disk.
1670 va_status = vaSyncSurface(va_dpy, gl_surfaces[current.display_order % SURFACE_NUM].src_surface);
1671 CHECK_VASTATUS(va_status, "vaSyncSurface");
1672 save_codeddata(current.display_order, current.encode_order, current.frame_type);
1675 std::unique_lock<std::mutex> lock(storage_task_queue_mutex);
1676 srcsurface_status[current.display_order % SURFACE_NUM] = SRC_SURFACE_FREE;
1677 storage_task_queue_changed.notify_all();
1682 static int release_encode()
1686 for (i = 0; i < SURFACE_NUM; i++) {
1687 vaDestroyBuffer(va_dpy, gl_surfaces[i].coded_buf);
1688 vaDestroySurfaces(va_dpy, &gl_surfaces[i].src_surface, 1);
1689 vaDestroySurfaces(va_dpy, &gl_surfaces[i].ref_surface, 1);
1692 vaDestroyContext(va_dpy, context_id);
1693 vaDestroyConfig(va_dpy, config_id);
1698 static int deinit_va()
1700 vaTerminate(va_dpy);
1702 va_close_display(va_dpy);
1708 static int print_input()
1710 printf("\n\nINPUT:Try to encode H264...\n");
1712 printf("INPUT: RateControl : %s\n", rc_to_string(rc_mode));
1713 printf("INPUT: Resolution : %dx%dframes\n", frame_width, frame_height);
1714 printf("INPUT: FrameRate : %d\n", frame_rate);
1715 printf("INPUT: Bitrate : %d\n", frame_bitrate);
1716 printf("INPUT: Slieces : %d\n", frame_slices);
1717 printf("INPUT: IntraPeriod : %d\n", intra_period);
1718 printf("INPUT: IDRPeriod : %d\n", intra_idr_period);
1719 printf("INPUT: IpPeriod : %d\n", ip_period);
1720 printf("INPUT: Initial QP : %d\n", initial_qp);
1721 printf("INPUT: Min QP : %d\n", minimal_qp);
1722 printf("INPUT: Coded Clip : %s\n", coded_fn);
1724 printf("\n\n"); /* return back to startpoint */
1730 //H264Encoder::H264Encoder(SDL_Window *window, SDL_GLContext context, int width, int height, const char *output_filename)
1731 H264Encoder::H264Encoder(QSurface *surface, int width, int height, const char *output_filename)
1732 : current_storage_frame(0), surface(surface)
1733 //: width(width), height(height), current_encoding_frame(0)
1736 avctx = avformat_alloc_context();
1737 avctx->oformat = av_guess_format(NULL, output_filename, NULL);
1738 strcpy(avctx->filename, output_filename);
1739 if (avio_open2(&avctx->pb, output_filename, AVIO_FLAG_WRITE, &avctx->interrupt_callback, NULL) < 0) {
1740 fprintf(stderr, "%s: avio_open2() failed\n", output_filename);
1743 AVCodec *codec = avcodec_find_encoder(AV_CODEC_ID_H264);
1744 avstream = avformat_new_stream(avctx, codec);
1745 if (avstream == nullptr) {
1746 fprintf(stderr, "%s: avformat_new_stream() failed\n", output_filename);
1749 avstream->time_base = AVRational{1, frame_rate};
1750 avstream->codec->width = width;
1751 avstream->codec->height = height;
1752 avstream->codec->time_base = AVRational{1, frame_rate};
1753 avstream->codec->ticks_per_frame = 1; // or 2?
1755 if (avformat_write_header(avctx, NULL) < 0) {
1756 fprintf(stderr, "%s: avformat_write_header() failed\n", output_filename);
1760 coded_fp = fopen("dump.h264", "wb");
1761 assert(coded_fp != NULL);
1763 frame_width = width;
1764 frame_height = height;
1765 frame_width_mbaligned = (frame_width + 15) & (~15);
1766 frame_height_mbaligned = (frame_height + 15) & (~15);
1767 frame_bitrate = 15000000; // / 60;
1768 current_frame_encoding = 0;
1775 // No frames are ready yet.
1776 memset(srcsurface_status, SRC_SURFACE_FREE, sizeof(srcsurface_status));
1778 memset(&seq_param, 0, sizeof(seq_param));
1779 memset(&pic_param, 0, sizeof(pic_param));
1780 memset(&slice_param, 0, sizeof(slice_param));
1782 storage_thread = std::thread(&H264Encoder::storage_task_thread, this);
1784 copy_thread = std::thread([this]{
1785 //SDL_GL_MakeCurrent(window, context);
1786 QOpenGLContext *context = create_context();
1787 eglBindAPI(EGL_OPENGL_API);
1788 if (!make_current(context, this->surface)) {
1789 printf("display=%p surface=%p context=%p curr=%p err=%d\n", eglGetCurrentDisplay(), this->surface, context, eglGetCurrentContext(),
1797 H264Encoder::~H264Encoder()
1800 unique_lock<mutex> lock(storage_task_queue_mutex);
1801 storage_thread_should_quit = true;
1802 storage_task_queue_changed.notify_all();
1805 unique_lock<mutex> lock(frame_queue_mutex);
1806 copy_thread_should_quit = true;
1807 frame_queue_nonempty.notify_one();
1809 storage_thread.join();
1815 av_write_trailer(avctx);
1816 avformat_free_context(avctx);
1819 bool H264Encoder::begin_frame(GLuint *y_tex, GLuint *cbcr_tex)
1822 // Wait until this frame slot is done encoding.
1823 std::unique_lock<std::mutex> lock(storage_task_queue_mutex);
1824 storage_task_queue_changed.wait(lock, [this]{ return storage_thread_should_quit || (srcsurface_status[current_storage_frame % SURFACE_NUM] == SRC_SURFACE_FREE); });
1825 if (storage_thread_should_quit) return false;
1828 //*fbo = fbos[current_storage_frame % SURFACE_NUM];
1829 GLSurface *surf = &gl_surfaces[current_storage_frame % SURFACE_NUM];
1830 *y_tex = surf->y_tex;
1831 *cbcr_tex = surf->cbcr_tex;
1833 VASurfaceID surface = surf->src_surface;
1834 VAStatus va_status = vaDeriveImage(va_dpy, surface, &surf->surface_image);
1835 CHECK_VASTATUS(va_status, "vaDeriveImage");
1837 VABufferInfo buf_info;
1838 buf_info.mem_type = VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME; // or VA_SURFACE_ATTRIB_MEM_TYPE_KERNEL_DRM?
1839 va_status = vaAcquireBufferHandle(va_dpy, surf->surface_image.buf, &buf_info);
1840 CHECK_VASTATUS(va_status, "vaAcquireBufferHandle");
1843 surf->y_egl_image = EGL_NO_IMAGE_KHR;
1844 EGLint y_attribs[] = {
1845 EGL_WIDTH, frame_width,
1846 EGL_HEIGHT, frame_height,
1847 EGL_LINUX_DRM_FOURCC_EXT, fourcc_code('R', '8', ' ', ' '),
1848 EGL_DMA_BUF_PLANE0_FD_EXT, EGLint(buf_info.handle),
1849 EGL_DMA_BUF_PLANE0_OFFSET_EXT, EGLint(surf->surface_image.offsets[0]),
1850 EGL_DMA_BUF_PLANE0_PITCH_EXT, EGLint(surf->surface_image.pitches[0]),
1854 surf->y_egl_image = eglCreateImageKHR(eglGetCurrentDisplay(), EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, NULL, y_attribs);
1855 assert(surf->y_egl_image != EGL_NO_IMAGE_KHR);
1857 // Associate Y image to a texture.
1858 glBindTexture(GL_TEXTURE_2D, *y_tex);
1859 glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, surf->y_egl_image);
1861 // Create CbCr image.
1862 surf->cbcr_egl_image = EGL_NO_IMAGE_KHR;
1863 EGLint cbcr_attribs[] = {
1864 EGL_WIDTH, frame_width,
1865 EGL_HEIGHT, frame_height,
1866 EGL_LINUX_DRM_FOURCC_EXT, fourcc_code('G', 'R', '8', '8'),
1867 EGL_DMA_BUF_PLANE0_FD_EXT, EGLint(buf_info.handle),
1868 EGL_DMA_BUF_PLANE0_OFFSET_EXT, EGLint(surf->surface_image.offsets[1]),
1869 EGL_DMA_BUF_PLANE0_PITCH_EXT, EGLint(surf->surface_image.pitches[1]),
1873 surf->cbcr_egl_image = eglCreateImageKHR(eglGetCurrentDisplay(), EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, NULL, cbcr_attribs);
1874 assert(surf->cbcr_egl_image != EGL_NO_IMAGE_KHR);
1876 // Associate CbCr image to a texture.
1877 glBindTexture(GL_TEXTURE_2D, *cbcr_tex);
1878 glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, surf->cbcr_egl_image);
1883 void H264Encoder::end_frame(RefCountedGLsync fence, const std::vector<FrameAllocator::Frame> &input_frames_to_release)
1886 unique_lock<mutex> lock(frame_queue_mutex);
1887 pending_frames[current_storage_frame++] = PendingFrame{ fence, input_frames_to_release };
1889 frame_queue_nonempty.notify_one();
1892 void H264Encoder::copy_thread_func()
1896 encoding2display_order(current_frame_encoding, intra_period, intra_idr_period, ip_period,
1897 ¤t_frame_display, ¤t_frame_type);
1898 if (current_frame_type == FRAME_IDR) {
1900 current_frame_num = 0;
1901 current_IDR_display = current_frame_display;
1905 unique_lock<mutex> lock(frame_queue_mutex);
1906 frame_queue_nonempty.wait(lock, [this]{ return copy_thread_should_quit || pending_frames.count(current_frame_display) != 0; });
1907 if (copy_thread_should_quit) return;
1908 frame = pending_frames[current_frame_display];
1909 pending_frames.erase(current_frame_display);
1912 // Wait for the GPU to be done with the frame.
1913 glClientWaitSync(frame.fence.get(), 0, 0);
1915 // Release back any input frames we needed to render this frame.
1916 // (Actually, those that were needed one output frame ago.)
1917 for (FrameAllocator::Frame input_frame : frame.input_frames_to_release) {
1918 input_frame.owner->release_frame(input_frame);
1922 GLSurface *surf = &gl_surfaces[current_frame_display % SURFACE_NUM];
1923 eglDestroyImageKHR(eglGetCurrentDisplay(), surf->y_egl_image);
1924 eglDestroyImageKHR(eglGetCurrentDisplay(), surf->cbcr_egl_image);
1925 VAStatus va_status = vaReleaseBufferHandle(va_dpy, surf->surface_image.buf);
1926 CHECK_VASTATUS(va_status, "vaReleaseBufferHandle");
1927 va_status = vaDestroyImage(va_dpy, surf->surface_image.image_id);
1928 CHECK_VASTATUS(va_status, "vaDestroyImage");
1930 VASurfaceID surface = surf->src_surface;
1932 // Schedule the frame for encoding.
1933 va_status = vaBeginPicture(va_dpy, context_id, surface);
1934 CHECK_VASTATUS(va_status, "vaBeginPicture");
1936 if (current_frame_type == FRAME_IDR) {
1939 if (h264_packedheader) {
1940 render_packedsequence();
1941 render_packedpicture();
1944 //render_sequence();
1949 va_status = vaEndPicture(va_dpy, context_id);
1950 CHECK_VASTATUS(va_status, "vaEndPicture");
1952 // so now the data is done encoding (well, async job kicked off)...
1953 // we send that to the storage thread
1954 storage_task_enqueue(current_frame_display, current_frame_encoding, current_frame_type);
1956 update_ReferenceFrames();
1957 ++current_frame_encoding;