2 * Copyright (c) 2007-2013 Intel Corporation. All Rights Reserved.
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sub license, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
12 * The above copyright notice and this permission notice (including the
13 * next paragraph) shall be included in all copies or substantial portions
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
19 * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR
20 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 #include <sys/types.h>
40 #include <va/va_enc_h264.h>
41 #include "va_display.h"
43 #define CHECK_VASTATUS(va_status,func) \
44 if (va_status != VA_STATUS_SUCCESS) { \
45 fprintf(stderr,"%s:%s (%d) failed,exit\n", __func__, func, __LINE__); \
49 #include "../loadsurface.h"
51 #define NAL_REF_IDC_NONE 0
52 #define NAL_REF_IDC_LOW 1
53 #define NAL_REF_IDC_MEDIUM 2
54 #define NAL_REF_IDC_HIGH 3
62 #define SLICE_TYPE_P 0
63 #define SLICE_TYPE_B 1
64 #define SLICE_TYPE_I 2
66 #define ENTROPY_MODE_CAVLC 0
67 #define ENTROPY_MODE_CABAC 1
69 #define PROFILE_IDC_BASELINE 66
70 #define PROFILE_IDC_MAIN 77
71 #define PROFILE_IDC_HIGH 100
73 #define BITSTREAM_ALLOCATE_STEPPING 4096
75 #define SURFACE_NUM 16 /* 16 surfaces for source YUV */
76 #define SURFACE_NUM 16 /* 16 surfaces for reference */
77 static VADisplay va_dpy;
78 static VAProfile h264_profile;
79 static VAConfigAttrib attrib[VAConfigAttribTypeMax];
80 static VAConfigAttrib config_attrib[VAConfigAttribTypeMax];
81 static int config_attrib_num = 0;
82 static VASurfaceID src_surface[SURFACE_NUM];
83 static VABufferID coded_buf[SURFACE_NUM];
84 static VASurfaceID ref_surface[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 char *coded_fn = NULL, *srcyuv_fn = NULL, *recyuv_fn = NULL;
104 static FILE *coded_fp = NULL, *srcyuv_fp = NULL, *recyuv_fp = NULL;
105 static unsigned long long srcyuv_frames = 0;
106 static int srcyuv_fourcc = VA_FOURCC_NV12;
107 static int calc_psnr = 0;
109 static int frame_width = 176;
110 static int frame_height = 144;
111 static int frame_rate = 30;
112 static unsigned int frame_count = 60;
113 static unsigned int frame_coded = 0;
114 static unsigned int frame_bitrate = 0;
115 static unsigned int frame_slices = 1;
116 static double frame_size = 0;
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 = VA_RC_VBR;
123 static unsigned long long current_frame_encoding = 0;
124 static unsigned long long current_frame_display = 0;
125 static unsigned long long current_IDR_display = 0;
126 static unsigned int current_frame_num = 0;
127 static int current_frame_type;
128 #define current_slot (current_frame_display % SURFACE_NUM)
130 #define MIN(a, b) ((a)>(b)?(b):(a))
131 #define MAX(a, b) ((a)>(b)?(a):(b))
133 /* thread to save coded data/upload source YUV */
134 struct storage_task_t {
136 unsigned long long display_order;
137 unsigned long long encode_order;
139 static struct storage_task_t *storage_task_header = NULL, *storage_task_tail = NULL;
140 #define SRC_SURFACE_IN_ENCODING 0
141 #define SRC_SURFACE_IN_STORAGE 1
142 static int srcsurface_status[SURFACE_NUM];
143 static int encode_syncmode = 0;
144 static pthread_mutex_t encode_mutex = PTHREAD_MUTEX_INITIALIZER;
145 static pthread_cond_t encode_cond = PTHREAD_COND_INITIALIZER;
146 static pthread_t encode_thread;
148 /* for performance profiling */
149 static unsigned int UploadPictureTicks=0;
150 static unsigned int BeginPictureTicks=0;
151 static unsigned int RenderPictureTicks=0;
152 static unsigned int EndPictureTicks=0;
153 static unsigned int SyncPictureTicks=0;
154 static unsigned int SavePictureTicks=0;
155 static unsigned int TotalTicks=0;
158 unsigned int *buffer;
160 int max_size_in_dword;
162 typedef struct __bitstream bitstream;
166 va_swap32(unsigned int val)
168 unsigned char *pval = (unsigned char *)&val;
170 return ((pval[0] << 24) |
177 bitstream_start(bitstream *bs)
179 bs->max_size_in_dword = BITSTREAM_ALLOCATE_STEPPING;
180 bs->buffer = calloc(bs->max_size_in_dword * sizeof(int), 1);
185 bitstream_end(bitstream *bs)
187 int pos = (bs->bit_offset >> 5);
188 int bit_offset = (bs->bit_offset & 0x1f);
189 int bit_left = 32 - bit_offset;
192 bs->buffer[pos] = va_swap32((bs->buffer[pos] << bit_left));
197 bitstream_put_ui(bitstream *bs, unsigned int val, int size_in_bits)
199 int pos = (bs->bit_offset >> 5);
200 int bit_offset = (bs->bit_offset & 0x1f);
201 int bit_left = 32 - bit_offset;
206 bs->bit_offset += size_in_bits;
208 if (bit_left > size_in_bits) {
209 bs->buffer[pos] = (bs->buffer[pos] << size_in_bits | val);
211 size_in_bits -= bit_left;
212 bs->buffer[pos] = (bs->buffer[pos] << bit_left) | (val >> size_in_bits);
213 bs->buffer[pos] = va_swap32(bs->buffer[pos]);
215 if (pos + 1 == bs->max_size_in_dword) {
216 bs->max_size_in_dword += BITSTREAM_ALLOCATE_STEPPING;
217 bs->buffer = realloc(bs->buffer, bs->max_size_in_dword * sizeof(unsigned int));
220 bs->buffer[pos + 1] = val;
225 bitstream_put_ue(bitstream *bs, unsigned int val)
227 int size_in_bits = 0;
235 bitstream_put_ui(bs, 0, size_in_bits - 1); // leading zero
236 bitstream_put_ui(bs, val, size_in_bits);
240 bitstream_put_se(bitstream *bs, int val)
242 unsigned int new_val;
247 new_val = 2 * val - 1;
249 bitstream_put_ue(bs, new_val);
253 bitstream_byte_aligning(bitstream *bs, int bit)
255 int bit_offset = (bs->bit_offset & 0x7);
256 int bit_left = 8 - bit_offset;
262 assert(bit == 0 || bit == 1);
265 new_val = (1 << bit_left) - 1;
269 bitstream_put_ui(bs, new_val, bit_left);
273 rbsp_trailing_bits(bitstream *bs)
275 bitstream_put_ui(bs, 1, 1);
276 bitstream_byte_aligning(bs, 0);
279 static void nal_start_code_prefix(bitstream *bs)
281 bitstream_put_ui(bs, 0x00000001, 32);
284 static void nal_header(bitstream *bs, int nal_ref_idc, int nal_unit_type)
286 bitstream_put_ui(bs, 0, 1); /* forbidden_zero_bit: 0 */
287 bitstream_put_ui(bs, nal_ref_idc, 2);
288 bitstream_put_ui(bs, nal_unit_type, 5);
291 static void sps_rbsp(bitstream *bs)
293 int profile_idc = PROFILE_IDC_BASELINE;
295 if (h264_profile == VAProfileH264High)
296 profile_idc = PROFILE_IDC_HIGH;
297 else if (h264_profile == VAProfileH264Main)
298 profile_idc = PROFILE_IDC_MAIN;
300 bitstream_put_ui(bs, profile_idc, 8); /* profile_idc */
301 bitstream_put_ui(bs, !!(constraint_set_flag & 1), 1); /* constraint_set0_flag */
302 bitstream_put_ui(bs, !!(constraint_set_flag & 2), 1); /* constraint_set1_flag */
303 bitstream_put_ui(bs, !!(constraint_set_flag & 4), 1); /* constraint_set2_flag */
304 bitstream_put_ui(bs, !!(constraint_set_flag & 8), 1); /* constraint_set3_flag */
305 bitstream_put_ui(bs, 0, 4); /* reserved_zero_4bits */
306 bitstream_put_ui(bs, seq_param.level_idc, 8); /* level_idc */
307 bitstream_put_ue(bs, seq_param.seq_parameter_set_id); /* seq_parameter_set_id */
309 if ( profile_idc == PROFILE_IDC_HIGH) {
310 bitstream_put_ue(bs, 1); /* chroma_format_idc = 1, 4:2:0 */
311 bitstream_put_ue(bs, 0); /* bit_depth_luma_minus8 */
312 bitstream_put_ue(bs, 0); /* bit_depth_chroma_minus8 */
313 bitstream_put_ui(bs, 0, 1); /* qpprime_y_zero_transform_bypass_flag */
314 bitstream_put_ui(bs, 0, 1); /* seq_scaling_matrix_present_flag */
317 bitstream_put_ue(bs, seq_param.seq_fields.bits.log2_max_frame_num_minus4); /* log2_max_frame_num_minus4 */
318 bitstream_put_ue(bs, seq_param.seq_fields.bits.pic_order_cnt_type); /* pic_order_cnt_type */
320 if (seq_param.seq_fields.bits.pic_order_cnt_type == 0)
321 bitstream_put_ue(bs, seq_param.seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4); /* log2_max_pic_order_cnt_lsb_minus4 */
326 bitstream_put_ue(bs, seq_param.max_num_ref_frames); /* num_ref_frames */
327 bitstream_put_ui(bs, 0, 1); /* gaps_in_frame_num_value_allowed_flag */
329 bitstream_put_ue(bs, seq_param.picture_width_in_mbs - 1); /* pic_width_in_mbs_minus1 */
330 bitstream_put_ue(bs, seq_param.picture_height_in_mbs - 1); /* pic_height_in_map_units_minus1 */
331 bitstream_put_ui(bs, seq_param.seq_fields.bits.frame_mbs_only_flag, 1); /* frame_mbs_only_flag */
333 if (!seq_param.seq_fields.bits.frame_mbs_only_flag) {
337 bitstream_put_ui(bs, seq_param.seq_fields.bits.direct_8x8_inference_flag, 1); /* direct_8x8_inference_flag */
338 bitstream_put_ui(bs, seq_param.frame_cropping_flag, 1); /* frame_cropping_flag */
340 if (seq_param.frame_cropping_flag) {
341 bitstream_put_ue(bs, seq_param.frame_crop_left_offset); /* frame_crop_left_offset */
342 bitstream_put_ue(bs, seq_param.frame_crop_right_offset); /* frame_crop_right_offset */
343 bitstream_put_ue(bs, seq_param.frame_crop_top_offset); /* frame_crop_top_offset */
344 bitstream_put_ue(bs, seq_param.frame_crop_bottom_offset); /* frame_crop_bottom_offset */
347 //if ( frame_bit_rate < 0 ) { //TODO EW: the vui header isn't correct
349 bitstream_put_ui(bs, 0, 1); /* vui_parameters_present_flag */
351 bitstream_put_ui(bs, 1, 1); /* vui_parameters_present_flag */
352 bitstream_put_ui(bs, 0, 1); /* aspect_ratio_info_present_flag */
353 bitstream_put_ui(bs, 0, 1); /* overscan_info_present_flag */
354 bitstream_put_ui(bs, 0, 1); /* video_signal_type_present_flag */
355 bitstream_put_ui(bs, 0, 1); /* chroma_loc_info_present_flag */
356 bitstream_put_ui(bs, 1, 1); /* timing_info_present_flag */
358 bitstream_put_ui(bs, 15, 32);
359 bitstream_put_ui(bs, 900, 32);
360 bitstream_put_ui(bs, 1, 1);
362 bitstream_put_ui(bs, 1, 1); /* nal_hrd_parameters_present_flag */
365 bitstream_put_ue(bs, 0); /* cpb_cnt_minus1 */
366 bitstream_put_ui(bs, 4, 4); /* bit_rate_scale */
367 bitstream_put_ui(bs, 6, 4); /* cpb_size_scale */
369 bitstream_put_ue(bs, frame_bitrate - 1); /* bit_rate_value_minus1[0] */
370 bitstream_put_ue(bs, frame_bitrate*8 - 1); /* cpb_size_value_minus1[0] */
371 bitstream_put_ui(bs, 1, 1); /* cbr_flag[0] */
373 bitstream_put_ui(bs, 23, 5); /* initial_cpb_removal_delay_length_minus1 */
374 bitstream_put_ui(bs, 23, 5); /* cpb_removal_delay_length_minus1 */
375 bitstream_put_ui(bs, 23, 5); /* dpb_output_delay_length_minus1 */
376 bitstream_put_ui(bs, 23, 5); /* time_offset_length */
378 bitstream_put_ui(bs, 0, 1); /* vcl_hrd_parameters_present_flag */
379 bitstream_put_ui(bs, 0, 1); /* low_delay_hrd_flag */
381 bitstream_put_ui(bs, 0, 1); /* pic_struct_present_flag */
382 bitstream_put_ui(bs, 0, 1); /* bitstream_restriction_flag */
385 rbsp_trailing_bits(bs); /* rbsp_trailing_bits */
389 static void pps_rbsp(bitstream *bs)
391 bitstream_put_ue(bs, pic_param.pic_parameter_set_id); /* pic_parameter_set_id */
392 bitstream_put_ue(bs, pic_param.seq_parameter_set_id); /* seq_parameter_set_id */
394 bitstream_put_ui(bs, pic_param.pic_fields.bits.entropy_coding_mode_flag, 1); /* entropy_coding_mode_flag */
396 bitstream_put_ui(bs, 0, 1); /* pic_order_present_flag: 0 */
398 bitstream_put_ue(bs, 0); /* num_slice_groups_minus1 */
400 bitstream_put_ue(bs, pic_param.num_ref_idx_l0_active_minus1); /* num_ref_idx_l0_active_minus1 */
401 bitstream_put_ue(bs, pic_param.num_ref_idx_l1_active_minus1); /* num_ref_idx_l1_active_minus1 1 */
403 bitstream_put_ui(bs, pic_param.pic_fields.bits.weighted_pred_flag, 1); /* weighted_pred_flag: 0 */
404 bitstream_put_ui(bs, pic_param.pic_fields.bits.weighted_bipred_idc, 2); /* weighted_bipred_idc: 0 */
406 bitstream_put_se(bs, pic_param.pic_init_qp - 26); /* pic_init_qp_minus26 */
407 bitstream_put_se(bs, 0); /* pic_init_qs_minus26 */
408 bitstream_put_se(bs, 0); /* chroma_qp_index_offset */
410 bitstream_put_ui(bs, pic_param.pic_fields.bits.deblocking_filter_control_present_flag, 1); /* deblocking_filter_control_present_flag */
411 bitstream_put_ui(bs, 0, 1); /* constrained_intra_pred_flag */
412 bitstream_put_ui(bs, 0, 1); /* redundant_pic_cnt_present_flag */
415 bitstream_put_ui(bs, pic_param.pic_fields.bits.transform_8x8_mode_flag, 1); /*transform_8x8_mode_flag */
416 bitstream_put_ui(bs, 0, 1); /* pic_scaling_matrix_present_flag */
417 bitstream_put_se(bs, pic_param.second_chroma_qp_index_offset ); /*second_chroma_qp_index_offset */
419 rbsp_trailing_bits(bs);
424 build_packed_pic_buffer(unsigned char **header_buffer)
428 bitstream_start(&bs);
429 nal_start_code_prefix(&bs);
430 nal_header(&bs, NAL_REF_IDC_HIGH, NAL_PPS);
434 *header_buffer = (unsigned char *)bs.buffer;
435 return bs.bit_offset;
439 build_packed_seq_buffer(unsigned char **header_buffer)
443 bitstream_start(&bs);
444 nal_start_code_prefix(&bs);
445 nal_header(&bs, NAL_REF_IDC_HIGH, NAL_SPS);
449 *header_buffer = (unsigned char *)bs.buffer;
450 return bs.bit_offset;
454 build_packed_sei_buffer_timing(unsigned int init_cpb_removal_length,
455 unsigned int init_cpb_removal_delay,
456 unsigned int init_cpb_removal_delay_offset,
457 unsigned int cpb_removal_length,
458 unsigned int cpb_removal_delay,
459 unsigned int dpb_output_length,
460 unsigned int dpb_output_delay,
461 unsigned char **sei_buffer)
463 unsigned char *byte_buf;
464 int bp_byte_size, i, pic_byte_size;
467 bitstream sei_bp_bs, sei_pic_bs;
469 bitstream_start(&sei_bp_bs);
470 bitstream_put_ue(&sei_bp_bs, 0); /*seq_parameter_set_id*/
471 bitstream_put_ui(&sei_bp_bs, init_cpb_removal_delay, cpb_removal_length);
472 bitstream_put_ui(&sei_bp_bs, init_cpb_removal_delay_offset, cpb_removal_length);
473 if ( sei_bp_bs.bit_offset & 0x7) {
474 bitstream_put_ui(&sei_bp_bs, 1, 1);
476 bitstream_end(&sei_bp_bs);
477 bp_byte_size = (sei_bp_bs.bit_offset + 7) / 8;
479 bitstream_start(&sei_pic_bs);
480 bitstream_put_ui(&sei_pic_bs, cpb_removal_delay, cpb_removal_length);
481 bitstream_put_ui(&sei_pic_bs, dpb_output_delay, dpb_output_length);
482 if ( sei_pic_bs.bit_offset & 0x7) {
483 bitstream_put_ui(&sei_pic_bs, 1, 1);
485 bitstream_end(&sei_pic_bs);
486 pic_byte_size = (sei_pic_bs.bit_offset + 7) / 8;
488 bitstream_start(&nal_bs);
489 nal_start_code_prefix(&nal_bs);
490 nal_header(&nal_bs, NAL_REF_IDC_NONE, NAL_SEI);
492 /* Write the SEI buffer period data */
493 bitstream_put_ui(&nal_bs, 0, 8);
494 bitstream_put_ui(&nal_bs, bp_byte_size, 8);
496 byte_buf = (unsigned char *)sei_bp_bs.buffer;
497 for(i = 0; i < bp_byte_size; i++) {
498 bitstream_put_ui(&nal_bs, byte_buf[i], 8);
501 /* write the SEI timing data */
502 bitstream_put_ui(&nal_bs, 0x01, 8);
503 bitstream_put_ui(&nal_bs, pic_byte_size, 8);
505 byte_buf = (unsigned char *)sei_pic_bs.buffer;
506 for(i = 0; i < pic_byte_size; i++) {
507 bitstream_put_ui(&nal_bs, byte_buf[i], 8);
511 rbsp_trailing_bits(&nal_bs);
512 bitstream_end(&nal_bs);
514 *sei_buffer = (unsigned char *)nal_bs.buffer;
516 return nal_bs.bit_offset;
522 * Helper function for profiling purposes
524 static unsigned int GetTickCount()
527 if (gettimeofday(&tv, NULL))
529 return tv.tv_usec/1000+tv.tv_sec*1000;
533 Assume frame sequence is: Frame#0,#1,#2,...,#M,...,#X,... (encoding order)
534 1) period between Frame #X and Frame #N = #X - #N
535 2) 0 means infinite for intra_period/intra_idr_period, and 0 is invalid for ip_period
536 3) intra_idr_period % intra_period (intra_period > 0) and intra_period % ip_period must be 0
537 4) intra_period and intra_idr_period take precedence over ip_period
538 5) if ip_period > 1, intra_period and intra_idr_period are not the strict periods
539 of I/IDR frames, see bellow examples
540 -------------------------------------------------------------------
541 intra_period intra_idr_period ip_period frame sequence (intra_period/intra_idr_period/ip_period)
542 0 ignored 1 IDRPPPPPPP ... (No IDR/I any more)
543 0 ignored >=2 IDR(PBB)(PBB)... (No IDR/I any more)
544 1 0 ignored IDRIIIIIII... (No IDR any more)
545 1 1 ignored IDR IDR IDR IDR...
546 1 >=2 ignored IDRII IDRII IDR... (1/3/ignore)
547 >=2 0 1 IDRPPP IPPP I... (3/0/1)
548 >=2 0 >=2 IDR(PBB)(PBB)(IBB) (6/0/3)
549 (PBB)(IBB)(PBB)(IBB)...
550 >=2 >=2 1 IDRPPPPP IPPPPP IPPPPP (6/18/1)
551 IDRPPPPP IPPPPP IPPPPP...
552 >=2 >=2 >=2 {IDR(PBB)(PBB)(IBB)(PBB)(IBB)(PBB)} (6/18/3)
553 {IDR(PBB)(PBB)(IBB)(PBB)(IBB)(PBB)}...
554 {IDR(PBB)(PBB)(IBB)(PBB)} (6/12/3)
555 {IDR(PBB)(PBB)(IBB)(PBB)}...
556 {IDR(PBB)(PBB)} (6/6/3)
561 * Return displaying order with specified periods and encoding order
562 * displaying_order: displaying order
563 * frame_type: frame type
569 void encoding2display_order(
570 unsigned long long encoding_order,int intra_period,
571 int intra_idr_period,int ip_period,
572 unsigned long long *displaying_order,
575 int encoding_order_gop = 0;
577 if (intra_period == 1) { /* all are I/IDR frames */
578 *displaying_order = encoding_order;
579 if (intra_idr_period == 0)
580 *frame_type = (encoding_order == 0)?FRAME_IDR:FRAME_I;
582 *frame_type = (encoding_order % intra_idr_period == 0)?FRAME_IDR:FRAME_I;
586 if (intra_period == 0)
587 intra_idr_period = 0;
591 * IDR (PBB)(PBB)(IBB)(PBB)
593 encoding_order_gop = (intra_idr_period == 0)? encoding_order:
594 (encoding_order % (intra_idr_period + ((ip_period == 1)?0:1)));
596 if (encoding_order_gop == 0) { /* the first frame */
597 *frame_type = FRAME_IDR;
598 *displaying_order = encoding_order;
599 } else if (((encoding_order_gop - 1) % ip_period) != 0) { /* B frames */
600 *frame_type = FRAME_B;
601 *displaying_order = encoding_order - 1;
602 } else if ((intra_period != 0) && /* have I frames */
603 (encoding_order_gop >= 2) &&
604 ((ip_period == 1 && encoding_order_gop % intra_period == 0) || /* for IDR PPPPP IPPPP */
605 /* for IDR (PBB)(PBB)(IBB) */
606 (ip_period >= 2 && ((encoding_order_gop - 1) / ip_period % (intra_period / ip_period)) == 0))) {
607 *frame_type = FRAME_I;
608 *displaying_order = encoding_order + ip_period - 1;
610 *frame_type = FRAME_P;
611 *displaying_order = encoding_order + ip_period - 1;
616 static char *fourcc_to_string(int fourcc)
632 static int string_to_fourcc(char *str)
636 if (!strncmp(str, "NV12", 4))
637 fourcc = VA_FOURCC_NV12;
638 else if (!strncmp(str, "IYUV", 4))
639 fourcc = VA_FOURCC_IYUV;
640 else if (!strncmp(str, "YV12", 4))
641 fourcc = VA_FOURCC_YV12;
642 else if (!strncmp(str, "UYVY", 4))
643 fourcc = VA_FOURCC_UYVY;
645 printf("Unknow FOURCC\n");
652 static char *rc_to_string(int rcmode)
665 case VA_RC_VBR_CONSTRAINED:
666 return "VBR_CONSTRAINED";
672 static int string_to_rc(char *str)
676 if (!strncmp(str, "NONE", 4))
677 rc_mode = VA_RC_NONE;
678 else if (!strncmp(str, "CBR", 3))
680 else if (!strncmp(str, "VBR", 3))
682 else if (!strncmp(str, "VCM", 3))
684 else if (!strncmp(str, "CQP", 3))
686 else if (!strncmp(str, "VBR_CONSTRAINED", 15))
687 rc_mode = VA_RC_VBR_CONSTRAINED;
689 printf("Unknown RC mode\n");
696 static int print_help(void)
698 printf("./h264encode <options>\n");
699 printf(" -w <width> -h <height>\n");
700 printf(" -n <frame number>\n");
701 printf(" -o <coded file>\n");
702 printf(" -f <frame rate>\n");
703 printf(" --intra_period <number>\n");
704 printf(" --idr_period <number>\n");
705 printf(" --ip_period <number>\n");
706 printf(" --bitrate <bitrate>\n");
707 printf(" --initialqp <number>\n");
708 printf(" --minqp <number>\n");
709 printf(" --rcmode <NONE|CBR|VBR|VCM|CQP|VBR_CONTRAINED>\n");
710 printf(" --syncmode: sequentially upload source, encoding, save result, no multi-thread\n");
711 printf(" --srcyuv <filename> load YUV from a file\n");
712 printf(" --fourcc <NV12|IYUV|YV12> source YUV fourcc\n");
713 printf(" --recyuv <filename> save reconstructed YUV into a file\n");
714 printf(" --enablePSNR calculate PSNR of recyuv vs. srcyuv\n");
719 static int process_cmdline(int argc, char *argv[])
722 const struct option long_opts[] = {
723 {"help", no_argument, NULL, 0 },
724 {"bitrate", required_argument, NULL, 1 },
725 {"minqp", required_argument, NULL, 2 },
726 {"initialqp", required_argument, NULL, 3 },
727 {"intra_period", required_argument, NULL, 4 },
728 {"idr_period", required_argument, NULL, 5 },
729 {"ip_period", required_argument, NULL, 6 },
730 {"rcmode", required_argument, NULL, 7 },
731 {"srcyuv", required_argument, NULL, 9 },
732 {"recyuv", required_argument, NULL, 10 },
733 {"fourcc", required_argument, NULL, 11 },
734 {"syncmode", no_argument, NULL, 12 },
735 {"enablePSNR", no_argument, NULL, 13 },
736 {NULL, no_argument, NULL, 0 }};
739 while ((c =getopt_long_only(argc,argv,"w:h:n:f:o:?",long_opts,&long_index)) != EOF) {
742 frame_width = atoi(optarg);
745 frame_height = atoi(optarg);
748 frame_count = atoi(optarg);
751 frame_rate = atoi(optarg);
754 coded_fn = strdup(optarg);
760 frame_bitrate = atoi(optarg);
763 minimal_qp = atoi(optarg);
766 initial_qp = atoi(optarg);
769 intra_period = atoi(optarg);
772 intra_idr_period = atoi(optarg);
775 ip_period = atoi(optarg);
778 rc_mode = string_to_rc(optarg);
785 srcyuv_fn = strdup(optarg);
788 recyuv_fn = strdup(optarg);
791 srcyuv_fourcc = string_to_fourcc(optarg);
792 if (srcyuv_fourcc <= 0) {
811 printf(" ip_period must be greater than 0\n");
814 if (intra_period != 1 && intra_period % ip_period != 0) {
815 printf(" intra_period must be a multiplier of ip_period\n");
818 if (intra_period != 0 && intra_idr_period % intra_period != 0) {
819 printf(" intra_idr_period must be a multiplier of intra_period\n");
823 if (frame_bitrate == 0)
824 frame_bitrate = frame_width * frame_height * 12 * frame_rate / 50;
826 /* open source file */
828 srcyuv_fp = fopen(srcyuv_fn,"r");
830 if (srcyuv_fp == NULL)
831 printf("Open source YUV file %s failed, use auto-generated YUV data\n", srcyuv_fn);
833 fseek(srcyuv_fp, 0L, SEEK_END);
834 srcyuv_frames = ftell(srcyuv_fp) / (frame_width * frame_height * 1.5);
835 printf("Source YUV file %s with %llu frames\n", srcyuv_fn, srcyuv_frames);
839 /* open source file */
841 recyuv_fp = fopen(recyuv_fn,"w+");
843 if (recyuv_fp == NULL)
844 printf("Open reconstructed YUV file %s failed\n", recyuv_fn);
847 if (coded_fn == NULL) {
849 if (stat("/tmp", &buf) == 0)
850 coded_fn = strdup("/tmp/test.264");
851 else if (stat("/sdcard", &buf) == 0)
852 coded_fn = strdup("/sdcard/test.264");
854 coded_fn = strdup("./test.264");
857 /* store coded data into a file */
858 coded_fp = fopen(coded_fn,"w+");
859 if (coded_fp == NULL) {
860 printf("Open file %s failed, exit\n", coded_fn);
868 static int init_va(void)
870 VAProfile profile_list[]={VAProfileH264High,VAProfileH264Main,VAProfileH264Baseline,VAProfileH264ConstrainedBaseline};
871 VAEntrypoint entrypoints[VAEntrypointMax]={0};
872 int num_entrypoints,slice_entrypoint;
873 int support_encode = 0;
874 int major_ver, minor_ver;
878 va_dpy = va_open_display();
879 va_status = vaInitialize(va_dpy, &major_ver, &minor_ver);
880 CHECK_VASTATUS(va_status, "vaInitialize");
882 /* use the highest profile */
883 for (i = 0; i < sizeof(profile_list)/sizeof(profile_list[0]); i++) {
884 h264_profile = profile_list[i];
885 vaQueryConfigEntrypoints(va_dpy, h264_profile, entrypoints, &num_entrypoints);
886 for (slice_entrypoint = 0; slice_entrypoint < num_entrypoints; slice_entrypoint++) {
887 if (entrypoints[slice_entrypoint] == VAEntrypointEncSlice) {
892 if (support_encode == 1)
896 if (support_encode == 0) {
897 printf("Can't find VAEntrypointEncSlice for H264 profiles\n");
900 switch (h264_profile) {
901 case VAProfileH264Baseline:
902 printf("Use profile VAProfileH264Baseline\n");
904 constraint_set_flag |= (1 << 0); /* Annex A.2.1 */
906 case VAProfileH264ConstrainedBaseline:
907 printf("Use profile VAProfileH264ConstrainedBaseline\n");
908 constraint_set_flag |= (1 << 0 | 1 << 1); /* Annex A.2.2 */
912 case VAProfileH264Main:
913 printf("Use profile VAProfileH264Main\n");
914 constraint_set_flag |= (1 << 1); /* Annex A.2.2 */
917 case VAProfileH264High:
918 constraint_set_flag |= (1 << 3); /* Annex A.2.4 */
919 printf("Use profile VAProfileH264High\n");
922 printf("unknow profile. Set to Baseline");
923 h264_profile = VAProfileH264Baseline;
925 constraint_set_flag |= (1 << 0); /* Annex A.2.1 */
930 /* find out the format for the render target, and rate control mode */
931 for (i = 0; i < VAConfigAttribTypeMax; i++)
934 va_status = vaGetConfigAttributes(va_dpy, h264_profile, VAEntrypointEncSlice,
935 &attrib[0], VAConfigAttribTypeMax);
936 CHECK_VASTATUS(va_status, "vaGetConfigAttributes");
937 /* check the interested configattrib */
938 if ((attrib[VAConfigAttribRTFormat].value & VA_RT_FORMAT_YUV420) == 0) {
939 printf("Not find desired YUV420 RT format\n");
942 config_attrib[config_attrib_num].type = VAConfigAttribRTFormat;
943 config_attrib[config_attrib_num].value = VA_RT_FORMAT_YUV420;
947 if (attrib[VAConfigAttribRateControl].value != VA_ATTRIB_NOT_SUPPORTED) {
948 int tmp = attrib[VAConfigAttribRateControl].value;
950 printf("Support rate control mode (0x%x):", tmp);
952 if (tmp & VA_RC_NONE)
962 if (tmp & VA_RC_VBR_CONSTRAINED)
963 printf("VBR_CONSTRAINED ");
967 /* need to check if support rc_mode */
968 config_attrib[config_attrib_num].type = VAConfigAttribRateControl;
969 config_attrib[config_attrib_num].value = rc_mode;
974 if (attrib[VAConfigAttribEncPackedHeaders].value != VA_ATTRIB_NOT_SUPPORTED) {
975 int tmp = attrib[VAConfigAttribEncPackedHeaders].value;
977 printf("Support VAConfigAttribEncPackedHeaders\n");
979 h264_packedheader = 1;
980 config_attrib[config_attrib_num].type = VAConfigAttribEncPackedHeaders;
981 config_attrib[config_attrib_num].value = VA_ENC_PACKED_HEADER_NONE;
983 if (tmp & VA_ENC_PACKED_HEADER_SEQUENCE) {
984 printf("Support packed sequence headers\n");
985 config_attrib[config_attrib_num].value |= VA_ENC_PACKED_HEADER_SEQUENCE;
988 if (tmp & VA_ENC_PACKED_HEADER_PICTURE) {
989 printf("Support packed picture headers\n");
990 config_attrib[config_attrib_num].value |= VA_ENC_PACKED_HEADER_PICTURE;
993 if (tmp & VA_ENC_PACKED_HEADER_SLICE) {
994 printf("Support packed slice headers\n");
995 config_attrib[config_attrib_num].value |= VA_ENC_PACKED_HEADER_SLICE;
998 if (tmp & VA_ENC_PACKED_HEADER_MISC) {
999 printf("Support packed misc headers\n");
1000 config_attrib[config_attrib_num].value |= VA_ENC_PACKED_HEADER_MISC;
1003 config_attrib_num++;
1006 if (attrib[VAConfigAttribEncInterlaced].value != VA_ATTRIB_NOT_SUPPORTED) {
1007 int tmp = attrib[VAConfigAttribEncInterlaced].value;
1009 printf("Support VAConfigAttribEncInterlaced\n");
1011 if (tmp & VA_ENC_INTERLACED_FRAME)
1012 printf("support VA_ENC_INTERLACED_FRAME\n");
1013 if (tmp & VA_ENC_INTERLACED_FIELD)
1014 printf("Support VA_ENC_INTERLACED_FIELD\n");
1015 if (tmp & VA_ENC_INTERLACED_MBAFF)
1016 printf("Support VA_ENC_INTERLACED_MBAFF\n");
1017 if (tmp & VA_ENC_INTERLACED_PAFF)
1018 printf("Support VA_ENC_INTERLACED_PAFF\n");
1020 config_attrib[config_attrib_num].type = VAConfigAttribEncInterlaced;
1021 config_attrib[config_attrib_num].value = VA_ENC_PACKED_HEADER_NONE;
1022 config_attrib_num++;
1025 if (attrib[VAConfigAttribEncMaxRefFrames].value != VA_ATTRIB_NOT_SUPPORTED) {
1026 h264_maxref = attrib[VAConfigAttribEncMaxRefFrames].value;
1028 printf("Support %d reference frames\n", h264_maxref);
1031 if (attrib[VAConfigAttribEncMaxSlices].value != VA_ATTRIB_NOT_SUPPORTED)
1032 printf("Support %d slices\n", attrib[VAConfigAttribEncMaxSlices].value);
1034 if (attrib[VAConfigAttribEncSliceStructure].value != VA_ATTRIB_NOT_SUPPORTED) {
1035 int tmp = attrib[VAConfigAttribEncSliceStructure].value;
1037 printf("Support VAConfigAttribEncSliceStructure\n");
1039 if (tmp & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS)
1040 printf("Support VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS\n");
1041 if (tmp & VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS)
1042 printf("Support VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS\n");
1043 if (tmp & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS)
1044 printf("Support VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS\n");
1046 if (attrib[VAConfigAttribEncMacroblockInfo].value != VA_ATTRIB_NOT_SUPPORTED) {
1047 printf("Support VAConfigAttribEncMacroblockInfo\n");
1053 static int setup_encode()
1056 VASurfaceID *tmp_surfaceid;
1057 int codedbuf_size, i;
1059 va_status = vaCreateConfig(va_dpy, h264_profile, VAEntrypointEncSlice,
1060 &config_attrib[0], config_attrib_num, &config_id);
1061 CHECK_VASTATUS(va_status, "vaCreateConfig");
1063 /* create source surfaces */
1064 va_status = vaCreateSurfaces(va_dpy,
1065 VA_RT_FORMAT_YUV420, frame_width, frame_height,
1066 &src_surface[0], SURFACE_NUM,
1068 CHECK_VASTATUS(va_status, "vaCreateSurfaces");
1070 /* create reference surfaces */
1071 va_status = vaCreateSurfaces(
1073 VA_RT_FORMAT_YUV420, frame_width, frame_height,
1074 &ref_surface[0], SURFACE_NUM,
1077 CHECK_VASTATUS(va_status, "vaCreateSurfaces");
1079 tmp_surfaceid = calloc(2 * SURFACE_NUM, sizeof(VASurfaceID));
1080 memcpy(tmp_surfaceid, src_surface, SURFACE_NUM * sizeof(VASurfaceID));
1081 memcpy(tmp_surfaceid + SURFACE_NUM, ref_surface, SURFACE_NUM * sizeof(VASurfaceID));
1083 /* Create a context for this encode pipe */
1084 va_status = vaCreateContext(va_dpy, config_id,
1085 frame_width, frame_height,
1087 tmp_surfaceid, 2 * SURFACE_NUM,
1089 CHECK_VASTATUS(va_status, "vaCreateContext");
1090 free(tmp_surfaceid);
1092 codedbuf_size = (frame_width * frame_height * 400) / (16*16);
1094 for (i = 0; i < SURFACE_NUM; i++) {
1095 /* create coded buffer once for all
1096 * other VA buffers which won't be used again after vaRenderPicture.
1097 * so APP can always vaCreateBuffer for every frame
1098 * but coded buffer need to be mapped and accessed after vaRenderPicture/vaEndPicture
1099 * so VA won't maintain the coded buffer
1101 va_status = vaCreateBuffer(va_dpy,context_id,VAEncCodedBufferType,
1102 codedbuf_size, 1, NULL, &coded_buf[i]);
1103 CHECK_VASTATUS(va_status,"vaCreateBuffer");
1111 #define partition(ref, field, key, ascending) \
1114 while (ref[i].field < key) \
1116 while (ref[j].field > key) \
1119 while (ref[i].field > key) \
1121 while (ref[j].field < key) \
1133 static void sort_one(VAPictureH264 ref[], int left, int right,
1134 int ascending, int frame_idx)
1136 int i = left, j = right;
1141 key = ref[(left + right) / 2].frame_idx;
1142 partition(ref, frame_idx, key, ascending);
1144 key = ref[(left + right) / 2].TopFieldOrderCnt;
1145 partition(ref, TopFieldOrderCnt, (signed int)key, ascending);
1150 sort_one(ref, left, j, ascending, frame_idx);
1153 sort_one(ref, i, right, ascending, frame_idx);
1156 static void sort_two(VAPictureH264 ref[], int left, int right, unsigned int key, unsigned int frame_idx,
1157 int partition_ascending, int list0_ascending, int list1_ascending)
1159 int i = left, j = right;
1163 partition(ref, frame_idx, key, partition_ascending);
1165 partition(ref, TopFieldOrderCnt, (signed int)key, partition_ascending);
1169 sort_one(ref, left, i-1, list0_ascending, frame_idx);
1170 sort_one(ref, j+1, right, list1_ascending, frame_idx);
1173 static int update_ReferenceFrames(void)
1177 if (current_frame_type == FRAME_B)
1180 CurrentCurrPic.flags = VA_PICTURE_H264_SHORT_TERM_REFERENCE;
1182 if (numShortTerm > num_ref_frames)
1183 numShortTerm = num_ref_frames;
1184 for (i=numShortTerm-1; i>0; i--)
1185 ReferenceFrames[i] = ReferenceFrames[i-1];
1186 ReferenceFrames[0] = CurrentCurrPic;
1188 if (current_frame_type != FRAME_B)
1189 current_frame_num++;
1190 if (current_frame_num > MaxFrameNum)
1191 current_frame_num = 0;
1197 static int update_RefPicList(void)
1199 unsigned int current_poc = CurrentCurrPic.TopFieldOrderCnt;
1201 if (current_frame_type == FRAME_P) {
1202 memcpy(RefPicList0_P, ReferenceFrames, numShortTerm * sizeof(VAPictureH264));
1203 sort_one(RefPicList0_P, 0, numShortTerm-1, 0, 1);
1206 if (current_frame_type == FRAME_B) {
1207 memcpy(RefPicList0_B, ReferenceFrames, numShortTerm * sizeof(VAPictureH264));
1208 sort_two(RefPicList0_B, 0, numShortTerm-1, current_poc, 0,
1211 memcpy(RefPicList1_B, ReferenceFrames, numShortTerm * sizeof(VAPictureH264));
1212 sort_two(RefPicList1_B, 0, numShortTerm-1, current_poc, 0,
1220 static int render_sequence(void)
1222 VABufferID seq_param_buf, rc_param_buf, render_id[2];
1224 VAEncMiscParameterBuffer *misc_param;
1225 VAEncMiscParameterRateControl *misc_rate_ctrl;
1227 seq_param.level_idc = 41 /*SH_LEVEL_3*/;
1228 seq_param.picture_width_in_mbs = frame_width / 16;
1229 seq_param.picture_height_in_mbs = frame_height / 16;
1230 seq_param.bits_per_second = frame_bitrate;
1232 seq_param.intra_period = intra_period;
1233 seq_param.intra_idr_period = intra_idr_period;
1234 seq_param.ip_period = ip_period;
1236 seq_param.max_num_ref_frames = num_ref_frames;
1237 seq_param.seq_fields.bits.frame_mbs_only_flag = 1;
1238 seq_param.time_scale = 900;
1239 seq_param.num_units_in_tick = 15; /* Tc = num_units_in_tick / time_sacle */
1240 seq_param.seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4 = Log2MaxPicOrderCntLsb - 4;
1241 seq_param.seq_fields.bits.log2_max_frame_num_minus4 = Log2MaxFrameNum - 4;;
1242 seq_param.seq_fields.bits.frame_mbs_only_flag = 1;
1244 va_status = vaCreateBuffer(va_dpy, context_id,
1245 VAEncSequenceParameterBufferType,
1246 sizeof(seq_param),1,&seq_param,&seq_param_buf);
1247 CHECK_VASTATUS(va_status,"vaCreateBuffer");
1249 va_status = vaCreateBuffer(va_dpy, context_id,
1250 VAEncMiscParameterBufferType,
1251 sizeof(VAEncMiscParameterBuffer) + sizeof(VAEncMiscParameterRateControl),
1252 1,NULL,&rc_param_buf);
1253 CHECK_VASTATUS(va_status,"vaCreateBuffer");
1255 vaMapBuffer(va_dpy, rc_param_buf,(void **)&misc_param);
1256 misc_param->type = VAEncMiscParameterTypeRateControl;
1257 misc_rate_ctrl = (VAEncMiscParameterRateControl *)misc_param->data;
1258 memset(misc_rate_ctrl, 0, sizeof(*misc_rate_ctrl));
1259 misc_rate_ctrl->bits_per_second = frame_bitrate;
1260 misc_rate_ctrl->initial_qp = initial_qp;
1261 misc_rate_ctrl->min_qp = minimal_qp;
1262 misc_rate_ctrl->basic_unit_size = 0;
1263 vaUnmapBuffer(va_dpy, rc_param_buf);
1265 render_id[0] = seq_param_buf;
1266 render_id[1] = rc_param_buf;
1268 va_status = vaRenderPicture(va_dpy,context_id, &render_id[0], 2);
1269 CHECK_VASTATUS(va_status,"vaRenderPicture");;
1274 static int calc_poc(int pic_order_cnt_lsb)
1276 static int PicOrderCntMsb_ref = 0, pic_order_cnt_lsb_ref = 0;
1277 int prevPicOrderCntMsb, prevPicOrderCntLsb;
1278 int PicOrderCntMsb, TopFieldOrderCnt;
1280 if (current_frame_type == FRAME_IDR)
1281 prevPicOrderCntMsb = prevPicOrderCntLsb = 0;
1283 prevPicOrderCntMsb = PicOrderCntMsb_ref;
1284 prevPicOrderCntLsb = pic_order_cnt_lsb_ref;
1287 if ((pic_order_cnt_lsb < prevPicOrderCntLsb) &&
1288 ((prevPicOrderCntLsb - pic_order_cnt_lsb) >= (int)(MaxPicOrderCntLsb / 2)))
1289 PicOrderCntMsb = prevPicOrderCntMsb + MaxPicOrderCntLsb;
1290 else if ((pic_order_cnt_lsb > prevPicOrderCntLsb) &&
1291 ((pic_order_cnt_lsb - prevPicOrderCntLsb) > (int)(MaxPicOrderCntLsb / 2)))
1292 PicOrderCntMsb = prevPicOrderCntMsb - MaxPicOrderCntLsb;
1294 PicOrderCntMsb = prevPicOrderCntMsb;
1296 TopFieldOrderCnt = PicOrderCntMsb + pic_order_cnt_lsb;
1298 if (current_frame_type != FRAME_B) {
1299 PicOrderCntMsb_ref = PicOrderCntMsb;
1300 pic_order_cnt_lsb_ref = pic_order_cnt_lsb;
1303 return TopFieldOrderCnt;
1306 static int render_picture(void)
1308 VABufferID pic_param_buf;
1312 pic_param.CurrPic.picture_id = ref_surface[current_slot];
1313 pic_param.CurrPic.frame_idx = current_frame_num;
1314 pic_param.CurrPic.flags = 0;
1315 pic_param.CurrPic.TopFieldOrderCnt = calc_poc((current_frame_display - current_IDR_display) % MaxPicOrderCntLsb);
1316 pic_param.CurrPic.BottomFieldOrderCnt = pic_param.CurrPic.TopFieldOrderCnt;
1317 CurrentCurrPic = pic_param.CurrPic;
1319 if (getenv("TO_DEL")) { /* set RefPicList into ReferenceFrames */
1320 update_RefPicList(); /* calc RefPicList */
1321 memset(pic_param.ReferenceFrames, 0xff, 16 * sizeof(VAPictureH264)); /* invalid all */
1322 if (current_frame_type == FRAME_P) {
1323 pic_param.ReferenceFrames[0] = RefPicList0_P[0];
1324 } else if (current_frame_type == FRAME_B) {
1325 pic_param.ReferenceFrames[0] = RefPicList0_B[0];
1326 pic_param.ReferenceFrames[1] = RefPicList1_B[0];
1329 memcpy(pic_param.ReferenceFrames, ReferenceFrames, numShortTerm*sizeof(VAPictureH264));
1330 for (i = numShortTerm; i < SURFACE_NUM; i++) {
1331 pic_param.ReferenceFrames[i].picture_id = VA_INVALID_SURFACE;
1332 pic_param.ReferenceFrames[i].flags = VA_PICTURE_H264_INVALID;
1336 pic_param.pic_fields.bits.idr_pic_flag = (current_frame_type == FRAME_IDR);
1337 pic_param.pic_fields.bits.reference_pic_flag = (current_frame_type != FRAME_B);
1338 pic_param.pic_fields.bits.entropy_coding_mode_flag = 1;
1339 pic_param.pic_fields.bits.deblocking_filter_control_present_flag = 1;
1340 pic_param.frame_num = current_frame_num;
1341 pic_param.coded_buf = coded_buf[current_slot];
1342 pic_param.last_picture = (current_frame_encoding == frame_count);
1343 pic_param.pic_init_qp = initial_qp;
1345 va_status = vaCreateBuffer(va_dpy, context_id,VAEncPictureParameterBufferType,
1346 sizeof(pic_param),1,&pic_param, &pic_param_buf);
1347 CHECK_VASTATUS(va_status,"vaCreateBuffer");;
1349 va_status = vaRenderPicture(va_dpy,context_id, &pic_param_buf, 1);
1350 CHECK_VASTATUS(va_status,"vaRenderPicture");
1355 static int render_packedsequence(void)
1357 VAEncPackedHeaderParameterBuffer packedheader_param_buffer;
1358 VABufferID packedseq_para_bufid, packedseq_data_bufid, render_id[2];
1359 unsigned int length_in_bits;
1360 unsigned char *packedseq_buffer = NULL;
1363 length_in_bits = build_packed_seq_buffer(&packedseq_buffer);
1365 packedheader_param_buffer.type = VAEncPackedHeaderSequence;
1367 packedheader_param_buffer.bit_length = length_in_bits; /*length_in_bits*/
1368 packedheader_param_buffer.has_emulation_bytes = 0;
1369 va_status = vaCreateBuffer(va_dpy,
1371 VAEncPackedHeaderParameterBufferType,
1372 sizeof(packedheader_param_buffer), 1, &packedheader_param_buffer,
1373 &packedseq_para_bufid);
1374 CHECK_VASTATUS(va_status,"vaCreateBuffer");
1376 va_status = vaCreateBuffer(va_dpy,
1378 VAEncPackedHeaderDataBufferType,
1379 (length_in_bits + 7) / 8, 1, packedseq_buffer,
1380 &packedseq_data_bufid);
1381 CHECK_VASTATUS(va_status,"vaCreateBuffer");
1383 render_id[0] = packedseq_para_bufid;
1384 render_id[1] = packedseq_data_bufid;
1385 va_status = vaRenderPicture(va_dpy,context_id, render_id, 2);
1386 CHECK_VASTATUS(va_status,"vaRenderPicture");
1388 free(packedseq_buffer);
1394 static int render_packedpicture(void)
1396 VAEncPackedHeaderParameterBuffer packedheader_param_buffer;
1397 VABufferID packedpic_para_bufid, packedpic_data_bufid, render_id[2];
1398 unsigned int length_in_bits;
1399 unsigned char *packedpic_buffer = NULL;
1402 length_in_bits = build_packed_pic_buffer(&packedpic_buffer);
1403 packedheader_param_buffer.type = VAEncPackedHeaderPicture;
1404 packedheader_param_buffer.bit_length = length_in_bits;
1405 packedheader_param_buffer.has_emulation_bytes = 0;
1407 va_status = vaCreateBuffer(va_dpy,
1409 VAEncPackedHeaderParameterBufferType,
1410 sizeof(packedheader_param_buffer), 1, &packedheader_param_buffer,
1411 &packedpic_para_bufid);
1412 CHECK_VASTATUS(va_status,"vaCreateBuffer");
1414 va_status = vaCreateBuffer(va_dpy,
1416 VAEncPackedHeaderDataBufferType,
1417 (length_in_bits + 7) / 8, 1, packedpic_buffer,
1418 &packedpic_data_bufid);
1419 CHECK_VASTATUS(va_status,"vaCreateBuffer");
1421 render_id[0] = packedpic_para_bufid;
1422 render_id[1] = packedpic_data_bufid;
1423 va_status = vaRenderPicture(va_dpy,context_id, render_id, 2);
1424 CHECK_VASTATUS(va_status,"vaRenderPicture");
1426 free(packedpic_buffer);
1431 static void render_packedsei(void)
1433 VAEncPackedHeaderParameterBuffer packed_header_param_buffer;
1434 VABufferID packed_sei_header_param_buf_id, packed_sei_buf_id, render_id[2];
1435 unsigned int length_in_bits /*offset_in_bytes*/;
1436 unsigned char *packed_sei_buffer = NULL;
1438 int init_cpb_size, target_bit_rate, i_initial_cpb_removal_delay_length, i_initial_cpb_removal_delay;
1439 int i_cpb_removal_delay, i_dpb_output_delay_length, i_cpb_removal_delay_length;
1441 /* it comes for the bps defined in SPS */
1442 target_bit_rate = frame_bitrate;
1443 init_cpb_size = (target_bit_rate * 8) >> 10;
1444 i_initial_cpb_removal_delay = init_cpb_size * 0.5 * 1024 / target_bit_rate * 90000;
1446 i_cpb_removal_delay = 2;
1447 i_initial_cpb_removal_delay_length = 24;
1448 i_cpb_removal_delay_length = 24;
1449 i_dpb_output_delay_length = 24;
1452 length_in_bits = build_packed_sei_buffer_timing(
1453 i_initial_cpb_removal_delay_length,
1454 i_initial_cpb_removal_delay,
1456 i_cpb_removal_delay_length,
1457 i_cpb_removal_delay * current_frame_encoding,
1458 i_dpb_output_delay_length,
1460 &packed_sei_buffer);
1462 //offset_in_bytes = 0;
1463 packed_header_param_buffer.type = VAEncPackedHeaderH264_SEI;
1464 packed_header_param_buffer.bit_length = length_in_bits;
1465 packed_header_param_buffer.has_emulation_bytes = 0;
1467 va_status = vaCreateBuffer(va_dpy,
1469 VAEncPackedHeaderParameterBufferType,
1470 sizeof(packed_header_param_buffer), 1, &packed_header_param_buffer,
1471 &packed_sei_header_param_buf_id);
1472 CHECK_VASTATUS(va_status,"vaCreateBuffer");
1474 va_status = vaCreateBuffer(va_dpy,
1476 VAEncPackedHeaderDataBufferType,
1477 (length_in_bits + 7) / 8, 1, packed_sei_buffer,
1478 &packed_sei_buf_id);
1479 CHECK_VASTATUS(va_status,"vaCreateBuffer");
1482 render_id[0] = packed_sei_header_param_buf_id;
1483 render_id[1] = packed_sei_buf_id;
1484 va_status = vaRenderPicture(va_dpy,context_id, render_id, 2);
1485 CHECK_VASTATUS(va_status,"vaRenderPicture");
1488 free(packed_sei_buffer);
1494 static int render_hrd(void)
1496 VABufferID misc_parameter_hrd_buf_id;
1498 VAEncMiscParameterBuffer *misc_param;
1499 VAEncMiscParameterHRD *misc_hrd_param;
1501 va_status = vaCreateBuffer(va_dpy, context_id,
1502 VAEncMiscParameterBufferType,
1503 sizeof(VAEncMiscParameterBuffer) + sizeof(VAEncMiscParameterHRD),
1506 &misc_parameter_hrd_buf_id);
1507 CHECK_VASTATUS(va_status, "vaCreateBuffer");
1510 misc_parameter_hrd_buf_id,
1511 (void **)&misc_param);
1512 misc_param->type = VAEncMiscParameterTypeHRD;
1513 misc_hrd_param = (VAEncMiscParameterHRD *)misc_param->data;
1515 if (frame_bitrate > 0) {
1516 misc_hrd_param->initial_buffer_fullness = frame_bitrate * 1024 * 4;
1517 misc_hrd_param->buffer_size = frame_bitrate * 1024 * 8;
1519 misc_hrd_param->initial_buffer_fullness = 0;
1520 misc_hrd_param->buffer_size = 0;
1522 vaUnmapBuffer(va_dpy, misc_parameter_hrd_buf_id);
1524 va_status = vaRenderPicture(va_dpy,context_id, &misc_parameter_hrd_buf_id, 1);
1525 CHECK_VASTATUS(va_status,"vaRenderPicture");;
1530 static int render_slice(void)
1532 VABufferID slice_param_buf;
1536 update_RefPicList();
1538 /* one frame, one slice */
1539 slice_param.macroblock_address = 0;
1540 slice_param.num_macroblocks = frame_width*frame_height/(16*16); /* Measured by MB */
1541 slice_param.slice_type = (current_frame_type == FRAME_IDR)?2:current_frame_type;
1542 if (current_frame_type == FRAME_IDR) {
1543 ++slice_param.idr_pic_id;
1544 } else if (current_frame_type == FRAME_P) {
1545 int refpiclist0_max = h264_maxref & 0xffff;
1546 memcpy(slice_param.RefPicList0, RefPicList0_P, refpiclist0_max*sizeof(VAPictureH264));
1548 for (i = refpiclist0_max; i < 32; i++) {
1549 slice_param.RefPicList0[i].picture_id = VA_INVALID_SURFACE;
1550 slice_param.RefPicList0[i].flags = VA_PICTURE_H264_INVALID;
1552 } else if (current_frame_type == FRAME_B) {
1553 int refpiclist0_max = h264_maxref & 0xffff;
1554 int refpiclist1_max = (h264_maxref >> 16) & 0xffff;
1556 memcpy(slice_param.RefPicList0, RefPicList0_B, refpiclist0_max*sizeof(VAPictureH264));
1557 for (i = refpiclist0_max; i < 32; i++) {
1558 slice_param.RefPicList0[i].picture_id = VA_INVALID_SURFACE;
1559 slice_param.RefPicList0[i].flags = VA_PICTURE_H264_INVALID;
1562 memcpy(slice_param.RefPicList1, RefPicList1_B, refpiclist1_max*sizeof(VAPictureH264));
1563 for (i = refpiclist1_max; i < 32; i++) {
1564 slice_param.RefPicList1[i].picture_id = VA_INVALID_SURFACE;
1565 slice_param.RefPicList1[i].flags = VA_PICTURE_H264_INVALID;
1569 slice_param.slice_alpha_c0_offset_div2 = 2;
1570 slice_param.slice_beta_offset_div2 = 2;
1571 slice_param.pic_order_cnt_lsb = (current_frame_display - current_IDR_display) % MaxPicOrderCntLsb;
1573 va_status = vaCreateBuffer(va_dpy,context_id,VAEncSliceParameterBufferType,
1574 sizeof(slice_param),1,&slice_param,&slice_param_buf);
1575 CHECK_VASTATUS(va_status,"vaCreateBuffer");;
1577 va_status = vaRenderPicture(va_dpy,context_id, &slice_param_buf, 1);
1578 CHECK_VASTATUS(va_status,"vaRenderPicture");
1584 static int upload_source_YUV_once_for_all()
1590 for (i = 0; i < SURFACE_NUM; i++) {
1591 printf("\rLoading data into surface %d.....", i);
1592 upload_surface(va_dpy, src_surface[i], box_width, row_shift, 0);
1595 if (row_shift==(2*box_width)) row_shift= 0;
1597 printf("Complete surface loading\n");
1602 #define check_ret(ret) \
1604 printf("fread doesn't return enough data\n"); \
1607 static int load_surface(VASurfaceID surface_id, unsigned long long display_order)
1609 unsigned char *src_Y = NULL, *src_U = NULL, *src_V = NULL;
1612 if (srcyuv_fp == NULL)
1615 /* rewind the file pointer if encoding more than srcyuv_frames */
1616 display_order = display_order % srcyuv_frames;
1617 fseek(srcyuv_fp, display_order * frame_width * frame_height * 1.5, SEEK_SET);
1620 if (srcyuv_fourcc == VA_FOURCC_NV12) {
1621 int uv_size = 2 * (frame_width/2) * (frame_height/2);
1623 src_Y = malloc(2 * uv_size);
1624 src_U = malloc(uv_size);
1626 ret = fread(src_Y, frame_width * frame_height, 1, srcyuv_fp);
1628 ret = fread(src_U, uv_size, 1, srcyuv_fp);
1630 } else if (srcyuv_fourcc == VA_FOURCC_IYUV ||
1631 srcyuv_fourcc == VA_FOURCC_YV12) {
1632 int uv_size = (frame_width/2) * (frame_height/2);
1634 src_Y = malloc(4 * uv_size);
1635 src_U = malloc(uv_size);
1636 src_V = malloc(uv_size);
1638 ret = fread(src_Y, frame_width * frame_height, 1, srcyuv_fp);
1640 if (srcyuv_fourcc == VA_FOURCC_IYUV) {
1641 ret = fread(src_U, uv_size, 1, srcyuv_fp);
1643 ret = fread(src_V, uv_size, 1, srcyuv_fp);
1646 ret = fread(src_V, uv_size, 1, srcyuv_fp);
1648 ret = fread(src_U, uv_size, 1, srcyuv_fp);
1652 printf("Unsupported source YUV format\n");
1656 upload_surface_yuv(va_dpy, surface_id,
1657 srcyuv_fourcc, frame_width, frame_height,
1658 src_Y, src_U, src_V);
1670 static int save_recyuv(VASurfaceID surface_id,
1671 unsigned long long display_order,
1672 unsigned long long encode_order)
1674 unsigned char *dst_Y = NULL, *dst_U = NULL, *dst_V = NULL;
1676 if (recyuv_fp == NULL)
1679 if (srcyuv_fourcc == VA_FOURCC_NV12) {
1680 int uv_size = 2 * (frame_width/2) * (frame_height/2);
1681 dst_Y = malloc(2*uv_size);
1682 dst_U = malloc(uv_size);
1683 } else if (srcyuv_fourcc == VA_FOURCC_IYUV ||
1684 srcyuv_fourcc == VA_FOURCC_YV12) {
1685 int uv_size = (frame_width/2) * (frame_height/2);
1686 dst_Y = malloc(4*uv_size);
1687 dst_U = malloc(uv_size);
1688 dst_V = malloc(uv_size);
1690 printf("Unsupported source YUV format\n");
1694 download_surface_yuv(va_dpy, surface_id,
1695 srcyuv_fourcc, frame_width, frame_height,
1696 dst_Y, dst_U, dst_V);
1697 fseek(recyuv_fp, display_order * frame_width * frame_height * 1.5, SEEK_SET);
1699 if (srcyuv_fourcc == VA_FOURCC_NV12) {
1700 int uv_size = 2 * (frame_width/2) * (frame_height/2);
1701 fwrite(dst_Y, uv_size * 2, 1, recyuv_fp);
1702 fwrite(dst_U, uv_size, 1, recyuv_fp);
1703 } else if (srcyuv_fourcc == VA_FOURCC_IYUV ||
1704 srcyuv_fourcc == VA_FOURCC_YV12) {
1705 int uv_size = (frame_width/2) * (frame_height/2);
1706 fwrite(dst_Y, uv_size * 4, 1, recyuv_fp);
1708 if (srcyuv_fourcc == VA_FOURCC_IYUV) {
1709 fwrite(dst_U, uv_size, 1, recyuv_fp);
1710 fwrite(dst_V, uv_size, 1, recyuv_fp);
1712 fwrite(dst_V, uv_size, 1, recyuv_fp);
1713 fwrite(dst_U, uv_size, 1, recyuv_fp);
1716 printf("Unsupported YUV format\n");
1731 static int save_codeddata(unsigned long long display_order, unsigned long long encode_order)
1733 VACodedBufferSegment *buf_list = NULL;
1735 unsigned int coded_size = 0;
1737 va_status = vaMapBuffer(va_dpy,coded_buf[display_order % SURFACE_NUM],(void **)(&buf_list));
1738 CHECK_VASTATUS(va_status,"vaMapBuffer");
1739 while (buf_list != NULL) {
1740 coded_size += fwrite(buf_list->buf, 1, buf_list->size, coded_fp);
1741 buf_list = (VACodedBufferSegment *) buf_list->next;
1743 frame_size += coded_size;
1745 vaUnmapBuffer(va_dpy,coded_buf[display_order % SURFACE_NUM]);
1747 printf("\r "); /* return back to startpoint */
1748 switch (encode_order % 4) {
1762 printf("%08lld", encode_order);
1764 if (current_frame_encoding % intra_count == 0)
1769 printf("(%06d bytes coded)",coded_size);
1770 /* skipped frame ? */
1777 static struct storage_task_t * storage_task_dequeue(void)
1779 struct storage_task_t *header;
1781 pthread_mutex_lock(&encode_mutex);
1783 header = storage_task_header;
1784 if (storage_task_header != NULL) {
1785 if (storage_task_tail == storage_task_header)
1786 storage_task_tail = NULL;
1787 storage_task_header = header->next;
1790 pthread_mutex_unlock(&encode_mutex);
1795 static int storage_task_queue(unsigned long long display_order, unsigned long long encode_order)
1797 struct storage_task_t *tmp;
1799 tmp = calloc(1, sizeof(struct storage_task_t));
1800 tmp->display_order = display_order;
1801 tmp->encode_order = encode_order;
1803 pthread_mutex_lock(&encode_mutex);
1805 if (storage_task_header == NULL) {
1806 storage_task_header = tmp;
1807 storage_task_tail = tmp;
1809 storage_task_tail->next = tmp;
1810 storage_task_tail = tmp;
1813 srcsurface_status[display_order % SURFACE_NUM] = SRC_SURFACE_IN_STORAGE;
1814 pthread_cond_signal(&encode_cond);
1816 pthread_mutex_unlock(&encode_mutex);
1821 static void storage_task(unsigned long long display_order, unsigned long long encode_order)
1826 tmp = GetTickCount();
1827 va_status = vaSyncSurface(va_dpy, src_surface[display_order % SURFACE_NUM]);
1828 CHECK_VASTATUS(va_status,"vaSyncSurface");
1829 SyncPictureTicks += GetTickCount() - tmp;
1830 tmp = GetTickCount();
1831 save_codeddata(display_order, encode_order);
1832 SavePictureTicks += GetTickCount() - tmp;
1834 save_recyuv(ref_surface[display_order % SURFACE_NUM], display_order, encode_order);
1836 /* reload a new frame data */
1837 tmp = GetTickCount();
1838 if (srcyuv_fp != NULL)
1839 load_surface(src_surface[display_order % SURFACE_NUM], display_order + SURFACE_NUM);
1840 UploadPictureTicks += GetTickCount() - tmp;
1842 pthread_mutex_lock(&encode_mutex);
1843 srcsurface_status[display_order % SURFACE_NUM] = SRC_SURFACE_IN_ENCODING;
1844 pthread_cond_signal(&encode_cond);
1845 pthread_mutex_unlock(&encode_mutex);
1849 static void * storage_task_thread(void *t)
1852 struct storage_task_t *current;
1854 current = storage_task_dequeue();
1855 if (current == NULL) {
1856 pthread_mutex_lock(&encode_mutex);
1857 pthread_cond_wait(&encode_cond, &encode_mutex);
1858 pthread_mutex_unlock(&encode_mutex);
1862 storage_task(current->display_order, current->encode_order);
1866 /* all frames are saved, exit the thread */
1867 if (++frame_coded >= frame_count)
1875 static int encode_frames(void)
1877 unsigned int i, tmp;
1879 //VASurfaceStatus surface_status;
1881 /* upload RAW YUV data into all surfaces */
1882 tmp = GetTickCount();
1883 if (srcyuv_fp != NULL) {
1884 for (i = 0; i < SURFACE_NUM; i++)
1885 load_surface(src_surface[i], i);
1887 upload_source_YUV_once_for_all();
1888 UploadPictureTicks += GetTickCount() - tmp;
1890 /* ready for encoding */
1891 memset(srcsurface_status, SRC_SURFACE_IN_ENCODING, sizeof(srcsurface_status));
1893 memset(&seq_param, 0, sizeof(seq_param));
1894 memset(&pic_param, 0, sizeof(pic_param));
1895 memset(&slice_param, 0, sizeof(slice_param));
1897 if (encode_syncmode == 0)
1898 pthread_create(&encode_thread, NULL, storage_task_thread, NULL);
1900 for (current_frame_encoding = 0; current_frame_encoding < frame_count; current_frame_encoding++) {
1901 encoding2display_order(current_frame_encoding, intra_period, intra_idr_period, ip_period,
1902 ¤t_frame_display, ¤t_frame_type);
1903 if (current_frame_type == FRAME_IDR) {
1905 current_frame_num = 0;
1906 current_IDR_display = current_frame_display;
1909 /* check if the source frame is ready */
1910 while (srcsurface_status[current_slot] != SRC_SURFACE_IN_ENCODING) {
1911 pthread_mutex_lock(&encode_mutex);
1912 pthread_cond_wait(&encode_cond, &encode_mutex);
1913 pthread_mutex_unlock(&encode_mutex);
1916 tmp = GetTickCount();
1917 va_status = vaBeginPicture(va_dpy, context_id, src_surface[current_slot]);
1918 CHECK_VASTATUS(va_status,"vaBeginPicture");
1919 BeginPictureTicks += GetTickCount() - tmp;
1921 tmp = GetTickCount();
1922 if (current_frame_type == FRAME_IDR) {
1925 if (h264_packedheader) {
1926 render_packedsequence();
1927 render_packedpicture();
1929 //if (rc_mode == VA_RC_CBR)
1930 // render_packedsei();
1933 //render_sequence();
1935 //if (rc_mode == VA_RC_CBR)
1936 // render_packedsei();
1940 RenderPictureTicks += GetTickCount() - tmp;
1942 tmp = GetTickCount();
1943 va_status = vaEndPicture(va_dpy,context_id);
1944 CHECK_VASTATUS(va_status,"vaEndPicture");;
1945 EndPictureTicks += GetTickCount() - tmp;
1947 if (encode_syncmode)
1948 storage_task(current_frame_display, current_frame_encoding);
1949 else /* queue the storage task queue */
1950 storage_task_queue(current_frame_display, current_frame_encoding);
1952 /* how to process skipped frames
1953 surface_status = (VASurfaceStatus) 0;
1954 va_status = vaQuerySurfaceStatus(va_dpy, src_surface[i%SURFACE_NUM],&surface_status);
1955 frame_skipped = (surface_status & VASurfaceSkipped);
1957 update_ReferenceFrames();
1960 if (encode_syncmode == 0) {
1962 pthread_join(encode_thread, (void **)&ret);
1969 static int release_encode()
1973 vaDestroySurfaces(va_dpy,&src_surface[0],SURFACE_NUM);
1974 vaDestroySurfaces(va_dpy,&ref_surface[0],SURFACE_NUM);
1976 for (i = 0; i < SURFACE_NUM; i++)
1977 vaDestroyBuffer(va_dpy,coded_buf[i]);
1979 vaDestroyContext(va_dpy,context_id);
1980 vaDestroyConfig(va_dpy,config_id);
1985 static int deinit_va()
1987 vaTerminate(va_dpy);
1989 va_close_display(va_dpy);
1995 static int print_input()
1997 printf("\n\nINPUT:Try to encode H264...\n");
1998 printf("INPUT: RateControl : %s\n", rc_to_string(rc_mode));
1999 printf("INPUT: Resolution : %dx%d, %d frames\n",
2000 frame_width, frame_height, frame_count);
2001 printf("INPUT: FrameRate : %d\n", frame_rate);
2002 printf("INPUT: Bitrate : %d\n", frame_bitrate);
2003 printf("INPUT: Slieces : %d\n", frame_slices);
2004 printf("INPUT: IntraPeriod : %d\n", intra_period);
2005 printf("INPUT: IDRPeriod : %d\n", intra_idr_period);
2006 printf("INPUT: IpPeriod : %d\n", ip_period);
2007 printf("INPUT: Initial QP : %d\n", initial_qp);
2008 printf("INPUT: Min QP : %d\n", minimal_qp);
2009 printf("INPUT: Source YUV : %s", srcyuv_fp?"FILE":"AUTO generated");
2011 printf(":%s (fourcc %s)\n", srcyuv_fn, fourcc_to_string(srcyuv_fourcc));
2014 printf("INPUT: Coded Clip : %s\n", coded_fn);
2015 if (recyuv_fp == NULL)
2016 printf("INPUT: Rec Clip : %s\n", "Not save reconstructed frame");
2018 printf("INPUT: Rec Clip : Save reconstructed frame into %s (fourcc %s)\n", recyuv_fn,
2019 fourcc_to_string(srcyuv_fourcc));
2021 printf("\n\n"); /* return back to startpoint */
2026 static int calc_PSNR(double *psnr)
2028 unsigned long srcyuv_size, recyuv_size, min_size;
2029 char *srcyuv_ptr, *recyuv_ptr;
2030 unsigned long i, sse=0;
2033 fseek(srcyuv_fp, 0L, SEEK_END);
2034 srcyuv_size = ftell(srcyuv_fp);
2035 fseek(recyuv_fp, 0L, SEEK_END);
2036 recyuv_size = ftell(recyuv_fp);
2038 fseek(srcyuv_fp, 0L, SEEK_SET);
2039 fseek(recyuv_fp, 0L, SEEK_SET);
2041 min_size = MIN(srcyuv_size,recyuv_size);
2042 srcyuv_ptr = mmap (0, min_size, PROT_READ, MAP_SHARED, fileno(srcyuv_fp), 0);
2043 recyuv_ptr = mmap (0, min_size, PROT_READ, MAP_SHARED, fileno(recyuv_fp), 0);
2044 if ((srcyuv_ptr == MAP_FAILED) || (recyuv_ptr == MAP_FAILED)) {
2045 printf("Failed to mmap YUV files\n");
2049 for (i=0; i<min_size; i++) {
2050 char tmp = srcyuv_ptr[i] - recyuv_ptr[i];
2053 ssemean = (double)sse/(double)min_size;
2054 *psnr = 20.0*log10(255) - 10.0*log10(ssemean);
2056 munmap(srcyuv_ptr, min_size);
2057 munmap(recyuv_ptr, min_size);
2062 static int print_performance(unsigned int PictureCount)
2064 unsigned int psnr_ret = 1, others = 0;
2065 double psnr = 0, total_size = frame_width * frame_height * 1.5 * frame_count;
2067 if (calc_psnr && srcyuv_fp && recyuv_fp)
2068 psnr_ret = calc_PSNR(&psnr);
2070 others = TotalTicks - UploadPictureTicks - BeginPictureTicks
2071 - RenderPictureTicks - EndPictureTicks - SyncPictureTicks - SavePictureTicks;
2075 printf("PERFORMANCE: Frame Rate : %.2f fps (%d frames, %d ms (%.2f ms per frame))\n",
2076 (double) 1000*PictureCount / TotalTicks, PictureCount,
2077 TotalTicks, ((double) TotalTicks) / (double) PictureCount);
2078 printf("PERFORMANCE: Compression ratio : %d:1\n", (unsigned int)(total_size / frame_size));
2080 printf("PERFORMANCE: PSNR : %.2f (%lld frames calculated)\n",
2081 psnr, MIN(frame_count, srcyuv_frames));
2083 printf("PERFORMANCE: UploadPicture : %d ms (%.2f, %.2f%% percent)\n",
2084 (int) UploadPictureTicks, ((double) UploadPictureTicks) / (double) PictureCount,
2085 UploadPictureTicks/(double) TotalTicks/0.01);
2086 printf("PERFORMANCE: vaBeginPicture : %d ms (%.2f, %.2f%% percent)\n",
2087 (int) BeginPictureTicks, ((double) BeginPictureTicks) / (double) PictureCount,
2088 BeginPictureTicks/(double) TotalTicks/0.01);
2089 printf("PERFORMANCE: vaRenderHeader : %d ms (%.2f, %.2f%% percent)\n",
2090 (int) RenderPictureTicks, ((double) RenderPictureTicks) / (double) PictureCount,
2091 RenderPictureTicks/(double) TotalTicks/0.01);
2092 printf("PERFORMANCE: vaEndPicture : %d ms (%.2f, %.2f%% percent)\n",
2093 (int) EndPictureTicks, ((double) EndPictureTicks) / (double) PictureCount,
2094 EndPictureTicks/(double) TotalTicks/0.01);
2095 printf("PERFORMANCE: vaSyncSurface : %d ms (%.2f, %.2f%% percent)\n",
2096 (int) SyncPictureTicks, ((double) SyncPictureTicks) / (double) PictureCount,
2097 SyncPictureTicks/(double) TotalTicks/0.01);
2098 printf("PERFORMANCE: SavePicture : %d ms (%.2f, %.2f%% percent)\n",
2099 (int) SavePictureTicks, ((double) SavePictureTicks) / (double) PictureCount,
2100 SavePictureTicks/(double) TotalTicks/0.01);
2101 printf("PERFORMANCE: Others : %d ms (%.2f, %.2f%% percent)\n",
2102 (int) others, ((double) others) / (double) PictureCount,
2103 others/(double) TotalTicks/0.01);
2105 if (encode_syncmode == 0)
2106 printf("(Multithread enabled, the timing is only for reference)\n");
2112 int main(int argc,char **argv)
2116 process_cmdline(argc, argv);
2120 start = GetTickCount();
2130 TotalTicks += GetTickCount() - start;
2131 print_performance(frame_count);