]> git.sesse.net Git - nageru/blob - h264encode.cpp
Rework entire pts handling.
[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 #include "timebase.h"
30
31 class QOpenGLContext;
32 class QSurface;
33
34 #define CHECK_VASTATUS(va_status, func)                                 \
35     if (va_status != VA_STATUS_SUCCESS) {                               \
36         fprintf(stderr, "%s:%d (%s) failed with %d\n", __func__, __LINE__, func, va_status); \
37         exit(1);                                                        \
38     }
39
40 //#include "loadsurface.h"
41
42 #define NAL_REF_IDC_NONE        0
43 #define NAL_REF_IDC_LOW         1
44 #define NAL_REF_IDC_MEDIUM      2
45 #define NAL_REF_IDC_HIGH        3
46
47 #define NAL_NON_IDR             1
48 #define NAL_IDR                 5
49 #define NAL_SPS                 7
50 #define NAL_PPS                 8
51 #define NAL_SEI                 6
52
53 #define SLICE_TYPE_P            0
54 #define SLICE_TYPE_B            1
55 #define SLICE_TYPE_I            2
56 #define IS_P_SLICE(type) (SLICE_TYPE_P == (type))
57 #define IS_B_SLICE(type) (SLICE_TYPE_B == (type))
58 #define IS_I_SLICE(type) (SLICE_TYPE_I == (type))
59
60
61 #define ENTROPY_MODE_CAVLC      0
62 #define ENTROPY_MODE_CABAC      1
63
64 #define PROFILE_IDC_BASELINE    66
65 #define PROFILE_IDC_MAIN        77
66 #define PROFILE_IDC_HIGH        100
67    
68 #define BITSTREAM_ALLOCATE_STEPPING     4096
69
70 #define SURFACE_NUM 16 /* 16 surfaces for source YUV */
71 static  VADisplay va_dpy;
72 static  VAProfile h264_profile = (VAProfile)~0;
73 static  VAConfigAttrib config_attrib[VAConfigAttribTypeMax];
74 static  int config_attrib_num = 0, enc_packed_header_idx;
75
76 struct GLSurface {
77         VASurfaceID src_surface, ref_surface;
78         VABufferID coded_buf;
79
80         VAImage surface_image;
81         GLuint y_tex, cbcr_tex;
82         EGLImage y_egl_image, cbcr_egl_image;
83 };
84 GLSurface gl_surfaces[SURFACE_NUM];
85
86 static  VAConfigID config_id;
87 static  VAContextID context_id;
88 static  VAEncSequenceParameterBufferH264 seq_param;
89 static  VAEncPictureParameterBufferH264 pic_param;
90 static  VAEncSliceParameterBufferH264 slice_param;
91 static  VAPictureH264 CurrentCurrPic;
92 static  VAPictureH264 ReferenceFrames[16], RefPicList0_P[32], RefPicList0_B[32], RefPicList1_B[32];
93
94 static  unsigned int MaxFrameNum = (2<<16);
95 static  unsigned int MaxPicOrderCntLsb = (2<<8);
96 static  unsigned int Log2MaxFrameNum = 16;
97 static  unsigned int Log2MaxPicOrderCntLsb = 8;
98
99 static  unsigned int num_ref_frames = 2;
100 static  unsigned int numShortTerm = 0;
101 static  int constraint_set_flag = 0;
102 static  int h264_packedheader = 0; /* support pack header? */
103 static  int h264_maxref = (1<<16|1);
104 static  int h264_entropy_mode = 1; /* cabac */
105
106 static  char *coded_fn = 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 = 3;
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, TIMEBASE * 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
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 = TIMEBASE * 2;
1257     seq_param.num_units_in_tick = 1; /* Tc = num_units_in_tick / scale */
1258     seq_param.seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4 = Log2MaxPicOrderCntLsb - 4;
1259     seq_param.seq_fields.bits.log2_max_frame_num_minus4 = Log2MaxFrameNum - 4;;
1260     seq_param.seq_fields.bits.frame_mbs_only_flag = 1;
1261     seq_param.seq_fields.bits.chroma_format_idc = 1;
1262     seq_param.seq_fields.bits.direct_8x8_inference_flag = 1;
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(storage_task task)
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[task.display_order % SURFACE_NUM].coded_buf, (void **)(&buf_list));
1582     CHECK_VASTATUS(va_status, "vaMapBuffer");
1583     while (buf_list != NULL) {
1584         data.append(reinterpret_cast<const char *>(buf_list->buf), buf_list->size);
1585         buf_list = (VACodedBufferSegment *) buf_list->next;
1586
1587         frame_size += coded_size;
1588     }
1589     vaUnmapBuffer(va_dpy, gl_surfaces[task.display_order % SURFACE_NUM].coded_buf);
1590
1591     const int64_t pts_dts_delay = (ip_period - 1) * (TIMEBASE / frame_rate);  // FIXME: Wrong for variable frame rate.
1592     const int64_t av_delay = TIMEBASE / 10;  // Corresponds to the fixed delay in resampler.h. TODO: Make less hard-coded.
1593     int64_t pts, dts;
1594     {
1595         {
1596              unique_lock<mutex> lock(frame_queue_mutex);
1597              assert(timestamps.count(task.display_order));
1598              assert(timestamps.count(task.encode_order));
1599              pts = timestamps[task.display_order];
1600              dts = timestamps[task.encode_order];
1601         }
1602         // Add video.
1603         AVPacket pkt;
1604         memset(&pkt, 0, sizeof(pkt));
1605         pkt.buf = nullptr;
1606         pkt.pts = av_rescale_q(pts + av_delay + pts_dts_delay, AVRational{1, TIMEBASE}, avstream_video->time_base);
1607         pkt.dts = av_rescale_q(dts + av_delay, AVRational{1, TIMEBASE}, avstream_video->time_base);
1608         pkt.data = reinterpret_cast<uint8_t *>(&data[0]);
1609         pkt.size = data.size();
1610         pkt.stream_index = 0;
1611         if (task.frame_type == FRAME_IDR || task.frame_type == FRAME_I) {
1612             pkt.flags = AV_PKT_FLAG_KEY;
1613         } else {
1614             pkt.flags = 0;
1615         }
1616         //pkt.duration = 1;
1617         av_interleaved_write_frame(avctx, &pkt);
1618     }
1619     // Encode and add all audio frames up to and including the pts of this video frame.
1620     // (They can never be queued to us after the video frame they belong to, only before.)
1621     for ( ;; ) {
1622         int64_t audio_pts;
1623         std::vector<float> audio;
1624         {
1625              unique_lock<mutex> lock(frame_queue_mutex);
1626              if (pending_audio_frames.empty()) break;
1627              auto it = pending_audio_frames.begin();
1628              if (it->first > int(pts)) break;
1629              audio_pts = it->first;
1630              audio = move(it->second);
1631              pending_audio_frames.erase(it); 
1632         }
1633         AVFrame *frame = avcodec_alloc_frame();
1634         frame->nb_samples = audio.size() / 2;
1635         frame->format = AV_SAMPLE_FMT_FLT;
1636         frame->channel_layout = AV_CH_LAYOUT_STEREO;
1637
1638         unique_ptr<float[]> planar_samples(new float[audio.size()]);
1639         avcodec_fill_audio_frame(frame, 2, AV_SAMPLE_FMT_FLTP, (const uint8_t*)planar_samples.get(), audio.size() * sizeof(float), 0);
1640         for (int i = 0; i < frame->nb_samples; ++i) {
1641             planar_samples[i] = audio[i * 2 + 0];
1642             planar_samples[i + frame->nb_samples] = audio[i * 2 + 1];
1643         }
1644
1645         AVPacket pkt;
1646         av_init_packet(&pkt);
1647         pkt.data = nullptr;
1648         pkt.size = 0;
1649         int got_output;
1650         avcodec_encode_audio2(avstream_audio->codec, &pkt, frame, &got_output);
1651         if (got_output) {
1652             pkt.pts = av_rescale_q(audio_pts + pts_dts_delay, AVRational{1, TIMEBASE}, avstream_audio->time_base);
1653             pkt.dts = pkt.pts;
1654             pkt.stream_index = 1;
1655             av_interleaved_write_frame(avctx, &pkt);
1656         }
1657         // TODO: Delayed frames.
1658         avcodec_free_frame(&frame);
1659     }
1660     {
1661         unique_lock<mutex> lock(frame_queue_mutex);
1662         timestamps.erase(task.encode_order - (ip_period - 1));
1663     }
1664
1665 #if 0
1666     printf("\r      "); /* return back to startpoint */
1667     switch (encode_order % 4) {
1668         case 0:
1669             printf("|");
1670             break;
1671         case 1:
1672             printf("/");
1673             break;
1674         case 2:
1675             printf("-");
1676             break;
1677         case 3:
1678             printf("\\");
1679             break;
1680     }
1681     printf("%08lld", encode_order);
1682     printf("(%06d bytes coded)", coded_size);
1683 #endif
1684
1685     return 0;
1686 }
1687
1688
1689 // this is weird. but it seems to put a new frame onto the queue
1690 void H264Encoder::storage_task_enqueue(storage_task task)
1691 {
1692         std::unique_lock<std::mutex> lock(storage_task_queue_mutex);
1693         storage_task_queue.push(move(task));
1694         srcsurface_status[task.display_order % SURFACE_NUM] = SRC_SURFACE_IN_ENCODING;
1695         storage_task_queue_changed.notify_all();
1696 }
1697
1698 void H264Encoder::storage_task_thread()
1699 {
1700         for ( ;; ) {
1701                 storage_task current;
1702                 {
1703                         // wait until there's an encoded frame  
1704                         std::unique_lock<std::mutex> lock(storage_task_queue_mutex);
1705                         storage_task_queue_changed.wait(lock, [this]{ return storage_thread_should_quit || !storage_task_queue.empty(); });
1706                         if (storage_thread_should_quit) return;
1707                         current = move(storage_task_queue.front());
1708                         storage_task_queue.pop();
1709                 }
1710
1711                 VAStatus va_status;
1712            
1713                 // waits for data, then saves it to disk.
1714                 va_status = vaSyncSurface(va_dpy, gl_surfaces[current.display_order % SURFACE_NUM].src_surface);
1715                 CHECK_VASTATUS(va_status, "vaSyncSurface");
1716                 save_codeddata(move(current));
1717
1718                 {
1719                         std::unique_lock<std::mutex> lock(storage_task_queue_mutex);
1720                         srcsurface_status[current.display_order % SURFACE_NUM] = SRC_SURFACE_FREE;
1721                         storage_task_queue_changed.notify_all();
1722                 }
1723         }
1724 }
1725
1726 static int release_encode()
1727 {
1728     int i;
1729     
1730     for (i = 0; i < SURFACE_NUM; i++) {
1731         vaDestroyBuffer(va_dpy, gl_surfaces[i].coded_buf);
1732         vaDestroySurfaces(va_dpy, &gl_surfaces[i].src_surface, 1);
1733         vaDestroySurfaces(va_dpy, &gl_surfaces[i].ref_surface, 1);
1734     }
1735     
1736     vaDestroyContext(va_dpy, context_id);
1737     vaDestroyConfig(va_dpy, config_id);
1738
1739     return 0;
1740 }
1741
1742 static int deinit_va()
1743
1744     vaTerminate(va_dpy);
1745
1746     va_close_display(va_dpy);
1747
1748     return 0;
1749 }
1750
1751
1752 static int print_input()
1753 {
1754     printf("\n\nINPUT:Try to encode H264...\n");
1755     if (rc_mode != -1)
1756         printf("INPUT: RateControl  : %s\n", rc_to_string(rc_mode));
1757     printf("INPUT: Resolution   : %dx%dframes\n", frame_width, frame_height);
1758     printf("INPUT: FrameRate    : %d\n", frame_rate);
1759     printf("INPUT: Bitrate      : %d\n", frame_bitrate);
1760     printf("INPUT: Slieces      : %d\n", frame_slices);
1761     printf("INPUT: IntraPeriod  : %d\n", intra_period);
1762     printf("INPUT: IDRPeriod    : %d\n", intra_idr_period);
1763     printf("INPUT: IpPeriod     : %d\n", ip_period);
1764     printf("INPUT: Initial QP   : %d\n", initial_qp);
1765     printf("INPUT: Min QP       : %d\n", minimal_qp);
1766     printf("INPUT: Coded Clip   : %s\n", coded_fn);
1767     
1768     printf("\n\n"); /* return back to startpoint */
1769     
1770     return 0;
1771 }
1772
1773
1774 //H264Encoder::H264Encoder(SDL_Window *window, SDL_GLContext context, int width, int height, const char *output_filename) 
1775 H264Encoder::H264Encoder(QSurface *surface, int width, int height, const char *output_filename)
1776         : current_storage_frame(0), surface(surface)
1777         //: width(width), height(height), current_encoding_frame(0)
1778 {
1779         av_register_all();
1780         avctx = avformat_alloc_context();
1781         avctx->oformat = av_guess_format(NULL, output_filename, NULL);
1782         strcpy(avctx->filename, output_filename);
1783         if (avio_open2(&avctx->pb, output_filename, AVIO_FLAG_WRITE, &avctx->interrupt_callback, NULL) < 0) {
1784                 fprintf(stderr, "%s: avio_open2() failed\n", output_filename);
1785                 exit(1);
1786         }
1787         AVCodec *codec_video = avcodec_find_encoder(AV_CODEC_ID_H264);
1788         avstream_video = avformat_new_stream(avctx, codec_video);
1789         if (avstream_video == nullptr) {
1790                 fprintf(stderr, "%s: avformat_new_stream() failed\n", output_filename);
1791                 exit(1);
1792         }
1793         avstream_video->time_base = AVRational{1, TIMEBASE};
1794         avstream_video->codec->width = width;
1795         avstream_video->codec->height = height;
1796         avstream_video->codec->time_base = AVRational{1, TIMEBASE};
1797         avstream_video->codec->ticks_per_frame = 1;  // or 2?
1798
1799         AVCodec *codec_audio = avcodec_find_encoder(AV_CODEC_ID_MP3);
1800         avstream_audio = avformat_new_stream(avctx, codec_audio);
1801         if (avstream_audio == nullptr) {
1802                 fprintf(stderr, "%s: avformat_new_stream() failed\n", output_filename);
1803                 exit(1);
1804         }
1805         avstream_audio->time_base = AVRational{1, TIMEBASE};
1806         avstream_audio->codec->bit_rate = 256000;
1807         avstream_audio->codec->sample_rate = 48000;
1808         avstream_audio->codec->sample_fmt = AV_SAMPLE_FMT_FLTP;
1809         avstream_audio->codec->channels = 2;
1810         avstream_audio->codec->channel_layout = AV_CH_LAYOUT_STEREO;
1811         avstream_audio->codec->time_base = AVRational{1, TIMEBASE};
1812
1813         /* open it */
1814         if (avcodec_open2(avstream_audio->codec, codec_audio, NULL) < 0) {
1815                 fprintf(stderr, "Could not open codec\n");
1816                 exit(1);
1817         }
1818
1819         if (avformat_write_header(avctx, NULL) < 0) {
1820                 fprintf(stderr, "%s: avformat_write_header() failed\n", output_filename);
1821                 exit(1);
1822         }
1823
1824         frame_width = width;
1825         frame_height = height;
1826         frame_width_mbaligned = (frame_width + 15) & (~15);
1827         frame_height_mbaligned = (frame_height + 15) & (~15);
1828         frame_bitrate = 15000000;  // / 60;
1829         current_frame_encoding = 0;
1830
1831         print_input();
1832
1833         init_va();
1834         setup_encode();
1835
1836         // No frames are ready yet.
1837         memset(srcsurface_status, SRC_SURFACE_FREE, sizeof(srcsurface_status));
1838             
1839         memset(&seq_param, 0, sizeof(seq_param));
1840         memset(&pic_param, 0, sizeof(pic_param));
1841         memset(&slice_param, 0, sizeof(slice_param));
1842
1843         storage_thread = std::thread(&H264Encoder::storage_task_thread, this);
1844
1845         copy_thread = std::thread([this]{
1846                 //SDL_GL_MakeCurrent(window, context);
1847                 QOpenGLContext *context = create_context();
1848                 eglBindAPI(EGL_OPENGL_API);
1849                 if (!make_current(context, this->surface)) {
1850                         printf("display=%p surface=%p context=%p curr=%p err=%d\n", eglGetCurrentDisplay(), this->surface, context, eglGetCurrentContext(),
1851                                 eglGetError());
1852                         exit(1);
1853                 }
1854                 copy_thread_func();
1855         });
1856 }
1857
1858 H264Encoder::~H264Encoder()
1859 {
1860         {
1861                 unique_lock<mutex> lock(storage_task_queue_mutex);
1862                 storage_thread_should_quit = true;
1863                 storage_task_queue_changed.notify_all();
1864         }
1865         {
1866                 unique_lock<mutex> lock(frame_queue_mutex);
1867                 copy_thread_should_quit = true;
1868                 frame_queue_nonempty.notify_one();
1869         }
1870         storage_thread.join();
1871         copy_thread.join();
1872
1873         release_encode();
1874         deinit_va();
1875
1876         av_write_trailer(avctx);
1877         avformat_free_context(avctx);
1878 }
1879
1880 bool H264Encoder::begin_frame(GLuint *y_tex, GLuint *cbcr_tex)
1881 {
1882         {
1883                 // Wait until this frame slot is done encoding.
1884                 std::unique_lock<std::mutex> lock(storage_task_queue_mutex);
1885                 storage_task_queue_changed.wait(lock, [this]{ return storage_thread_should_quit || (srcsurface_status[current_storage_frame % SURFACE_NUM] == SRC_SURFACE_FREE); });
1886                 if (storage_thread_should_quit) return false;
1887         }
1888
1889         //*fbo = fbos[current_storage_frame % SURFACE_NUM];
1890         GLSurface *surf = &gl_surfaces[current_storage_frame % SURFACE_NUM];
1891         *y_tex = surf->y_tex;
1892         *cbcr_tex = surf->cbcr_tex;
1893
1894         VASurfaceID surface = surf->src_surface;
1895         VAStatus va_status = vaDeriveImage(va_dpy, surface, &surf->surface_image);
1896         CHECK_VASTATUS(va_status, "vaDeriveImage");
1897
1898         VABufferInfo buf_info;
1899         buf_info.mem_type = VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME;  // or VA_SURFACE_ATTRIB_MEM_TYPE_KERNEL_DRM?
1900         va_status = vaAcquireBufferHandle(va_dpy, surf->surface_image.buf, &buf_info);
1901         CHECK_VASTATUS(va_status, "vaAcquireBufferHandle");
1902
1903         // Create Y image.
1904         surf->y_egl_image = EGL_NO_IMAGE_KHR;
1905         EGLint y_attribs[] = {
1906                 EGL_WIDTH, frame_width,
1907                 EGL_HEIGHT, frame_height,
1908                 EGL_LINUX_DRM_FOURCC_EXT, fourcc_code('R', '8', ' ', ' '),
1909                 EGL_DMA_BUF_PLANE0_FD_EXT, EGLint(buf_info.handle),
1910                 EGL_DMA_BUF_PLANE0_OFFSET_EXT, EGLint(surf->surface_image.offsets[0]),
1911                 EGL_DMA_BUF_PLANE0_PITCH_EXT, EGLint(surf->surface_image.pitches[0]),
1912                 EGL_NONE
1913         };
1914
1915         surf->y_egl_image = eglCreateImageKHR(eglGetCurrentDisplay(), EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, NULL, y_attribs);
1916         assert(surf->y_egl_image != EGL_NO_IMAGE_KHR);
1917
1918         // Associate Y image to a texture.
1919         glBindTexture(GL_TEXTURE_2D, *y_tex);
1920         glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, surf->y_egl_image);
1921
1922         // Create CbCr image.
1923         surf->cbcr_egl_image = EGL_NO_IMAGE_KHR;
1924         EGLint cbcr_attribs[] = {
1925                 EGL_WIDTH, frame_width,
1926                 EGL_HEIGHT, frame_height,
1927                 EGL_LINUX_DRM_FOURCC_EXT, fourcc_code('G', 'R', '8', '8'),
1928                 EGL_DMA_BUF_PLANE0_FD_EXT, EGLint(buf_info.handle),
1929                 EGL_DMA_BUF_PLANE0_OFFSET_EXT, EGLint(surf->surface_image.offsets[1]),
1930                 EGL_DMA_BUF_PLANE0_PITCH_EXT, EGLint(surf->surface_image.pitches[1]),
1931                 EGL_NONE
1932         };
1933
1934         surf->cbcr_egl_image = eglCreateImageKHR(eglGetCurrentDisplay(), EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, NULL, cbcr_attribs);
1935         assert(surf->cbcr_egl_image != EGL_NO_IMAGE_KHR);
1936
1937         // Associate CbCr image to a texture.
1938         glBindTexture(GL_TEXTURE_2D, *cbcr_tex);
1939         glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, surf->cbcr_egl_image);
1940
1941         return true;
1942 }
1943
1944 void H264Encoder::add_audio(int64_t pts, std::vector<float> audio)
1945 {
1946         {
1947                 unique_lock<mutex> lock(frame_queue_mutex);
1948                 pending_audio_frames[pts] = move(audio);
1949         }
1950         frame_queue_nonempty.notify_one();
1951 }
1952
1953
1954 void H264Encoder::end_frame(RefCountedGLsync fence, int64_t pts, const std::vector<RefCountedFrame> &input_frames)
1955 {
1956         {
1957                 unique_lock<mutex> lock(frame_queue_mutex);
1958                 pending_video_frames[current_storage_frame] = PendingFrame{ fence, input_frames };
1959                 timestamps[current_storage_frame] = pts;
1960                 ++current_storage_frame;
1961         }
1962         frame_queue_nonempty.notify_one();
1963 }
1964
1965 void H264Encoder::copy_thread_func()
1966 {
1967         for ( ;; ) {
1968                 PendingFrame frame;
1969                 encoding2display_order(current_frame_encoding, intra_period, intra_idr_period, ip_period,
1970                                        &current_frame_display, &current_frame_type);
1971                 if (current_frame_type == FRAME_IDR) {
1972                         numShortTerm = 0;
1973                         current_frame_num = 0;
1974                         current_IDR_display = current_frame_display;
1975                 }
1976
1977                 {
1978                         unique_lock<mutex> lock(frame_queue_mutex);
1979                         frame_queue_nonempty.wait(lock, [this]{ return copy_thread_should_quit || pending_video_frames.count(current_frame_display) != 0; });
1980                         if (copy_thread_should_quit) return;
1981                         frame = move(pending_video_frames[current_frame_display]);
1982                         pending_video_frames.erase(current_frame_display);
1983                 }
1984
1985                 // Wait for the GPU to be done with the frame.
1986                 glClientWaitSync(frame.fence.get(), 0, 0);
1987
1988                 // Release back any input frames we needed to render this frame.
1989                 frame.input_frames.clear();
1990
1991                 // Unmap the image.
1992                 GLSurface *surf = &gl_surfaces[current_frame_display % SURFACE_NUM];
1993                 eglDestroyImageKHR(eglGetCurrentDisplay(), surf->y_egl_image);
1994                 eglDestroyImageKHR(eglGetCurrentDisplay(), surf->cbcr_egl_image);
1995                 VAStatus va_status = vaReleaseBufferHandle(va_dpy, surf->surface_image.buf);
1996                 CHECK_VASTATUS(va_status, "vaReleaseBufferHandle");
1997                 va_status = vaDestroyImage(va_dpy, surf->surface_image.image_id);
1998                 CHECK_VASTATUS(va_status, "vaDestroyImage");
1999
2000                 VASurfaceID surface = surf->src_surface;
2001
2002                 // Schedule the frame for encoding.
2003                 va_status = vaBeginPicture(va_dpy, context_id, surface);
2004                 CHECK_VASTATUS(va_status, "vaBeginPicture");
2005
2006                 if (current_frame_type == FRAME_IDR) {
2007                         render_sequence();
2008                         render_picture();            
2009                         if (h264_packedheader) {
2010                                 render_packedsequence();
2011                                 render_packedpicture();
2012                         }
2013                 } else {
2014                         //render_sequence();
2015                         render_picture();
2016                 }
2017                 render_slice();
2018                 
2019                 va_status = vaEndPicture(va_dpy, context_id);
2020                 CHECK_VASTATUS(va_status, "vaEndPicture");
2021
2022                 // so now the data is done encoding (well, async job kicked off)...
2023                 // we send that to the storage thread
2024                 storage_task tmp;
2025                 tmp.display_order = current_frame_display;
2026                 tmp.encode_order = current_frame_encoding;
2027                 tmp.frame_type = current_frame_type;
2028                 storage_task_enqueue(move(tmp));
2029                 
2030                 update_ReferenceFrames();
2031                 ++current_frame_encoding;
2032         }
2033 }