]> git.sesse.net Git - nageru/blob - nageru/mjpeg_encoder.cpp
Increase the MJPEG encoding queue size by a lot.
[nageru] / nageru / mjpeg_encoder.cpp
1 #include "mjpeg_encoder.h"
2
3 #include <jpeglib.h>
4 #include <unistd.h>
5 #if __SSE2__
6 #include <immintrin.h>
7 #endif
8 #include <list>
9
10 extern "C" {
11 #include <libavformat/avformat.h>
12 }
13
14 #include "defs.h"
15 #include "shared/ffmpeg_raii.h"
16 #include "flags.h"
17 #include "shared/httpd.h"
18 #include "shared/memcpy_interleaved.h"
19 #include "pbo_frame_allocator.h"
20 #include "shared/timebase.h"
21 #include "va_display_with_cleanup.h"
22
23 #include <va/va.h>
24 #include <va/va_drm.h>
25 #include <va/va_x11.h>
26
27 using namespace bmusb;
28 using namespace std;
29
30 extern void memcpy_with_pitch(uint8_t *dst, const uint8_t *src, size_t src_width, size_t dst_pitch, size_t height);
31
32 #define CHECK_VASTATUS(va_status, func)                                 \
33     if (va_status != VA_STATUS_SUCCESS) {                               \
34         fprintf(stderr, "%s:%d (%s) failed with %d\n", __func__, __LINE__, func, va_status); \
35         exit(1);                                                        \
36     }
37
38 // From libjpeg (although it's of course identical between implementations).
39 static const int jpeg_natural_order[DCTSIZE2] = {
40          0,  1,  8, 16,  9,  2,  3, 10,
41         17, 24, 32, 25, 18, 11,  4,  5,
42         12, 19, 26, 33, 40, 48, 41, 34,
43         27, 20, 13,  6,  7, 14, 21, 28,
44         35, 42, 49, 56, 57, 50, 43, 36,
45         29, 22, 15, 23, 30, 37, 44, 51,
46         58, 59, 52, 45, 38, 31, 39, 46,
47         53, 60, 61, 54, 47, 55, 62, 63,
48 };
49
50 struct VectorDestinationManager {
51         jpeg_destination_mgr pub;
52         std::vector<uint8_t> dest;
53
54         VectorDestinationManager()
55         {
56                 pub.init_destination = init_destination_thunk;
57                 pub.empty_output_buffer = empty_output_buffer_thunk;
58                 pub.term_destination = term_destination_thunk;
59         }
60
61         static void init_destination_thunk(j_compress_ptr ptr)
62         {
63                 ((VectorDestinationManager *)(ptr->dest))->init_destination();
64         }
65
66         inline void init_destination()
67         {
68                 make_room(0);
69         }
70
71         static boolean empty_output_buffer_thunk(j_compress_ptr ptr)
72         {
73                 return ((VectorDestinationManager *)(ptr->dest))->empty_output_buffer();
74         }
75
76         inline bool empty_output_buffer()
77         {
78                 make_room(dest.size());  // Should ignore pub.free_in_buffer!
79                 return true;
80         }
81
82         inline void make_room(size_t bytes_used)
83         {
84                 dest.resize(bytes_used + 4096);
85                 dest.resize(dest.capacity());
86                 pub.next_output_byte = dest.data() + bytes_used;
87                 pub.free_in_buffer = dest.size() - bytes_used;
88         }
89
90         static void term_destination_thunk(j_compress_ptr ptr)
91         {
92                 ((VectorDestinationManager *)(ptr->dest))->term_destination();
93         }
94
95         inline void term_destination()
96         {
97                 dest.resize(dest.size() - pub.free_in_buffer);
98         }
99 };
100 static_assert(std::is_standard_layout<VectorDestinationManager>::value, "");
101
102 int MJPEGEncoder::write_packet2_thunk(void *opaque, uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
103 {
104         MJPEGEncoder *engine = (MJPEGEncoder *)opaque;
105         return engine->write_packet2(buf, buf_size, type, time);
106 }
107
108 int MJPEGEncoder::write_packet2(uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
109 {
110         if (type == AVIO_DATA_MARKER_HEADER) {
111                 mux_header.append((char *)buf, buf_size);
112                 httpd->set_header(HTTPD::MULTICAM_STREAM, mux_header);
113         } else {
114                 httpd->add_data(HTTPD::MULTICAM_STREAM, (char *)buf, buf_size, /*keyframe=*/true, AV_NOPTS_VALUE, AVRational{ AV_TIME_BASE, 1 });
115         }
116         return buf_size;
117 }
118
119 MJPEGEncoder::MJPEGEncoder(HTTPD *httpd, const string &va_display)
120         : httpd(httpd)
121 {
122         // Set up the mux. We don't use the Mux wrapper, because it's geared towards
123         // a situation with only one video stream (and possibly one audio stream)
124         // with known width/height, and we don't need the extra functionality it provides.
125         avctx.reset(avformat_alloc_context());
126         avctx->oformat = av_guess_format("mp4", nullptr, nullptr);
127
128         uint8_t *buf = (uint8_t *)av_malloc(MUX_BUFFER_SIZE);
129         avctx->pb = avio_alloc_context(buf, MUX_BUFFER_SIZE, 1, this, nullptr, nullptr, nullptr);
130         avctx->pb->write_data_type = &MJPEGEncoder::write_packet2_thunk;
131         avctx->flags = AVFMT_FLAG_CUSTOM_IO;
132
133         for (unsigned card_idx = 0; card_idx < global_flags.card_to_mjpeg_stream_export.size(); ++card_idx) {
134                 AVStream *stream = avformat_new_stream(avctx.get(), nullptr);
135                 if (stream == nullptr) {
136                         fprintf(stderr, "avformat_new_stream() failed\n");
137                         exit(1);
138                 }
139                 stream->time_base = AVRational{ 1, TIMEBASE };
140                 stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
141                 stream->codecpar->codec_id = AV_CODEC_ID_MJPEG;
142
143                 // Used for aspect ratio only. Can change without notice (the mux won't care).
144                 stream->codecpar->width = global_flags.width;
145                 stream->codecpar->height = global_flags.height;
146
147                 // TODO: We could perhaps use the interpretation for each card here
148                 // (or at least the command-line flags) instead of the defaults,
149                 // but what would we do when they change?
150                 stream->codecpar->color_primaries = AVCOL_PRI_BT709;
151                 stream->codecpar->color_trc = AVCOL_TRC_IEC61966_2_1;
152                 stream->codecpar->color_space = AVCOL_SPC_BT709;
153                 stream->codecpar->color_range = AVCOL_RANGE_MPEG;
154                 stream->codecpar->chroma_location = AVCHROMA_LOC_LEFT;
155                 stream->codecpar->field_order = AV_FIELD_PROGRESSIVE;
156         }
157
158         AVDictionary *options = NULL;
159         vector<pair<string, string>> opts = MUX_OPTS;
160         for (pair<string, string> opt : opts) {
161                 av_dict_set(&options, opt.first.c_str(), opt.second.c_str(), 0);
162         }
163         if (avformat_write_header(avctx.get(), &options) < 0) {
164                 fprintf(stderr, "avformat_write_header() failed\n");
165                 exit(1);
166         }
167
168         // Initialize VA-API.
169         string error;
170         va_dpy = try_open_va(va_display, &error, &config_id);
171         if (va_dpy == nullptr) {
172                 fprintf(stderr, "Could not initialize VA-API for MJPEG encoding: %s. JPEGs will be encoded in software if needed.\n", error.c_str());
173         }
174
175         encoder_thread = thread(&MJPEGEncoder::encoder_thread_func, this);
176         if (va_dpy != nullptr) {
177                 va_receiver_thread = thread(&MJPEGEncoder::va_receiver_thread_func, this);
178         }
179
180         running = true;
181 }
182
183 MJPEGEncoder::~MJPEGEncoder()
184 {
185         av_free(avctx->pb->buffer);
186 }
187
188 void MJPEGEncoder::stop()
189 {
190         if (!running) {
191                 return;
192         }
193         running = false;
194         should_quit = true;
195         any_frames_to_be_encoded.notify_all();
196         encoder_thread.join();
197         if (va_dpy != nullptr) {
198                 va_receiver_thread.join();
199         }
200 }
201
202 unique_ptr<VADisplayWithCleanup> MJPEGEncoder::try_open_va(const string &va_display, string *error, VAConfigID *config_id)
203 {
204         unique_ptr<VADisplayWithCleanup> va_dpy = va_open_display(va_display);
205         if (va_dpy == nullptr) {
206                 if (error) *error = "Opening VA display failed";
207                 return nullptr;
208         }
209         int major_ver, minor_ver;
210         VAStatus va_status = vaInitialize(va_dpy->va_dpy, &major_ver, &minor_ver);
211         if (va_status != VA_STATUS_SUCCESS) {
212                 char buf[256];
213                 snprintf(buf, sizeof(buf), "vaInitialize() failed with status %d\n", va_status);
214                 if (error != nullptr) *error = buf;
215                 return nullptr;
216         }
217
218         VAConfigAttrib attr = { VAConfigAttribRTFormat, VA_RT_FORMAT_YUV422 };
219         va_status = vaCreateConfig(va_dpy->va_dpy, VAProfileJPEGBaseline, VAEntrypointEncPicture,
220                 &attr, 1, config_id);
221         if (va_status == VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT) {
222                 if (error != nullptr) *error = "No hardware support";
223                 return nullptr;
224         } else if (va_status != VA_STATUS_SUCCESS) {
225                 char buf[256];
226                 snprintf(buf, sizeof(buf), "vaCreateConfig() failed with status %d\n", va_status);
227                 if (error != nullptr) *error = buf;
228                 return nullptr;
229         }
230
231         int num_formats = vaMaxNumImageFormats(va_dpy->va_dpy);
232         assert(num_formats > 0);
233
234         unique_ptr<VAImageFormat[]> formats(new VAImageFormat[num_formats]);
235         va_status = vaQueryImageFormats(va_dpy->va_dpy, formats.get(), &num_formats);
236         if (va_status != VA_STATUS_SUCCESS) {
237                 char buf[256];
238                 snprintf(buf, sizeof(buf), "vaQueryImageFormats() failed with status %d\n", va_status);
239                 if (error != nullptr) *error = buf;
240                 return nullptr;
241         }
242
243         return va_dpy;
244 }
245
246 void MJPEGEncoder::upload_frame(int64_t pts, unsigned card_index, RefCountedFrame frame, const bmusb::VideoFormat &video_format, size_t y_offset, size_t cbcr_offset)
247 {
248         PBOFrameAllocator::Userdata *userdata = (PBOFrameAllocator::Userdata *)frame->userdata;
249         if (video_format.width == 0 || video_format.height == 0) {
250                 return;
251         }
252         if (video_format.interlaced) {
253                 fprintf(stderr, "Card %u: Ignoring JPEG encoding for interlaced frame\n", card_index);
254                 return;
255         }
256         if (userdata->pixel_format != PixelFormat_8BitYCbCr ||
257             !frame->interleaved) {
258                 fprintf(stderr, "Card %u: Ignoring JPEG encoding for unsupported pixel format\n", card_index);
259                 return;
260         }
261         if (video_format.width > 4096 || video_format.height > 4096) {
262                 fprintf(stderr, "Card %u: Ignoring JPEG encoding for oversized frame\n", card_index);
263                 return;
264         }
265
266         lock_guard<mutex> lock(mu);
267         if (frames_to_be_encoded.size() + frames_encoding.size() > 50) {
268                 fprintf(stderr, "WARNING: MJPEG encoding doesn't keep up, discarding frame.\n");
269                 return;
270         }
271         frames_to_be_encoded.push(QueuedFrame{ pts, card_index, frame, video_format, y_offset, cbcr_offset });
272         any_frames_to_be_encoded.notify_all();
273 }
274
275 void MJPEGEncoder::encoder_thread_func()
276 {
277         pthread_setname_np(pthread_self(), "MJPEG_Encode");
278         posix_memalign((void **)&tmp_y, 4096, 4096 * 8);
279         posix_memalign((void **)&tmp_cbcr, 4096, 4096 * 8);
280         posix_memalign((void **)&tmp_cb, 4096, 4096 * 8);
281         posix_memalign((void **)&tmp_cr, 4096, 4096 * 8);
282
283         for (;;) {
284                 QueuedFrame qf;
285                 {
286                         unique_lock<mutex> lock(mu);
287                         any_frames_to_be_encoded.wait(lock, [this] { return !frames_to_be_encoded.empty() || should_quit; });
288                         if (should_quit) break;
289                         qf = move(frames_to_be_encoded.front());
290                         frames_to_be_encoded.pop();
291                 }
292
293                 if (va_dpy != nullptr) {
294                         // Will call back in the receiver thread.
295                         encode_jpeg_va(move(qf));
296                 } else {
297                         // Encode synchronously, in the same thread.
298                         vector<uint8_t> jpeg = encode_jpeg_libjpeg(qf);
299                         write_mjpeg_packet(qf.pts, qf.card_index, jpeg);
300                 }
301         }
302
303         free(tmp_y);
304         free(tmp_cbcr);
305         free(tmp_cb);
306         free(tmp_cr);
307 }
308
309 void MJPEGEncoder::write_mjpeg_packet(int64_t pts, unsigned card_index, const vector<uint8_t> &jpeg)
310 {
311         AVPacket pkt;
312         memset(&pkt, 0, sizeof(pkt));
313         pkt.buf = nullptr;
314         pkt.data = const_cast<uint8_t *>(&jpeg[0]);
315         pkt.size = jpeg.size();
316         pkt.stream_index = card_index;
317         pkt.flags = AV_PKT_FLAG_KEY;
318         pkt.pts = pkt.dts = pts;
319
320         if (av_write_frame(avctx.get(), &pkt) < 0) {
321                 fprintf(stderr, "av_write_frame() failed\n");
322                 exit(1);
323         }
324 }
325
326 class VABufferDestroyer {
327 public:
328         VABufferDestroyer(VADisplay dpy, VABufferID buf)
329                 : dpy(dpy), buf(buf) {}
330
331         ~VABufferDestroyer() {
332                 VAStatus va_status = vaDestroyBuffer(dpy, buf);
333                 CHECK_VASTATUS(va_status, "vaDestroyBuffer");
334         }
335
336 private:
337         VADisplay dpy;
338         VABufferID buf;
339 };
340
341 MJPEGEncoder::VAResources MJPEGEncoder::get_va_resources(unsigned width, unsigned height)
342 {
343         {
344                 lock_guard<mutex> lock(va_resources_mutex);
345                 for (auto it = va_resources_freelist.begin(); it != va_resources_freelist.end(); ++it) {
346                         if (it->width == width && it->height == height) {
347                                 VAResources ret = *it;
348                                 va_resources_freelist.erase(it);
349                                 return ret;
350                         }
351                 }
352         }
353
354         VAResources ret;
355
356         ret.width = width;
357         ret.height = height;
358
359         VASurfaceAttrib attrib;
360         attrib.flags = VA_SURFACE_ATTRIB_SETTABLE;
361         attrib.type = VASurfaceAttribPixelFormat;
362         attrib.value.type = VAGenericValueTypeInteger;
363         attrib.value.value.i = VA_FOURCC_UYVY;
364
365         VAStatus va_status = vaCreateSurfaces(va_dpy->va_dpy, VA_RT_FORMAT_YUV422,
366                 width, height,
367                 &ret.surface, 1, &attrib, 1);
368         CHECK_VASTATUS(va_status, "vaCreateSurfaces");
369
370         va_status = vaCreateContext(va_dpy->va_dpy, config_id, width, height, 0, &ret.surface, 1, &ret.context);
371         CHECK_VASTATUS(va_status, "vaCreateContext");
372
373         va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAEncCodedBufferType, width * height * 3 + 8192, 1, nullptr, &ret.data_buffer);
374         CHECK_VASTATUS(va_status, "vaCreateBuffer");
375
376         return ret;
377 }
378
379 void MJPEGEncoder::release_va_resources(MJPEGEncoder::VAResources resources)
380 {
381         lock_guard<mutex> lock(va_resources_mutex);
382         if (va_resources_freelist.size() > 10) {
383                 auto it = va_resources_freelist.end();
384                 --it;
385
386                 VAStatus va_status = vaDestroyBuffer(va_dpy->va_dpy, it->data_buffer);
387                 CHECK_VASTATUS(va_status, "vaDestroyBuffer");
388
389                 va_status = vaDestroyContext(va_dpy->va_dpy, it->context);
390                 CHECK_VASTATUS(va_status, "vaDestroyContext");
391
392                 va_status = vaDestroySurfaces(va_dpy->va_dpy, &it->surface, 1);
393                 CHECK_VASTATUS(va_status, "vaDestroySurfaces");
394
395                 va_resources_freelist.erase(it);
396         }
397
398         va_resources_freelist.push_front(resources);
399 }
400
401 void MJPEGEncoder::init_jpeg_422(unsigned width, unsigned height, VectorDestinationManager *dest, jpeg_compress_struct *cinfo)
402 {
403         jpeg_error_mgr jerr;
404         cinfo->err = jpeg_std_error(&jerr);
405         jpeg_create_compress(cinfo);
406
407         cinfo->dest = (jpeg_destination_mgr *)dest;
408
409         cinfo->input_components = 3;
410         jpeg_set_defaults(cinfo);
411         jpeg_set_quality(cinfo, quality, /*force_baseline=*/false);
412
413         cinfo->image_width = width;
414         cinfo->image_height = height;
415         cinfo->raw_data_in = true;
416         jpeg_set_colorspace(cinfo, JCS_YCbCr);
417         cinfo->comp_info[0].h_samp_factor = 2;
418         cinfo->comp_info[0].v_samp_factor = 1;
419         cinfo->comp_info[1].h_samp_factor = 1;
420         cinfo->comp_info[1].v_samp_factor = 1;
421         cinfo->comp_info[2].h_samp_factor = 1;
422         cinfo->comp_info[2].v_samp_factor = 1;
423         cinfo->CCIR601_sampling = true;  // Seems to be mostly ignored by libjpeg, though.
424         jpeg_start_compress(cinfo, true);
425
426         // This comment marker is private to FFmpeg. It signals limited Y'CbCr range
427         // (and nothing else).
428         jpeg_write_marker(cinfo, JPEG_COM, (const JOCTET *)"CS=ITU601", strlen("CS=ITU601"));
429 }
430
431 vector<uint8_t> MJPEGEncoder::get_jpeg_header(unsigned width, unsigned height, jpeg_compress_struct *cinfo)
432 {
433         VectorDestinationManager dest;
434         init_jpeg_422(width, height, &dest, cinfo);
435
436         // Make a dummy black image; there's seemingly no other easy way of
437         // making libjpeg outputting all of its headers.
438         JSAMPROW yptr[8], cbptr[8], crptr[8];
439         JSAMPARRAY data[3] = { yptr, cbptr, crptr };
440         memset(tmp_y, 0, 4096);
441         memset(tmp_cb, 0, 4096);
442         memset(tmp_cr, 0, 4096);
443         for (unsigned yy = 0; yy < 8; ++yy) {
444                 yptr[yy] = tmp_y;
445                 cbptr[yy] = tmp_cb;
446                 crptr[yy] = tmp_cr;
447         }
448         for (unsigned y = 0; y < height; y += 8) {
449                 jpeg_write_raw_data(cinfo, data, /*num_lines=*/8);
450         }
451         jpeg_finish_compress(cinfo);
452
453         // We're only interested in the header, not the data after it.
454         dest.term_destination();
455         for (size_t i = 0; i < dest.dest.size() - 1; ++i) {
456                 if (dest.dest[i] == 0xff && dest.dest[i + 1] == 0xda) {  // Start of scan (SOS).
457                         unsigned len = dest.dest[i + 2] * 256 + dest.dest[i + 3];
458                         dest.dest.resize(i + len + 2);
459                         break;
460                 }
461         }
462
463         return dest.dest;
464 }
465
466 MJPEGEncoder::VAData MJPEGEncoder::get_va_data_for_resolution(unsigned width, unsigned height)
467 {
468         pair<unsigned, unsigned> key(width, height);
469         if (va_data_for_resolution.count(key)) {
470                 return va_data_for_resolution[key];
471         }
472
473         // Use libjpeg to generate a header and set sane defaults for e.g.
474         // quantization tables. Then do the actual encode with VA-API.
475         jpeg_compress_struct cinfo;
476         vector<uint8_t> jpeg_header = get_jpeg_header(width, height, &cinfo);
477
478         // Picture parameters.
479         VAEncPictureParameterBufferJPEG pic_param;
480         memset(&pic_param, 0, sizeof(pic_param));
481         pic_param.reconstructed_picture = VA_INVALID_ID;
482         pic_param.picture_width = cinfo.image_width;
483         pic_param.picture_height = cinfo.image_height;
484         for (int component_idx = 0; component_idx < cinfo.num_components; ++component_idx) {
485                 const jpeg_component_info *comp = &cinfo.comp_info[component_idx];
486                 pic_param.component_id[component_idx] = comp->component_id;
487                 pic_param.quantiser_table_selector[component_idx] = comp->quant_tbl_no;
488         }
489         pic_param.num_components = cinfo.num_components;
490         pic_param.num_scan = 1;
491         pic_param.sample_bit_depth = 8;
492         pic_param.coded_buf = VA_INVALID_ID;  // To be filled out by caller.
493         pic_param.pic_flags.bits.huffman = 1;
494         pic_param.quality = 50;  // Don't scale the given quantization matrices. (See gen8_mfc_jpeg_fqm_state)
495
496         // Quantization matrices.
497         VAQMatrixBufferJPEG q;
498         memset(&q, 0, sizeof(q));
499
500         q.load_lum_quantiser_matrix = true;
501         q.load_chroma_quantiser_matrix = true;
502         for (int quant_tbl_idx = 0; quant_tbl_idx < min(4, NUM_QUANT_TBLS); ++quant_tbl_idx) {
503                 const JQUANT_TBL *qtbl = cinfo.quant_tbl_ptrs[quant_tbl_idx];
504                 assert((qtbl == nullptr) == (quant_tbl_idx >= 2));
505                 if (qtbl == nullptr) continue;
506
507                 uint8_t *qmatrix = (quant_tbl_idx == 0) ? q.lum_quantiser_matrix : q.chroma_quantiser_matrix;
508                 for (int i = 0; i < 64; ++i) {
509                         if (qtbl->quantval[i] > 255) {
510                                 fprintf(stderr, "Baseline JPEG only!\n");
511                                 abort();
512                         }
513                         qmatrix[i] = qtbl->quantval[jpeg_natural_order[i]];
514                 }
515         }
516
517         // Huffman tables (arithmetic is not supported).
518         VAHuffmanTableBufferJPEGBaseline huff;
519         memset(&huff, 0, sizeof(huff));
520
521         for (int huff_tbl_idx = 0; huff_tbl_idx < min(2, NUM_HUFF_TBLS); ++huff_tbl_idx) {
522                 const JHUFF_TBL *ac_hufftbl = cinfo.ac_huff_tbl_ptrs[huff_tbl_idx];
523                 const JHUFF_TBL *dc_hufftbl = cinfo.dc_huff_tbl_ptrs[huff_tbl_idx];
524                 if (ac_hufftbl == nullptr) {
525                         assert(dc_hufftbl == nullptr);
526                         huff.load_huffman_table[huff_tbl_idx] = 0;
527                 } else {
528                         assert(dc_hufftbl != nullptr);
529                         huff.load_huffman_table[huff_tbl_idx] = 1;
530
531                         for (int i = 0; i < 16; ++i) {
532                                 huff.huffman_table[huff_tbl_idx].num_dc_codes[i] = dc_hufftbl->bits[i + 1];
533                         }
534                         for (int i = 0; i < 12; ++i) {
535                                 huff.huffman_table[huff_tbl_idx].dc_values[i] = dc_hufftbl->huffval[i];
536                         }
537                         for (int i = 0; i < 16; ++i) {
538                                 huff.huffman_table[huff_tbl_idx].num_ac_codes[i] = ac_hufftbl->bits[i + 1];
539                         }
540                         for (int i = 0; i < 162; ++i) {
541                                 huff.huffman_table[huff_tbl_idx].ac_values[i] = ac_hufftbl->huffval[i];
542                         }
543                 }
544         }
545
546         // Slice parameters (metadata about the slice).
547         VAEncSliceParameterBufferJPEG parms;
548         memset(&parms, 0, sizeof(parms));
549         for (int component_idx = 0; component_idx < cinfo.num_components; ++component_idx) {
550                 const jpeg_component_info *comp = &cinfo.comp_info[component_idx];
551                 parms.components[component_idx].component_selector = comp->component_id;
552                 parms.components[component_idx].dc_table_selector = comp->dc_tbl_no;
553                 parms.components[component_idx].ac_table_selector = comp->ac_tbl_no;
554                 if (parms.components[component_idx].dc_table_selector > 1 ||
555                     parms.components[component_idx].ac_table_selector > 1) {
556                         fprintf(stderr, "Uses too many Huffman tables\n");
557                         abort();
558                 }
559         }
560         parms.num_components = cinfo.num_components;
561         parms.restart_interval = cinfo.restart_interval;
562
563         jpeg_destroy_compress(&cinfo);
564
565         VAData ret;
566         ret.jpeg_header = move(jpeg_header);
567         ret.pic_param = pic_param;
568         ret.q = q;
569         ret.huff = huff;
570         ret.parms = parms;
571         va_data_for_resolution[key] = ret;
572         return ret;
573 }
574
575 void MJPEGEncoder::encode_jpeg_va(QueuedFrame &&qf)
576 {
577         unsigned width = qf.video_format.width;
578         unsigned height = qf.video_format.height;
579
580         VAResources resources = get_va_resources(width, height);
581         ReleaseVAResources release(this, resources);
582
583         VAData va_data = get_va_data_for_resolution(width, height);
584         va_data.pic_param.coded_buf = resources.data_buffer;
585
586         VABufferID pic_param_buffer;
587         VAStatus va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAEncPictureParameterBufferType, sizeof(va_data.pic_param), 1, &va_data.pic_param, &pic_param_buffer);
588         CHECK_VASTATUS(va_status, "vaCreateBuffer");
589         VABufferDestroyer destroy_pic_param(va_dpy->va_dpy, pic_param_buffer);
590
591         VABufferID q_buffer;
592         va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAQMatrixBufferType, sizeof(va_data.q), 1, &va_data.q, &q_buffer);
593         CHECK_VASTATUS(va_status, "vaCreateBuffer");
594         VABufferDestroyer destroy_iq(va_dpy->va_dpy, q_buffer);
595
596         VABufferID huff_buffer;
597         va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAHuffmanTableBufferType, sizeof(va_data.huff), 1, &va_data.huff, &huff_buffer);
598         CHECK_VASTATUS(va_status, "vaCreateBuffer");
599         VABufferDestroyer destroy_huff(va_dpy->va_dpy, huff_buffer);
600
601         VABufferID slice_param_buffer;
602         va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAEncSliceParameterBufferType, sizeof(va_data.parms), 1, &va_data.parms, &slice_param_buffer);
603         CHECK_VASTATUS(va_status, "vaCreateBuffer");
604         VABufferDestroyer destroy_slice_param(va_dpy->va_dpy, slice_param_buffer);
605
606         VAImage image;
607         va_status = vaDeriveImage(va_dpy->va_dpy, resources.surface, &image);
608         CHECK_VASTATUS(va_status, "vaDeriveImage");
609
610         // Upload the pixel data.
611         uint8_t *surface_p = nullptr;
612         vaMapBuffer(va_dpy->va_dpy, image.buf, (void **)&surface_p);
613
614         size_t field_start_line = qf.video_format.extra_lines_top;  // No interlacing support.
615         size_t field_start = qf.cbcr_offset * 2 + qf.video_format.width * field_start_line * 2;
616
617         {
618                 const uint8_t *src = qf.frame->data_copy + field_start;
619                 uint8_t *dst = (unsigned char *)surface_p + image.offsets[0];
620                 memcpy_with_pitch(dst, src, qf.video_format.width * 2, image.pitches[0], qf.video_format.height);
621         }
622
623         va_status = vaUnmapBuffer(va_dpy->va_dpy, image.buf);
624         CHECK_VASTATUS(va_status, "vaUnmapBuffer");
625         va_status = vaDestroyImage(va_dpy->va_dpy, image.image_id);
626         CHECK_VASTATUS(va_status, "vaDestroyImage");
627
628         // Finally, stick in the JPEG header.
629         VAEncPackedHeaderParameterBuffer header_parm;
630         header_parm.type = VAEncPackedHeaderRawData;
631         header_parm.bit_length = 8 * va_data.jpeg_header.size();
632
633         VABufferID header_parm_buffer;
634         va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAEncPackedHeaderParameterBufferType, sizeof(header_parm), 1, &header_parm, &header_parm_buffer);
635         CHECK_VASTATUS(va_status, "vaCreateBuffer");
636         VABufferDestroyer destroy_header(va_dpy->va_dpy, header_parm_buffer);
637
638         VABufferID header_data_buffer;
639         va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAEncPackedHeaderDataBufferType, va_data.jpeg_header.size(), 1, va_data.jpeg_header.data(), &header_data_buffer);
640         CHECK_VASTATUS(va_status, "vaCreateBuffer");
641         VABufferDestroyer destroy_header_data(va_dpy->va_dpy, header_data_buffer);
642
643         va_status = vaBeginPicture(va_dpy->va_dpy, resources.context, resources.surface);
644         CHECK_VASTATUS(va_status, "vaBeginPicture");
645         va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &pic_param_buffer, 1);
646         CHECK_VASTATUS(va_status, "vaRenderPicture(pic_param)");
647         va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &q_buffer, 1);
648         CHECK_VASTATUS(va_status, "vaRenderPicture(q)");
649         va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &huff_buffer, 1);
650         CHECK_VASTATUS(va_status, "vaRenderPicture(huff)");
651         va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &slice_param_buffer, 1);
652         CHECK_VASTATUS(va_status, "vaRenderPicture(slice_param)");
653         va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &header_parm_buffer, 1);
654         CHECK_VASTATUS(va_status, "vaRenderPicture(header_parm)");
655         va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &header_data_buffer, 1);
656         CHECK_VASTATUS(va_status, "vaRenderPicture(header_data)");
657         va_status = vaEndPicture(va_dpy->va_dpy, resources.context);
658         CHECK_VASTATUS(va_status, "vaEndPicture");
659
660         qf.resources = move(resources);
661         qf.resource_releaser = move(release);
662
663         lock_guard<mutex> lock(mu);
664         frames_encoding.push(move(qf));
665         any_frames_encoding.notify_all();
666 }
667
668 void MJPEGEncoder::va_receiver_thread_func()
669 {
670         pthread_setname_np(pthread_self(), "MJPEG_Receive");
671         for (;;) {
672                 QueuedFrame qf;
673                 {
674                         unique_lock<mutex> lock(mu);
675                         any_frames_encoding.wait(lock, [this] { return !frames_encoding.empty() || should_quit; });
676                         if (should_quit) return;
677                         qf = move(frames_encoding.front());
678                         frames_encoding.pop();
679                 }
680
681                 VAStatus va_status = vaSyncSurface(va_dpy->va_dpy, qf.resources.surface);
682                 CHECK_VASTATUS(va_status, "vaSyncSurface");
683
684                 VACodedBufferSegment *segment;
685                 va_status = vaMapBuffer(va_dpy->va_dpy, qf.resources.data_buffer, (void **)&segment);
686                 CHECK_VASTATUS(va_status, "vaMapBuffer");
687
688                 const char *coded_buf = reinterpret_cast<char *>(segment->buf);
689                 vector<uint8_t> jpeg(coded_buf, coded_buf + segment->size);
690
691                 va_status = vaUnmapBuffer(va_dpy->va_dpy, qf.resources.data_buffer);
692                 CHECK_VASTATUS(va_status, "vaUnmapBuffer");
693
694                 write_mjpeg_packet(qf.pts, qf.card_index, jpeg);
695         }
696 }
697
698 vector<uint8_t> MJPEGEncoder::encode_jpeg_libjpeg(const QueuedFrame &qf)
699 {
700         unsigned width = qf.video_format.width;
701         unsigned height = qf.video_format.height;
702
703         VectorDestinationManager dest;
704         jpeg_compress_struct cinfo;
705         init_jpeg_422(width, height, &dest, &cinfo);
706
707         size_t field_start_line = qf.video_format.extra_lines_top;  // No interlacing support.
708         size_t field_start = qf.cbcr_offset * 2 + qf.video_format.width * field_start_line * 2;
709
710         JSAMPROW yptr[8], cbptr[8], crptr[8];
711         JSAMPARRAY data[3] = { yptr, cbptr, crptr };
712         for (unsigned y = 0; y < qf.video_format.height; y += 8) {
713                 const uint8_t *src = qf.frame->data_copy + field_start + y * qf.video_format.width * 2;
714
715                 memcpy_interleaved(tmp_y, tmp_cbcr, src, qf.video_format.width * 8 * 2);
716                 memcpy_interleaved(tmp_cb, tmp_cr, tmp_cbcr, qf.video_format.width * 8);
717                 for (unsigned yy = 0; yy < 8; ++yy) {
718                         yptr[yy] = tmp_y + yy * width;
719                         cbptr[yy] = tmp_cb + yy * width / 2;
720                         crptr[yy] = tmp_cr + yy * width / 2;
721                 }
722                 jpeg_write_raw_data(&cinfo, data, /*num_lines=*/8);
723         }
724         jpeg_finish_compress(&cinfo);
725
726         return dest.dest;
727 }