]> git.sesse.net Git - nageru/blob - h264encode.cpp
fe51b9e8d06a50ae4739c676d039a497fa058a12
[nageru] / h264encode.cpp
1 //#include "sysdeps.h"
2 #include <stdio.h>
3 #include <string.h>
4 #include <stdlib.h>
5 #include <getopt.h>
6 #include <unistd.h>
7 #include <sys/types.h>
8 #include <sys/stat.h>
9 #include <sys/time.h>
10 #include <sys/mman.h>
11 #include <fcntl.h>
12 #include <assert.h>
13 #include <pthread.h>
14 #include <errno.h>
15 #include <math.h>
16 #include <va/va.h>
17 #include <va/va_x11.h>
18 #include <va/va_enc_h264.h>
19 #include <va/va_drmcommon.h>
20 #include <libdrm/drm_fourcc.h>
21 #include <thread>
22 #include <mutex>
23 #include <queue>
24 #include <condition_variable>
25 #include "h264encode.h"
26
27 #define CHECK_VASTATUS(va_status, func)                                 \
28     if (va_status != VA_STATUS_SUCCESS) {                               \
29         fprintf(stderr, "%s:%d (%s) failed with %d\n", __func__, __LINE__, func, va_status); \
30         exit(1);                                                        \
31     }
32
33 //#include "loadsurface.h"
34
35 #define NAL_REF_IDC_NONE        0
36 #define NAL_REF_IDC_LOW         1
37 #define NAL_REF_IDC_MEDIUM      2
38 #define NAL_REF_IDC_HIGH        3
39
40 #define NAL_NON_IDR             1
41 #define NAL_IDR                 5
42 #define NAL_SPS                 7
43 #define NAL_PPS                 8
44 #define NAL_SEI                 6
45
46 #define SLICE_TYPE_P            0
47 #define SLICE_TYPE_B            1
48 #define SLICE_TYPE_I            2
49 #define IS_P_SLICE(type) (SLICE_TYPE_P == (type))
50 #define IS_B_SLICE(type) (SLICE_TYPE_B == (type))
51 #define IS_I_SLICE(type) (SLICE_TYPE_I == (type))
52
53
54 #define ENTROPY_MODE_CAVLC      0
55 #define ENTROPY_MODE_CABAC      1
56
57 #define PROFILE_IDC_BASELINE    66
58 #define PROFILE_IDC_MAIN        77
59 #define PROFILE_IDC_HIGH        100
60    
61 #define BITSTREAM_ALLOCATE_STEPPING     4096
62
63 #define SURFACE_NUM 16 /* 16 surfaces for source YUV */
64 static  VADisplay va_dpy;
65 static  VAProfile h264_profile = (VAProfile)~0;
66 static  VAConfigAttrib config_attrib[VAConfigAttribTypeMax];
67 static  int config_attrib_num = 0, enc_packed_header_idx;
68
69 struct GLSurface {
70         VASurfaceID src_surface, ref_surface;
71         VABufferID coded_buf;
72
73         VAImage surface_image;
74         GLuint y_tex, cbcr_tex;
75         EGLImage y_egl_image, cbcr_egl_image;
76 };
77 GLSurface gl_surfaces[SURFACE_NUM];
78
79 static  VAConfigID config_id;
80 static  VAContextID context_id;
81 static  VAEncSequenceParameterBufferH264 seq_param;
82 static  VAEncPictureParameterBufferH264 pic_param;
83 static  VAEncSliceParameterBufferH264 slice_param;
84 static  VAPictureH264 CurrentCurrPic;
85 static  VAPictureH264 ReferenceFrames[16], RefPicList0_P[32], RefPicList0_B[32], RefPicList1_B[32];
86
87 static  unsigned int MaxFrameNum = (2<<16);
88 static  unsigned int MaxPicOrderCntLsb = (2<<8);
89 static  unsigned int Log2MaxFrameNum = 16;
90 static  unsigned int Log2MaxPicOrderCntLsb = 8;
91
92 static  unsigned int num_ref_frames = 2;
93 static  unsigned int numShortTerm = 0;
94 static  int constraint_set_flag = 0;
95 static  int h264_packedheader = 0; /* support pack header? */
96 static  int h264_maxref = (1<<16|1);
97 static  int h264_entropy_mode = 1; /* cabac */
98
99 static  char *coded_fn = NULL;
100 static  FILE *coded_fp = NULL;
101
102 static  int frame_width = 176;
103 static  int frame_height = 144;
104 static  int frame_width_mbaligned;
105 static  int frame_height_mbaligned;
106 static  int frame_rate = 60;
107 static  unsigned int frame_bitrate = 0;
108 static  unsigned int frame_slices = 1;
109 static  double frame_size = 0;
110 static  int initial_qp = 15;
111 //static  int initial_qp = 28;
112 static  int minimal_qp = 0;
113 static  int intra_period = 30;
114 static  int intra_idr_period = 60;
115 static  int ip_period = 1;
116 static  int rc_mode = -1;
117 static  int rc_default_modes[] = {
118     VA_RC_VBR,
119     VA_RC_CQP,
120     VA_RC_VBR_CONSTRAINED,
121     VA_RC_CBR,
122     VA_RC_VCM,
123     VA_RC_NONE,
124 };
125 static  unsigned long long current_frame_encoding = 0;
126 static  unsigned long long current_frame_display = 0;
127 static  unsigned long long current_IDR_display = 0;
128 static  unsigned int current_frame_num = 0;
129 static  int current_frame_type;
130
131 static  int misc_priv_type = 0;
132 static  int misc_priv_value = 0;
133
134 /* thread to save coded data */
135 #define SRC_SURFACE_FREE        0
136 #define SRC_SURFACE_IN_ENCODING 1
137     
138 struct __bitstream {
139     unsigned int *buffer;
140     int bit_offset;
141     int max_size_in_dword;
142 };
143 typedef struct __bitstream bitstream;
144
145 using namespace std;
146
147 static unsigned int 
148 va_swap32(unsigned int val)
149 {
150     unsigned char *pval = (unsigned char *)&val;
151
152     return ((pval[0] << 24)     |
153             (pval[1] << 16)     |
154             (pval[2] << 8)      |
155             (pval[3] << 0));
156 }
157
158 static void
159 bitstream_start(bitstream *bs)
160 {
161     bs->max_size_in_dword = BITSTREAM_ALLOCATE_STEPPING;
162     bs->buffer = (unsigned int *)calloc(bs->max_size_in_dword * sizeof(int), 1);
163     bs->bit_offset = 0;
164 }
165
166 static void
167 bitstream_end(bitstream *bs)
168 {
169     int pos = (bs->bit_offset >> 5);
170     int bit_offset = (bs->bit_offset & 0x1f);
171     int bit_left = 32 - bit_offset;
172
173     if (bit_offset) {
174         bs->buffer[pos] = va_swap32((bs->buffer[pos] << bit_left));
175     }
176 }
177  
178 static void
179 bitstream_put_ui(bitstream *bs, unsigned int val, int size_in_bits)
180 {
181     int pos = (bs->bit_offset >> 5);
182     int bit_offset = (bs->bit_offset & 0x1f);
183     int bit_left = 32 - bit_offset;
184
185     if (!size_in_bits)
186         return;
187
188     bs->bit_offset += size_in_bits;
189
190     if (bit_left > size_in_bits) {
191         bs->buffer[pos] = (bs->buffer[pos] << size_in_bits | val);
192     } else {
193         size_in_bits -= bit_left;
194         bs->buffer[pos] = (bs->buffer[pos] << bit_left) | (val >> size_in_bits);
195         bs->buffer[pos] = va_swap32(bs->buffer[pos]);
196
197         if (pos + 1 == bs->max_size_in_dword) {
198             bs->max_size_in_dword += BITSTREAM_ALLOCATE_STEPPING;
199             bs->buffer = (unsigned int *)realloc(bs->buffer, bs->max_size_in_dword * sizeof(unsigned int));
200         }
201
202         bs->buffer[pos + 1] = val;
203     }
204 }
205
206 static void
207 bitstream_put_ue(bitstream *bs, unsigned int val)
208 {
209     int size_in_bits = 0;
210     int tmp_val = ++val;
211
212     while (tmp_val) {
213         tmp_val >>= 1;
214         size_in_bits++;
215     }
216
217     bitstream_put_ui(bs, 0, size_in_bits - 1); // leading zero
218     bitstream_put_ui(bs, val, size_in_bits);
219 }
220
221 static void
222 bitstream_put_se(bitstream *bs, int val)
223 {
224     unsigned int new_val;
225
226     if (val <= 0)
227         new_val = -2 * val;
228     else
229         new_val = 2 * val - 1;
230
231     bitstream_put_ue(bs, new_val);
232 }
233
234 static void
235 bitstream_byte_aligning(bitstream *bs, int bit)
236 {
237     int bit_offset = (bs->bit_offset & 0x7);
238     int bit_left = 8 - bit_offset;
239     int new_val;
240
241     if (!bit_offset)
242         return;
243
244     assert(bit == 0 || bit == 1);
245
246     if (bit)
247         new_val = (1 << bit_left) - 1;
248     else
249         new_val = 0;
250
251     bitstream_put_ui(bs, new_val, bit_left);
252 }
253
254 static void 
255 rbsp_trailing_bits(bitstream *bs)
256 {
257     bitstream_put_ui(bs, 1, 1);
258     bitstream_byte_aligning(bs, 0);
259 }
260
261 static void nal_start_code_prefix(bitstream *bs)
262 {
263     bitstream_put_ui(bs, 0x00000001, 32);
264 }
265
266 static void nal_header(bitstream *bs, int nal_ref_idc, int nal_unit_type)
267 {
268     bitstream_put_ui(bs, 0, 1);                /* forbidden_zero_bit: 0 */
269     bitstream_put_ui(bs, nal_ref_idc, 2);
270     bitstream_put_ui(bs, nal_unit_type, 5);
271 }
272
273 static void sps_rbsp(bitstream *bs)
274 {
275     int profile_idc = PROFILE_IDC_BASELINE;
276
277     if (h264_profile  == VAProfileH264High)
278         profile_idc = PROFILE_IDC_HIGH;
279     else if (h264_profile  == VAProfileH264Main)
280         profile_idc = PROFILE_IDC_MAIN;
281
282     bitstream_put_ui(bs, profile_idc, 8);               /* profile_idc */
283     bitstream_put_ui(bs, !!(constraint_set_flag & 1), 1);                         /* constraint_set0_flag */
284     bitstream_put_ui(bs, !!(constraint_set_flag & 2), 1);                         /* constraint_set1_flag */
285     bitstream_put_ui(bs, !!(constraint_set_flag & 4), 1);                         /* constraint_set2_flag */
286     bitstream_put_ui(bs, !!(constraint_set_flag & 8), 1);                         /* constraint_set3_flag */
287     bitstream_put_ui(bs, 0, 4);                         /* reserved_zero_4bits */
288     bitstream_put_ui(bs, seq_param.level_idc, 8);      /* level_idc */
289     bitstream_put_ue(bs, seq_param.seq_parameter_set_id);      /* seq_parameter_set_id */
290
291     if ( profile_idc == PROFILE_IDC_HIGH) {
292         bitstream_put_ue(bs, 1);        /* chroma_format_idc = 1, 4:2:0 */ 
293         bitstream_put_ue(bs, 0);        /* bit_depth_luma_minus8 */
294         bitstream_put_ue(bs, 0);        /* bit_depth_chroma_minus8 */
295         bitstream_put_ui(bs, 0, 1);     /* qpprime_y_zero_transform_bypass_flag */
296         bitstream_put_ui(bs, 0, 1);     /* seq_scaling_matrix_present_flag */
297     }
298
299     bitstream_put_ue(bs, seq_param.seq_fields.bits.log2_max_frame_num_minus4); /* log2_max_frame_num_minus4 */
300     bitstream_put_ue(bs, seq_param.seq_fields.bits.pic_order_cnt_type);        /* pic_order_cnt_type */
301
302     if (seq_param.seq_fields.bits.pic_order_cnt_type == 0)
303         bitstream_put_ue(bs, seq_param.seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4);     /* log2_max_pic_order_cnt_lsb_minus4 */
304     else {
305         assert(0);
306     }
307
308     bitstream_put_ue(bs, seq_param.max_num_ref_frames);        /* num_ref_frames */
309     bitstream_put_ui(bs, 0, 1);                                 /* gaps_in_frame_num_value_allowed_flag */
310
311     bitstream_put_ue(bs, seq_param.picture_width_in_mbs - 1);  /* pic_width_in_mbs_minus1 */
312     bitstream_put_ue(bs, seq_param.picture_height_in_mbs - 1); /* pic_height_in_map_units_minus1 */
313     bitstream_put_ui(bs, seq_param.seq_fields.bits.frame_mbs_only_flag, 1);    /* frame_mbs_only_flag */
314
315     if (!seq_param.seq_fields.bits.frame_mbs_only_flag) {
316         assert(0);
317     }
318
319     bitstream_put_ui(bs, seq_param.seq_fields.bits.direct_8x8_inference_flag, 1);      /* direct_8x8_inference_flag */
320     bitstream_put_ui(bs, seq_param.frame_cropping_flag, 1);            /* frame_cropping_flag */
321
322     if (seq_param.frame_cropping_flag) {
323         bitstream_put_ue(bs, seq_param.frame_crop_left_offset);        /* frame_crop_left_offset */
324         bitstream_put_ue(bs, seq_param.frame_crop_right_offset);       /* frame_crop_right_offset */
325         bitstream_put_ue(bs, seq_param.frame_crop_top_offset);         /* frame_crop_top_offset */
326         bitstream_put_ue(bs, seq_param.frame_crop_bottom_offset);      /* frame_crop_bottom_offset */
327     }
328     
329     //if ( frame_bit_rate < 0 ) { //TODO EW: the vui header isn't correct
330     if ( false ) {
331         bitstream_put_ui(bs, 0, 1); /* vui_parameters_present_flag */
332     } else {
333         bitstream_put_ui(bs, 1, 1); /* vui_parameters_present_flag */
334         bitstream_put_ui(bs, 0, 1); /* aspect_ratio_info_present_flag */
335         bitstream_put_ui(bs, 0, 1); /* overscan_info_present_flag */
336         bitstream_put_ui(bs, 0, 1); /* video_signal_type_present_flag */
337         bitstream_put_ui(bs, 0, 1); /* chroma_loc_info_present_flag */
338         bitstream_put_ui(bs, 1, 1); /* timing_info_present_flag */
339         {
340             bitstream_put_ui(bs, 1, 32);  // FPS
341             bitstream_put_ui(bs, frame_rate * 2, 32);  // FPS
342             bitstream_put_ui(bs, 1, 1);
343         }
344         bitstream_put_ui(bs, 1, 1); /* nal_hrd_parameters_present_flag */
345         {
346             // hrd_parameters 
347             bitstream_put_ue(bs, 0);    /* cpb_cnt_minus1 */
348             bitstream_put_ui(bs, 4, 4); /* bit_rate_scale */
349             bitstream_put_ui(bs, 6, 4); /* cpb_size_scale */
350            
351             bitstream_put_ue(bs, frame_bitrate - 1); /* bit_rate_value_minus1[0] */
352             bitstream_put_ue(bs, frame_bitrate*8 - 1); /* cpb_size_value_minus1[0] */
353             bitstream_put_ui(bs, 1, 1);  /* cbr_flag[0] */
354
355             bitstream_put_ui(bs, 23, 5);   /* initial_cpb_removal_delay_length_minus1 */
356             bitstream_put_ui(bs, 23, 5);   /* cpb_removal_delay_length_minus1 */
357             bitstream_put_ui(bs, 23, 5);   /* dpb_output_delay_length_minus1 */
358             bitstream_put_ui(bs, 23, 5);   /* time_offset_length  */
359         }
360         bitstream_put_ui(bs, 0, 1);   /* vcl_hrd_parameters_present_flag */
361         bitstream_put_ui(bs, 0, 1);   /* low_delay_hrd_flag */ 
362
363         bitstream_put_ui(bs, 0, 1); /* pic_struct_present_flag */
364         bitstream_put_ui(bs, 0, 1); /* bitstream_restriction_flag */
365     }
366
367     rbsp_trailing_bits(bs);     /* rbsp_trailing_bits */
368 }
369
370
371 static void pps_rbsp(bitstream *bs)
372 {
373     bitstream_put_ue(bs, pic_param.pic_parameter_set_id);      /* pic_parameter_set_id */
374     bitstream_put_ue(bs, pic_param.seq_parameter_set_id);      /* seq_parameter_set_id */
375
376     bitstream_put_ui(bs, pic_param.pic_fields.bits.entropy_coding_mode_flag, 1);  /* entropy_coding_mode_flag */
377
378     bitstream_put_ui(bs, 0, 1);                         /* pic_order_present_flag: 0 */
379
380     bitstream_put_ue(bs, 0);                            /* num_slice_groups_minus1 */
381
382     bitstream_put_ue(bs, pic_param.num_ref_idx_l0_active_minus1);      /* num_ref_idx_l0_active_minus1 */
383     bitstream_put_ue(bs, pic_param.num_ref_idx_l1_active_minus1);      /* num_ref_idx_l1_active_minus1 1 */
384
385     bitstream_put_ui(bs, pic_param.pic_fields.bits.weighted_pred_flag, 1);     /* weighted_pred_flag: 0 */
386     bitstream_put_ui(bs, pic_param.pic_fields.bits.weighted_bipred_idc, 2);     /* weighted_bipred_idc: 0 */
387
388     bitstream_put_se(bs, pic_param.pic_init_qp - 26);  /* pic_init_qp_minus26 */
389     bitstream_put_se(bs, 0);                            /* pic_init_qs_minus26 */
390     bitstream_put_se(bs, 0);                            /* chroma_qp_index_offset */
391
392     bitstream_put_ui(bs, pic_param.pic_fields.bits.deblocking_filter_control_present_flag, 1); /* deblocking_filter_control_present_flag */
393     bitstream_put_ui(bs, 0, 1);                         /* constrained_intra_pred_flag */
394     bitstream_put_ui(bs, 0, 1);                         /* redundant_pic_cnt_present_flag */
395     
396     /* more_rbsp_data */
397     bitstream_put_ui(bs, pic_param.pic_fields.bits.transform_8x8_mode_flag, 1);    /*transform_8x8_mode_flag */
398     bitstream_put_ui(bs, 0, 1);                         /* pic_scaling_matrix_present_flag */
399     bitstream_put_se(bs, pic_param.second_chroma_qp_index_offset );    /*second_chroma_qp_index_offset */
400
401     rbsp_trailing_bits(bs);
402 }
403
404 static void slice_header(bitstream *bs)
405 {
406     int first_mb_in_slice = slice_param.macroblock_address;
407
408     bitstream_put_ue(bs, first_mb_in_slice);        /* first_mb_in_slice: 0 */
409     bitstream_put_ue(bs, slice_param.slice_type);   /* slice_type */
410     bitstream_put_ue(bs, slice_param.pic_parameter_set_id);        /* pic_parameter_set_id: 0 */
411     bitstream_put_ui(bs, pic_param.frame_num, seq_param.seq_fields.bits.log2_max_frame_num_minus4 + 4); /* frame_num */
412
413     /* frame_mbs_only_flag == 1 */
414     if (!seq_param.seq_fields.bits.frame_mbs_only_flag) {
415         /* FIXME: */
416         assert(0);
417     }
418
419     if (pic_param.pic_fields.bits.idr_pic_flag)
420         bitstream_put_ue(bs, slice_param.idr_pic_id);           /* idr_pic_id: 0 */
421
422     if (seq_param.seq_fields.bits.pic_order_cnt_type == 0) {
423         bitstream_put_ui(bs, pic_param.CurrPic.TopFieldOrderCnt, seq_param.seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4 + 4);
424         /* pic_order_present_flag == 0 */
425     } else {
426         /* FIXME: */
427         assert(0);
428     }
429
430     /* redundant_pic_cnt_present_flag == 0 */
431     /* slice type */
432     if (IS_P_SLICE(slice_param.slice_type)) {
433         bitstream_put_ui(bs, slice_param.num_ref_idx_active_override_flag, 1);            /* num_ref_idx_active_override_flag: */
434
435         if (slice_param.num_ref_idx_active_override_flag)
436             bitstream_put_ue(bs, slice_param.num_ref_idx_l0_active_minus1);
437
438         /* ref_pic_list_reordering */
439         bitstream_put_ui(bs, 0, 1);            /* ref_pic_list_reordering_flag_l0: 0 */
440     } else if (IS_B_SLICE(slice_param.slice_type)) {
441         bitstream_put_ui(bs, slice_param.direct_spatial_mv_pred_flag, 1);            /* direct_spatial_mv_pred: 1 */
442
443         bitstream_put_ui(bs, slice_param.num_ref_idx_active_override_flag, 1);       /* num_ref_idx_active_override_flag: */
444
445         if (slice_param.num_ref_idx_active_override_flag) {
446             bitstream_put_ue(bs, slice_param.num_ref_idx_l0_active_minus1);
447             bitstream_put_ue(bs, slice_param.num_ref_idx_l1_active_minus1);
448         }
449
450         /* ref_pic_list_reordering */
451         bitstream_put_ui(bs, 0, 1);            /* ref_pic_list_reordering_flag_l0: 0 */
452         bitstream_put_ui(bs, 0, 1);            /* ref_pic_list_reordering_flag_l1: 0 */
453     }
454
455     if ((pic_param.pic_fields.bits.weighted_pred_flag &&
456          IS_P_SLICE(slice_param.slice_type)) ||
457         ((pic_param.pic_fields.bits.weighted_bipred_idc == 1) &&
458          IS_B_SLICE(slice_param.slice_type))) {
459         /* FIXME: fill weight/offset table */
460         assert(0);
461     }
462
463     /* dec_ref_pic_marking */
464     if (pic_param.pic_fields.bits.reference_pic_flag) {     /* nal_ref_idc != 0 */
465         unsigned char no_output_of_prior_pics_flag = 0;
466         unsigned char long_term_reference_flag = 0;
467         unsigned char adaptive_ref_pic_marking_mode_flag = 0;
468
469         if (pic_param.pic_fields.bits.idr_pic_flag) {
470             bitstream_put_ui(bs, no_output_of_prior_pics_flag, 1);            /* no_output_of_prior_pics_flag: 0 */
471             bitstream_put_ui(bs, long_term_reference_flag, 1);            /* long_term_reference_flag: 0 */
472         } else {
473             bitstream_put_ui(bs, adaptive_ref_pic_marking_mode_flag, 1);            /* adaptive_ref_pic_marking_mode_flag: 0 */
474         }
475     }
476
477     if (pic_param.pic_fields.bits.entropy_coding_mode_flag &&
478         !IS_I_SLICE(slice_param.slice_type))
479         bitstream_put_ue(bs, slice_param.cabac_init_idc);               /* cabac_init_idc: 0 */
480
481     bitstream_put_se(bs, slice_param.slice_qp_delta);                   /* slice_qp_delta: 0 */
482
483     /* ignore for SP/SI */
484
485     if (pic_param.pic_fields.bits.deblocking_filter_control_present_flag) {
486         bitstream_put_ue(bs, slice_param.disable_deblocking_filter_idc);           /* disable_deblocking_filter_idc: 0 */
487
488         if (slice_param.disable_deblocking_filter_idc != 1) {
489             bitstream_put_se(bs, slice_param.slice_alpha_c0_offset_div2);          /* slice_alpha_c0_offset_div2: 2 */
490             bitstream_put_se(bs, slice_param.slice_beta_offset_div2);              /* slice_beta_offset_div2: 2 */
491         }
492     }
493
494     if (pic_param.pic_fields.bits.entropy_coding_mode_flag) {
495         bitstream_byte_aligning(bs, 1);
496     }
497 }
498
499 static int
500 build_packed_pic_buffer(unsigned char **header_buffer)
501 {
502     bitstream bs;
503
504     bitstream_start(&bs);
505     nal_start_code_prefix(&bs);
506     nal_header(&bs, NAL_REF_IDC_HIGH, NAL_PPS);
507     pps_rbsp(&bs);
508     bitstream_end(&bs);
509
510     *header_buffer = (unsigned char *)bs.buffer;
511     return bs.bit_offset;
512 }
513
514 static int
515 build_packed_seq_buffer(unsigned char **header_buffer)
516 {
517     bitstream bs;
518
519     bitstream_start(&bs);
520     nal_start_code_prefix(&bs);
521     nal_header(&bs, NAL_REF_IDC_HIGH, NAL_SPS);
522     sps_rbsp(&bs);
523     bitstream_end(&bs);
524
525     *header_buffer = (unsigned char *)bs.buffer;
526     return bs.bit_offset;
527 }
528
529 static int build_packed_slice_buffer(unsigned char **header_buffer)
530 {
531     bitstream bs;
532     int is_idr = !!pic_param.pic_fields.bits.idr_pic_flag;
533     int is_ref = !!pic_param.pic_fields.bits.reference_pic_flag;
534
535     bitstream_start(&bs);
536     nal_start_code_prefix(&bs);
537
538     if (IS_I_SLICE(slice_param.slice_type)) {
539         nal_header(&bs, NAL_REF_IDC_HIGH, is_idr ? NAL_IDR : NAL_NON_IDR);
540     } else if (IS_P_SLICE(slice_param.slice_type)) {
541         nal_header(&bs, NAL_REF_IDC_MEDIUM, NAL_NON_IDR);
542     } else {
543         assert(IS_B_SLICE(slice_param.slice_type));
544         nal_header(&bs, is_ref ? NAL_REF_IDC_LOW : NAL_REF_IDC_NONE, NAL_NON_IDR);
545     }
546
547     slice_header(&bs);
548     bitstream_end(&bs);
549
550     *header_buffer = (unsigned char *)bs.buffer;
551     return bs.bit_offset;
552 }
553
554
555 /*
556   Assume frame sequence is: Frame#0, #1, #2, ..., #M, ..., #X, ... (encoding order)
557   1) period between Frame #X and Frame #N = #X - #N
558   2) 0 means infinite for intra_period/intra_idr_period, and 0 is invalid for ip_period
559   3) intra_idr_period % intra_period (intra_period > 0) and intra_period % ip_period must be 0
560   4) intra_period and intra_idr_period take precedence over ip_period
561   5) if ip_period > 1, intra_period and intra_idr_period are not  the strict periods 
562      of I/IDR frames, see bellow examples
563   -------------------------------------------------------------------
564   intra_period intra_idr_period ip_period frame sequence (intra_period/intra_idr_period/ip_period)
565   0            ignored          1          IDRPPPPPPP ...     (No IDR/I any more)
566   0            ignored        >=2          IDR(PBB)(PBB)...   (No IDR/I any more)
567   1            0                ignored    IDRIIIIIII...      (No IDR any more)
568   1            1                ignored    IDR IDR IDR IDR...
569   1            >=2              ignored    IDRII IDRII IDR... (1/3/ignore)
570   >=2          0                1          IDRPPP IPPP I...   (3/0/1)
571   >=2          0              >=2          IDR(PBB)(PBB)(IBB) (6/0/3)
572                                               (PBB)(IBB)(PBB)(IBB)... 
573   >=2          >=2              1          IDRPPPPP IPPPPP IPPPPP (6/18/1)
574                                            IDRPPPPP IPPPPP IPPPPP...
575   >=2          >=2              >=2        {IDR(PBB)(PBB)(IBB)(PBB)(IBB)(PBB)} (6/18/3)
576                                            {IDR(PBB)(PBB)(IBB)(PBB)(IBB)(PBB)}...
577                                            {IDR(PBB)(PBB)(IBB)(PBB)}           (6/12/3)
578                                            {IDR(PBB)(PBB)(IBB)(PBB)}...
579                                            {IDR(PBB)(PBB)}                     (6/6/3)
580                                            {IDR(PBB)(PBB)}.
581 */
582
583 /*
584  * Return displaying order with specified periods and encoding order
585  * displaying_order: displaying order
586  * frame_type: frame type 
587  */
588 #define FRAME_P 0
589 #define FRAME_B 1
590 #define FRAME_I 2
591 #define FRAME_IDR 7
592 void encoding2display_order(
593     unsigned long long encoding_order, int intra_period,
594     int intra_idr_period, int ip_period,
595     unsigned long long *displaying_order,
596     int *frame_type)
597 {
598     int encoding_order_gop = 0;
599
600     if (intra_period == 1) { /* all are I/IDR frames */
601         *displaying_order = encoding_order;
602         if (intra_idr_period == 0)
603             *frame_type = (encoding_order == 0)?FRAME_IDR:FRAME_I;
604         else
605             *frame_type = (encoding_order % intra_idr_period == 0)?FRAME_IDR:FRAME_I;
606         return;
607     }
608
609     if (intra_period == 0)
610         intra_idr_period = 0;
611
612     /* new sequence like
613      * IDR PPPPP IPPPPP
614      * IDR (PBB)(PBB)(IBB)(PBB)
615      */
616     encoding_order_gop = (intra_idr_period == 0)? encoding_order:
617         (encoding_order % (intra_idr_period + ((ip_period == 1)?0:1)));
618          
619     if (encoding_order_gop == 0) { /* the first frame */
620         *frame_type = FRAME_IDR;
621         *displaying_order = encoding_order;
622     } else if (((encoding_order_gop - 1) % ip_period) != 0) { /* B frames */
623         *frame_type = FRAME_B;
624         *displaying_order = encoding_order - 1;
625     } else if ((intra_period != 0) && /* have I frames */
626                (encoding_order_gop >= 2) &&
627                ((ip_period == 1 && encoding_order_gop % intra_period == 0) || /* for IDR PPPPP IPPPP */
628                 /* for IDR (PBB)(PBB)(IBB) */
629                 (ip_period >= 2 && ((encoding_order_gop - 1) / ip_period % (intra_period / ip_period)) == 0))) {
630         *frame_type = FRAME_I;
631         *displaying_order = encoding_order + ip_period - 1;
632     } else {
633         *frame_type = FRAME_P;
634         *displaying_order = encoding_order + ip_period - 1;
635     }
636 }
637
638
639 static const char *rc_to_string(int rcmode)
640 {
641     switch (rc_mode) {
642     case VA_RC_NONE:
643         return "NONE";
644     case VA_RC_CBR:
645         return "CBR";
646     case VA_RC_VBR:
647         return "VBR";
648     case VA_RC_VCM:
649         return "VCM";
650     case VA_RC_CQP:
651         return "CQP";
652     case VA_RC_VBR_CONSTRAINED:
653         return "VBR_CONSTRAINED";
654     default:
655         return "Unknown";
656     }
657 }
658
659 #if 0
660 static int process_cmdline(int argc, char *argv[])
661 {
662     char c;
663     const struct option long_opts[] = {
664         {"help", no_argument, NULL, 0 },
665         {"bitrate", required_argument, NULL, 1 },
666         {"minqp", required_argument, NULL, 2 },
667         {"initialqp", required_argument, NULL, 3 },
668         {"intra_period", required_argument, NULL, 4 },
669         {"idr_period", required_argument, NULL, 5 },
670         {"ip_period", required_argument, NULL, 6 },
671         {"rcmode", required_argument, NULL, 7 },
672         {"srcyuv", required_argument, NULL, 9 },
673         {"recyuv", required_argument, NULL, 10 },
674         {"fourcc", required_argument, NULL, 11 },
675         {"syncmode", no_argument, NULL, 12 },
676         {"enablePSNR", no_argument, NULL, 13 },
677         {"prit", required_argument, NULL, 14 },
678         {"priv", required_argument, NULL, 15 },
679         {"framecount", required_argument, NULL, 16 },
680         {"entropy", required_argument, NULL, 17 },
681         {"profile", required_argument, NULL, 18 },
682         {NULL, no_argument, NULL, 0 }};
683     int long_index;
684     
685     while ((c =getopt_long_only(argc, argv, "w:h:n:f:o:?", long_opts, &long_index)) != EOF) {
686         switch (c) {
687         case 'w':
688             frame_width = atoi(optarg);
689             break;
690         case 'h':
691             frame_height = atoi(optarg);
692             break;
693         case 'n':
694         case 'f':
695             frame_rate = atoi(optarg);
696             break;
697         case 'o':
698             coded_fn = strdup(optarg);
699             break;
700         case 0:
701             print_help();
702             exit(0);
703         case 1:
704             frame_bitrate = atoi(optarg);
705             break;
706         case 2:
707             minimal_qp = atoi(optarg);
708             break;
709         case 3:
710             initial_qp = atoi(optarg);
711             break;
712         case 4:
713             intra_period = atoi(optarg);
714             break;
715         case 5:
716             intra_idr_period = atoi(optarg);
717             break;
718         case 6:
719             ip_period = atoi(optarg);
720             break;
721         case 7:
722             rc_mode = string_to_rc(optarg);
723             if (rc_mode < 0) {
724                 print_help();
725                 exit(1);
726             }
727             break;
728         case 9:
729             srcyuv_fn = strdup(optarg);
730             break;
731         case 11:
732             srcyuv_fourcc = string_to_fourcc(optarg);
733             if (srcyuv_fourcc <= 0) {
734                 print_help();
735                 exit(1);
736             }
737             break;
738         case 13:
739             calc_psnr = 1;
740             break;
741         case 14:
742             misc_priv_type = strtol(optarg, NULL, 0);
743             break;
744         case 15:
745             misc_priv_value = strtol(optarg, NULL, 0);
746             break;
747         case 17:
748             h264_entropy_mode = atoi(optarg) ? 1: 0;
749             break;
750         case 18:
751             if (strncmp(optarg, "BP", 2) == 0)
752                 h264_profile = VAProfileH264Baseline;
753             else if (strncmp(optarg, "MP", 2) == 0)
754                 h264_profile = VAProfileH264Main;
755             else if (strncmp(optarg, "HP", 2) == 0)
756                 h264_profile = VAProfileH264High;
757             else
758                 h264_profile = (VAProfile)0;
759             break;
760         case ':':
761         case '?':
762             print_help();
763             exit(0);
764         }
765     }
766
767     if (ip_period < 1) {
768         printf(" ip_period must be greater than 0\n");
769         exit(0);
770     }
771     if (intra_period != 1 && intra_period % ip_period != 0) {
772         printf(" intra_period must be a multiplier of ip_period\n");
773         exit(0);        
774     }
775     if (intra_period != 0 && intra_idr_period % intra_period != 0) {
776         printf(" intra_idr_period must be a multiplier of intra_period\n");
777         exit(0);        
778     }
779
780     if (frame_bitrate == 0)
781         frame_bitrate = frame_width * frame_height * 12 * frame_rate / 50;
782         
783     if (coded_fn == NULL) {
784         struct stat buf;
785         if (stat("/tmp", &buf) == 0)
786             coded_fn = strdup("/tmp/test.264");
787         else if (stat("/sdcard", &buf) == 0)
788             coded_fn = strdup("/sdcard/test.264");
789         else
790             coded_fn = strdup("./test.264");
791     }
792     
793     /* store coded data into a file */
794     coded_fp = fopen(coded_fn, "w+");
795     if (coded_fp == NULL) {
796         printf("Open file %s failed, exit\n", coded_fn);
797         exit(1);
798     }
799
800     frame_width_mbaligned = (frame_width + 15) & (~15);
801     frame_height_mbaligned = (frame_height + 15) & (~15);
802     if (frame_width != frame_width_mbaligned ||
803         frame_height != frame_height_mbaligned) {
804         printf("Source frame is %dx%d and will code clip to %dx%d with crop\n",
805                frame_width, frame_height,
806                frame_width_mbaligned, frame_height_mbaligned
807                );
808     }
809     
810     return 0;
811 }
812 #endif
813
814 static Display *x11_display;
815 static Window   x11_window;
816
817 VADisplay
818 va_open_display(void)
819 {
820     x11_display = XOpenDisplay(NULL);
821     if (!x11_display) {
822         fprintf(stderr, "error: can't connect to X server!\n");
823         return NULL;
824     }
825     return vaGetDisplay(x11_display);
826 }
827
828 void
829 va_close_display(VADisplay va_dpy)
830 {
831     if (!x11_display)
832         return;
833
834     if (x11_window) {
835         XUnmapWindow(x11_display, x11_window);
836         XDestroyWindow(x11_display, x11_window);
837         x11_window = None;
838     }
839     XCloseDisplay(x11_display);
840     x11_display = NULL;
841 }
842
843 static int init_va(void)
844 {
845     VAProfile profile_list[]={VAProfileH264High, VAProfileH264Main, VAProfileH264Baseline, VAProfileH264ConstrainedBaseline};
846     VAEntrypoint *entrypoints;
847     int num_entrypoints, slice_entrypoint;
848     int support_encode = 0;    
849     int major_ver, minor_ver;
850     VAStatus va_status;
851     unsigned int i;
852
853     va_dpy = va_open_display();
854     va_status = vaInitialize(va_dpy, &major_ver, &minor_ver);
855     CHECK_VASTATUS(va_status, "vaInitialize");
856
857     num_entrypoints = vaMaxNumEntrypoints(va_dpy);
858     entrypoints = (VAEntrypoint *)malloc(num_entrypoints * sizeof(*entrypoints));
859     if (!entrypoints) {
860         fprintf(stderr, "error: failed to initialize VA entrypoints array\n");
861         exit(1);
862     }
863
864     /* use the highest profile */
865     for (i = 0; i < sizeof(profile_list)/sizeof(profile_list[0]); i++) {
866         if ((h264_profile != ~0) && h264_profile != profile_list[i])
867             continue;
868         
869         h264_profile = profile_list[i];
870         vaQueryConfigEntrypoints(va_dpy, h264_profile, entrypoints, &num_entrypoints);
871         for (slice_entrypoint = 0; slice_entrypoint < num_entrypoints; slice_entrypoint++) {
872             if (entrypoints[slice_entrypoint] == VAEntrypointEncSlice) {
873                 support_encode = 1;
874                 break;
875             }
876         }
877         if (support_encode == 1)
878             break;
879     }
880     
881     if (support_encode == 0) {
882         printf("Can't find VAEntrypointEncSlice for H264 profiles\n");
883         exit(1);
884     } else {
885         switch (h264_profile) {
886             case VAProfileH264Baseline:
887                 printf("Use profile VAProfileH264Baseline\n");
888                 ip_period = 1;
889                 constraint_set_flag |= (1 << 0); /* Annex A.2.1 */
890                 h264_entropy_mode = 0;
891                 break;
892             case VAProfileH264ConstrainedBaseline:
893                 printf("Use profile VAProfileH264ConstrainedBaseline\n");
894                 constraint_set_flag |= (1 << 0 | 1 << 1); /* Annex A.2.2 */
895                 ip_period = 1;
896                 break;
897
898             case VAProfileH264Main:
899                 printf("Use profile VAProfileH264Main\n");
900                 constraint_set_flag |= (1 << 1); /* Annex A.2.2 */
901                 break;
902
903             case VAProfileH264High:
904                 constraint_set_flag |= (1 << 3); /* Annex A.2.4 */
905                 printf("Use profile VAProfileH264High\n");
906                 break;
907             default:
908                 printf("unknow profile. Set to Baseline");
909                 h264_profile = VAProfileH264Baseline;
910                 ip_period = 1;
911                 constraint_set_flag |= (1 << 0); /* Annex A.2.1 */
912                 break;
913         }
914     }
915
916     VAConfigAttrib attrib[VAConfigAttribTypeMax];
917
918     /* find out the format for the render target, and rate control mode */
919     for (i = 0; i < VAConfigAttribTypeMax; i++)
920         attrib[i].type = (VAConfigAttribType)i;
921
922     va_status = vaGetConfigAttributes(va_dpy, h264_profile, VAEntrypointEncSlice,
923                                       &attrib[0], VAConfigAttribTypeMax);
924     CHECK_VASTATUS(va_status, "vaGetConfigAttributes");
925     /* check the interested configattrib */
926     if ((attrib[VAConfigAttribRTFormat].value & VA_RT_FORMAT_YUV420) == 0) {
927         printf("Not find desired YUV420 RT format\n");
928         exit(1);
929     } else {
930         config_attrib[config_attrib_num].type = VAConfigAttribRTFormat;
931         config_attrib[config_attrib_num].value = VA_RT_FORMAT_YUV420;
932         config_attrib_num++;
933     }
934     
935     if (attrib[VAConfigAttribRateControl].value != VA_ATTRIB_NOT_SUPPORTED) {
936         int tmp = attrib[VAConfigAttribRateControl].value;
937
938         printf("Support rate control mode (0x%x):", tmp);
939         
940         if (tmp & VA_RC_NONE)
941             printf("NONE ");
942         if (tmp & VA_RC_CBR)
943             printf("CBR ");
944         if (tmp & VA_RC_VBR)
945             printf("VBR ");
946         if (tmp & VA_RC_VCM)
947             printf("VCM ");
948         if (tmp & VA_RC_CQP)
949             printf("CQP ");
950         if (tmp & VA_RC_VBR_CONSTRAINED)
951             printf("VBR_CONSTRAINED ");
952
953         printf("\n");
954
955         if (rc_mode == -1 || !(rc_mode & tmp))  {
956             if (rc_mode != -1) {
957                 printf("Warning: Don't support the specified RateControl mode: %s!!!, switch to ", rc_to_string(rc_mode));
958             }
959
960             for (i = 0; i < sizeof(rc_default_modes) / sizeof(rc_default_modes[0]); i++) {
961                 if (rc_default_modes[i] & tmp) {
962                     rc_mode = rc_default_modes[i];
963                     break;
964                 }
965             }
966
967             printf("RateControl mode: %s\n", rc_to_string(rc_mode));
968         }
969
970         config_attrib[config_attrib_num].type = VAConfigAttribRateControl;
971         config_attrib[config_attrib_num].value = rc_mode;
972         config_attrib_num++;
973     }
974     
975
976     if (attrib[VAConfigAttribEncPackedHeaders].value != VA_ATTRIB_NOT_SUPPORTED) {
977         int tmp = attrib[VAConfigAttribEncPackedHeaders].value;
978
979         printf("Support VAConfigAttribEncPackedHeaders\n");
980         
981         h264_packedheader = 1;
982         config_attrib[config_attrib_num].type = VAConfigAttribEncPackedHeaders;
983         config_attrib[config_attrib_num].value = VA_ENC_PACKED_HEADER_NONE;
984         
985         if (tmp & VA_ENC_PACKED_HEADER_SEQUENCE) {
986             printf("Support packed sequence headers\n");
987             config_attrib[config_attrib_num].value |= VA_ENC_PACKED_HEADER_SEQUENCE;
988         }
989         
990         if (tmp & VA_ENC_PACKED_HEADER_PICTURE) {
991             printf("Support packed picture headers\n");
992             config_attrib[config_attrib_num].value |= VA_ENC_PACKED_HEADER_PICTURE;
993         }
994         
995         if (tmp & VA_ENC_PACKED_HEADER_SLICE) {
996             printf("Support packed slice headers\n");
997             config_attrib[config_attrib_num].value |= VA_ENC_PACKED_HEADER_SLICE;
998         }
999         
1000         if (tmp & VA_ENC_PACKED_HEADER_MISC) {
1001             printf("Support packed misc headers\n");
1002             config_attrib[config_attrib_num].value |= VA_ENC_PACKED_HEADER_MISC;
1003         }
1004         
1005         enc_packed_header_idx = config_attrib_num;
1006         config_attrib_num++;
1007     }
1008
1009     if (attrib[VAConfigAttribEncInterlaced].value != VA_ATTRIB_NOT_SUPPORTED) {
1010         int tmp = attrib[VAConfigAttribEncInterlaced].value;
1011         
1012         printf("Support VAConfigAttribEncInterlaced\n");
1013
1014         if (tmp & VA_ENC_INTERLACED_FRAME)
1015             printf("support VA_ENC_INTERLACED_FRAME\n");
1016         if (tmp & VA_ENC_INTERLACED_FIELD)
1017             printf("Support VA_ENC_INTERLACED_FIELD\n");
1018         if (tmp & VA_ENC_INTERLACED_MBAFF)
1019             printf("Support VA_ENC_INTERLACED_MBAFF\n");
1020         if (tmp & VA_ENC_INTERLACED_PAFF)
1021             printf("Support VA_ENC_INTERLACED_PAFF\n");
1022         
1023         config_attrib[config_attrib_num].type = VAConfigAttribEncInterlaced;
1024         config_attrib[config_attrib_num].value = VA_ENC_PACKED_HEADER_NONE;
1025         config_attrib_num++;
1026     }
1027     
1028     if (attrib[VAConfigAttribEncMaxRefFrames].value != VA_ATTRIB_NOT_SUPPORTED) {
1029         h264_maxref = attrib[VAConfigAttribEncMaxRefFrames].value;
1030         
1031         printf("Support %d RefPicList0 and %d RefPicList1\n",
1032                h264_maxref & 0xffff, (h264_maxref >> 16) & 0xffff );
1033     }
1034
1035     if (attrib[VAConfigAttribEncMaxSlices].value != VA_ATTRIB_NOT_SUPPORTED)
1036         printf("Support %d slices\n", attrib[VAConfigAttribEncMaxSlices].value);
1037
1038     if (attrib[VAConfigAttribEncSliceStructure].value != VA_ATTRIB_NOT_SUPPORTED) {
1039         int tmp = attrib[VAConfigAttribEncSliceStructure].value;
1040         
1041         printf("Support VAConfigAttribEncSliceStructure\n");
1042
1043         if (tmp & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS)
1044             printf("Support VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS\n");
1045         if (tmp & VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS)
1046             printf("Support VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS\n");
1047         if (tmp & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS)
1048             printf("Support VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS\n");
1049     }
1050     if (attrib[VAConfigAttribEncMacroblockInfo].value != VA_ATTRIB_NOT_SUPPORTED) {
1051         printf("Support VAConfigAttribEncMacroblockInfo\n");
1052     }
1053
1054     free(entrypoints);
1055     return 0;
1056 }
1057
1058 static int setup_encode()
1059 {
1060     VAStatus va_status;
1061     VASurfaceID *tmp_surfaceid;
1062     int codedbuf_size, i;
1063     static VASurfaceID src_surface[SURFACE_NUM];
1064     static VASurfaceID ref_surface[SURFACE_NUM];
1065     
1066     va_status = vaCreateConfig(va_dpy, h264_profile, VAEntrypointEncSlice,
1067             &config_attrib[0], config_attrib_num, &config_id);
1068     CHECK_VASTATUS(va_status, "vaCreateConfig");
1069
1070     /* create source surfaces */
1071     va_status = vaCreateSurfaces(va_dpy,
1072                                  VA_RT_FORMAT_YUV420, frame_width_mbaligned, frame_height_mbaligned,
1073                                  &src_surface[0], SURFACE_NUM,
1074                                  NULL, 0);
1075     CHECK_VASTATUS(va_status, "vaCreateSurfaces");
1076
1077     /* create reference surfaces */
1078     va_status = vaCreateSurfaces(va_dpy,
1079                                  VA_RT_FORMAT_YUV420, frame_width_mbaligned, frame_height_mbaligned,
1080                                  &ref_surface[0], SURFACE_NUM,
1081                                  NULL, 0);
1082     CHECK_VASTATUS(va_status, "vaCreateSurfaces");
1083
1084     tmp_surfaceid = (VASurfaceID *)calloc(2 * SURFACE_NUM, sizeof(VASurfaceID));
1085     memcpy(tmp_surfaceid, src_surface, SURFACE_NUM * sizeof(VASurfaceID));
1086     memcpy(tmp_surfaceid + SURFACE_NUM, ref_surface, SURFACE_NUM * sizeof(VASurfaceID));
1087     
1088     /* Create a context for this encode pipe */
1089     va_status = vaCreateContext(va_dpy, config_id,
1090                                 frame_width_mbaligned, frame_height_mbaligned,
1091                                 VA_PROGRESSIVE,
1092                                 tmp_surfaceid, 2 * SURFACE_NUM,
1093                                 &context_id);
1094     CHECK_VASTATUS(va_status, "vaCreateContext");
1095     free(tmp_surfaceid);
1096
1097     codedbuf_size = (frame_width_mbaligned * frame_height_mbaligned * 400) / (16*16);
1098
1099     for (i = 0; i < SURFACE_NUM; i++) {
1100         /* create coded buffer once for all
1101          * other VA buffers which won't be used again after vaRenderPicture.
1102          * so APP can always vaCreateBuffer for every frame
1103          * but coded buffer need to be mapped and accessed after vaRenderPicture/vaEndPicture
1104          * so VA won't maintain the coded buffer
1105          */
1106         va_status = vaCreateBuffer(va_dpy, context_id, VAEncCodedBufferType,
1107                 codedbuf_size, 1, NULL, &gl_surfaces[i].coded_buf);
1108         CHECK_VASTATUS(va_status, "vaCreateBuffer");
1109     }
1110
1111     /* create OpenGL objects */
1112     //glGenFramebuffers(SURFACE_NUM, fbos);
1113     
1114     for (i = 0; i < SURFACE_NUM; i++) {
1115         glGenTextures(1, &gl_surfaces[i].y_tex);
1116         glGenTextures(1, &gl_surfaces[i].cbcr_tex);
1117     }
1118
1119     for (i = 0; i < SURFACE_NUM; i++) {
1120         gl_surfaces[i].src_surface = src_surface[i];
1121         gl_surfaces[i].ref_surface = ref_surface[i];
1122     }
1123     
1124     return 0;
1125 }
1126
1127
1128
1129 #define partition(ref, field, key, ascending)   \
1130     while (i <= j) {                            \
1131         if (ascending) {                        \
1132             while (ref[i].field < key)          \
1133                 i++;                            \
1134             while (ref[j].field > key)          \
1135                 j--;                            \
1136         } else {                                \
1137             while (ref[i].field > key)          \
1138                 i++;                            \
1139             while (ref[j].field < key)          \
1140                 j--;                            \
1141         }                                       \
1142         if (i <= j) {                           \
1143             tmp = ref[i];                       \
1144             ref[i] = ref[j];                    \
1145             ref[j] = tmp;                       \
1146             i++;                                \
1147             j--;                                \
1148         }                                       \
1149     }                                           \
1150
1151 static void sort_one(VAPictureH264 ref[], int left, int right,
1152                      int ascending, int frame_idx)
1153 {
1154     int i = left, j = right;
1155     unsigned int key;
1156     VAPictureH264 tmp;
1157
1158     if (frame_idx) {
1159         key = ref[(left + right) / 2].frame_idx;
1160         partition(ref, frame_idx, key, ascending);
1161     } else {
1162         key = ref[(left + right) / 2].TopFieldOrderCnt;
1163         partition(ref, TopFieldOrderCnt, (signed int)key, ascending);
1164     }
1165     
1166     /* recursion */
1167     if (left < j)
1168         sort_one(ref, left, j, ascending, frame_idx);
1169     
1170     if (i < right)
1171         sort_one(ref, i, right, ascending, frame_idx);
1172 }
1173
1174 static void sort_two(VAPictureH264 ref[], int left, int right, unsigned int key, unsigned int frame_idx,
1175                      int partition_ascending, int list0_ascending, int list1_ascending)
1176 {
1177     int i = left, j = right;
1178     VAPictureH264 tmp;
1179
1180     if (frame_idx) {
1181         partition(ref, frame_idx, key, partition_ascending);
1182     } else {
1183         partition(ref, TopFieldOrderCnt, (signed int)key, partition_ascending);
1184     }
1185     
1186
1187     sort_one(ref, left, i-1, list0_ascending, frame_idx);
1188     sort_one(ref, j+1, right, list1_ascending, frame_idx);
1189 }
1190
1191 static int update_ReferenceFrames(void)
1192 {
1193     int i;
1194     
1195     if (current_frame_type == FRAME_B)
1196         return 0;
1197
1198     CurrentCurrPic.flags = VA_PICTURE_H264_SHORT_TERM_REFERENCE;
1199     numShortTerm++;
1200     if (numShortTerm > num_ref_frames)
1201         numShortTerm = num_ref_frames;
1202     for (i=numShortTerm-1; i>0; i--)
1203         ReferenceFrames[i] = ReferenceFrames[i-1];
1204     ReferenceFrames[0] = CurrentCurrPic;
1205     
1206     if (current_frame_type != FRAME_B)
1207         current_frame_num++;
1208     if (current_frame_num > MaxFrameNum)
1209         current_frame_num = 0;
1210     
1211     return 0;
1212 }
1213
1214
1215 static int update_RefPicList(void)
1216 {
1217     unsigned int current_poc = CurrentCurrPic.TopFieldOrderCnt;
1218     
1219     if (current_frame_type == FRAME_P) {
1220         memcpy(RefPicList0_P, ReferenceFrames, numShortTerm * sizeof(VAPictureH264));
1221         sort_one(RefPicList0_P, 0, numShortTerm-1, 0, 1);
1222     }
1223     
1224     if (current_frame_type == FRAME_B) {
1225         memcpy(RefPicList0_B, ReferenceFrames, numShortTerm * sizeof(VAPictureH264));
1226         sort_two(RefPicList0_B, 0, numShortTerm-1, current_poc, 0,
1227                  1, 0, 1);
1228
1229         memcpy(RefPicList1_B, ReferenceFrames, numShortTerm * sizeof(VAPictureH264));
1230         sort_two(RefPicList1_B, 0, numShortTerm-1, current_poc, 0,
1231                  0, 1, 0);
1232     }
1233     
1234     return 0;
1235 }
1236
1237
1238 static int render_sequence(void)
1239 {
1240     VABufferID seq_param_buf, rc_param_buf, misc_param_tmpbuf, render_id[2];
1241     VAStatus va_status;
1242     VAEncMiscParameterBuffer *misc_param, *misc_param_tmp;
1243     VAEncMiscParameterRateControl *misc_rate_ctrl;
1244     
1245     seq_param.level_idc = 41 /*SH_LEVEL_3*/;
1246     seq_param.picture_width_in_mbs = frame_width_mbaligned / 16;
1247     seq_param.picture_height_in_mbs = frame_height_mbaligned / 16;
1248     seq_param.bits_per_second = frame_bitrate;
1249
1250     seq_param.intra_period = intra_period;
1251     seq_param.intra_idr_period = intra_idr_period;
1252     seq_param.ip_period = ip_period;
1253
1254     seq_param.max_num_ref_frames = num_ref_frames;
1255     seq_param.seq_fields.bits.frame_mbs_only_flag = 1;
1256     seq_param.time_scale = frame_rate * 2;
1257     seq_param.num_units_in_tick = 1; /* Tc = num_units_in_tick / scale */
1258     seq_param.seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4 = Log2MaxPicOrderCntLsb - 4;
1259     seq_param.seq_fields.bits.log2_max_frame_num_minus4 = Log2MaxFrameNum - 4;;
1260     seq_param.seq_fields.bits.frame_mbs_only_flag = 1;
1261     seq_param.seq_fields.bits.chroma_format_idc = 1;
1262     seq_param.seq_fields.bits.direct_8x8_inference_flag = 1;
1263     
1264     if (frame_width != frame_width_mbaligned ||
1265         frame_height != frame_height_mbaligned) {
1266         seq_param.frame_cropping_flag = 1;
1267         seq_param.frame_crop_left_offset = 0;
1268         seq_param.frame_crop_right_offset = (frame_width_mbaligned - frame_width)/2;
1269         seq_param.frame_crop_top_offset = 0;
1270         seq_param.frame_crop_bottom_offset = (frame_height_mbaligned - frame_height)/2;
1271     }
1272     
1273     va_status = vaCreateBuffer(va_dpy, context_id,
1274                                VAEncSequenceParameterBufferType,
1275                                sizeof(seq_param), 1, &seq_param, &seq_param_buf);
1276     CHECK_VASTATUS(va_status, "vaCreateBuffer");
1277     
1278     va_status = vaCreateBuffer(va_dpy, context_id,
1279                                VAEncMiscParameterBufferType,
1280                                sizeof(VAEncMiscParameterBuffer) + sizeof(VAEncMiscParameterRateControl),
1281                                1, NULL, &rc_param_buf);
1282     CHECK_VASTATUS(va_status, "vaCreateBuffer");
1283     
1284     vaMapBuffer(va_dpy, rc_param_buf, (void **)&misc_param);
1285     misc_param->type = VAEncMiscParameterTypeRateControl;
1286     misc_rate_ctrl = (VAEncMiscParameterRateControl *)misc_param->data;
1287     memset(misc_rate_ctrl, 0, sizeof(*misc_rate_ctrl));
1288     misc_rate_ctrl->bits_per_second = frame_bitrate;
1289     misc_rate_ctrl->target_percentage = 66;
1290     misc_rate_ctrl->window_size = 1000;
1291     misc_rate_ctrl->initial_qp = initial_qp;
1292     misc_rate_ctrl->min_qp = minimal_qp;
1293     misc_rate_ctrl->basic_unit_size = 0;
1294     vaUnmapBuffer(va_dpy, rc_param_buf);
1295
1296     render_id[0] = seq_param_buf;
1297     render_id[1] = rc_param_buf;
1298     
1299     va_status = vaRenderPicture(va_dpy, context_id, &render_id[0], 2);
1300     CHECK_VASTATUS(va_status, "vaRenderPicture");;
1301
1302     if (misc_priv_type != 0) {
1303         va_status = vaCreateBuffer(va_dpy, context_id,
1304                                    VAEncMiscParameterBufferType,
1305                                    sizeof(VAEncMiscParameterBuffer),
1306                                    1, NULL, &misc_param_tmpbuf);
1307         CHECK_VASTATUS(va_status, "vaCreateBuffer");
1308         vaMapBuffer(va_dpy, misc_param_tmpbuf, (void **)&misc_param_tmp);
1309         misc_param_tmp->type = (VAEncMiscParameterType)misc_priv_type;
1310         misc_param_tmp->data[0] = misc_priv_value;
1311         vaUnmapBuffer(va_dpy, misc_param_tmpbuf);
1312     
1313         va_status = vaRenderPicture(va_dpy, context_id, &misc_param_tmpbuf, 1);
1314     }
1315     
1316     return 0;
1317 }
1318
1319 static int calc_poc(int pic_order_cnt_lsb)
1320 {
1321     static int PicOrderCntMsb_ref = 0, pic_order_cnt_lsb_ref = 0;
1322     int prevPicOrderCntMsb, prevPicOrderCntLsb;
1323     int PicOrderCntMsb, TopFieldOrderCnt;
1324     
1325     if (current_frame_type == FRAME_IDR)
1326         prevPicOrderCntMsb = prevPicOrderCntLsb = 0;
1327     else {
1328         prevPicOrderCntMsb = PicOrderCntMsb_ref;
1329         prevPicOrderCntLsb = pic_order_cnt_lsb_ref;
1330     }
1331     
1332     if ((pic_order_cnt_lsb < prevPicOrderCntLsb) &&
1333         ((prevPicOrderCntLsb - pic_order_cnt_lsb) >= (int)(MaxPicOrderCntLsb / 2)))
1334         PicOrderCntMsb = prevPicOrderCntMsb + MaxPicOrderCntLsb;
1335     else if ((pic_order_cnt_lsb > prevPicOrderCntLsb) &&
1336              ((pic_order_cnt_lsb - prevPicOrderCntLsb) > (int)(MaxPicOrderCntLsb / 2)))
1337         PicOrderCntMsb = prevPicOrderCntMsb - MaxPicOrderCntLsb;
1338     else
1339         PicOrderCntMsb = prevPicOrderCntMsb;
1340     
1341     TopFieldOrderCnt = PicOrderCntMsb + pic_order_cnt_lsb;
1342
1343     if (current_frame_type != FRAME_B) {
1344         PicOrderCntMsb_ref = PicOrderCntMsb;
1345         pic_order_cnt_lsb_ref = pic_order_cnt_lsb;
1346     }
1347     
1348     return TopFieldOrderCnt;
1349 }
1350
1351 static int render_picture(void)
1352 {
1353     VABufferID pic_param_buf;
1354     VAStatus va_status;
1355     int i = 0;
1356
1357     pic_param.CurrPic.picture_id = gl_surfaces[current_frame_display % SURFACE_NUM].ref_surface;
1358     pic_param.CurrPic.frame_idx = current_frame_num;
1359     pic_param.CurrPic.flags = 0;
1360     pic_param.CurrPic.TopFieldOrderCnt = calc_poc((current_frame_display - current_IDR_display) % MaxPicOrderCntLsb);
1361     pic_param.CurrPic.BottomFieldOrderCnt = pic_param.CurrPic.TopFieldOrderCnt;
1362     CurrentCurrPic = pic_param.CurrPic;
1363
1364     if (getenv("TO_DEL")) { /* set RefPicList into ReferenceFrames */
1365         update_RefPicList(); /* calc RefPicList */
1366         memset(pic_param.ReferenceFrames, 0xff, 16 * sizeof(VAPictureH264)); /* invalid all */
1367         if (current_frame_type == FRAME_P) {
1368             pic_param.ReferenceFrames[0] = RefPicList0_P[0];
1369         } else if (current_frame_type == FRAME_B) {
1370             pic_param.ReferenceFrames[0] = RefPicList0_B[0];
1371             pic_param.ReferenceFrames[1] = RefPicList1_B[0];
1372         }
1373     } else {
1374         memcpy(pic_param.ReferenceFrames, ReferenceFrames, numShortTerm*sizeof(VAPictureH264));
1375         for (i = numShortTerm; i < SURFACE_NUM; i++) {
1376             pic_param.ReferenceFrames[i].picture_id = VA_INVALID_SURFACE;
1377             pic_param.ReferenceFrames[i].flags = VA_PICTURE_H264_INVALID;
1378         }
1379     }
1380     
1381     pic_param.pic_fields.bits.idr_pic_flag = (current_frame_type == FRAME_IDR);
1382     pic_param.pic_fields.bits.reference_pic_flag = (current_frame_type != FRAME_B);
1383     pic_param.pic_fields.bits.entropy_coding_mode_flag = h264_entropy_mode;
1384     pic_param.pic_fields.bits.deblocking_filter_control_present_flag = 1;
1385     pic_param.frame_num = current_frame_num;
1386     pic_param.coded_buf = gl_surfaces[current_frame_display % SURFACE_NUM].coded_buf;
1387     pic_param.last_picture = false;  // FIXME
1388     pic_param.pic_init_qp = initial_qp;
1389
1390     va_status = vaCreateBuffer(va_dpy, context_id, VAEncPictureParameterBufferType,
1391                                sizeof(pic_param), 1, &pic_param, &pic_param_buf);
1392     CHECK_VASTATUS(va_status, "vaCreateBuffer");;
1393
1394     va_status = vaRenderPicture(va_dpy, context_id, &pic_param_buf, 1);
1395     CHECK_VASTATUS(va_status, "vaRenderPicture");
1396
1397     return 0;
1398 }
1399
1400 static int render_packedsequence(void)
1401 {
1402     VAEncPackedHeaderParameterBuffer packedheader_param_buffer;
1403     VABufferID packedseq_para_bufid, packedseq_data_bufid, render_id[2];
1404     unsigned int length_in_bits;
1405     unsigned char *packedseq_buffer = NULL;
1406     VAStatus va_status;
1407
1408     length_in_bits = build_packed_seq_buffer(&packedseq_buffer); 
1409     
1410     packedheader_param_buffer.type = VAEncPackedHeaderSequence;
1411     
1412     packedheader_param_buffer.bit_length = length_in_bits; /*length_in_bits*/
1413     packedheader_param_buffer.has_emulation_bytes = 0;
1414     va_status = vaCreateBuffer(va_dpy,
1415                                context_id,
1416                                VAEncPackedHeaderParameterBufferType,
1417                                sizeof(packedheader_param_buffer), 1, &packedheader_param_buffer,
1418                                &packedseq_para_bufid);
1419     CHECK_VASTATUS(va_status, "vaCreateBuffer");
1420
1421     va_status = vaCreateBuffer(va_dpy,
1422                                context_id,
1423                                VAEncPackedHeaderDataBufferType,
1424                                (length_in_bits + 7) / 8, 1, packedseq_buffer,
1425                                &packedseq_data_bufid);
1426     CHECK_VASTATUS(va_status, "vaCreateBuffer");
1427
1428     render_id[0] = packedseq_para_bufid;
1429     render_id[1] = packedseq_data_bufid;
1430     va_status = vaRenderPicture(va_dpy, context_id, render_id, 2);
1431     CHECK_VASTATUS(va_status, "vaRenderPicture");
1432
1433     free(packedseq_buffer);
1434     
1435     return 0;
1436 }
1437
1438
1439 static int render_packedpicture(void)
1440 {
1441     VAEncPackedHeaderParameterBuffer packedheader_param_buffer;
1442     VABufferID packedpic_para_bufid, packedpic_data_bufid, render_id[2];
1443     unsigned int length_in_bits;
1444     unsigned char *packedpic_buffer = NULL;
1445     VAStatus va_status;
1446
1447     length_in_bits = build_packed_pic_buffer(&packedpic_buffer); 
1448     packedheader_param_buffer.type = VAEncPackedHeaderPicture;
1449     packedheader_param_buffer.bit_length = length_in_bits;
1450     packedheader_param_buffer.has_emulation_bytes = 0;
1451
1452     va_status = vaCreateBuffer(va_dpy,
1453                                context_id,
1454                                VAEncPackedHeaderParameterBufferType,
1455                                sizeof(packedheader_param_buffer), 1, &packedheader_param_buffer,
1456                                &packedpic_para_bufid);
1457     CHECK_VASTATUS(va_status, "vaCreateBuffer");
1458
1459     va_status = vaCreateBuffer(va_dpy,
1460                                context_id,
1461                                VAEncPackedHeaderDataBufferType,
1462                                (length_in_bits + 7) / 8, 1, packedpic_buffer,
1463                                &packedpic_data_bufid);
1464     CHECK_VASTATUS(va_status, "vaCreateBuffer");
1465
1466     render_id[0] = packedpic_para_bufid;
1467     render_id[1] = packedpic_data_bufid;
1468     va_status = vaRenderPicture(va_dpy, context_id, render_id, 2);
1469     CHECK_VASTATUS(va_status, "vaRenderPicture");
1470
1471     free(packedpic_buffer);
1472     
1473     return 0;
1474 }
1475
1476 static void render_packedslice()
1477 {
1478     VAEncPackedHeaderParameterBuffer packedheader_param_buffer;
1479     VABufferID packedslice_para_bufid, packedslice_data_bufid, render_id[2];
1480     unsigned int length_in_bits;
1481     unsigned char *packedslice_buffer = NULL;
1482     VAStatus va_status;
1483
1484     length_in_bits = build_packed_slice_buffer(&packedslice_buffer);
1485     packedheader_param_buffer.type = VAEncPackedHeaderSlice;
1486     packedheader_param_buffer.bit_length = length_in_bits;
1487     packedheader_param_buffer.has_emulation_bytes = 0;
1488
1489     va_status = vaCreateBuffer(va_dpy,
1490                                context_id,
1491                                VAEncPackedHeaderParameterBufferType,
1492                                sizeof(packedheader_param_buffer), 1, &packedheader_param_buffer,
1493                                &packedslice_para_bufid);
1494     CHECK_VASTATUS(va_status, "vaCreateBuffer");
1495
1496     va_status = vaCreateBuffer(va_dpy,
1497                                context_id,
1498                                VAEncPackedHeaderDataBufferType,
1499                                (length_in_bits + 7) / 8, 1, packedslice_buffer,
1500                                &packedslice_data_bufid);
1501     CHECK_VASTATUS(va_status, "vaCreateBuffer");
1502
1503     render_id[0] = packedslice_para_bufid;
1504     render_id[1] = packedslice_data_bufid;
1505     va_status = vaRenderPicture(va_dpy, context_id, render_id, 2);
1506     CHECK_VASTATUS(va_status, "vaRenderPicture");
1507
1508     free(packedslice_buffer);
1509 }
1510
1511 static int render_slice(void)
1512 {
1513     VABufferID slice_param_buf;
1514     VAStatus va_status;
1515     int i;
1516
1517     update_RefPicList();
1518     
1519     /* one frame, one slice */
1520     slice_param.macroblock_address = 0;
1521     slice_param.num_macroblocks = frame_width_mbaligned * frame_height_mbaligned/(16*16); /* Measured by MB */
1522     slice_param.slice_type = (current_frame_type == FRAME_IDR)?2:current_frame_type;
1523     if (current_frame_type == FRAME_IDR) {
1524         if (current_frame_encoding != 0)
1525             ++slice_param.idr_pic_id;
1526     } else if (current_frame_type == FRAME_P) {
1527         int refpiclist0_max = h264_maxref & 0xffff;
1528         memcpy(slice_param.RefPicList0, RefPicList0_P, refpiclist0_max*sizeof(VAPictureH264));
1529
1530         for (i = refpiclist0_max; i < 32; i++) {
1531             slice_param.RefPicList0[i].picture_id = VA_INVALID_SURFACE;
1532             slice_param.RefPicList0[i].flags = VA_PICTURE_H264_INVALID;
1533         }
1534     } else if (current_frame_type == FRAME_B) {
1535         int refpiclist0_max = h264_maxref & 0xffff;
1536         int refpiclist1_max = (h264_maxref >> 16) & 0xffff;
1537
1538         memcpy(slice_param.RefPicList0, RefPicList0_B, refpiclist0_max*sizeof(VAPictureH264));
1539         for (i = refpiclist0_max; i < 32; i++) {
1540             slice_param.RefPicList0[i].picture_id = VA_INVALID_SURFACE;
1541             slice_param.RefPicList0[i].flags = VA_PICTURE_H264_INVALID;
1542         }
1543
1544         memcpy(slice_param.RefPicList1, RefPicList1_B, refpiclist1_max*sizeof(VAPictureH264));
1545         for (i = refpiclist1_max; i < 32; i++) {
1546             slice_param.RefPicList1[i].picture_id = VA_INVALID_SURFACE;
1547             slice_param.RefPicList1[i].flags = VA_PICTURE_H264_INVALID;
1548         }
1549     }
1550
1551     slice_param.slice_alpha_c0_offset_div2 = 0;
1552     slice_param.slice_beta_offset_div2 = 0;
1553     slice_param.direct_spatial_mv_pred_flag = 1;
1554     slice_param.pic_order_cnt_lsb = (current_frame_display - current_IDR_display) % MaxPicOrderCntLsb;
1555     
1556
1557     if (h264_packedheader &&
1558         config_attrib[enc_packed_header_idx].value & VA_ENC_PACKED_HEADER_SLICE)
1559         render_packedslice();
1560
1561     va_status = vaCreateBuffer(va_dpy, context_id, VAEncSliceParameterBufferType,
1562                                sizeof(slice_param), 1, &slice_param, &slice_param_buf);
1563     CHECK_VASTATUS(va_status, "vaCreateBuffer");;
1564
1565     va_status = vaRenderPicture(va_dpy, context_id, &slice_param_buf, 1);
1566     CHECK_VASTATUS(va_status, "vaRenderPicture");
1567     
1568     return 0;
1569 }
1570
1571
1572
1573 int H264Encoder::save_codeddata(unsigned long long display_order, unsigned long long encode_order, int frame_type)
1574 {    
1575     VACodedBufferSegment *buf_list = NULL;
1576     VAStatus va_status;
1577     unsigned int coded_size = 0;
1578
1579     string data;
1580
1581     va_status = vaMapBuffer(va_dpy, gl_surfaces[display_order % SURFACE_NUM].coded_buf, (void **)(&buf_list));
1582     CHECK_VASTATUS(va_status, "vaMapBuffer");
1583     while (buf_list != NULL) {
1584         data.append(reinterpret_cast<const char *>(buf_list->buf), buf_list->size);
1585         if (coded_fp != nullptr)
1586             coded_size += fwrite(buf_list->buf, 1, buf_list->size, coded_fp);
1587         buf_list = (VACodedBufferSegment *) buf_list->next;
1588
1589         frame_size += coded_size;
1590     }
1591     vaUnmapBuffer(va_dpy, gl_surfaces[display_order % SURFACE_NUM].coded_buf);
1592
1593     AVPacket pkt;
1594     memset(&pkt, 0, sizeof(pkt));
1595     pkt.buf = nullptr;
1596     pkt.pts = av_rescale_q(display_order, AVRational{1, frame_rate}, avstream->time_base);
1597     pkt.dts = av_rescale_q(encode_order, AVRational{1, frame_rate}, avstream->time_base);
1598     pkt.data = reinterpret_cast<uint8_t *>(&data[0]);
1599     pkt.size = data.size();
1600     pkt.stream_index = 0;
1601     if (frame_type == FRAME_IDR || frame_type == FRAME_I) {
1602         pkt.flags = AV_PKT_FLAG_KEY;
1603     } else {
1604         pkt.flags = 0;
1605     }
1606     pkt.duration = 1;
1607     av_interleaved_write_frame(avctx, &pkt);
1608
1609 #if 0
1610     printf("\r      "); /* return back to startpoint */
1611     switch (encode_order % 4) {
1612         case 0:
1613             printf("|");
1614             break;
1615         case 1:
1616             printf("/");
1617             break;
1618         case 2:
1619             printf("-");
1620             break;
1621         case 3:
1622             printf("\\");
1623             break;
1624     }
1625     printf("%08lld", encode_order);
1626     printf("(%06d bytes coded)", coded_size);
1627 #endif
1628
1629     return 0;
1630 }
1631
1632
1633 // this is weird. but it seems to put a new frame onto the queue
1634 void H264Encoder::storage_task_enqueue(unsigned long long display_order, unsigned long long encode_order, int frame_type)
1635 {
1636         std::unique_lock<std::mutex> lock(storage_task_queue_mutex);
1637
1638         storage_task tmp;
1639         tmp.display_order = display_order;
1640         tmp.encode_order = encode_order;
1641         tmp.frame_type = frame_type;
1642         storage_task_queue.push(tmp);
1643         srcsurface_status[display_order % SURFACE_NUM] = SRC_SURFACE_IN_ENCODING;
1644
1645         storage_task_queue_changed.notify_all();
1646 }
1647
1648 void H264Encoder::storage_task_thread()
1649 {
1650         for ( ;; ) {
1651                 storage_task current;
1652                 {
1653                         // wait until there's an encoded frame  
1654                         std::unique_lock<std::mutex> lock(storage_task_queue_mutex);
1655                         storage_task_queue_changed.wait(lock, [this]{ return storage_thread_should_quit || !storage_task_queue.empty(); });
1656                         if (storage_thread_should_quit) return;
1657                         current = storage_task_queue.front();
1658                         storage_task_queue.pop();
1659                 }
1660
1661                 VAStatus va_status;
1662            
1663                 // waits for data, then saves it to disk.
1664                 va_status = vaSyncSurface(va_dpy, gl_surfaces[current.display_order % SURFACE_NUM].src_surface);
1665                 CHECK_VASTATUS(va_status, "vaSyncSurface");
1666                 save_codeddata(current.display_order, current.encode_order, current.frame_type);
1667
1668                 {
1669                         std::unique_lock<std::mutex> lock(storage_task_queue_mutex);
1670                         srcsurface_status[current.display_order % SURFACE_NUM] = SRC_SURFACE_FREE;
1671                         storage_task_queue_changed.notify_all();
1672                 }
1673         }
1674 }
1675
1676 static int release_encode()
1677 {
1678     int i;
1679     
1680     for (i = 0; i < SURFACE_NUM; i++) {
1681         vaDestroyBuffer(va_dpy, gl_surfaces[i].coded_buf);
1682         vaDestroySurfaces(va_dpy, &gl_surfaces[i].src_surface, 1);
1683         vaDestroySurfaces(va_dpy, &gl_surfaces[i].ref_surface, 1);
1684     }
1685     
1686     vaDestroyContext(va_dpy, context_id);
1687     vaDestroyConfig(va_dpy, config_id);
1688
1689     return 0;
1690 }
1691
1692 static int deinit_va()
1693
1694     vaTerminate(va_dpy);
1695
1696     va_close_display(va_dpy);
1697
1698     return 0;
1699 }
1700
1701
1702 static int print_input()
1703 {
1704     printf("\n\nINPUT:Try to encode H264...\n");
1705     if (rc_mode != -1)
1706         printf("INPUT: RateControl  : %s\n", rc_to_string(rc_mode));
1707     printf("INPUT: Resolution   : %dx%dframes\n", frame_width, frame_height);
1708     printf("INPUT: FrameRate    : %d\n", frame_rate);
1709     printf("INPUT: Bitrate      : %d\n", frame_bitrate);
1710     printf("INPUT: Slieces      : %d\n", frame_slices);
1711     printf("INPUT: IntraPeriod  : %d\n", intra_period);
1712     printf("INPUT: IDRPeriod    : %d\n", intra_idr_period);
1713     printf("INPUT: IpPeriod     : %d\n", ip_period);
1714     printf("INPUT: Initial QP   : %d\n", initial_qp);
1715     printf("INPUT: Min QP       : %d\n", minimal_qp);
1716     printf("INPUT: Coded Clip   : %s\n", coded_fn);
1717     
1718     printf("\n\n"); /* return back to startpoint */
1719     
1720     return 0;
1721 }
1722
1723
1724 //H264Encoder::H264Encoder(SDL_Window *window, SDL_GLContext context, int width, int height, const char *output_filename) 
1725 H264Encoder::H264Encoder(QSurface *surface, int width, int height, const char *output_filename)
1726         : current_storage_frame(0), surface(surface)
1727         //: width(width), height(height), current_encoding_frame(0)
1728 {
1729         av_register_all();
1730         avctx = avformat_alloc_context();
1731         avctx->oformat = av_guess_format(NULL, output_filename, NULL);
1732         strcpy(avctx->filename, output_filename);
1733         if (avio_open2(&avctx->pb, output_filename, AVIO_FLAG_WRITE, &avctx->interrupt_callback, NULL) < 0) {
1734                 fprintf(stderr, "%s: avio_open2() failed\n", output_filename);
1735                 exit(1);
1736         }
1737         AVCodec *codec = avcodec_find_encoder(AV_CODEC_ID_H264);
1738         avstream = avformat_new_stream(avctx, codec);
1739         if (avstream == nullptr) {
1740                 fprintf(stderr, "%s: avformat_new_stream() failed\n", output_filename);
1741                 exit(1);
1742         }
1743         avstream->time_base = AVRational{1, frame_rate};
1744         avstream->codec->width = width;
1745         avstream->codec->height = height;
1746         avstream->codec->time_base = AVRational{1, frame_rate};
1747         avstream->codec->ticks_per_frame = 1;  // or 2?
1748
1749         if (avformat_write_header(avctx, NULL) < 0) {
1750                 fprintf(stderr, "%s: avformat_write_header() failed\n", output_filename);
1751                 exit(1);
1752         }
1753
1754         coded_fp = fopen("dump.h264", "wb");
1755         assert(coded_fp != NULL);
1756
1757         frame_width = width;
1758         frame_height = height;
1759         frame_width_mbaligned = (frame_width + 15) & (~15);
1760         frame_height_mbaligned = (frame_height + 15) & (~15);
1761         frame_bitrate = 15000000;  // / 60;
1762         current_frame_encoding = 0;
1763
1764         print_input();
1765
1766         init_va();
1767         setup_encode();
1768
1769         // No frames are ready yet.
1770         memset(srcsurface_status, SRC_SURFACE_FREE, sizeof(srcsurface_status));
1771             
1772         memset(&seq_param, 0, sizeof(seq_param));
1773         memset(&pic_param, 0, sizeof(pic_param));
1774         memset(&slice_param, 0, sizeof(slice_param));
1775
1776         storage_thread = std::thread(&H264Encoder::storage_task_thread, this);
1777
1778         copy_thread = std::thread([this]{
1779                 //SDL_GL_MakeCurrent(window, context);
1780                 QOpenGLContext *context = create_context();
1781                 eglBindAPI(EGL_OPENGL_API);
1782                 if (!make_current(context, this->surface)) {
1783                         printf("display=%p surface=%p context=%p curr=%p err=%d\n", eglGetCurrentDisplay(), this->surface, context, eglGetCurrentContext(),
1784                                 eglGetError());
1785                         exit(1);
1786                 }
1787                 copy_thread_func();
1788         });
1789 }
1790
1791 H264Encoder::~H264Encoder()
1792 {
1793         {
1794                 unique_lock<mutex> lock(storage_task_queue_mutex);
1795                 storage_thread_should_quit = true;
1796                 storage_task_queue_changed.notify_all();
1797         }
1798         {
1799                 unique_lock<mutex> lock(frame_queue_mutex);
1800                 copy_thread_should_quit = true;
1801                 frame_queue_nonempty.notify_one();
1802         }
1803         storage_thread.join();
1804         copy_thread.join();
1805
1806         release_encode();
1807         deinit_va();
1808
1809         av_write_trailer(avctx);
1810         avformat_free_context(avctx);
1811 }
1812
1813 bool H264Encoder::begin_frame(GLuint *y_tex, GLuint *cbcr_tex)
1814 {
1815         {
1816                 // Wait until this frame slot is done encoding.
1817                 std::unique_lock<std::mutex> lock(storage_task_queue_mutex);
1818                 storage_task_queue_changed.wait(lock, [this]{ return storage_thread_should_quit || (srcsurface_status[current_storage_frame % SURFACE_NUM] == SRC_SURFACE_FREE); });
1819                 if (storage_thread_should_quit) return false;
1820         }
1821
1822         //*fbo = fbos[current_storage_frame % SURFACE_NUM];
1823         GLSurface *surf = &gl_surfaces[current_storage_frame % SURFACE_NUM];
1824         *y_tex = surf->y_tex;
1825         *cbcr_tex = surf->cbcr_tex;
1826
1827         VASurfaceID surface = surf->src_surface;
1828         VAStatus va_status = vaDeriveImage(va_dpy, surface, &surf->surface_image);
1829         CHECK_VASTATUS(va_status, "vaDeriveImage");
1830
1831         VABufferInfo buf_info;
1832         buf_info.mem_type = VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME;  // or VA_SURFACE_ATTRIB_MEM_TYPE_KERNEL_DRM?
1833         va_status = vaAcquireBufferHandle(va_dpy, surf->surface_image.buf, &buf_info);
1834         CHECK_VASTATUS(va_status, "vaAcquireBufferHandle");
1835
1836         // Create Y image.
1837         surf->y_egl_image = EGL_NO_IMAGE_KHR;
1838         EGLint y_attribs[] = {
1839                 EGL_WIDTH, frame_width,
1840                 EGL_HEIGHT, frame_height,
1841                 EGL_LINUX_DRM_FOURCC_EXT, fourcc_code('R', '8', ' ', ' '),
1842                 EGL_DMA_BUF_PLANE0_FD_EXT, EGLint(buf_info.handle),
1843                 EGL_DMA_BUF_PLANE0_OFFSET_EXT, EGLint(surf->surface_image.offsets[0]),
1844                 EGL_DMA_BUF_PLANE0_PITCH_EXT, EGLint(surf->surface_image.pitches[0]),
1845                 EGL_NONE
1846         };
1847
1848         surf->y_egl_image = eglCreateImageKHR(eglGetCurrentDisplay(), EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, NULL, y_attribs);
1849         assert(surf->y_egl_image != EGL_NO_IMAGE_KHR);
1850
1851         // Associate Y image to a texture.
1852         glBindTexture(GL_TEXTURE_2D, *y_tex);
1853         glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, surf->y_egl_image);
1854
1855         // Create CbCr image.
1856         surf->cbcr_egl_image = EGL_NO_IMAGE_KHR;
1857         EGLint cbcr_attribs[] = {
1858                 EGL_WIDTH, frame_width,
1859                 EGL_HEIGHT, frame_height,
1860                 EGL_LINUX_DRM_FOURCC_EXT, fourcc_code('G', 'R', '8', '8'),
1861                 EGL_DMA_BUF_PLANE0_FD_EXT, EGLint(buf_info.handle),
1862                 EGL_DMA_BUF_PLANE0_OFFSET_EXT, EGLint(surf->surface_image.offsets[1]),
1863                 EGL_DMA_BUF_PLANE0_PITCH_EXT, EGLint(surf->surface_image.pitches[1]),
1864                 EGL_NONE
1865         };
1866
1867         surf->cbcr_egl_image = eglCreateImageKHR(eglGetCurrentDisplay(), EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, NULL, cbcr_attribs);
1868         assert(surf->cbcr_egl_image != EGL_NO_IMAGE_KHR);
1869
1870         // Associate CbCr image to a texture.
1871         glBindTexture(GL_TEXTURE_2D, *cbcr_tex);
1872         glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, surf->cbcr_egl_image);
1873
1874         return true;
1875 }
1876
1877 void H264Encoder::end_frame(GLsync fence, const std::vector<FrameAllocator::Frame> &input_frames_to_release)
1878 {
1879         {
1880                 unique_lock<mutex> lock(frame_queue_mutex);
1881                 pending_frames[current_storage_frame++] = PendingFrame{ fence, input_frames_to_release };
1882         }
1883         frame_queue_nonempty.notify_one();
1884 }
1885
1886 void H264Encoder::copy_thread_func()
1887 {
1888         for ( ;; ) {
1889                 PendingFrame frame;
1890                 encoding2display_order(current_frame_encoding, intra_period, intra_idr_period, ip_period,
1891                                        &current_frame_display, &current_frame_type);
1892                 if (current_frame_type == FRAME_IDR) {
1893                         numShortTerm = 0;
1894                         current_frame_num = 0;
1895                         current_IDR_display = current_frame_display;
1896                 }
1897
1898                 {
1899                         unique_lock<mutex> lock(frame_queue_mutex);
1900                         frame_queue_nonempty.wait(lock, [this]{ return copy_thread_should_quit || pending_frames.count(current_frame_display) != 0; });
1901                         if (copy_thread_should_quit) return;
1902                         frame = pending_frames[current_frame_display];
1903                         pending_frames.erase(current_frame_display);
1904                 }
1905
1906                 // Wait for the GPU to be done with the frame.
1907                 glClientWaitSync(frame.fence, 0, 0);
1908                 glDeleteSync(frame.fence);
1909
1910                 // Release back any input frames we needed to render this frame.
1911                 // (Actually, those that were needed one output frame ago.)
1912                 for (FrameAllocator::Frame input_frame : frame.input_frames_to_release) {
1913                         input_frame.owner->release_frame(input_frame);
1914                 }
1915
1916                 // Unmap the image.
1917                 GLSurface *surf = &gl_surfaces[current_frame_display % SURFACE_NUM];
1918                 eglDestroyImageKHR(eglGetCurrentDisplay(), surf->y_egl_image);
1919                 eglDestroyImageKHR(eglGetCurrentDisplay(), surf->cbcr_egl_image);
1920                 VAStatus va_status = vaReleaseBufferHandle(va_dpy, surf->surface_image.buf);
1921                 CHECK_VASTATUS(va_status, "vaReleaseBufferHandle");
1922                 va_status = vaDestroyImage(va_dpy, surf->surface_image.image_id);
1923                 CHECK_VASTATUS(va_status, "vaDestroyImage");
1924
1925                 VASurfaceID surface = surf->src_surface;
1926
1927                 // Schedule the frame for encoding.
1928                 va_status = vaBeginPicture(va_dpy, context_id, surface);
1929                 CHECK_VASTATUS(va_status, "vaBeginPicture");
1930
1931                 if (current_frame_type == FRAME_IDR) {
1932                         render_sequence();
1933                         render_picture();            
1934                         if (h264_packedheader) {
1935                                 render_packedsequence();
1936                                 render_packedpicture();
1937                         }
1938                 } else {
1939                         //render_sequence();
1940                         render_picture();
1941                 }
1942                 render_slice();
1943                 
1944                 va_status = vaEndPicture(va_dpy, context_id);
1945                 CHECK_VASTATUS(va_status, "vaEndPicture");
1946
1947                 // so now the data is done encoding (well, async job kicked off)...
1948                 // we send that to the storage thread
1949                 storage_task_enqueue(current_frame_display, current_frame_encoding, current_frame_type);
1950                 
1951                 update_ReferenceFrames();
1952                 ++current_frame_encoding;
1953         }
1954 }