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