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