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>
34 #define CHECK_VASTATUS(va_status, func) \
35 if (va_status != VA_STATUS_SUCCESS) { \
36 fprintf(stderr, "%s:%d (%s) failed with %d\n", __func__, __LINE__, func, va_status); \
40 //#include "loadsurface.h"
42 #define NAL_REF_IDC_NONE 0
43 #define NAL_REF_IDC_LOW 1
44 #define NAL_REF_IDC_MEDIUM 2
45 #define NAL_REF_IDC_HIGH 3
53 #define SLICE_TYPE_P 0
54 #define SLICE_TYPE_B 1
55 #define SLICE_TYPE_I 2
56 #define IS_P_SLICE(type) (SLICE_TYPE_P == (type))
57 #define IS_B_SLICE(type) (SLICE_TYPE_B == (type))
58 #define IS_I_SLICE(type) (SLICE_TYPE_I == (type))
61 #define ENTROPY_MODE_CAVLC 0
62 #define ENTROPY_MODE_CABAC 1
64 #define PROFILE_IDC_BASELINE 66
65 #define PROFILE_IDC_MAIN 77
66 #define PROFILE_IDC_HIGH 100
68 #define BITSTREAM_ALLOCATE_STEPPING 4096
70 #define SURFACE_NUM 16 /* 16 surfaces for source YUV */
71 static VADisplay va_dpy;
72 static VAProfile h264_profile = (VAProfile)~0;
73 static VAConfigAttrib config_attrib[VAConfigAttribTypeMax];
74 static int config_attrib_num = 0, enc_packed_header_idx;
77 VASurfaceID src_surface, ref_surface;
80 VAImage surface_image;
81 GLuint y_tex, cbcr_tex;
82 EGLImage y_egl_image, cbcr_egl_image;
84 GLSurface gl_surfaces[SURFACE_NUM];
86 static VAConfigID config_id;
87 static VAContextID context_id;
88 static VAEncSequenceParameterBufferH264 seq_param;
89 static VAEncPictureParameterBufferH264 pic_param;
90 static VAEncSliceParameterBufferH264 slice_param;
91 static VAPictureH264 CurrentCurrPic;
92 static VAPictureH264 ReferenceFrames[16], RefPicList0_P[32], RefPicList0_B[32], RefPicList1_B[32];
94 static unsigned int MaxFrameNum = (2<<16);
95 static unsigned int MaxPicOrderCntLsb = (2<<8);
96 static unsigned int Log2MaxFrameNum = 16;
97 static unsigned int Log2MaxPicOrderCntLsb = 8;
99 static unsigned int num_ref_frames = 2;
100 static unsigned int numShortTerm = 0;
101 static int constraint_set_flag = 0;
102 static int h264_packedheader = 0; /* support pack header? */
103 static int h264_maxref = (1<<16|1);
104 static int h264_entropy_mode = 1; /* cabac */
106 static char *coded_fn = 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 = 3;
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, TIMEBASE * 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");
800 frame_width_mbaligned = (frame_width + 15) & (~15);
801 frame_height_mbaligned = (frame_height + 15) & (~15);
802 if (frame_width != frame_width_mbaligned ||
803 frame_height != frame_height_mbaligned) {
804 printf("Source frame is %dx%d and will code clip to %dx%d with crop\n",
805 frame_width, frame_height,
806 frame_width_mbaligned, frame_height_mbaligned
814 static Display *x11_display;
815 static Window x11_window;
818 va_open_display(void)
820 x11_display = XOpenDisplay(NULL);
822 fprintf(stderr, "error: can't connect to X server!\n");
825 return vaGetDisplay(x11_display);
829 va_close_display(VADisplay va_dpy)
835 XUnmapWindow(x11_display, x11_window);
836 XDestroyWindow(x11_display, x11_window);
839 XCloseDisplay(x11_display);
843 static int init_va(void)
845 VAProfile profile_list[]={VAProfileH264High, VAProfileH264Main, VAProfileH264Baseline, VAProfileH264ConstrainedBaseline};
846 VAEntrypoint *entrypoints;
847 int num_entrypoints, slice_entrypoint;
848 int support_encode = 0;
849 int major_ver, minor_ver;
853 va_dpy = va_open_display();
854 va_status = vaInitialize(va_dpy, &major_ver, &minor_ver);
855 CHECK_VASTATUS(va_status, "vaInitialize");
857 num_entrypoints = vaMaxNumEntrypoints(va_dpy);
858 entrypoints = (VAEntrypoint *)malloc(num_entrypoints * sizeof(*entrypoints));
860 fprintf(stderr, "error: failed to initialize VA entrypoints array\n");
864 /* use the highest profile */
865 for (i = 0; i < sizeof(profile_list)/sizeof(profile_list[0]); i++) {
866 if ((h264_profile != ~0) && h264_profile != profile_list[i])
869 h264_profile = profile_list[i];
870 vaQueryConfigEntrypoints(va_dpy, h264_profile, entrypoints, &num_entrypoints);
871 for (slice_entrypoint = 0; slice_entrypoint < num_entrypoints; slice_entrypoint++) {
872 if (entrypoints[slice_entrypoint] == VAEntrypointEncSlice) {
877 if (support_encode == 1)
881 if (support_encode == 0) {
882 printf("Can't find VAEntrypointEncSlice for H264 profiles\n");
885 switch (h264_profile) {
886 case VAProfileH264Baseline:
887 printf("Use profile VAProfileH264Baseline\n");
889 constraint_set_flag |= (1 << 0); /* Annex A.2.1 */
890 h264_entropy_mode = 0;
892 case VAProfileH264ConstrainedBaseline:
893 printf("Use profile VAProfileH264ConstrainedBaseline\n");
894 constraint_set_flag |= (1 << 0 | 1 << 1); /* Annex A.2.2 */
898 case VAProfileH264Main:
899 printf("Use profile VAProfileH264Main\n");
900 constraint_set_flag |= (1 << 1); /* Annex A.2.2 */
903 case VAProfileH264High:
904 constraint_set_flag |= (1 << 3); /* Annex A.2.4 */
905 printf("Use profile VAProfileH264High\n");
908 printf("unknow profile. Set to Baseline");
909 h264_profile = VAProfileH264Baseline;
911 constraint_set_flag |= (1 << 0); /* Annex A.2.1 */
916 VAConfigAttrib attrib[VAConfigAttribTypeMax];
918 /* find out the format for the render target, and rate control mode */
919 for (i = 0; i < VAConfigAttribTypeMax; i++)
920 attrib[i].type = (VAConfigAttribType)i;
922 va_status = vaGetConfigAttributes(va_dpy, h264_profile, VAEntrypointEncSlice,
923 &attrib[0], VAConfigAttribTypeMax);
924 CHECK_VASTATUS(va_status, "vaGetConfigAttributes");
925 /* check the interested configattrib */
926 if ((attrib[VAConfigAttribRTFormat].value & VA_RT_FORMAT_YUV420) == 0) {
927 printf("Not find desired YUV420 RT format\n");
930 config_attrib[config_attrib_num].type = VAConfigAttribRTFormat;
931 config_attrib[config_attrib_num].value = VA_RT_FORMAT_YUV420;
935 if (attrib[VAConfigAttribRateControl].value != VA_ATTRIB_NOT_SUPPORTED) {
936 int tmp = attrib[VAConfigAttribRateControl].value;
938 printf("Support rate control mode (0x%x):", tmp);
940 if (tmp & VA_RC_NONE)
950 if (tmp & VA_RC_VBR_CONSTRAINED)
951 printf("VBR_CONSTRAINED ");
955 if (rc_mode == -1 || !(rc_mode & tmp)) {
957 printf("Warning: Don't support the specified RateControl mode: %s!!!, switch to ", rc_to_string(rc_mode));
960 for (i = 0; i < sizeof(rc_default_modes) / sizeof(rc_default_modes[0]); i++) {
961 if (rc_default_modes[i] & tmp) {
962 rc_mode = rc_default_modes[i];
967 printf("RateControl mode: %s\n", rc_to_string(rc_mode));
970 config_attrib[config_attrib_num].type = VAConfigAttribRateControl;
971 config_attrib[config_attrib_num].value = rc_mode;
976 if (attrib[VAConfigAttribEncPackedHeaders].value != VA_ATTRIB_NOT_SUPPORTED) {
977 int tmp = attrib[VAConfigAttribEncPackedHeaders].value;
979 printf("Support VAConfigAttribEncPackedHeaders\n");
981 h264_packedheader = 1;
982 config_attrib[config_attrib_num].type = VAConfigAttribEncPackedHeaders;
983 config_attrib[config_attrib_num].value = VA_ENC_PACKED_HEADER_NONE;
985 if (tmp & VA_ENC_PACKED_HEADER_SEQUENCE) {
986 printf("Support packed sequence headers\n");
987 config_attrib[config_attrib_num].value |= VA_ENC_PACKED_HEADER_SEQUENCE;
990 if (tmp & VA_ENC_PACKED_HEADER_PICTURE) {
991 printf("Support packed picture headers\n");
992 config_attrib[config_attrib_num].value |= VA_ENC_PACKED_HEADER_PICTURE;
995 if (tmp & VA_ENC_PACKED_HEADER_SLICE) {
996 printf("Support packed slice headers\n");
997 config_attrib[config_attrib_num].value |= VA_ENC_PACKED_HEADER_SLICE;
1000 if (tmp & VA_ENC_PACKED_HEADER_MISC) {
1001 printf("Support packed misc headers\n");
1002 config_attrib[config_attrib_num].value |= VA_ENC_PACKED_HEADER_MISC;
1005 enc_packed_header_idx = config_attrib_num;
1006 config_attrib_num++;
1009 if (attrib[VAConfigAttribEncInterlaced].value != VA_ATTRIB_NOT_SUPPORTED) {
1010 int tmp = attrib[VAConfigAttribEncInterlaced].value;
1012 printf("Support VAConfigAttribEncInterlaced\n");
1014 if (tmp & VA_ENC_INTERLACED_FRAME)
1015 printf("support VA_ENC_INTERLACED_FRAME\n");
1016 if (tmp & VA_ENC_INTERLACED_FIELD)
1017 printf("Support VA_ENC_INTERLACED_FIELD\n");
1018 if (tmp & VA_ENC_INTERLACED_MBAFF)
1019 printf("Support VA_ENC_INTERLACED_MBAFF\n");
1020 if (tmp & VA_ENC_INTERLACED_PAFF)
1021 printf("Support VA_ENC_INTERLACED_PAFF\n");
1023 config_attrib[config_attrib_num].type = VAConfigAttribEncInterlaced;
1024 config_attrib[config_attrib_num].value = VA_ENC_PACKED_HEADER_NONE;
1025 config_attrib_num++;
1028 if (attrib[VAConfigAttribEncMaxRefFrames].value != VA_ATTRIB_NOT_SUPPORTED) {
1029 h264_maxref = attrib[VAConfigAttribEncMaxRefFrames].value;
1031 printf("Support %d RefPicList0 and %d RefPicList1\n",
1032 h264_maxref & 0xffff, (h264_maxref >> 16) & 0xffff );
1035 if (attrib[VAConfigAttribEncMaxSlices].value != VA_ATTRIB_NOT_SUPPORTED)
1036 printf("Support %d slices\n", attrib[VAConfigAttribEncMaxSlices].value);
1038 if (attrib[VAConfigAttribEncSliceStructure].value != VA_ATTRIB_NOT_SUPPORTED) {
1039 int tmp = attrib[VAConfigAttribEncSliceStructure].value;
1041 printf("Support VAConfigAttribEncSliceStructure\n");
1043 if (tmp & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS)
1044 printf("Support VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS\n");
1045 if (tmp & VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS)
1046 printf("Support VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS\n");
1047 if (tmp & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS)
1048 printf("Support VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS\n");
1050 if (attrib[VAConfigAttribEncMacroblockInfo].value != VA_ATTRIB_NOT_SUPPORTED) {
1051 printf("Support VAConfigAttribEncMacroblockInfo\n");
1058 static int setup_encode()
1061 VASurfaceID *tmp_surfaceid;
1062 int codedbuf_size, i;
1063 static VASurfaceID src_surface[SURFACE_NUM];
1064 static VASurfaceID ref_surface[SURFACE_NUM];
1066 va_status = vaCreateConfig(va_dpy, h264_profile, VAEntrypointEncSlice,
1067 &config_attrib[0], config_attrib_num, &config_id);
1068 CHECK_VASTATUS(va_status, "vaCreateConfig");
1070 /* create source surfaces */
1071 va_status = vaCreateSurfaces(va_dpy,
1072 VA_RT_FORMAT_YUV420, frame_width_mbaligned, frame_height_mbaligned,
1073 &src_surface[0], SURFACE_NUM,
1075 CHECK_VASTATUS(va_status, "vaCreateSurfaces");
1077 /* create reference surfaces */
1078 va_status = vaCreateSurfaces(va_dpy,
1079 VA_RT_FORMAT_YUV420, frame_width_mbaligned, frame_height_mbaligned,
1080 &ref_surface[0], SURFACE_NUM,
1082 CHECK_VASTATUS(va_status, "vaCreateSurfaces");
1084 tmp_surfaceid = (VASurfaceID *)calloc(2 * SURFACE_NUM, sizeof(VASurfaceID));
1085 memcpy(tmp_surfaceid, src_surface, SURFACE_NUM * sizeof(VASurfaceID));
1086 memcpy(tmp_surfaceid + SURFACE_NUM, ref_surface, SURFACE_NUM * sizeof(VASurfaceID));
1088 /* Create a context for this encode pipe */
1089 va_status = vaCreateContext(va_dpy, config_id,
1090 frame_width_mbaligned, frame_height_mbaligned,
1092 tmp_surfaceid, 2 * SURFACE_NUM,
1094 CHECK_VASTATUS(va_status, "vaCreateContext");
1095 free(tmp_surfaceid);
1097 codedbuf_size = (frame_width_mbaligned * frame_height_mbaligned * 400) / (16*16);
1099 for (i = 0; i < SURFACE_NUM; i++) {
1100 /* create coded buffer once for all
1101 * other VA buffers which won't be used again after vaRenderPicture.
1102 * so APP can always vaCreateBuffer for every frame
1103 * but coded buffer need to be mapped and accessed after vaRenderPicture/vaEndPicture
1104 * so VA won't maintain the coded buffer
1106 va_status = vaCreateBuffer(va_dpy, context_id, VAEncCodedBufferType,
1107 codedbuf_size, 1, NULL, &gl_surfaces[i].coded_buf);
1108 CHECK_VASTATUS(va_status, "vaCreateBuffer");
1111 /* create OpenGL objects */
1112 //glGenFramebuffers(SURFACE_NUM, fbos);
1114 for (i = 0; i < SURFACE_NUM; i++) {
1115 glGenTextures(1, &gl_surfaces[i].y_tex);
1116 glGenTextures(1, &gl_surfaces[i].cbcr_tex);
1119 for (i = 0; i < SURFACE_NUM; i++) {
1120 gl_surfaces[i].src_surface = src_surface[i];
1121 gl_surfaces[i].ref_surface = ref_surface[i];
1129 #define partition(ref, field, key, ascending) \
1132 while (ref[i].field < key) \
1134 while (ref[j].field > key) \
1137 while (ref[i].field > key) \
1139 while (ref[j].field < key) \
1151 static void sort_one(VAPictureH264 ref[], int left, int right,
1152 int ascending, int frame_idx)
1154 int i = left, j = right;
1159 key = ref[(left + right) / 2].frame_idx;
1160 partition(ref, frame_idx, key, ascending);
1162 key = ref[(left + right) / 2].TopFieldOrderCnt;
1163 partition(ref, TopFieldOrderCnt, (signed int)key, ascending);
1168 sort_one(ref, left, j, ascending, frame_idx);
1171 sort_one(ref, i, right, ascending, frame_idx);
1174 static void sort_two(VAPictureH264 ref[], int left, int right, unsigned int key, unsigned int frame_idx,
1175 int partition_ascending, int list0_ascending, int list1_ascending)
1177 int i = left, j = right;
1181 partition(ref, frame_idx, key, partition_ascending);
1183 partition(ref, TopFieldOrderCnt, (signed int)key, partition_ascending);
1187 sort_one(ref, left, i-1, list0_ascending, frame_idx);
1188 sort_one(ref, j+1, right, list1_ascending, frame_idx);
1191 static int update_ReferenceFrames(void)
1195 if (current_frame_type == FRAME_B)
1198 CurrentCurrPic.flags = VA_PICTURE_H264_SHORT_TERM_REFERENCE;
1200 if (numShortTerm > num_ref_frames)
1201 numShortTerm = num_ref_frames;
1202 for (i=numShortTerm-1; i>0; i--)
1203 ReferenceFrames[i] = ReferenceFrames[i-1];
1204 ReferenceFrames[0] = CurrentCurrPic;
1206 if (current_frame_type != FRAME_B)
1207 current_frame_num++;
1208 if (current_frame_num > MaxFrameNum)
1209 current_frame_num = 0;
1215 static int update_RefPicList(void)
1217 unsigned int current_poc = CurrentCurrPic.TopFieldOrderCnt;
1219 if (current_frame_type == FRAME_P) {
1220 memcpy(RefPicList0_P, ReferenceFrames, numShortTerm * sizeof(VAPictureH264));
1221 sort_one(RefPicList0_P, 0, numShortTerm-1, 0, 1);
1224 if (current_frame_type == FRAME_B) {
1225 memcpy(RefPicList0_B, ReferenceFrames, numShortTerm * sizeof(VAPictureH264));
1226 sort_two(RefPicList0_B, 0, numShortTerm-1, current_poc, 0,
1229 memcpy(RefPicList1_B, ReferenceFrames, numShortTerm * sizeof(VAPictureH264));
1230 sort_two(RefPicList1_B, 0, numShortTerm-1, current_poc, 0,
1238 static int render_sequence(void)
1240 VABufferID seq_param_buf, rc_param_buf, misc_param_tmpbuf, render_id[2];
1242 VAEncMiscParameterBuffer *misc_param, *misc_param_tmp;
1243 VAEncMiscParameterRateControl *misc_rate_ctrl;
1245 seq_param.level_idc = 41 /*SH_LEVEL_3*/;
1246 seq_param.picture_width_in_mbs = frame_width_mbaligned / 16;
1247 seq_param.picture_height_in_mbs = frame_height_mbaligned / 16;
1248 seq_param.bits_per_second = frame_bitrate;
1250 seq_param.intra_period = intra_period;
1251 seq_param.intra_idr_period = intra_idr_period;
1252 seq_param.ip_period = ip_period;
1254 seq_param.max_num_ref_frames = num_ref_frames;
1255 seq_param.seq_fields.bits.frame_mbs_only_flag = 1;
1256 seq_param.time_scale = TIMEBASE * 2;
1257 seq_param.num_units_in_tick = 1; /* Tc = num_units_in_tick / scale */
1258 seq_param.seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4 = Log2MaxPicOrderCntLsb - 4;
1259 seq_param.seq_fields.bits.log2_max_frame_num_minus4 = Log2MaxFrameNum - 4;;
1260 seq_param.seq_fields.bits.frame_mbs_only_flag = 1;
1261 seq_param.seq_fields.bits.chroma_format_idc = 1;
1262 seq_param.seq_fields.bits.direct_8x8_inference_flag = 1;
1264 if (frame_width != frame_width_mbaligned ||
1265 frame_height != frame_height_mbaligned) {
1266 seq_param.frame_cropping_flag = 1;
1267 seq_param.frame_crop_left_offset = 0;
1268 seq_param.frame_crop_right_offset = (frame_width_mbaligned - frame_width)/2;
1269 seq_param.frame_crop_top_offset = 0;
1270 seq_param.frame_crop_bottom_offset = (frame_height_mbaligned - frame_height)/2;
1273 va_status = vaCreateBuffer(va_dpy, context_id,
1274 VAEncSequenceParameterBufferType,
1275 sizeof(seq_param), 1, &seq_param, &seq_param_buf);
1276 CHECK_VASTATUS(va_status, "vaCreateBuffer");
1278 va_status = vaCreateBuffer(va_dpy, context_id,
1279 VAEncMiscParameterBufferType,
1280 sizeof(VAEncMiscParameterBuffer) + sizeof(VAEncMiscParameterRateControl),
1281 1, NULL, &rc_param_buf);
1282 CHECK_VASTATUS(va_status, "vaCreateBuffer");
1284 vaMapBuffer(va_dpy, rc_param_buf, (void **)&misc_param);
1285 misc_param->type = VAEncMiscParameterTypeRateControl;
1286 misc_rate_ctrl = (VAEncMiscParameterRateControl *)misc_param->data;
1287 memset(misc_rate_ctrl, 0, sizeof(*misc_rate_ctrl));
1288 misc_rate_ctrl->bits_per_second = frame_bitrate;
1289 misc_rate_ctrl->target_percentage = 66;
1290 misc_rate_ctrl->window_size = 1000;
1291 misc_rate_ctrl->initial_qp = initial_qp;
1292 misc_rate_ctrl->min_qp = minimal_qp;
1293 misc_rate_ctrl->basic_unit_size = 0;
1294 vaUnmapBuffer(va_dpy, rc_param_buf);
1296 render_id[0] = seq_param_buf;
1297 render_id[1] = rc_param_buf;
1299 va_status = vaRenderPicture(va_dpy, context_id, &render_id[0], 2);
1300 CHECK_VASTATUS(va_status, "vaRenderPicture");;
1302 if (misc_priv_type != 0) {
1303 va_status = vaCreateBuffer(va_dpy, context_id,
1304 VAEncMiscParameterBufferType,
1305 sizeof(VAEncMiscParameterBuffer),
1306 1, NULL, &misc_param_tmpbuf);
1307 CHECK_VASTATUS(va_status, "vaCreateBuffer");
1308 vaMapBuffer(va_dpy, misc_param_tmpbuf, (void **)&misc_param_tmp);
1309 misc_param_tmp->type = (VAEncMiscParameterType)misc_priv_type;
1310 misc_param_tmp->data[0] = misc_priv_value;
1311 vaUnmapBuffer(va_dpy, misc_param_tmpbuf);
1313 va_status = vaRenderPicture(va_dpy, context_id, &misc_param_tmpbuf, 1);
1319 static int calc_poc(int pic_order_cnt_lsb)
1321 static int PicOrderCntMsb_ref = 0, pic_order_cnt_lsb_ref = 0;
1322 int prevPicOrderCntMsb, prevPicOrderCntLsb;
1323 int PicOrderCntMsb, TopFieldOrderCnt;
1325 if (current_frame_type == FRAME_IDR)
1326 prevPicOrderCntMsb = prevPicOrderCntLsb = 0;
1328 prevPicOrderCntMsb = PicOrderCntMsb_ref;
1329 prevPicOrderCntLsb = pic_order_cnt_lsb_ref;
1332 if ((pic_order_cnt_lsb < prevPicOrderCntLsb) &&
1333 ((prevPicOrderCntLsb - pic_order_cnt_lsb) >= (int)(MaxPicOrderCntLsb / 2)))
1334 PicOrderCntMsb = prevPicOrderCntMsb + MaxPicOrderCntLsb;
1335 else if ((pic_order_cnt_lsb > prevPicOrderCntLsb) &&
1336 ((pic_order_cnt_lsb - prevPicOrderCntLsb) > (int)(MaxPicOrderCntLsb / 2)))
1337 PicOrderCntMsb = prevPicOrderCntMsb - MaxPicOrderCntLsb;
1339 PicOrderCntMsb = prevPicOrderCntMsb;
1341 TopFieldOrderCnt = PicOrderCntMsb + pic_order_cnt_lsb;
1343 if (current_frame_type != FRAME_B) {
1344 PicOrderCntMsb_ref = PicOrderCntMsb;
1345 pic_order_cnt_lsb_ref = pic_order_cnt_lsb;
1348 return TopFieldOrderCnt;
1351 static int render_picture(void)
1353 VABufferID pic_param_buf;
1357 pic_param.CurrPic.picture_id = gl_surfaces[current_frame_display % SURFACE_NUM].ref_surface;
1358 pic_param.CurrPic.frame_idx = current_frame_num;
1359 pic_param.CurrPic.flags = 0;
1360 pic_param.CurrPic.TopFieldOrderCnt = calc_poc((current_frame_display - current_IDR_display) % MaxPicOrderCntLsb);
1361 pic_param.CurrPic.BottomFieldOrderCnt = pic_param.CurrPic.TopFieldOrderCnt;
1362 CurrentCurrPic = pic_param.CurrPic;
1364 if (getenv("TO_DEL")) { /* set RefPicList into ReferenceFrames */
1365 update_RefPicList(); /* calc RefPicList */
1366 memset(pic_param.ReferenceFrames, 0xff, 16 * sizeof(VAPictureH264)); /* invalid all */
1367 if (current_frame_type == FRAME_P) {
1368 pic_param.ReferenceFrames[0] = RefPicList0_P[0];
1369 } else if (current_frame_type == FRAME_B) {
1370 pic_param.ReferenceFrames[0] = RefPicList0_B[0];
1371 pic_param.ReferenceFrames[1] = RefPicList1_B[0];
1374 memcpy(pic_param.ReferenceFrames, ReferenceFrames, numShortTerm*sizeof(VAPictureH264));
1375 for (i = numShortTerm; i < SURFACE_NUM; i++) {
1376 pic_param.ReferenceFrames[i].picture_id = VA_INVALID_SURFACE;
1377 pic_param.ReferenceFrames[i].flags = VA_PICTURE_H264_INVALID;
1381 pic_param.pic_fields.bits.idr_pic_flag = (current_frame_type == FRAME_IDR);
1382 pic_param.pic_fields.bits.reference_pic_flag = (current_frame_type != FRAME_B);
1383 pic_param.pic_fields.bits.entropy_coding_mode_flag = h264_entropy_mode;
1384 pic_param.pic_fields.bits.deblocking_filter_control_present_flag = 1;
1385 pic_param.frame_num = current_frame_num;
1386 pic_param.coded_buf = gl_surfaces[current_frame_display % SURFACE_NUM].coded_buf;
1387 pic_param.last_picture = false; // FIXME
1388 pic_param.pic_init_qp = initial_qp;
1390 va_status = vaCreateBuffer(va_dpy, context_id, VAEncPictureParameterBufferType,
1391 sizeof(pic_param), 1, &pic_param, &pic_param_buf);
1392 CHECK_VASTATUS(va_status, "vaCreateBuffer");;
1394 va_status = vaRenderPicture(va_dpy, context_id, &pic_param_buf, 1);
1395 CHECK_VASTATUS(va_status, "vaRenderPicture");
1400 static int render_packedsequence(void)
1402 VAEncPackedHeaderParameterBuffer packedheader_param_buffer;
1403 VABufferID packedseq_para_bufid, packedseq_data_bufid, render_id[2];
1404 unsigned int length_in_bits;
1405 unsigned char *packedseq_buffer = NULL;
1408 length_in_bits = build_packed_seq_buffer(&packedseq_buffer);
1410 packedheader_param_buffer.type = VAEncPackedHeaderSequence;
1412 packedheader_param_buffer.bit_length = length_in_bits; /*length_in_bits*/
1413 packedheader_param_buffer.has_emulation_bytes = 0;
1414 va_status = vaCreateBuffer(va_dpy,
1416 VAEncPackedHeaderParameterBufferType,
1417 sizeof(packedheader_param_buffer), 1, &packedheader_param_buffer,
1418 &packedseq_para_bufid);
1419 CHECK_VASTATUS(va_status, "vaCreateBuffer");
1421 va_status = vaCreateBuffer(va_dpy,
1423 VAEncPackedHeaderDataBufferType,
1424 (length_in_bits + 7) / 8, 1, packedseq_buffer,
1425 &packedseq_data_bufid);
1426 CHECK_VASTATUS(va_status, "vaCreateBuffer");
1428 render_id[0] = packedseq_para_bufid;
1429 render_id[1] = packedseq_data_bufid;
1430 va_status = vaRenderPicture(va_dpy, context_id, render_id, 2);
1431 CHECK_VASTATUS(va_status, "vaRenderPicture");
1433 free(packedseq_buffer);
1439 static int render_packedpicture(void)
1441 VAEncPackedHeaderParameterBuffer packedheader_param_buffer;
1442 VABufferID packedpic_para_bufid, packedpic_data_bufid, render_id[2];
1443 unsigned int length_in_bits;
1444 unsigned char *packedpic_buffer = NULL;
1447 length_in_bits = build_packed_pic_buffer(&packedpic_buffer);
1448 packedheader_param_buffer.type = VAEncPackedHeaderPicture;
1449 packedheader_param_buffer.bit_length = length_in_bits;
1450 packedheader_param_buffer.has_emulation_bytes = 0;
1452 va_status = vaCreateBuffer(va_dpy,
1454 VAEncPackedHeaderParameterBufferType,
1455 sizeof(packedheader_param_buffer), 1, &packedheader_param_buffer,
1456 &packedpic_para_bufid);
1457 CHECK_VASTATUS(va_status, "vaCreateBuffer");
1459 va_status = vaCreateBuffer(va_dpy,
1461 VAEncPackedHeaderDataBufferType,
1462 (length_in_bits + 7) / 8, 1, packedpic_buffer,
1463 &packedpic_data_bufid);
1464 CHECK_VASTATUS(va_status, "vaCreateBuffer");
1466 render_id[0] = packedpic_para_bufid;
1467 render_id[1] = packedpic_data_bufid;
1468 va_status = vaRenderPicture(va_dpy, context_id, render_id, 2);
1469 CHECK_VASTATUS(va_status, "vaRenderPicture");
1471 free(packedpic_buffer);
1476 static void render_packedslice()
1478 VAEncPackedHeaderParameterBuffer packedheader_param_buffer;
1479 VABufferID packedslice_para_bufid, packedslice_data_bufid, render_id[2];
1480 unsigned int length_in_bits;
1481 unsigned char *packedslice_buffer = NULL;
1484 length_in_bits = build_packed_slice_buffer(&packedslice_buffer);
1485 packedheader_param_buffer.type = VAEncPackedHeaderSlice;
1486 packedheader_param_buffer.bit_length = length_in_bits;
1487 packedheader_param_buffer.has_emulation_bytes = 0;
1489 va_status = vaCreateBuffer(va_dpy,
1491 VAEncPackedHeaderParameterBufferType,
1492 sizeof(packedheader_param_buffer), 1, &packedheader_param_buffer,
1493 &packedslice_para_bufid);
1494 CHECK_VASTATUS(va_status, "vaCreateBuffer");
1496 va_status = vaCreateBuffer(va_dpy,
1498 VAEncPackedHeaderDataBufferType,
1499 (length_in_bits + 7) / 8, 1, packedslice_buffer,
1500 &packedslice_data_bufid);
1501 CHECK_VASTATUS(va_status, "vaCreateBuffer");
1503 render_id[0] = packedslice_para_bufid;
1504 render_id[1] = packedslice_data_bufid;
1505 va_status = vaRenderPicture(va_dpy, context_id, render_id, 2);
1506 CHECK_VASTATUS(va_status, "vaRenderPicture");
1508 free(packedslice_buffer);
1511 static int render_slice(void)
1513 VABufferID slice_param_buf;
1517 update_RefPicList();
1519 /* one frame, one slice */
1520 slice_param.macroblock_address = 0;
1521 slice_param.num_macroblocks = frame_width_mbaligned * frame_height_mbaligned/(16*16); /* Measured by MB */
1522 slice_param.slice_type = (current_frame_type == FRAME_IDR)?2:current_frame_type;
1523 if (current_frame_type == FRAME_IDR) {
1524 if (current_frame_encoding != 0)
1525 ++slice_param.idr_pic_id;
1526 } else if (current_frame_type == FRAME_P) {
1527 int refpiclist0_max = h264_maxref & 0xffff;
1528 memcpy(slice_param.RefPicList0, RefPicList0_P, refpiclist0_max*sizeof(VAPictureH264));
1530 for (i = refpiclist0_max; i < 32; i++) {
1531 slice_param.RefPicList0[i].picture_id = VA_INVALID_SURFACE;
1532 slice_param.RefPicList0[i].flags = VA_PICTURE_H264_INVALID;
1534 } else if (current_frame_type == FRAME_B) {
1535 int refpiclist0_max = h264_maxref & 0xffff;
1536 int refpiclist1_max = (h264_maxref >> 16) & 0xffff;
1538 memcpy(slice_param.RefPicList0, RefPicList0_B, refpiclist0_max*sizeof(VAPictureH264));
1539 for (i = refpiclist0_max; i < 32; i++) {
1540 slice_param.RefPicList0[i].picture_id = VA_INVALID_SURFACE;
1541 slice_param.RefPicList0[i].flags = VA_PICTURE_H264_INVALID;
1544 memcpy(slice_param.RefPicList1, RefPicList1_B, refpiclist1_max*sizeof(VAPictureH264));
1545 for (i = refpiclist1_max; i < 32; i++) {
1546 slice_param.RefPicList1[i].picture_id = VA_INVALID_SURFACE;
1547 slice_param.RefPicList1[i].flags = VA_PICTURE_H264_INVALID;
1551 slice_param.slice_alpha_c0_offset_div2 = 0;
1552 slice_param.slice_beta_offset_div2 = 0;
1553 slice_param.direct_spatial_mv_pred_flag = 1;
1554 slice_param.pic_order_cnt_lsb = (current_frame_display - current_IDR_display) % MaxPicOrderCntLsb;
1557 if (h264_packedheader &&
1558 config_attrib[enc_packed_header_idx].value & VA_ENC_PACKED_HEADER_SLICE)
1559 render_packedslice();
1561 va_status = vaCreateBuffer(va_dpy, context_id, VAEncSliceParameterBufferType,
1562 sizeof(slice_param), 1, &slice_param, &slice_param_buf);
1563 CHECK_VASTATUS(va_status, "vaCreateBuffer");;
1565 va_status = vaRenderPicture(va_dpy, context_id, &slice_param_buf, 1);
1566 CHECK_VASTATUS(va_status, "vaRenderPicture");
1573 int H264Encoder::save_codeddata(storage_task task)
1575 VACodedBufferSegment *buf_list = NULL;
1577 unsigned int coded_size = 0;
1581 va_status = vaMapBuffer(va_dpy, gl_surfaces[task.display_order % SURFACE_NUM].coded_buf, (void **)(&buf_list));
1582 CHECK_VASTATUS(va_status, "vaMapBuffer");
1583 while (buf_list != NULL) {
1584 data.append(reinterpret_cast<const char *>(buf_list->buf), buf_list->size);
1585 buf_list = (VACodedBufferSegment *) buf_list->next;
1587 frame_size += coded_size;
1589 vaUnmapBuffer(va_dpy, gl_surfaces[task.display_order % SURFACE_NUM].coded_buf);
1591 const int64_t pts_dts_delay = (ip_period - 1) * (TIMEBASE / frame_rate);
1592 const int64_t av_delay = TIMEBASE / 30; // Corresponds to the fixed delay in resampler.h. TODO: Make less hard-coded.
1596 unique_lock<mutex> lock(frame_queue_mutex);
1597 assert(timestamps.count(task.display_order));
1598 assert(timestamps.count(task.encode_order));
1599 pts = timestamps[task.display_order];
1600 dts = timestamps[task.encode_order];
1604 memset(&pkt, 0, sizeof(pkt));
1606 pkt.pts = av_rescale_q(pts + av_delay + pts_dts_delay, AVRational{1, TIMEBASE}, avstream_video->time_base);
1607 pkt.dts = av_rescale_q(dts + av_delay, AVRational{1, TIMEBASE}, avstream_video->time_base);
1608 pkt.data = reinterpret_cast<uint8_t *>(&data[0]);
1609 pkt.size = data.size();
1610 pkt.stream_index = 0;
1611 if (task.frame_type == FRAME_IDR || task.frame_type == FRAME_I) {
1612 pkt.flags = AV_PKT_FLAG_KEY;
1617 av_interleaved_write_frame(avctx, &pkt);
1619 // Encode and add all audio frames up to and including the pts of this video frame.
1620 // (They can never be queued to us after the video frame they belong to, only before.)
1624 std::vector<float> audio;
1626 unique_lock<mutex> lock(frame_queue_mutex);
1627 if (pending_audio_frames.empty()) break;
1628 auto it = pending_audio_frames.begin();
1629 if (it->first > int(task.display_order)) break;
1630 display_order = it->first;
1631 audio = move(it->second);
1632 pending_audio_frames.erase(it);
1634 auto pts_it = timestamps.find(display_order);
1635 assert(pts_it != timestamps.end());
1636 pts = pts_it->second;
1638 AVFrame *frame = avcodec_alloc_frame();
1639 frame->nb_samples = audio.size() / 2;
1640 frame->format = AV_SAMPLE_FMT_FLT;
1641 frame->channel_layout = AV_CH_LAYOUT_STEREO;
1643 unique_ptr<float[]> planar_samples(new float[audio.size()]);
1644 avcodec_fill_audio_frame(frame, 2, AV_SAMPLE_FMT_FLTP, (const uint8_t*)planar_samples.get(), audio.size() * sizeof(float), 0);
1645 for (int i = 0; i < frame->nb_samples; ++i) {
1646 planar_samples[i] = audio[i * 2 + 0];
1647 planar_samples[i + frame->nb_samples] = audio[i * 2 + 1];
1651 av_init_packet(&pkt);
1655 avcodec_encode_audio2(avstream_audio->codec, &pkt, frame, &got_output);
1657 pkt.pts = av_rescale_q(pts + pts_dts_delay, AVRational{1, TIMEBASE}, avstream_audio->time_base);
1659 pkt.stream_index = 1;
1660 av_interleaved_write_frame(avctx, &pkt);
1662 // TODO: Delayed frames.
1663 avcodec_free_frame(&frame);
1666 unique_lock<mutex> lock(frame_queue_mutex);
1667 timestamps.erase(task.encode_order - (ip_period - 1));
1671 printf("\r "); /* return back to startpoint */
1672 switch (encode_order % 4) {
1686 printf("%08lld", encode_order);
1687 printf("(%06d bytes coded)", coded_size);
1694 // this is weird. but it seems to put a new frame onto the queue
1695 void H264Encoder::storage_task_enqueue(storage_task task)
1697 std::unique_lock<std::mutex> lock(storage_task_queue_mutex);
1698 storage_task_queue.push(move(task));
1699 srcsurface_status[task.display_order % SURFACE_NUM] = SRC_SURFACE_IN_ENCODING;
1700 storage_task_queue_changed.notify_all();
1703 void H264Encoder::storage_task_thread()
1706 storage_task current;
1708 // wait until there's an encoded frame
1709 std::unique_lock<std::mutex> lock(storage_task_queue_mutex);
1710 storage_task_queue_changed.wait(lock, [this]{ return storage_thread_should_quit || !storage_task_queue.empty(); });
1711 if (storage_thread_should_quit) return;
1712 current = move(storage_task_queue.front());
1713 storage_task_queue.pop();
1718 // waits for data, then saves it to disk.
1719 va_status = vaSyncSurface(va_dpy, gl_surfaces[current.display_order % SURFACE_NUM].src_surface);
1720 CHECK_VASTATUS(va_status, "vaSyncSurface");
1721 save_codeddata(move(current));
1724 std::unique_lock<std::mutex> lock(storage_task_queue_mutex);
1725 srcsurface_status[current.display_order % SURFACE_NUM] = SRC_SURFACE_FREE;
1726 storage_task_queue_changed.notify_all();
1731 static int release_encode()
1735 for (i = 0; i < SURFACE_NUM; i++) {
1736 vaDestroyBuffer(va_dpy, gl_surfaces[i].coded_buf);
1737 vaDestroySurfaces(va_dpy, &gl_surfaces[i].src_surface, 1);
1738 vaDestroySurfaces(va_dpy, &gl_surfaces[i].ref_surface, 1);
1741 vaDestroyContext(va_dpy, context_id);
1742 vaDestroyConfig(va_dpy, config_id);
1747 static int deinit_va()
1749 vaTerminate(va_dpy);
1751 va_close_display(va_dpy);
1757 static int print_input()
1759 printf("\n\nINPUT:Try to encode H264...\n");
1761 printf("INPUT: RateControl : %s\n", rc_to_string(rc_mode));
1762 printf("INPUT: Resolution : %dx%dframes\n", frame_width, frame_height);
1763 printf("INPUT: FrameRate : %d\n", frame_rate);
1764 printf("INPUT: Bitrate : %d\n", frame_bitrate);
1765 printf("INPUT: Slieces : %d\n", frame_slices);
1766 printf("INPUT: IntraPeriod : %d\n", intra_period);
1767 printf("INPUT: IDRPeriod : %d\n", intra_idr_period);
1768 printf("INPUT: IpPeriod : %d\n", ip_period);
1769 printf("INPUT: Initial QP : %d\n", initial_qp);
1770 printf("INPUT: Min QP : %d\n", minimal_qp);
1771 printf("INPUT: Coded Clip : %s\n", coded_fn);
1773 printf("\n\n"); /* return back to startpoint */
1779 //H264Encoder::H264Encoder(SDL_Window *window, SDL_GLContext context, int width, int height, const char *output_filename)
1780 H264Encoder::H264Encoder(QSurface *surface, int width, int height, const char *output_filename)
1781 : current_storage_frame(0), surface(surface)
1782 //: width(width), height(height), current_encoding_frame(0)
1785 avctx = avformat_alloc_context();
1786 avctx->oformat = av_guess_format(NULL, output_filename, NULL);
1787 strcpy(avctx->filename, output_filename);
1788 if (avio_open2(&avctx->pb, output_filename, AVIO_FLAG_WRITE, &avctx->interrupt_callback, NULL) < 0) {
1789 fprintf(stderr, "%s: avio_open2() failed\n", output_filename);
1792 AVCodec *codec_video = avcodec_find_encoder(AV_CODEC_ID_H264);
1793 avstream_video = avformat_new_stream(avctx, codec_video);
1794 if (avstream_video == nullptr) {
1795 fprintf(stderr, "%s: avformat_new_stream() failed\n", output_filename);
1798 avstream_video->time_base = AVRational{1, TIMEBASE};
1799 avstream_video->codec->width = width;
1800 avstream_video->codec->height = height;
1801 avstream_video->codec->time_base = AVRational{1, TIMEBASE};
1802 avstream_video->codec->ticks_per_frame = 1; // or 2?
1804 AVCodec *codec_audio = avcodec_find_encoder(AV_CODEC_ID_MP3);
1805 avstream_audio = avformat_new_stream(avctx, codec_audio);
1806 if (avstream_audio == nullptr) {
1807 fprintf(stderr, "%s: avformat_new_stream() failed\n", output_filename);
1810 avstream_audio->time_base = AVRational{1, TIMEBASE};
1811 avstream_audio->codec->bit_rate = 256000;
1812 avstream_audio->codec->sample_rate = 48000;
1813 avstream_audio->codec->sample_fmt = AV_SAMPLE_FMT_FLTP;
1814 avstream_audio->codec->channels = 2;
1815 avstream_audio->codec->channel_layout = AV_CH_LAYOUT_STEREO;
1816 avstream_audio->codec->time_base = AVRational{1, TIMEBASE};
1819 if (avcodec_open2(avstream_audio->codec, codec_audio, NULL) < 0) {
1820 fprintf(stderr, "Could not open codec\n");
1824 if (avformat_write_header(avctx, NULL) < 0) {
1825 fprintf(stderr, "%s: avformat_write_header() failed\n", output_filename);
1829 frame_width = width;
1830 frame_height = height;
1831 frame_width_mbaligned = (frame_width + 15) & (~15);
1832 frame_height_mbaligned = (frame_height + 15) & (~15);
1833 frame_bitrate = 15000000; // / 60;
1834 current_frame_encoding = 0;
1841 // No frames are ready yet.
1842 memset(srcsurface_status, SRC_SURFACE_FREE, sizeof(srcsurface_status));
1844 memset(&seq_param, 0, sizeof(seq_param));
1845 memset(&pic_param, 0, sizeof(pic_param));
1846 memset(&slice_param, 0, sizeof(slice_param));
1848 storage_thread = std::thread(&H264Encoder::storage_task_thread, this);
1850 copy_thread = std::thread([this]{
1851 //SDL_GL_MakeCurrent(window, context);
1852 QOpenGLContext *context = create_context();
1853 eglBindAPI(EGL_OPENGL_API);
1854 if (!make_current(context, this->surface)) {
1855 printf("display=%p surface=%p context=%p curr=%p err=%d\n", eglGetCurrentDisplay(), this->surface, context, eglGetCurrentContext(),
1863 H264Encoder::~H264Encoder()
1866 unique_lock<mutex> lock(storage_task_queue_mutex);
1867 storage_thread_should_quit = true;
1868 storage_task_queue_changed.notify_all();
1871 unique_lock<mutex> lock(frame_queue_mutex);
1872 copy_thread_should_quit = true;
1873 frame_queue_nonempty.notify_one();
1875 storage_thread.join();
1881 av_write_trailer(avctx);
1882 avformat_free_context(avctx);
1885 bool H264Encoder::begin_frame(GLuint *y_tex, GLuint *cbcr_tex)
1888 // Wait until this frame slot is done encoding.
1889 std::unique_lock<std::mutex> lock(storage_task_queue_mutex);
1890 storage_task_queue_changed.wait(lock, [this]{ return storage_thread_should_quit || (srcsurface_status[current_storage_frame % SURFACE_NUM] == SRC_SURFACE_FREE); });
1891 if (storage_thread_should_quit) return false;
1894 //*fbo = fbos[current_storage_frame % SURFACE_NUM];
1895 GLSurface *surf = &gl_surfaces[current_storage_frame % SURFACE_NUM];
1896 *y_tex = surf->y_tex;
1897 *cbcr_tex = surf->cbcr_tex;
1899 VASurfaceID surface = surf->src_surface;
1900 VAStatus va_status = vaDeriveImage(va_dpy, surface, &surf->surface_image);
1901 CHECK_VASTATUS(va_status, "vaDeriveImage");
1903 VABufferInfo buf_info;
1904 buf_info.mem_type = VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME; // or VA_SURFACE_ATTRIB_MEM_TYPE_KERNEL_DRM?
1905 va_status = vaAcquireBufferHandle(va_dpy, surf->surface_image.buf, &buf_info);
1906 CHECK_VASTATUS(va_status, "vaAcquireBufferHandle");
1909 surf->y_egl_image = EGL_NO_IMAGE_KHR;
1910 EGLint y_attribs[] = {
1911 EGL_WIDTH, frame_width,
1912 EGL_HEIGHT, frame_height,
1913 EGL_LINUX_DRM_FOURCC_EXT, fourcc_code('R', '8', ' ', ' '),
1914 EGL_DMA_BUF_PLANE0_FD_EXT, EGLint(buf_info.handle),
1915 EGL_DMA_BUF_PLANE0_OFFSET_EXT, EGLint(surf->surface_image.offsets[0]),
1916 EGL_DMA_BUF_PLANE0_PITCH_EXT, EGLint(surf->surface_image.pitches[0]),
1920 surf->y_egl_image = eglCreateImageKHR(eglGetCurrentDisplay(), EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, NULL, y_attribs);
1921 assert(surf->y_egl_image != EGL_NO_IMAGE_KHR);
1923 // Associate Y image to a texture.
1924 glBindTexture(GL_TEXTURE_2D, *y_tex);
1925 glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, surf->y_egl_image);
1927 // Create CbCr image.
1928 surf->cbcr_egl_image = EGL_NO_IMAGE_KHR;
1929 EGLint cbcr_attribs[] = {
1930 EGL_WIDTH, frame_width,
1931 EGL_HEIGHT, frame_height,
1932 EGL_LINUX_DRM_FOURCC_EXT, fourcc_code('G', 'R', '8', '8'),
1933 EGL_DMA_BUF_PLANE0_FD_EXT, EGLint(buf_info.handle),
1934 EGL_DMA_BUF_PLANE0_OFFSET_EXT, EGLint(surf->surface_image.offsets[1]),
1935 EGL_DMA_BUF_PLANE0_PITCH_EXT, EGLint(surf->surface_image.pitches[1]),
1939 surf->cbcr_egl_image = eglCreateImageKHR(eglGetCurrentDisplay(), EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, NULL, cbcr_attribs);
1940 assert(surf->cbcr_egl_image != EGL_NO_IMAGE_KHR);
1942 // Associate CbCr image to a texture.
1943 glBindTexture(GL_TEXTURE_2D, *cbcr_tex);
1944 glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, surf->cbcr_egl_image);
1949 void H264Encoder::end_frame(RefCountedGLsync fence, int64_t pts, std::vector<float> audio, const std::vector<RefCountedFrame> &input_frames)
1952 unique_lock<mutex> lock(frame_queue_mutex);
1953 pending_video_frames[current_storage_frame] = PendingFrame{ fence, input_frames };
1954 pending_audio_frames[current_storage_frame] = move(audio);
1955 timestamps[current_storage_frame] = pts;
1956 ++current_storage_frame;
1958 frame_queue_nonempty.notify_one();
1961 void H264Encoder::copy_thread_func()
1965 encoding2display_order(current_frame_encoding, intra_period, intra_idr_period, ip_period,
1966 ¤t_frame_display, ¤t_frame_type);
1967 if (current_frame_type == FRAME_IDR) {
1969 current_frame_num = 0;
1970 current_IDR_display = current_frame_display;
1974 unique_lock<mutex> lock(frame_queue_mutex);
1975 frame_queue_nonempty.wait(lock, [this]{ return copy_thread_should_quit || pending_video_frames.count(current_frame_display) != 0; });
1976 if (copy_thread_should_quit) return;
1977 frame = move(pending_video_frames[current_frame_display]);
1978 pending_video_frames.erase(current_frame_display);
1981 // Wait for the GPU to be done with the frame.
1982 glClientWaitSync(frame.fence.get(), 0, 0);
1984 // Release back any input frames we needed to render this frame.
1985 frame.input_frames.clear();
1988 GLSurface *surf = &gl_surfaces[current_frame_display % SURFACE_NUM];
1989 eglDestroyImageKHR(eglGetCurrentDisplay(), surf->y_egl_image);
1990 eglDestroyImageKHR(eglGetCurrentDisplay(), surf->cbcr_egl_image);
1991 VAStatus va_status = vaReleaseBufferHandle(va_dpy, surf->surface_image.buf);
1992 CHECK_VASTATUS(va_status, "vaReleaseBufferHandle");
1993 va_status = vaDestroyImage(va_dpy, surf->surface_image.image_id);
1994 CHECK_VASTATUS(va_status, "vaDestroyImage");
1996 VASurfaceID surface = surf->src_surface;
1998 // Schedule the frame for encoding.
1999 va_status = vaBeginPicture(va_dpy, context_id, surface);
2000 CHECK_VASTATUS(va_status, "vaBeginPicture");
2002 if (current_frame_type == FRAME_IDR) {
2005 if (h264_packedheader) {
2006 render_packedsequence();
2007 render_packedpicture();
2010 //render_sequence();
2015 va_status = vaEndPicture(va_dpy, context_id);
2016 CHECK_VASTATUS(va_status, "vaEndPicture");
2018 // so now the data is done encoding (well, async job kicked off)...
2019 // we send that to the storage thread
2021 tmp.display_order = current_frame_display;
2022 tmp.encode_order = current_frame_encoding;
2023 tmp.frame_type = current_frame_type;
2024 storage_task_enqueue(move(tmp));
2026 update_ReferenceFrames();
2027 ++current_frame_encoding;