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