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