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