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