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