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 RefPicList0 and %d RefPicList1\n",
1029 h264_maxref & 0xffff, (h264_maxref >> 16) & 0xffff );
1032 if (attrib[VAConfigAttribEncMaxSlices].value != VA_ATTRIB_NOT_SUPPORTED)
1033 printf("Support %d slices\n", attrib[VAConfigAttribEncMaxSlices].value);
1035 if (attrib[VAConfigAttribEncSliceStructure].value != VA_ATTRIB_NOT_SUPPORTED) {
1036 int tmp = attrib[VAConfigAttribEncSliceStructure].value;
1038 printf("Support VAConfigAttribEncSliceStructure\n");
1040 if (tmp & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS)
1041 printf("Support VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS\n");
1042 if (tmp & VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS)
1043 printf("Support VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS\n");
1044 if (tmp & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS)
1045 printf("Support VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS\n");
1047 if (attrib[VAConfigAttribEncMacroblockInfo].value != VA_ATTRIB_NOT_SUPPORTED) {
1048 printf("Support VAConfigAttribEncMacroblockInfo\n");
1054 static int setup_encode()
1057 VASurfaceID *tmp_surfaceid;
1058 int codedbuf_size, i;
1060 va_status = vaCreateConfig(va_dpy, h264_profile, VAEntrypointEncSlice,
1061 &config_attrib[0], config_attrib_num, &config_id);
1062 CHECK_VASTATUS(va_status, "vaCreateConfig");
1064 /* create source surfaces */
1065 va_status = vaCreateSurfaces(va_dpy,
1066 VA_RT_FORMAT_YUV420, frame_width, frame_height,
1067 &src_surface[0], SURFACE_NUM,
1069 CHECK_VASTATUS(va_status, "vaCreateSurfaces");
1071 /* create reference surfaces */
1072 va_status = vaCreateSurfaces(
1074 VA_RT_FORMAT_YUV420, frame_width, frame_height,
1075 &ref_surface[0], SURFACE_NUM,
1078 CHECK_VASTATUS(va_status, "vaCreateSurfaces");
1080 tmp_surfaceid = calloc(2 * SURFACE_NUM, sizeof(VASurfaceID));
1081 memcpy(tmp_surfaceid, src_surface, SURFACE_NUM * sizeof(VASurfaceID));
1082 memcpy(tmp_surfaceid + SURFACE_NUM, ref_surface, SURFACE_NUM * sizeof(VASurfaceID));
1084 /* Create a context for this encode pipe */
1085 va_status = vaCreateContext(va_dpy, config_id,
1086 frame_width, frame_height,
1088 tmp_surfaceid, 2 * SURFACE_NUM,
1090 CHECK_VASTATUS(va_status, "vaCreateContext");
1091 free(tmp_surfaceid);
1093 codedbuf_size = (frame_width * frame_height * 400) / (16*16);
1095 for (i = 0; i < SURFACE_NUM; i++) {
1096 /* create coded buffer once for all
1097 * other VA buffers which won't be used again after vaRenderPicture.
1098 * so APP can always vaCreateBuffer for every frame
1099 * but coded buffer need to be mapped and accessed after vaRenderPicture/vaEndPicture
1100 * so VA won't maintain the coded buffer
1102 va_status = vaCreateBuffer(va_dpy,context_id,VAEncCodedBufferType,
1103 codedbuf_size, 1, NULL, &coded_buf[i]);
1104 CHECK_VASTATUS(va_status,"vaCreateBuffer");
1112 #define partition(ref, field, key, ascending) \
1115 while (ref[i].field < key) \
1117 while (ref[j].field > key) \
1120 while (ref[i].field > key) \
1122 while (ref[j].field < key) \
1134 static void sort_one(VAPictureH264 ref[], int left, int right,
1135 int ascending, int frame_idx)
1137 int i = left, j = right;
1142 key = ref[(left + right) / 2].frame_idx;
1143 partition(ref, frame_idx, key, ascending);
1145 key = ref[(left + right) / 2].TopFieldOrderCnt;
1146 partition(ref, TopFieldOrderCnt, (signed int)key, ascending);
1151 sort_one(ref, left, j, ascending, frame_idx);
1154 sort_one(ref, i, right, ascending, frame_idx);
1157 static void sort_two(VAPictureH264 ref[], int left, int right, unsigned int key, unsigned int frame_idx,
1158 int partition_ascending, int list0_ascending, int list1_ascending)
1160 int i = left, j = right;
1164 partition(ref, frame_idx, key, partition_ascending);
1166 partition(ref, TopFieldOrderCnt, (signed int)key, partition_ascending);
1170 sort_one(ref, left, i-1, list0_ascending, frame_idx);
1171 sort_one(ref, j+1, right, list1_ascending, frame_idx);
1174 static int update_ReferenceFrames(void)
1178 if (current_frame_type == FRAME_B)
1181 CurrentCurrPic.flags = VA_PICTURE_H264_SHORT_TERM_REFERENCE;
1183 if (numShortTerm > num_ref_frames)
1184 numShortTerm = num_ref_frames;
1185 for (i=numShortTerm-1; i>0; i--)
1186 ReferenceFrames[i] = ReferenceFrames[i-1];
1187 ReferenceFrames[0] = CurrentCurrPic;
1189 if (current_frame_type != FRAME_B)
1190 current_frame_num++;
1191 if (current_frame_num > MaxFrameNum)
1192 current_frame_num = 0;
1198 static int update_RefPicList(void)
1200 unsigned int current_poc = CurrentCurrPic.TopFieldOrderCnt;
1202 if (current_frame_type == FRAME_P) {
1203 memcpy(RefPicList0_P, ReferenceFrames, numShortTerm * sizeof(VAPictureH264));
1204 sort_one(RefPicList0_P, 0, numShortTerm-1, 0, 1);
1207 if (current_frame_type == FRAME_B) {
1208 memcpy(RefPicList0_B, ReferenceFrames, numShortTerm * sizeof(VAPictureH264));
1209 sort_two(RefPicList0_B, 0, numShortTerm-1, current_poc, 0,
1212 memcpy(RefPicList1_B, ReferenceFrames, numShortTerm * sizeof(VAPictureH264));
1213 sort_two(RefPicList1_B, 0, numShortTerm-1, current_poc, 0,
1221 static int render_sequence(void)
1223 VABufferID seq_param_buf, rc_param_buf, render_id[2];
1225 VAEncMiscParameterBuffer *misc_param;
1226 VAEncMiscParameterRateControl *misc_rate_ctrl;
1228 seq_param.level_idc = 41 /*SH_LEVEL_3*/;
1229 seq_param.picture_width_in_mbs = frame_width / 16;
1230 seq_param.picture_height_in_mbs = frame_height / 16;
1231 seq_param.bits_per_second = frame_bitrate;
1233 seq_param.intra_period = intra_period;
1234 seq_param.intra_idr_period = intra_idr_period;
1235 seq_param.ip_period = ip_period;
1237 seq_param.max_num_ref_frames = num_ref_frames;
1238 seq_param.seq_fields.bits.frame_mbs_only_flag = 1;
1239 seq_param.time_scale = 900;
1240 seq_param.num_units_in_tick = 15; /* Tc = num_units_in_tick / time_sacle */
1241 seq_param.seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4 = Log2MaxPicOrderCntLsb - 4;
1242 seq_param.seq_fields.bits.log2_max_frame_num_minus4 = Log2MaxFrameNum - 4;;
1243 seq_param.seq_fields.bits.frame_mbs_only_flag = 1;
1245 va_status = vaCreateBuffer(va_dpy, context_id,
1246 VAEncSequenceParameterBufferType,
1247 sizeof(seq_param),1,&seq_param,&seq_param_buf);
1248 CHECK_VASTATUS(va_status,"vaCreateBuffer");
1250 va_status = vaCreateBuffer(va_dpy, context_id,
1251 VAEncMiscParameterBufferType,
1252 sizeof(VAEncMiscParameterBuffer) + sizeof(VAEncMiscParameterRateControl),
1253 1,NULL,&rc_param_buf);
1254 CHECK_VASTATUS(va_status,"vaCreateBuffer");
1256 vaMapBuffer(va_dpy, rc_param_buf,(void **)&misc_param);
1257 misc_param->type = VAEncMiscParameterTypeRateControl;
1258 misc_rate_ctrl = (VAEncMiscParameterRateControl *)misc_param->data;
1259 memset(misc_rate_ctrl, 0, sizeof(*misc_rate_ctrl));
1260 misc_rate_ctrl->bits_per_second = frame_bitrate;
1261 misc_rate_ctrl->initial_qp = initial_qp;
1262 misc_rate_ctrl->min_qp = minimal_qp;
1263 misc_rate_ctrl->basic_unit_size = 0;
1264 vaUnmapBuffer(va_dpy, rc_param_buf);
1266 render_id[0] = seq_param_buf;
1267 render_id[1] = rc_param_buf;
1269 va_status = vaRenderPicture(va_dpy,context_id, &render_id[0], 2);
1270 CHECK_VASTATUS(va_status,"vaRenderPicture");;
1275 static int calc_poc(int pic_order_cnt_lsb)
1277 static int PicOrderCntMsb_ref = 0, pic_order_cnt_lsb_ref = 0;
1278 int prevPicOrderCntMsb, prevPicOrderCntLsb;
1279 int PicOrderCntMsb, TopFieldOrderCnt;
1281 if (current_frame_type == FRAME_IDR)
1282 prevPicOrderCntMsb = prevPicOrderCntLsb = 0;
1284 prevPicOrderCntMsb = PicOrderCntMsb_ref;
1285 prevPicOrderCntLsb = pic_order_cnt_lsb_ref;
1288 if ((pic_order_cnt_lsb < prevPicOrderCntLsb) &&
1289 ((prevPicOrderCntLsb - pic_order_cnt_lsb) >= (int)(MaxPicOrderCntLsb / 2)))
1290 PicOrderCntMsb = prevPicOrderCntMsb + MaxPicOrderCntLsb;
1291 else if ((pic_order_cnt_lsb > prevPicOrderCntLsb) &&
1292 ((pic_order_cnt_lsb - prevPicOrderCntLsb) > (int)(MaxPicOrderCntLsb / 2)))
1293 PicOrderCntMsb = prevPicOrderCntMsb - MaxPicOrderCntLsb;
1295 PicOrderCntMsb = prevPicOrderCntMsb;
1297 TopFieldOrderCnt = PicOrderCntMsb + pic_order_cnt_lsb;
1299 if (current_frame_type != FRAME_B) {
1300 PicOrderCntMsb_ref = PicOrderCntMsb;
1301 pic_order_cnt_lsb_ref = pic_order_cnt_lsb;
1304 return TopFieldOrderCnt;
1307 static int render_picture(void)
1309 VABufferID pic_param_buf;
1313 pic_param.CurrPic.picture_id = ref_surface[current_slot];
1314 pic_param.CurrPic.frame_idx = current_frame_num;
1315 pic_param.CurrPic.flags = 0;
1316 pic_param.CurrPic.TopFieldOrderCnt = calc_poc((current_frame_display - current_IDR_display) % MaxPicOrderCntLsb);
1317 pic_param.CurrPic.BottomFieldOrderCnt = pic_param.CurrPic.TopFieldOrderCnt;
1318 CurrentCurrPic = pic_param.CurrPic;
1320 if (getenv("TO_DEL")) { /* set RefPicList into ReferenceFrames */
1321 update_RefPicList(); /* calc RefPicList */
1322 memset(pic_param.ReferenceFrames, 0xff, 16 * sizeof(VAPictureH264)); /* invalid all */
1323 if (current_frame_type == FRAME_P) {
1324 pic_param.ReferenceFrames[0] = RefPicList0_P[0];
1325 } else if (current_frame_type == FRAME_B) {
1326 pic_param.ReferenceFrames[0] = RefPicList0_B[0];
1327 pic_param.ReferenceFrames[1] = RefPicList1_B[0];
1330 memcpy(pic_param.ReferenceFrames, ReferenceFrames, numShortTerm*sizeof(VAPictureH264));
1331 for (i = numShortTerm; i < SURFACE_NUM; i++) {
1332 pic_param.ReferenceFrames[i].picture_id = VA_INVALID_SURFACE;
1333 pic_param.ReferenceFrames[i].flags = VA_PICTURE_H264_INVALID;
1337 pic_param.pic_fields.bits.idr_pic_flag = (current_frame_type == FRAME_IDR);
1338 pic_param.pic_fields.bits.reference_pic_flag = (current_frame_type != FRAME_B);
1339 pic_param.pic_fields.bits.entropy_coding_mode_flag = 1;
1340 pic_param.pic_fields.bits.deblocking_filter_control_present_flag = 1;
1341 pic_param.frame_num = current_frame_num;
1342 pic_param.coded_buf = coded_buf[current_slot];
1343 pic_param.last_picture = (current_frame_encoding == frame_count);
1344 pic_param.pic_init_qp = initial_qp;
1346 va_status = vaCreateBuffer(va_dpy, context_id,VAEncPictureParameterBufferType,
1347 sizeof(pic_param),1,&pic_param, &pic_param_buf);
1348 CHECK_VASTATUS(va_status,"vaCreateBuffer");;
1350 va_status = vaRenderPicture(va_dpy,context_id, &pic_param_buf, 1);
1351 CHECK_VASTATUS(va_status,"vaRenderPicture");
1356 static int render_packedsequence(void)
1358 VAEncPackedHeaderParameterBuffer packedheader_param_buffer;
1359 VABufferID packedseq_para_bufid, packedseq_data_bufid, render_id[2];
1360 unsigned int length_in_bits;
1361 unsigned char *packedseq_buffer = NULL;
1364 length_in_bits = build_packed_seq_buffer(&packedseq_buffer);
1366 packedheader_param_buffer.type = VAEncPackedHeaderSequence;
1368 packedheader_param_buffer.bit_length = length_in_bits; /*length_in_bits*/
1369 packedheader_param_buffer.has_emulation_bytes = 0;
1370 va_status = vaCreateBuffer(va_dpy,
1372 VAEncPackedHeaderParameterBufferType,
1373 sizeof(packedheader_param_buffer), 1, &packedheader_param_buffer,
1374 &packedseq_para_bufid);
1375 CHECK_VASTATUS(va_status,"vaCreateBuffer");
1377 va_status = vaCreateBuffer(va_dpy,
1379 VAEncPackedHeaderDataBufferType,
1380 (length_in_bits + 7) / 8, 1, packedseq_buffer,
1381 &packedseq_data_bufid);
1382 CHECK_VASTATUS(va_status,"vaCreateBuffer");
1384 render_id[0] = packedseq_para_bufid;
1385 render_id[1] = packedseq_data_bufid;
1386 va_status = vaRenderPicture(va_dpy,context_id, render_id, 2);
1387 CHECK_VASTATUS(va_status,"vaRenderPicture");
1389 free(packedseq_buffer);
1395 static int render_packedpicture(void)
1397 VAEncPackedHeaderParameterBuffer packedheader_param_buffer;
1398 VABufferID packedpic_para_bufid, packedpic_data_bufid, render_id[2];
1399 unsigned int length_in_bits;
1400 unsigned char *packedpic_buffer = NULL;
1403 length_in_bits = build_packed_pic_buffer(&packedpic_buffer);
1404 packedheader_param_buffer.type = VAEncPackedHeaderPicture;
1405 packedheader_param_buffer.bit_length = length_in_bits;
1406 packedheader_param_buffer.has_emulation_bytes = 0;
1408 va_status = vaCreateBuffer(va_dpy,
1410 VAEncPackedHeaderParameterBufferType,
1411 sizeof(packedheader_param_buffer), 1, &packedheader_param_buffer,
1412 &packedpic_para_bufid);
1413 CHECK_VASTATUS(va_status,"vaCreateBuffer");
1415 va_status = vaCreateBuffer(va_dpy,
1417 VAEncPackedHeaderDataBufferType,
1418 (length_in_bits + 7) / 8, 1, packedpic_buffer,
1419 &packedpic_data_bufid);
1420 CHECK_VASTATUS(va_status,"vaCreateBuffer");
1422 render_id[0] = packedpic_para_bufid;
1423 render_id[1] = packedpic_data_bufid;
1424 va_status = vaRenderPicture(va_dpy,context_id, render_id, 2);
1425 CHECK_VASTATUS(va_status,"vaRenderPicture");
1427 free(packedpic_buffer);
1432 static void render_packedsei(void)
1434 VAEncPackedHeaderParameterBuffer packed_header_param_buffer;
1435 VABufferID packed_sei_header_param_buf_id, packed_sei_buf_id, render_id[2];
1436 unsigned int length_in_bits /*offset_in_bytes*/;
1437 unsigned char *packed_sei_buffer = NULL;
1439 int init_cpb_size, target_bit_rate, i_initial_cpb_removal_delay_length, i_initial_cpb_removal_delay;
1440 int i_cpb_removal_delay, i_dpb_output_delay_length, i_cpb_removal_delay_length;
1442 /* it comes for the bps defined in SPS */
1443 target_bit_rate = frame_bitrate;
1444 init_cpb_size = (target_bit_rate * 8) >> 10;
1445 i_initial_cpb_removal_delay = init_cpb_size * 0.5 * 1024 / target_bit_rate * 90000;
1447 i_cpb_removal_delay = 2;
1448 i_initial_cpb_removal_delay_length = 24;
1449 i_cpb_removal_delay_length = 24;
1450 i_dpb_output_delay_length = 24;
1453 length_in_bits = build_packed_sei_buffer_timing(
1454 i_initial_cpb_removal_delay_length,
1455 i_initial_cpb_removal_delay,
1457 i_cpb_removal_delay_length,
1458 i_cpb_removal_delay * current_frame_encoding,
1459 i_dpb_output_delay_length,
1461 &packed_sei_buffer);
1463 //offset_in_bytes = 0;
1464 packed_header_param_buffer.type = VAEncPackedHeaderH264_SEI;
1465 packed_header_param_buffer.bit_length = length_in_bits;
1466 packed_header_param_buffer.has_emulation_bytes = 0;
1468 va_status = vaCreateBuffer(va_dpy,
1470 VAEncPackedHeaderParameterBufferType,
1471 sizeof(packed_header_param_buffer), 1, &packed_header_param_buffer,
1472 &packed_sei_header_param_buf_id);
1473 CHECK_VASTATUS(va_status,"vaCreateBuffer");
1475 va_status = vaCreateBuffer(va_dpy,
1477 VAEncPackedHeaderDataBufferType,
1478 (length_in_bits + 7) / 8, 1, packed_sei_buffer,
1479 &packed_sei_buf_id);
1480 CHECK_VASTATUS(va_status,"vaCreateBuffer");
1483 render_id[0] = packed_sei_header_param_buf_id;
1484 render_id[1] = packed_sei_buf_id;
1485 va_status = vaRenderPicture(va_dpy,context_id, render_id, 2);
1486 CHECK_VASTATUS(va_status,"vaRenderPicture");
1489 free(packed_sei_buffer);
1495 static int render_hrd(void)
1497 VABufferID misc_parameter_hrd_buf_id;
1499 VAEncMiscParameterBuffer *misc_param;
1500 VAEncMiscParameterHRD *misc_hrd_param;
1502 va_status = vaCreateBuffer(va_dpy, context_id,
1503 VAEncMiscParameterBufferType,
1504 sizeof(VAEncMiscParameterBuffer) + sizeof(VAEncMiscParameterHRD),
1507 &misc_parameter_hrd_buf_id);
1508 CHECK_VASTATUS(va_status, "vaCreateBuffer");
1511 misc_parameter_hrd_buf_id,
1512 (void **)&misc_param);
1513 misc_param->type = VAEncMiscParameterTypeHRD;
1514 misc_hrd_param = (VAEncMiscParameterHRD *)misc_param->data;
1516 if (frame_bitrate > 0) {
1517 misc_hrd_param->initial_buffer_fullness = frame_bitrate * 1024 * 4;
1518 misc_hrd_param->buffer_size = frame_bitrate * 1024 * 8;
1520 misc_hrd_param->initial_buffer_fullness = 0;
1521 misc_hrd_param->buffer_size = 0;
1523 vaUnmapBuffer(va_dpy, misc_parameter_hrd_buf_id);
1525 va_status = vaRenderPicture(va_dpy,context_id, &misc_parameter_hrd_buf_id, 1);
1526 CHECK_VASTATUS(va_status,"vaRenderPicture");;
1531 static int render_slice(void)
1533 VABufferID slice_param_buf;
1537 update_RefPicList();
1539 /* one frame, one slice */
1540 slice_param.macroblock_address = 0;
1541 slice_param.num_macroblocks = frame_width*frame_height/(16*16); /* Measured by MB */
1542 slice_param.slice_type = (current_frame_type == FRAME_IDR)?2:current_frame_type;
1543 if (current_frame_type == FRAME_IDR) {
1544 ++slice_param.idr_pic_id;
1545 } else if (current_frame_type == FRAME_P) {
1546 int refpiclist0_max = h264_maxref & 0xffff;
1547 memcpy(slice_param.RefPicList0, RefPicList0_P, refpiclist0_max*sizeof(VAPictureH264));
1549 for (i = refpiclist0_max; i < 32; i++) {
1550 slice_param.RefPicList0[i].picture_id = VA_INVALID_SURFACE;
1551 slice_param.RefPicList0[i].flags = VA_PICTURE_H264_INVALID;
1553 } else if (current_frame_type == FRAME_B) {
1554 int refpiclist0_max = h264_maxref & 0xffff;
1555 int refpiclist1_max = (h264_maxref >> 16) & 0xffff;
1557 memcpy(slice_param.RefPicList0, RefPicList0_B, refpiclist0_max*sizeof(VAPictureH264));
1558 for (i = refpiclist0_max; i < 32; i++) {
1559 slice_param.RefPicList0[i].picture_id = VA_INVALID_SURFACE;
1560 slice_param.RefPicList0[i].flags = VA_PICTURE_H264_INVALID;
1563 memcpy(slice_param.RefPicList1, RefPicList1_B, refpiclist1_max*sizeof(VAPictureH264));
1564 for (i = refpiclist1_max; i < 32; i++) {
1565 slice_param.RefPicList1[i].picture_id = VA_INVALID_SURFACE;
1566 slice_param.RefPicList1[i].flags = VA_PICTURE_H264_INVALID;
1570 slice_param.slice_alpha_c0_offset_div2 = 2;
1571 slice_param.slice_beta_offset_div2 = 2;
1572 slice_param.pic_order_cnt_lsb = (current_frame_display - current_IDR_display) % MaxPicOrderCntLsb;
1574 va_status = vaCreateBuffer(va_dpy,context_id,VAEncSliceParameterBufferType,
1575 sizeof(slice_param),1,&slice_param,&slice_param_buf);
1576 CHECK_VASTATUS(va_status,"vaCreateBuffer");;
1578 va_status = vaRenderPicture(va_dpy,context_id, &slice_param_buf, 1);
1579 CHECK_VASTATUS(va_status,"vaRenderPicture");
1585 static int upload_source_YUV_once_for_all()
1591 for (i = 0; i < SURFACE_NUM; i++) {
1592 printf("\rLoading data into surface %d.....", i);
1593 upload_surface(va_dpy, src_surface[i], box_width, row_shift, 0);
1596 if (row_shift==(2*box_width)) row_shift= 0;
1598 printf("Complete surface loading\n");
1603 #define check_ret(ret) \
1605 printf("fread doesn't return enough data\n"); \
1608 static int load_surface(VASurfaceID surface_id, unsigned long long display_order)
1610 unsigned char *src_Y = NULL, *src_U = NULL, *src_V = NULL;
1613 if (srcyuv_fp == NULL)
1616 /* rewind the file pointer if encoding more than srcyuv_frames */
1617 display_order = display_order % srcyuv_frames;
1618 fseek(srcyuv_fp, display_order * frame_width * frame_height * 1.5, SEEK_SET);
1621 if (srcyuv_fourcc == VA_FOURCC_NV12) {
1622 int uv_size = 2 * (frame_width/2) * (frame_height/2);
1624 src_Y = malloc(2 * uv_size);
1625 src_U = malloc(uv_size);
1627 ret = fread(src_Y, frame_width * frame_height, 1, srcyuv_fp);
1629 ret = fread(src_U, uv_size, 1, srcyuv_fp);
1631 } else if (srcyuv_fourcc == VA_FOURCC_IYUV ||
1632 srcyuv_fourcc == VA_FOURCC_YV12) {
1633 int uv_size = (frame_width/2) * (frame_height/2);
1635 src_Y = malloc(4 * uv_size);
1636 src_U = malloc(uv_size);
1637 src_V = malloc(uv_size);
1639 ret = fread(src_Y, frame_width * frame_height, 1, srcyuv_fp);
1641 if (srcyuv_fourcc == VA_FOURCC_IYUV) {
1642 ret = fread(src_U, uv_size, 1, srcyuv_fp);
1644 ret = fread(src_V, uv_size, 1, srcyuv_fp);
1647 ret = fread(src_V, uv_size, 1, srcyuv_fp);
1649 ret = fread(src_U, uv_size, 1, srcyuv_fp);
1653 printf("Unsupported source YUV format\n");
1657 upload_surface_yuv(va_dpy, surface_id,
1658 srcyuv_fourcc, frame_width, frame_height,
1659 src_Y, src_U, src_V);
1671 static int save_recyuv(VASurfaceID surface_id,
1672 unsigned long long display_order,
1673 unsigned long long encode_order)
1675 unsigned char *dst_Y = NULL, *dst_U = NULL, *dst_V = NULL;
1677 if (recyuv_fp == NULL)
1680 if (srcyuv_fourcc == VA_FOURCC_NV12) {
1681 int uv_size = 2 * (frame_width/2) * (frame_height/2);
1682 dst_Y = malloc(2*uv_size);
1683 dst_U = malloc(uv_size);
1684 } else if (srcyuv_fourcc == VA_FOURCC_IYUV ||
1685 srcyuv_fourcc == VA_FOURCC_YV12) {
1686 int uv_size = (frame_width/2) * (frame_height/2);
1687 dst_Y = malloc(4*uv_size);
1688 dst_U = malloc(uv_size);
1689 dst_V = malloc(uv_size);
1691 printf("Unsupported source YUV format\n");
1695 download_surface_yuv(va_dpy, surface_id,
1696 srcyuv_fourcc, frame_width, frame_height,
1697 dst_Y, dst_U, dst_V);
1698 fseek(recyuv_fp, display_order * frame_width * frame_height * 1.5, SEEK_SET);
1700 if (srcyuv_fourcc == VA_FOURCC_NV12) {
1701 int uv_size = 2 * (frame_width/2) * (frame_height/2);
1702 fwrite(dst_Y, uv_size * 2, 1, recyuv_fp);
1703 fwrite(dst_U, uv_size, 1, recyuv_fp);
1704 } else if (srcyuv_fourcc == VA_FOURCC_IYUV ||
1705 srcyuv_fourcc == VA_FOURCC_YV12) {
1706 int uv_size = (frame_width/2) * (frame_height/2);
1707 fwrite(dst_Y, uv_size * 4, 1, recyuv_fp);
1709 if (srcyuv_fourcc == VA_FOURCC_IYUV) {
1710 fwrite(dst_U, uv_size, 1, recyuv_fp);
1711 fwrite(dst_V, uv_size, 1, recyuv_fp);
1713 fwrite(dst_V, uv_size, 1, recyuv_fp);
1714 fwrite(dst_U, uv_size, 1, recyuv_fp);
1717 printf("Unsupported YUV format\n");
1732 static int save_codeddata(unsigned long long display_order, unsigned long long encode_order)
1734 VACodedBufferSegment *buf_list = NULL;
1736 unsigned int coded_size = 0;
1738 va_status = vaMapBuffer(va_dpy,coded_buf[display_order % SURFACE_NUM],(void **)(&buf_list));
1739 CHECK_VASTATUS(va_status,"vaMapBuffer");
1740 while (buf_list != NULL) {
1741 coded_size += fwrite(buf_list->buf, 1, buf_list->size, coded_fp);
1742 buf_list = (VACodedBufferSegment *) buf_list->next;
1744 frame_size += coded_size;
1746 vaUnmapBuffer(va_dpy,coded_buf[display_order % SURFACE_NUM]);
1748 printf("\r "); /* return back to startpoint */
1749 switch (encode_order % 4) {
1763 printf("%08lld", encode_order);
1765 if (current_frame_encoding % intra_count == 0)
1770 printf("(%06d bytes coded)",coded_size);
1771 /* skipped frame ? */
1778 static struct storage_task_t * storage_task_dequeue(void)
1780 struct storage_task_t *header;
1782 pthread_mutex_lock(&encode_mutex);
1784 header = storage_task_header;
1785 if (storage_task_header != NULL) {
1786 if (storage_task_tail == storage_task_header)
1787 storage_task_tail = NULL;
1788 storage_task_header = header->next;
1791 pthread_mutex_unlock(&encode_mutex);
1796 static int storage_task_queue(unsigned long long display_order, unsigned long long encode_order)
1798 struct storage_task_t *tmp;
1800 tmp = calloc(1, sizeof(struct storage_task_t));
1801 tmp->display_order = display_order;
1802 tmp->encode_order = encode_order;
1804 pthread_mutex_lock(&encode_mutex);
1806 if (storage_task_header == NULL) {
1807 storage_task_header = tmp;
1808 storage_task_tail = tmp;
1810 storage_task_tail->next = tmp;
1811 storage_task_tail = tmp;
1814 srcsurface_status[display_order % SURFACE_NUM] = SRC_SURFACE_IN_STORAGE;
1815 pthread_cond_signal(&encode_cond);
1817 pthread_mutex_unlock(&encode_mutex);
1822 static void storage_task(unsigned long long display_order, unsigned long long encode_order)
1827 tmp = GetTickCount();
1828 va_status = vaSyncSurface(va_dpy, src_surface[display_order % SURFACE_NUM]);
1829 CHECK_VASTATUS(va_status,"vaSyncSurface");
1830 SyncPictureTicks += GetTickCount() - tmp;
1831 tmp = GetTickCount();
1832 save_codeddata(display_order, encode_order);
1833 SavePictureTicks += GetTickCount() - tmp;
1835 save_recyuv(ref_surface[display_order % SURFACE_NUM], display_order, encode_order);
1837 /* reload a new frame data */
1838 tmp = GetTickCount();
1839 if (srcyuv_fp != NULL)
1840 load_surface(src_surface[display_order % SURFACE_NUM], display_order + SURFACE_NUM);
1841 UploadPictureTicks += GetTickCount() - tmp;
1843 pthread_mutex_lock(&encode_mutex);
1844 srcsurface_status[display_order % SURFACE_NUM] = SRC_SURFACE_IN_ENCODING;
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) {
1914 tmp = GetTickCount();
1915 va_status = vaBeginPicture(va_dpy, context_id, src_surface[current_slot]);
1916 CHECK_VASTATUS(va_status,"vaBeginPicture");
1917 BeginPictureTicks += GetTickCount() - tmp;
1919 tmp = GetTickCount();
1920 if (current_frame_type == FRAME_IDR) {
1923 if (h264_packedheader) {
1924 render_packedsequence();
1925 render_packedpicture();
1927 //if (rc_mode == VA_RC_CBR)
1928 // render_packedsei();
1931 //render_sequence();
1933 //if (rc_mode == VA_RC_CBR)
1934 // render_packedsei();
1938 RenderPictureTicks += GetTickCount() - tmp;
1940 tmp = GetTickCount();
1941 va_status = vaEndPicture(va_dpy,context_id);
1942 CHECK_VASTATUS(va_status,"vaEndPicture");;
1943 EndPictureTicks += GetTickCount() - tmp;
1945 if (encode_syncmode)
1946 storage_task(current_frame_display, current_frame_encoding);
1947 else /* queue the storage task queue */
1948 storage_task_queue(current_frame_display, current_frame_encoding);
1950 /* how to process skipped frames
1951 surface_status = (VASurfaceStatus) 0;
1952 va_status = vaQuerySurfaceStatus(va_dpy, src_surface[i%SURFACE_NUM],&surface_status);
1953 frame_skipped = (surface_status & VASurfaceSkipped);
1955 update_ReferenceFrames();
1958 if (encode_syncmode == 0) {
1960 pthread_join(encode_thread, (void **)&ret);
1967 static int release_encode()
1971 vaDestroySurfaces(va_dpy,&src_surface[0],SURFACE_NUM);
1972 vaDestroySurfaces(va_dpy,&ref_surface[0],SURFACE_NUM);
1974 for (i = 0; i < SURFACE_NUM; i++)
1975 vaDestroyBuffer(va_dpy,coded_buf[i]);
1977 vaDestroyContext(va_dpy,context_id);
1978 vaDestroyConfig(va_dpy,config_id);
1983 static int deinit_va()
1985 vaTerminate(va_dpy);
1987 va_close_display(va_dpy);
1993 static int print_input()
1995 printf("\n\nINPUT:Try to encode H264...\n");
1996 printf("INPUT: RateControl : %s\n", rc_to_string(rc_mode));
1997 printf("INPUT: Resolution : %dx%d, %d frames\n",
1998 frame_width, frame_height, frame_count);
1999 printf("INPUT: FrameRate : %d\n", frame_rate);
2000 printf("INPUT: Bitrate : %d\n", frame_bitrate);
2001 printf("INPUT: Slieces : %d\n", frame_slices);
2002 printf("INPUT: IntraPeriod : %d\n", intra_period);
2003 printf("INPUT: IDRPeriod : %d\n", intra_idr_period);
2004 printf("INPUT: IpPeriod : %d\n", ip_period);
2005 printf("INPUT: Initial QP : %d\n", initial_qp);
2006 printf("INPUT: Min QP : %d\n", minimal_qp);
2007 printf("INPUT: Source YUV : %s", srcyuv_fp?"FILE":"AUTO generated");
2009 printf(":%s (fourcc %s)\n", srcyuv_fn, fourcc_to_string(srcyuv_fourcc));
2012 printf("INPUT: Coded Clip : %s\n", coded_fn);
2013 if (recyuv_fp == NULL)
2014 printf("INPUT: Rec Clip : %s\n", "Not save reconstructed frame");
2016 printf("INPUT: Rec Clip : Save reconstructed frame into %s (fourcc %s)\n", recyuv_fn,
2017 fourcc_to_string(srcyuv_fourcc));
2019 printf("\n\n"); /* return back to startpoint */
2024 static int calc_PSNR(double *psnr)
2026 unsigned long srcyuv_size, recyuv_size, min_size;
2027 char *srcyuv_ptr, *recyuv_ptr;
2028 unsigned long i, sse=0;
2031 fseek(srcyuv_fp, 0L, SEEK_END);
2032 srcyuv_size = ftell(srcyuv_fp);
2033 fseek(recyuv_fp, 0L, SEEK_END);
2034 recyuv_size = ftell(recyuv_fp);
2036 fseek(srcyuv_fp, 0L, SEEK_SET);
2037 fseek(recyuv_fp, 0L, SEEK_SET);
2039 min_size = MIN(srcyuv_size,recyuv_size);
2040 srcyuv_ptr = mmap (0, min_size, PROT_READ, MAP_SHARED, fileno(srcyuv_fp), 0);
2041 recyuv_ptr = mmap (0, min_size, PROT_READ, MAP_SHARED, fileno(recyuv_fp), 0);
2042 if ((srcyuv_ptr == MAP_FAILED) || (recyuv_ptr == MAP_FAILED)) {
2043 printf("Failed to mmap YUV files\n");
2047 for (i=0; i<min_size; i++) {
2048 char tmp = srcyuv_ptr[i] - recyuv_ptr[i];
2051 ssemean = (double)sse/(double)min_size;
2052 *psnr = 20.0*log10(255) - 10.0*log10(ssemean);
2054 munmap(srcyuv_ptr, min_size);
2055 munmap(recyuv_ptr, min_size);
2060 static int print_performance(unsigned int PictureCount)
2062 unsigned int psnr_ret = 1, others = 0;
2063 double psnr = 0, total_size = frame_width * frame_height * 1.5 * frame_count;
2065 if (calc_psnr && srcyuv_fp && recyuv_fp)
2066 psnr_ret = calc_PSNR(&psnr);
2068 others = TotalTicks - UploadPictureTicks - BeginPictureTicks
2069 - RenderPictureTicks - EndPictureTicks - SyncPictureTicks - SavePictureTicks;
2073 printf("PERFORMANCE: Frame Rate : %.2f fps (%d frames, %d ms (%.2f ms per frame))\n",
2074 (double) 1000*PictureCount / TotalTicks, PictureCount,
2075 TotalTicks, ((double) TotalTicks) / (double) PictureCount);
2076 printf("PERFORMANCE: Compression ratio : %d:1\n", (unsigned int)(total_size / frame_size));
2078 printf("PERFORMANCE: PSNR : %.2f (%lld frames calculated)\n",
2079 psnr, MIN(frame_count, srcyuv_frames));
2081 printf("PERFORMANCE: UploadPicture : %d ms (%.2f, %.2f%% percent)\n",
2082 (int) UploadPictureTicks, ((double) UploadPictureTicks) / (double) PictureCount,
2083 UploadPictureTicks/(double) TotalTicks/0.01);
2084 printf("PERFORMANCE: vaBeginPicture : %d ms (%.2f, %.2f%% percent)\n",
2085 (int) BeginPictureTicks, ((double) BeginPictureTicks) / (double) PictureCount,
2086 BeginPictureTicks/(double) TotalTicks/0.01);
2087 printf("PERFORMANCE: vaRenderHeader : %d ms (%.2f, %.2f%% percent)\n",
2088 (int) RenderPictureTicks, ((double) RenderPictureTicks) / (double) PictureCount,
2089 RenderPictureTicks/(double) TotalTicks/0.01);
2090 printf("PERFORMANCE: vaEndPicture : %d ms (%.2f, %.2f%% percent)\n",
2091 (int) EndPictureTicks, ((double) EndPictureTicks) / (double) PictureCount,
2092 EndPictureTicks/(double) TotalTicks/0.01);
2093 printf("PERFORMANCE: vaSyncSurface : %d ms (%.2f, %.2f%% percent)\n",
2094 (int) SyncPictureTicks, ((double) SyncPictureTicks) / (double) PictureCount,
2095 SyncPictureTicks/(double) TotalTicks/0.01);
2096 printf("PERFORMANCE: SavePicture : %d ms (%.2f, %.2f%% percent)\n",
2097 (int) SavePictureTicks, ((double) SavePictureTicks) / (double) PictureCount,
2098 SavePictureTicks/(double) TotalTicks/0.01);
2099 printf("PERFORMANCE: Others : %d ms (%.2f, %.2f%% percent)\n",
2100 (int) others, ((double) others) / (double) PictureCount,
2101 others/(double) TotalTicks/0.01);
2103 if (encode_syncmode == 0)
2104 printf("(Multithread enabled, the timing is only for reference)\n");
2110 int main(int argc,char **argv)
2114 process_cmdline(argc, argv);
2118 start = GetTickCount();
2128 TotalTicks += GetTickCount() - start;
2129 print_performance(frame_count);