1 #include "vaapi_jpeg_decoder.h"
3 #include "jpeg_destroyer.h"
4 #include "jpeg_frame.h"
5 #include "shared/memcpy_interleaved.h"
21 #include <va/va_drm.h>
22 #include <va/va_x11.h>
26 static unique_ptr<VADisplayWithCleanup> va_dpy;
27 static VAConfigID config_id;
28 static VAImageFormat uyvy_format;
29 bool vaapi_jpeg_decoding_usable = false;
32 unsigned width, height;
37 static list<VAResources> va_resources_freelist;
38 static mutex va_resources_mutex;
40 #define CHECK_VASTATUS(va_status, func) \
41 if (va_status != VA_STATUS_SUCCESS) { \
42 fprintf(stderr, "%s:%d (%s) failed with %d\n", __func__, __LINE__, func, va_status); \
46 #define CHECK_VASTATUS_RET(va_status, func) \
47 if (va_status != VA_STATUS_SUCCESS) { \
48 fprintf(stderr, "%s:%d (%s) failed with %d\n", __func__, __LINE__, func, va_status); \
52 // From libjpeg (although it's of course identical between implementations).
53 static const int jpeg_natural_order[DCTSIZE2] = {
54 0, 1, 8, 16, 9, 2, 3, 10,
55 17, 24, 32, 25, 18, 11, 4, 5,
56 12, 19, 26, 33, 40, 48, 41, 34,
57 27, 20, 13, 6, 7, 14, 21, 28,
58 35, 42, 49, 56, 57, 50, 43, 36,
59 29, 22, 15, 23, 30, 37, 44, 51,
60 58, 59, 52, 45, 38, 31, 39, 46,
61 53, 60, 61, 54, 47, 55, 62, 63,
64 VAResources get_va_resources(unsigned width, unsigned height)
67 lock_guard<mutex> lock(va_resources_mutex);
68 for (auto it = va_resources_freelist.begin(); it != va_resources_freelist.end(); ++it) {
69 if (it->width == width && it->height == height) {
70 VAResources ret = *it;
71 va_resources_freelist.erase(it);
82 VAStatus va_status = vaCreateSurfaces(va_dpy->va_dpy, VA_RT_FORMAT_YUV422,
84 &ret.surface, 1, nullptr, 0);
85 CHECK_VASTATUS(va_status, "vaCreateSurfaces");
87 va_status = vaCreateContext(va_dpy->va_dpy, config_id, width, height, 0, &ret.surface, 1, &ret.context);
88 CHECK_VASTATUS(va_status, "vaCreateContext");
90 va_status = vaCreateImage(va_dpy->va_dpy, &uyvy_format, width, height, &ret.image);
91 CHECK_VASTATUS(va_status, "vaCreateImage");
96 void release_va_resources(VAResources resources)
98 lock_guard<mutex> lock(va_resources_mutex);
99 if (va_resources_freelist.size() > 10) {
100 auto it = va_resources_freelist.end();
103 VAStatus va_status = vaDestroyImage(va_dpy->va_dpy, it->image.image_id);
104 CHECK_VASTATUS(va_status, "vaDestroyImage");
106 va_status = vaDestroyContext(va_dpy->va_dpy, it->context);
107 CHECK_VASTATUS(va_status, "vaDestroyContext");
109 va_status = vaDestroySurfaces(va_dpy->va_dpy, &it->surface, 1);
110 CHECK_VASTATUS(va_status, "vaDestroySurfaces");
112 va_resources_freelist.erase(it);
115 va_resources_freelist.push_front(resources);
118 // RAII wrapper to release VAResources on return (even on error).
119 class ReleaseVAResources {
121 ReleaseVAResources(const VAResources &resources)
122 : resources(resources) {}
123 ~ReleaseVAResources()
126 release_va_resources(resources);
130 void commit() { committed = true; }
133 const VAResources &resources;
134 bool committed = false;
137 VADisplayWithCleanup::~VADisplayWithCleanup()
139 if (va_dpy != nullptr) {
142 if (x11_display != nullptr) {
143 XCloseDisplay(x11_display);
150 unique_ptr<VADisplayWithCleanup> va_open_display(const string &va_display)
152 if (va_display.empty() || va_display[0] != '/') { // An X display.
153 Display *x11_display = XOpenDisplay(va_display.empty() ? nullptr : va_display.c_str());
154 if (x11_display == nullptr) {
155 fprintf(stderr, "error: can't connect to X server!\n");
159 unique_ptr<VADisplayWithCleanup> ret(new VADisplayWithCleanup);
160 ret->x11_display = x11_display;
161 ret->va_dpy = vaGetDisplay(x11_display);
162 if (ret->va_dpy == nullptr) {
166 } else { // A DRM node on the filesystem (e.g. /dev/dri/renderD128).
167 int drm_fd = open(va_display.c_str(), O_RDWR);
169 perror(va_display.c_str());
172 unique_ptr<VADisplayWithCleanup> ret(new VADisplayWithCleanup);
173 ret->drm_fd = drm_fd;
174 ret->va_dpy = vaGetDisplayDRM(drm_fd);
175 if (ret->va_dpy == nullptr) {
182 unique_ptr<VADisplayWithCleanup> try_open_va(const string &va_display, string *error)
184 unique_ptr<VADisplayWithCleanup> va_dpy = va_open_display(va_display);
185 if (va_dpy == nullptr) {
187 *error = "Opening VA display failed";
190 int major_ver, minor_ver;
191 VAStatus va_status = vaInitialize(va_dpy->va_dpy, &major_ver, &minor_ver);
192 if (va_status != VA_STATUS_SUCCESS) {
194 snprintf(buf, sizeof(buf), "vaInitialize() failed with status %d\n", va_status);
195 if (error != nullptr)
200 int num_entrypoints = vaMaxNumEntrypoints(va_dpy->va_dpy);
201 unique_ptr<VAEntrypoint[]> entrypoints(new VAEntrypoint[num_entrypoints]);
202 if (entrypoints == nullptr) {
203 if (error != nullptr)
204 *error = "Failed to allocate memory for VA entry points";
208 vaQueryConfigEntrypoints(va_dpy->va_dpy, VAProfileJPEGBaseline, entrypoints.get(), &num_entrypoints);
209 for (int slice_entrypoint = 0; slice_entrypoint < num_entrypoints; slice_entrypoint++) {
210 if (entrypoints[slice_entrypoint] != VAEntrypointVLD) {
214 // We found a usable decode, so return it.
218 if (error != nullptr)
219 *error = "Can't find VAEntrypointVLD for the JPEG profile";
223 string get_usable_va_display()
225 // Reduce the amount of chatter while probing,
226 // unless the user has specified otherwise.
227 bool need_env_reset = false;
228 if (getenv("LIBVA_MESSAGING_LEVEL") == nullptr) {
229 setenv("LIBVA_MESSAGING_LEVEL", "0", true);
230 need_env_reset = true;
233 // First try the default (ie., whatever $DISPLAY is set to).
234 unique_ptr<VADisplayWithCleanup> va_dpy = try_open_va("", nullptr);
235 if (va_dpy != nullptr) {
236 if (need_env_reset) {
237 unsetenv("LIBVA_MESSAGING_LEVEL");
242 fprintf(stderr, "The X11 display did not expose a VA-API JPEG decoder.\n");
244 // Try all /dev/dri/render* in turn. TODO: Accept /dev/dri/card*, too?
246 int err = glob("/dev/dri/renderD*", 0, nullptr, &g);
248 fprintf(stderr, "Couldn't list render nodes (%s) when trying to autodetect a replacement.\n", strerror(errno));
250 for (size_t i = 0; i < g.gl_pathc; ++i) {
251 string path = g.gl_pathv[i];
252 va_dpy = try_open_va(path, nullptr);
253 if (va_dpy != nullptr) {
254 fprintf(stderr, "Autodetected %s as a suitable replacement; using it.\n",
257 if (need_env_reset) {
258 unsetenv("LIBVA_MESSAGING_LEVEL");
265 fprintf(stderr, "No suitable VA-API JPEG decoders were found in /dev/dri; giving up.\n");
266 fprintf(stderr, "Note that if you are using an Intel CPU with an external GPU,\n");
267 fprintf(stderr, "you may need to enable the integrated Intel GPU in your BIOS\n");
268 fprintf(stderr, "to expose Quick Sync.\n");
272 void init_jpeg_vaapi()
274 string dpy = get_usable_va_display();
279 va_dpy = try_open_va(dpy, nullptr);
280 if (va_dpy == nullptr) {
284 VAConfigAttrib attr = { VAConfigAttribRTFormat, VA_RT_FORMAT_YUV422 };
286 VAStatus va_status = vaCreateConfig(va_dpy->va_dpy, VAProfileJPEGBaseline, VAEntrypointVLD,
287 &attr, 1, &config_id);
288 CHECK_VASTATUS(va_status, "vaCreateConfig");
290 int num_formats = vaMaxNumImageFormats(va_dpy->va_dpy);
291 assert(num_formats > 0);
293 unique_ptr<VAImageFormat[]> formats(new VAImageFormat[num_formats]);
294 va_status = vaQueryImageFormats(va_dpy->va_dpy, formats.get(), &num_formats);
295 CHECK_VASTATUS(va_status, "vaQueryImageFormats");
298 for (int i = 0; i < num_formats; ++i) {
299 // Seemingly VA_FOURCC_422H is no good for vaGetImage(). :-/
300 if (formats[i].fourcc == VA_FOURCC_UYVY) {
301 memcpy(&uyvy_format, &formats[i], sizeof(VAImageFormat));
310 fprintf(stderr, "VA-API JPEG decoding initialized.\n");
311 vaapi_jpeg_decoding_usable = true;
314 class VABufferDestroyer {
316 VABufferDestroyer(VADisplay dpy, VABufferID buf)
317 : dpy(dpy), buf(buf) {}
319 ~VABufferDestroyer() {
320 VAStatus va_status = vaDestroyBuffer(dpy, buf);
321 CHECK_VASTATUS(va_status, "vaDestroyBuffer");
329 shared_ptr<Frame> decode_jpeg_vaapi(const string &jpeg)
331 jpeg_decompress_struct dinfo;
333 dinfo.err = jpeg_std_error(&jerr);
334 jpeg_create_decompress(&dinfo);
335 JPEGDestroyer destroy_dinfo(&dinfo);
337 jpeg_mem_src(&dinfo, reinterpret_cast<const unsigned char *>(jpeg.data()), jpeg.size());
338 jpeg_read_header(&dinfo, true);
340 if (dinfo.num_components != 3) {
341 fprintf(stderr, "Not a color JPEG. (%d components, Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
342 dinfo.num_components,
343 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
344 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
345 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
348 if (dinfo.comp_info[0].h_samp_factor != 2 ||
349 dinfo.comp_info[1].h_samp_factor != 1 ||
350 dinfo.comp_info[1].v_samp_factor != dinfo.comp_info[0].v_samp_factor ||
351 dinfo.comp_info[2].h_samp_factor != 1 ||
352 dinfo.comp_info[2].v_samp_factor != dinfo.comp_info[0].v_samp_factor) {
353 fprintf(stderr, "Not 4:2:2. (Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
354 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
355 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
356 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
360 // Picture parameters.
361 VAPictureParameterBufferJPEGBaseline pic_param;
362 memset(&pic_param, 0, sizeof(pic_param));
363 pic_param.picture_width = dinfo.image_width;
364 pic_param.picture_height = dinfo.image_height;
365 for (int component_idx = 0; component_idx < dinfo.num_components; ++component_idx) {
366 const jpeg_component_info *comp = &dinfo.comp_info[component_idx];
367 pic_param.components[component_idx].component_id = comp->component_id;
368 pic_param.components[component_idx].h_sampling_factor = comp->h_samp_factor;
369 pic_param.components[component_idx].v_sampling_factor = comp->v_samp_factor;
370 pic_param.components[component_idx].quantiser_table_selector = comp->quant_tbl_no;
372 pic_param.num_components = dinfo.num_components;
373 pic_param.color_space = 0; // YUV.
374 pic_param.rotation = VA_ROTATION_NONE;
376 VABufferID pic_param_buffer;
377 VAStatus va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAPictureParameterBufferType, sizeof(pic_param), 1, &pic_param, &pic_param_buffer);
378 CHECK_VASTATUS_RET(va_status, "vaCreateBuffer");
379 VABufferDestroyer destroy_pic_param(va_dpy->va_dpy, pic_param_buffer);
381 // Quantization matrices.
382 VAIQMatrixBufferJPEGBaseline iq;
383 memset(&iq, 0, sizeof(iq));
385 for (int quant_tbl_idx = 0; quant_tbl_idx < min(4, NUM_QUANT_TBLS); ++quant_tbl_idx) {
386 const JQUANT_TBL *qtbl = dinfo.quant_tbl_ptrs[quant_tbl_idx];
387 if (qtbl == nullptr) {
388 iq.load_quantiser_table[quant_tbl_idx] = 0;
390 iq.load_quantiser_table[quant_tbl_idx] = 1;
391 for (int i = 0; i < 64; ++i) {
392 if (qtbl->quantval[i] > 255) {
393 fprintf(stderr, "Baseline JPEG only!\n");
396 iq.quantiser_table[quant_tbl_idx][i] = qtbl->quantval[jpeg_natural_order[i]];
401 VABufferID iq_buffer;
402 va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAIQMatrixBufferType, sizeof(iq), 1, &iq, &iq_buffer);
403 CHECK_VASTATUS_RET(va_status, "vaCreateBuffer");
404 VABufferDestroyer destroy_iq(va_dpy->va_dpy, iq_buffer);
406 // Huffman tables (arithmetic is not supported).
407 VAHuffmanTableBufferJPEGBaseline huff;
408 memset(&huff, 0, sizeof(huff));
410 for (int huff_tbl_idx = 0; huff_tbl_idx < min(2, NUM_HUFF_TBLS); ++huff_tbl_idx) {
411 const JHUFF_TBL *ac_hufftbl = dinfo.ac_huff_tbl_ptrs[huff_tbl_idx];
412 const JHUFF_TBL *dc_hufftbl = dinfo.dc_huff_tbl_ptrs[huff_tbl_idx];
413 if (ac_hufftbl == nullptr) {
414 assert(dc_hufftbl == nullptr);
415 huff.load_huffman_table[huff_tbl_idx] = 0;
417 assert(dc_hufftbl != nullptr);
418 huff.load_huffman_table[huff_tbl_idx] = 1;
420 for (int i = 0; i < 16; ++i) {
421 huff.huffman_table[huff_tbl_idx].num_dc_codes[i] = dc_hufftbl->bits[i + 1];
423 for (int i = 0; i < 12; ++i) {
424 huff.huffman_table[huff_tbl_idx].dc_values[i] = dc_hufftbl->huffval[i];
426 for (int i = 0; i < 16; ++i) {
427 huff.huffman_table[huff_tbl_idx].num_ac_codes[i] = ac_hufftbl->bits[i + 1];
429 for (int i = 0; i < 162; ++i) {
430 huff.huffman_table[huff_tbl_idx].ac_values[i] = ac_hufftbl->huffval[i];
435 VABufferID huff_buffer;
436 va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAHuffmanTableBufferType, sizeof(huff), 1, &huff, &huff_buffer);
437 CHECK_VASTATUS_RET(va_status, "vaCreateBuffer");
438 VABufferDestroyer destroy_huff(va_dpy->va_dpy, huff_buffer);
440 // Slice parameters (metadata about the slice).
441 VASliceParameterBufferJPEGBaseline parms;
442 memset(&parms, 0, sizeof(parms));
443 parms.slice_data_size = dinfo.src->bytes_in_buffer;
444 parms.slice_data_offset = 0;
445 parms.slice_data_flag = VA_SLICE_DATA_FLAG_ALL;
446 parms.slice_horizontal_position = 0;
447 parms.slice_vertical_position = 0;
448 for (int component_idx = 0; component_idx < dinfo.num_components; ++component_idx) {
449 const jpeg_component_info *comp = &dinfo.comp_info[component_idx];
450 parms.components[component_idx].component_selector = comp->component_id;
451 parms.components[component_idx].dc_table_selector = comp->dc_tbl_no;
452 parms.components[component_idx].ac_table_selector = comp->ac_tbl_no;
453 if (parms.components[component_idx].dc_table_selector > 1 ||
454 parms.components[component_idx].ac_table_selector > 1) {
455 fprintf(stderr, "Uses too many Huffman tables\n");
459 parms.num_components = dinfo.num_components;
460 parms.restart_interval = dinfo.restart_interval;
461 int horiz_mcus = (dinfo.image_width + (DCTSIZE * 2) - 1) / (DCTSIZE * 2);
462 int vert_mcus = (dinfo.image_height + DCTSIZE - 1) / DCTSIZE;
463 parms.num_mcus = horiz_mcus * vert_mcus;
465 VABufferID slice_param_buffer;
466 va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VASliceParameterBufferType, sizeof(parms), 1, &parms, &slice_param_buffer);
467 CHECK_VASTATUS_RET(va_status, "vaCreateBuffer");
468 VABufferDestroyer destroy_slice_param(va_dpy->va_dpy, slice_param_buffer);
470 // The actual data. VA-API will destuff and all for us.
471 VABufferID data_buffer;
472 va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VASliceDataBufferType, dinfo.src->bytes_in_buffer, 1, const_cast<unsigned char *>(dinfo.src->next_input_byte), &data_buffer);
473 CHECK_VASTATUS_RET(va_status, "vaCreateBuffer");
474 VABufferDestroyer destroy_data(va_dpy->va_dpy, data_buffer);
476 VAResources resources = get_va_resources(dinfo.image_width, dinfo.image_height);
477 ReleaseVAResources release(resources);
479 va_status = vaBeginPicture(va_dpy->va_dpy, resources.context, resources.surface);
480 CHECK_VASTATUS_RET(va_status, "vaBeginPicture");
481 va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &pic_param_buffer, 1);
482 CHECK_VASTATUS_RET(va_status, "vaRenderPicture(pic_param)");
483 va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &iq_buffer, 1);
484 CHECK_VASTATUS_RET(va_status, "vaRenderPicture(iq)");
485 va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &huff_buffer, 1);
486 CHECK_VASTATUS_RET(va_status, "vaRenderPicture(huff)");
487 va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &slice_param_buffer, 1);
488 CHECK_VASTATUS_RET(va_status, "vaRenderPicture(slice_param)");
489 va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &data_buffer, 1);
490 CHECK_VASTATUS_RET(va_status, "vaRenderPicture(data)");
491 va_status = vaEndPicture(va_dpy->va_dpy, resources.context);
492 CHECK_VASTATUS_RET(va_status, "vaEndPicture");
494 // vaDeriveImage() works, but the resulting image seems to live in
495 // uncached memory, which makes copying data out from it very, very slow.
496 // Thanks to FFmpeg for the observation that you can vaGetImage() the
497 // surface onto your own image (although then, it can't be planar, which
498 // is unfortunate for us).
501 va_status = vaDeriveImage(va_dpy->va_dpy, surf, &image);
502 CHECK_VASTATUS_RET(va_status, "vaDeriveImage");
504 va_status = vaSyncSurface(va_dpy->va_dpy, resources.surface);
505 CHECK_VASTATUS_RET(va_status, "vaSyncSurface");
507 va_status = vaGetImage(va_dpy->va_dpy, resources.surface, 0, 0, dinfo.image_width, dinfo.image_height, resources.image.image_id);
508 CHECK_VASTATUS_RET(va_status, "vaGetImage");
512 va_status = vaMapBuffer(va_dpy->va_dpy, resources.image.buf, &mapped);
513 CHECK_VASTATUS_RET(va_status, "vaMapBuffer");
515 shared_ptr<Frame> frame(new Frame);
517 // 4:2:2 planar (for vaDeriveImage).
518 frame->y.reset(new uint8_t[dinfo.image_width * dinfo.image_height]);
519 frame->cb.reset(new uint8_t[(dinfo.image_width / 2) * dinfo.image_height]);
520 frame->cr.reset(new uint8_t[(dinfo.image_width / 2) * dinfo.image_height]);
521 for (int component_idx = 0; component_idx < dinfo.num_components; ++component_idx) {
524 if (component_idx == 0) {
525 dptr = frame->y.get();
526 width = dinfo.image_width;
527 } else if (component_idx == 1) {
528 dptr = frame->cb.get();
529 width = dinfo.image_width / 2;
530 } else if (component_idx == 2) {
531 dptr = frame->cr.get();
532 width = dinfo.image_width / 2;
536 const uint8_t *sptr = (const uint8_t *)mapped + image.offsets[component_idx];
537 size_t spitch = image.pitches[component_idx];
538 for (size_t y = 0; y < dinfo.image_height; ++y) {
539 memcpy(dptr + y * width, sptr + y * spitch, width);
543 // Convert Y'CbCr to separate Y' and CbCr.
544 frame->is_semiplanar = true;
545 frame->y.reset(new uint8_t[dinfo.image_width * dinfo.image_height]);
546 frame->cbcr.reset(new uint8_t[dinfo.image_width * dinfo.image_height]);
547 const uint8_t *src = (const uint8_t *)mapped + resources.image.offsets[0];
548 if (resources.image.pitches[0] == dinfo.image_width * 2) {
549 memcpy_interleaved(frame->cbcr.get(), frame->y.get(), src, dinfo.image_width * dinfo.image_height * 2);
551 for (unsigned y = 0; y < dinfo.image_height; ++y) {
552 memcpy_interleaved(frame->cbcr.get() + y * dinfo.image_width, frame->y.get() + y * dinfo.image_width,
553 src + y * resources.image.pitches[0], dinfo.image_width * 2);
557 frame->width = dinfo.image_width;
558 frame->height = dinfo.image_height;
559 frame->chroma_subsampling_x = 2;
560 frame->chroma_subsampling_y = 1;
561 frame->pitch_y = dinfo.image_width;
562 frame->pitch_chroma = dinfo.image_width / 2;
564 va_status = vaUnmapBuffer(va_dpy->va_dpy, resources.image.buf);
565 CHECK_VASTATUS_RET(va_status, "vaUnmapBuffer");