1 #include "mjpeg_encoder.h"
11 #include <libavformat/avformat.h>
15 #include "shared/ffmpeg_raii.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"
25 #include <va/va_drm.h>
26 #include <va/va_x11.h>
28 using namespace bmusb;
31 static VAImageFormat uyvy_format;
33 extern void memcpy_with_pitch(uint8_t *dst, const uint8_t *src, size_t src_width, size_t dst_pitch, size_t height);
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,
47 struct VectorDestinationManager {
48 jpeg_destination_mgr pub;
49 std::vector<uint8_t> dest;
51 VectorDestinationManager()
53 pub.init_destination = init_destination_thunk;
54 pub.empty_output_buffer = empty_output_buffer_thunk;
55 pub.term_destination = term_destination_thunk;
58 static void init_destination_thunk(j_compress_ptr ptr)
60 ((VectorDestinationManager *)(ptr->dest))->init_destination();
63 inline void init_destination()
68 static boolean empty_output_buffer_thunk(j_compress_ptr ptr)
70 return ((VectorDestinationManager *)(ptr->dest))->empty_output_buffer();
73 inline bool empty_output_buffer()
75 make_room(dest.size()); // Should ignore pub.free_in_buffer!
79 inline void make_room(size_t bytes_used)
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;
87 static void term_destination_thunk(j_compress_ptr ptr)
89 ((VectorDestinationManager *)(ptr->dest))->term_destination();
92 inline void term_destination()
94 dest.resize(dest.size() - pub.free_in_buffer);
97 static_assert(std::is_standard_layout<VectorDestinationManager>::value, "");
99 int MJPEGEncoder::write_packet2_thunk(void *opaque, uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
101 MJPEGEncoder *engine = (MJPEGEncoder *)opaque;
102 return engine->write_packet2(buf, buf_size, type, time);
105 int MJPEGEncoder::write_packet2(uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
107 if (type == AVIO_DATA_MARKER_HEADER) {
108 mux_header.append((char *)buf, buf_size);
109 httpd->set_header(HTTPD::MULTICAM_STREAM, mux_header);
111 httpd->add_data(HTTPD::MULTICAM_STREAM, (char *)buf, buf_size, /*keyframe=*/true, AV_NOPTS_VALUE, AVRational{ AV_TIME_BASE, 1 });
116 MJPEGEncoder::MJPEGEncoder(HTTPD *httpd, const string &va_display)
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("nut", nullptr, nullptr);
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;
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");
137 // FFmpeg is very picky about having audio at 1/48000 timebase,
138 // no matter what we write. Even though we'd prefer our usual 1/120000,
139 // put the video on the same one, so that we can have locked audio.
140 stream->time_base = AVRational{ 1, OUTPUT_FREQUENCY };
141 stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
142 stream->codecpar->codec_id = AV_CODEC_ID_MJPEG;
144 // Used for aspect ratio only. Can change without notice (the mux won't care).
145 stream->codecpar->width = global_flags.width;
146 stream->codecpar->height = global_flags.height;
148 // TODO: We could perhaps use the interpretation for each card here
149 // (or at least the command-line flags) instead of the defaults,
150 // but what would we do when they change?
151 stream->codecpar->color_primaries = AVCOL_PRI_BT709;
152 stream->codecpar->color_trc = AVCOL_TRC_IEC61966_2_1;
153 stream->codecpar->color_space = AVCOL_SPC_BT709;
154 stream->codecpar->color_range = AVCOL_RANGE_MPEG;
155 stream->codecpar->chroma_location = AVCHROMA_LOC_LEFT;
156 stream->codecpar->field_order = AV_FIELD_PROGRESSIVE;
158 for (unsigned card_idx = 0; card_idx < global_flags.card_to_mjpeg_stream_export.size(); ++card_idx) {
159 AVStream *stream = avformat_new_stream(avctx.get(), nullptr);
160 if (stream == nullptr) {
161 fprintf(stderr, "avformat_new_stream() failed\n");
164 stream->time_base = AVRational{ 1, OUTPUT_FREQUENCY };
165 stream->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
166 stream->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
167 stream->codecpar->channel_layout = AV_CH_LAYOUT_STEREO;
168 stream->codecpar->channels = 2;
169 stream->codecpar->sample_rate = OUTPUT_FREQUENCY;
172 AVDictionary *options = NULL;
173 vector<pair<string, string>> opts = MUX_OPTS;
174 for (pair<string, string> opt : opts) {
175 av_dict_set(&options, opt.first.c_str(), opt.second.c_str(), 0);
177 if (avformat_write_header(avctx.get(), &options) < 0) {
178 fprintf(stderr, "avformat_write_header() failed\n");
182 // Initialize VA-API.
184 va_dpy = try_open_va(va_display, &error, &config_id);
185 if (va_dpy == nullptr) {
186 fprintf(stderr, "Could not initialize VA-API for MJPEG encoding: %s. JPEGs will be encoded in software if needed.\n", error.c_str());
189 encoder_thread = thread(&MJPEGEncoder::encoder_thread_func, this);
190 if (va_dpy != nullptr) {
191 va_receiver_thread = thread(&MJPEGEncoder::va_receiver_thread_func, this);
194 global_metrics.add("mjpeg_frames", {{ "status", "dropped" }, { "reason", "zero_size" }}, &metric_mjpeg_frames_zero_size_dropped);
195 global_metrics.add("mjpeg_frames", {{ "status", "dropped" }, { "reason", "interlaced" }}, &metric_mjpeg_frames_interlaced_dropped);
196 global_metrics.add("mjpeg_frames", {{ "status", "dropped" }, { "reason", "unsupported_pixel_format" }}, &metric_mjpeg_frames_unsupported_pixel_format_dropped);
197 global_metrics.add("mjpeg_frames", {{ "status", "dropped" }, { "reason", "oversized" }}, &metric_mjpeg_frames_oversized_dropped);
198 global_metrics.add("mjpeg_frames", {{ "status", "dropped" }, { "reason", "overrun" }}, &metric_mjpeg_overrun_dropped);
199 global_metrics.add("mjpeg_frames", {{ "status", "submitted" }}, &metric_mjpeg_overrun_submitted);
204 MJPEGEncoder::~MJPEGEncoder()
206 av_free(avctx->pb->buffer);
208 global_metrics.remove("mjpeg_frames", {{ "status", "dropped" }, { "reason", "zero_size" }});
209 global_metrics.remove("mjpeg_frames", {{ "status", "dropped" }, { "reason", "interlaced" }});
210 global_metrics.remove("mjpeg_frames", {{ "status", "dropped" }, { "reason", "unsupported_pixel_format" }});
211 global_metrics.remove("mjpeg_frames", {{ "status", "dropped" }, { "reason", "oversized" }});
212 global_metrics.remove("mjpeg_frames", {{ "status", "dropped" }, { "reason", "overrun" }});
213 global_metrics.remove("mjpeg_frames", {{ "status", "submitted" }});
216 void MJPEGEncoder::stop()
223 any_frames_to_be_encoded.notify_all();
224 any_frames_encoding.notify_all();
225 encoder_thread.join();
226 if (va_dpy != nullptr) {
227 va_receiver_thread.join();
231 unique_ptr<VADisplayWithCleanup> MJPEGEncoder::try_open_va(const string &va_display, string *error, VAConfigID *config_id)
233 unique_ptr<VADisplayWithCleanup> va_dpy = va_open_display(va_display);
234 if (va_dpy == nullptr) {
235 if (error) *error = "Opening VA display failed";
238 int major_ver, minor_ver;
239 VAStatus va_status = vaInitialize(va_dpy->va_dpy, &major_ver, &minor_ver);
240 if (va_status != VA_STATUS_SUCCESS) {
242 snprintf(buf, sizeof(buf), "vaInitialize() failed with status %d\n", va_status);
243 if (error != nullptr) *error = buf;
247 VAConfigAttrib attr = { VAConfigAttribRTFormat, VA_RT_FORMAT_YUV422 };
248 va_status = vaCreateConfig(va_dpy->va_dpy, VAProfileJPEGBaseline, VAEntrypointEncPicture,
249 &attr, 1, config_id);
250 if (va_status == VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT) {
251 if (error != nullptr) *error = "No hardware support";
253 } else if (va_status != VA_STATUS_SUCCESS) {
255 snprintf(buf, sizeof(buf), "vaCreateConfig() failed with status %d\n", va_status);
256 if (error != nullptr) *error = buf;
260 // TODO: Unify with the code in Futatabi.
261 int num_formats = vaMaxNumImageFormats(va_dpy->va_dpy);
262 assert(num_formats > 0);
264 unique_ptr<VAImageFormat[]> formats(new VAImageFormat[num_formats]);
265 va_status = vaQueryImageFormats(va_dpy->va_dpy, formats.get(), &num_formats);
266 if (va_status != VA_STATUS_SUCCESS) {
268 snprintf(buf, sizeof(buf), "vaQueryImageFormats() failed with status %d\n", va_status);
269 if (error != nullptr) *error = buf;
274 for (int i = 0; i < num_formats; ++i) {
275 if (formats[i].fourcc == VA_FOURCC_UYVY) {
276 memcpy(&uyvy_format, &formats[i], sizeof(VAImageFormat));
282 if (error != nullptr) *error = "UYVY format not found";
289 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, vector<int32_t> audio)
291 PBOFrameAllocator::Userdata *userdata = (PBOFrameAllocator::Userdata *)frame->userdata;
292 if (video_format.width == 0 || video_format.height == 0) {
293 ++metric_mjpeg_frames_zero_size_dropped;
296 if (video_format.interlaced) {
297 fprintf(stderr, "Card %u: Ignoring JPEG encoding for interlaced frame\n", card_index);
298 ++metric_mjpeg_frames_interlaced_dropped;
301 if (userdata->pixel_format != PixelFormat_8BitYCbCr ||
302 !frame->interleaved) {
303 fprintf(stderr, "Card %u: Ignoring JPEG encoding for unsupported pixel format\n", card_index);
304 ++metric_mjpeg_frames_unsupported_pixel_format_dropped;
307 if (video_format.width > 4096 || video_format.height > 4096) {
308 fprintf(stderr, "Card %u: Ignoring JPEG encoding for oversized frame\n", card_index);
309 ++metric_mjpeg_frames_oversized_dropped;
313 lock_guard<mutex> lock(mu);
314 if (frames_to_be_encoded.size() + frames_encoding.size() > 50) {
315 fprintf(stderr, "WARNING: MJPEG encoding doesn't keep up, discarding frame.\n");
316 ++metric_mjpeg_overrun_dropped;
319 ++metric_mjpeg_overrun_submitted;
320 frames_to_be_encoded.push(QueuedFrame{ pts, card_index, frame, video_format, y_offset, cbcr_offset, move(audio) });
321 any_frames_to_be_encoded.notify_all();
324 int MJPEGEncoder::get_mjpeg_stream_for_card(unsigned card_index)
326 // Only bother doing MJPEG encoding if there are any connected clients
327 // that want the stream.
328 if (httpd->get_num_connected_multicam_clients() == 0) {
332 auto it = global_flags.card_to_mjpeg_stream_export.find(card_index);
333 if (it == global_flags.card_to_mjpeg_stream_export.end()) {
339 void MJPEGEncoder::encoder_thread_func()
341 pthread_setname_np(pthread_self(), "MJPEG_Encode");
342 posix_memalign((void **)&tmp_y, 4096, 4096 * 8);
343 posix_memalign((void **)&tmp_cbcr, 4096, 4096 * 8);
344 posix_memalign((void **)&tmp_cb, 4096, 4096 * 8);
345 posix_memalign((void **)&tmp_cr, 4096, 4096 * 8);
350 unique_lock<mutex> lock(mu);
351 any_frames_to_be_encoded.wait(lock, [this] { return !frames_to_be_encoded.empty() || should_quit; });
352 if (should_quit) break;
353 qf = move(frames_to_be_encoded.front());
354 frames_to_be_encoded.pop();
357 if (va_dpy != nullptr) {
358 // Will call back in the receiver thread.
359 encode_jpeg_va(move(qf));
361 // Write audio before video, since Futatabi expects it.
362 if (qf.audio.size() > 0) {
363 write_audio_packet(qf.pts, qf.card_index, qf.audio);
366 // Encode synchronously, in the same thread.
367 vector<uint8_t> jpeg = encode_jpeg_libjpeg(qf);
368 write_mjpeg_packet(qf.pts, qf.card_index, jpeg.data(), jpeg.size());
378 void MJPEGEncoder::write_mjpeg_packet(int64_t pts, unsigned card_index, const uint8_t *jpeg, size_t jpeg_size)
381 memset(&pkt, 0, sizeof(pkt));
383 pkt.data = const_cast<uint8_t *>(jpeg);
384 pkt.size = jpeg_size;
385 pkt.stream_index = card_index;
386 pkt.flags = AV_PKT_FLAG_KEY;
387 AVRational time_base = avctx->streams[pkt.stream_index]->time_base;
388 pkt.pts = pkt.dts = av_rescale_q(pts, AVRational{ 1, TIMEBASE }, time_base);
391 if (av_write_frame(avctx.get(), &pkt) < 0) {
392 fprintf(stderr, "av_write_frame() failed\n");
397 void MJPEGEncoder::write_audio_packet(int64_t pts, unsigned card_index, const vector<int32_t> &audio)
400 memset(&pkt, 0, sizeof(pkt));
402 pkt.data = reinterpret_cast<uint8_t *>(const_cast<int32_t *>(&audio[0]));
403 pkt.size = audio.size() * sizeof(audio[0]);
404 pkt.stream_index = card_index + global_flags.card_to_mjpeg_stream_export.size();
405 pkt.flags = AV_PKT_FLAG_KEY;
406 AVRational time_base = avctx->streams[pkt.stream_index]->time_base;
407 pkt.pts = pkt.dts = av_rescale_q(pts, AVRational{ 1, TIMEBASE }, time_base);
408 size_t num_stereo_samples = audio.size() / 2;
409 pkt.duration = av_rescale_q(num_stereo_samples, AVRational{ 1, OUTPUT_FREQUENCY }, time_base);
411 if (av_write_frame(avctx.get(), &pkt) < 0) {
412 fprintf(stderr, "av_write_frame() failed\n");
417 class VABufferDestroyer {
419 VABufferDestroyer(VADisplay dpy, VABufferID buf)
420 : dpy(dpy), buf(buf) {}
422 ~VABufferDestroyer() {
423 VAStatus va_status = vaDestroyBuffer(dpy, buf);
424 CHECK_VASTATUS(va_status, "vaDestroyBuffer");
432 MJPEGEncoder::VAResources MJPEGEncoder::get_va_resources(unsigned width, unsigned height)
435 lock_guard<mutex> lock(va_resources_mutex);
436 for (auto it = va_resources_freelist.begin(); it != va_resources_freelist.end(); ++it) {
437 if (it->width == width && it->height == height) {
438 VAResources ret = *it;
439 va_resources_freelist.erase(it);
450 VASurfaceAttrib attrib;
451 attrib.flags = VA_SURFACE_ATTRIB_SETTABLE;
452 attrib.type = VASurfaceAttribPixelFormat;
453 attrib.value.type = VAGenericValueTypeInteger;
454 attrib.value.value.i = VA_FOURCC_UYVY;
456 VAStatus va_status = vaCreateSurfaces(va_dpy->va_dpy, VA_RT_FORMAT_YUV422,
458 &ret.surface, 1, &attrib, 1);
459 CHECK_VASTATUS(va_status, "vaCreateSurfaces");
461 va_status = vaCreateContext(va_dpy->va_dpy, config_id, width, height, 0, &ret.surface, 1, &ret.context);
462 CHECK_VASTATUS(va_status, "vaCreateContext");
464 va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAEncCodedBufferType, width * height * 3 + 8192, 1, nullptr, &ret.data_buffer);
465 CHECK_VASTATUS(va_status, "vaCreateBuffer");
467 va_status = vaCreateImage(va_dpy->va_dpy, &uyvy_format, width, height, &ret.image);
468 CHECK_VASTATUS(va_status, "vaCreateImage");
473 void MJPEGEncoder::release_va_resources(MJPEGEncoder::VAResources resources)
475 lock_guard<mutex> lock(va_resources_mutex);
476 if (va_resources_freelist.size() > 50) {
477 auto it = va_resources_freelist.end();
480 VAStatus va_status = vaDestroyBuffer(va_dpy->va_dpy, it->data_buffer);
481 CHECK_VASTATUS(va_status, "vaDestroyBuffer");
483 va_status = vaDestroyContext(va_dpy->va_dpy, it->context);
484 CHECK_VASTATUS(va_status, "vaDestroyContext");
486 va_status = vaDestroySurfaces(va_dpy->va_dpy, &it->surface, 1);
487 CHECK_VASTATUS(va_status, "vaDestroySurfaces");
489 va_status = vaDestroyImage(va_dpy->va_dpy, it->image.image_id);
490 CHECK_VASTATUS(va_status, "vaDestroyImage");
492 va_resources_freelist.erase(it);
495 va_resources_freelist.push_front(resources);
498 void MJPEGEncoder::init_jpeg_422(unsigned width, unsigned height, VectorDestinationManager *dest, jpeg_compress_struct *cinfo)
501 cinfo->err = jpeg_std_error(&jerr);
502 jpeg_create_compress(cinfo);
504 cinfo->dest = (jpeg_destination_mgr *)dest;
506 cinfo->input_components = 3;
507 jpeg_set_defaults(cinfo);
508 jpeg_set_quality(cinfo, quality, /*force_baseline=*/false);
510 cinfo->image_width = width;
511 cinfo->image_height = height;
512 cinfo->raw_data_in = true;
513 jpeg_set_colorspace(cinfo, JCS_YCbCr);
514 cinfo->comp_info[0].h_samp_factor = 2;
515 cinfo->comp_info[0].v_samp_factor = 1;
516 cinfo->comp_info[1].h_samp_factor = 1;
517 cinfo->comp_info[1].v_samp_factor = 1;
518 cinfo->comp_info[2].h_samp_factor = 1;
519 cinfo->comp_info[2].v_samp_factor = 1;
520 cinfo->CCIR601_sampling = true; // Seems to be mostly ignored by libjpeg, though.
521 jpeg_start_compress(cinfo, true);
523 // This comment marker is private to FFmpeg. It signals limited Y'CbCr range
524 // (and nothing else).
525 jpeg_write_marker(cinfo, JPEG_COM, (const JOCTET *)"CS=ITU601", strlen("CS=ITU601"));
528 vector<uint8_t> MJPEGEncoder::get_jpeg_header(unsigned width, unsigned height, jpeg_compress_struct *cinfo)
530 VectorDestinationManager dest;
531 init_jpeg_422(width, height, &dest, cinfo);
533 // Make a dummy black image; there's seemingly no other easy way of
534 // making libjpeg outputting all of its headers.
535 JSAMPROW yptr[8], cbptr[8], crptr[8];
536 JSAMPARRAY data[3] = { yptr, cbptr, crptr };
537 memset(tmp_y, 0, 4096);
538 memset(tmp_cb, 0, 4096);
539 memset(tmp_cr, 0, 4096);
540 for (unsigned yy = 0; yy < 8; ++yy) {
545 for (unsigned y = 0; y < height; y += 8) {
546 jpeg_write_raw_data(cinfo, data, /*num_lines=*/8);
548 jpeg_finish_compress(cinfo);
550 // We're only interested in the header, not the data after it.
551 dest.term_destination();
552 for (size_t i = 0; i < dest.dest.size() - 1; ++i) {
553 if (dest.dest[i] == 0xff && dest.dest[i + 1] == 0xda) { // Start of scan (SOS).
554 unsigned len = dest.dest[i + 2] * 256 + dest.dest[i + 3];
555 dest.dest.resize(i + len + 2);
563 MJPEGEncoder::VAData MJPEGEncoder::get_va_data_for_resolution(unsigned width, unsigned height)
565 pair<unsigned, unsigned> key(width, height);
566 if (va_data_for_resolution.count(key)) {
567 return va_data_for_resolution[key];
570 // Use libjpeg to generate a header and set sane defaults for e.g.
571 // quantization tables. Then do the actual encode with VA-API.
572 jpeg_compress_struct cinfo;
573 vector<uint8_t> jpeg_header = get_jpeg_header(width, height, &cinfo);
575 // Picture parameters.
576 VAEncPictureParameterBufferJPEG pic_param;
577 memset(&pic_param, 0, sizeof(pic_param));
578 pic_param.reconstructed_picture = VA_INVALID_ID;
579 pic_param.picture_width = cinfo.image_width;
580 pic_param.picture_height = cinfo.image_height;
581 for (int component_idx = 0; component_idx < cinfo.num_components; ++component_idx) {
582 const jpeg_component_info *comp = &cinfo.comp_info[component_idx];
583 pic_param.component_id[component_idx] = comp->component_id;
584 pic_param.quantiser_table_selector[component_idx] = comp->quant_tbl_no;
586 pic_param.num_components = cinfo.num_components;
587 pic_param.num_scan = 1;
588 pic_param.sample_bit_depth = 8;
589 pic_param.coded_buf = VA_INVALID_ID; // To be filled out by caller.
590 pic_param.pic_flags.bits.huffman = 1;
591 pic_param.quality = 50; // Don't scale the given quantization matrices. (See gen8_mfc_jpeg_fqm_state)
593 // Quantization matrices.
594 VAQMatrixBufferJPEG q;
595 memset(&q, 0, sizeof(q));
597 q.load_lum_quantiser_matrix = true;
598 q.load_chroma_quantiser_matrix = true;
599 for (int quant_tbl_idx = 0; quant_tbl_idx < min(4, NUM_QUANT_TBLS); ++quant_tbl_idx) {
600 const JQUANT_TBL *qtbl = cinfo.quant_tbl_ptrs[quant_tbl_idx];
601 assert((qtbl == nullptr) == (quant_tbl_idx >= 2));
602 if (qtbl == nullptr) continue;
604 uint8_t *qmatrix = (quant_tbl_idx == 0) ? q.lum_quantiser_matrix : q.chroma_quantiser_matrix;
605 for (int i = 0; i < 64; ++i) {
606 if (qtbl->quantval[i] > 255) {
607 fprintf(stderr, "Baseline JPEG only!\n");
610 qmatrix[i] = qtbl->quantval[jpeg_natural_order[i]];
614 // Huffman tables (arithmetic is not supported).
615 VAHuffmanTableBufferJPEGBaseline huff;
616 memset(&huff, 0, sizeof(huff));
618 for (int huff_tbl_idx = 0; huff_tbl_idx < min(2, NUM_HUFF_TBLS); ++huff_tbl_idx) {
619 const JHUFF_TBL *ac_hufftbl = cinfo.ac_huff_tbl_ptrs[huff_tbl_idx];
620 const JHUFF_TBL *dc_hufftbl = cinfo.dc_huff_tbl_ptrs[huff_tbl_idx];
621 if (ac_hufftbl == nullptr) {
622 assert(dc_hufftbl == nullptr);
623 huff.load_huffman_table[huff_tbl_idx] = 0;
625 assert(dc_hufftbl != nullptr);
626 huff.load_huffman_table[huff_tbl_idx] = 1;
628 for (int i = 0; i < 16; ++i) {
629 huff.huffman_table[huff_tbl_idx].num_dc_codes[i] = dc_hufftbl->bits[i + 1];
631 for (int i = 0; i < 12; ++i) {
632 huff.huffman_table[huff_tbl_idx].dc_values[i] = dc_hufftbl->huffval[i];
634 for (int i = 0; i < 16; ++i) {
635 huff.huffman_table[huff_tbl_idx].num_ac_codes[i] = ac_hufftbl->bits[i + 1];
637 for (int i = 0; i < 162; ++i) {
638 huff.huffman_table[huff_tbl_idx].ac_values[i] = ac_hufftbl->huffval[i];
643 // Slice parameters (metadata about the slice).
644 VAEncSliceParameterBufferJPEG parms;
645 memset(&parms, 0, sizeof(parms));
646 for (int component_idx = 0; component_idx < cinfo.num_components; ++component_idx) {
647 const jpeg_component_info *comp = &cinfo.comp_info[component_idx];
648 parms.components[component_idx].component_selector = comp->component_id;
649 parms.components[component_idx].dc_table_selector = comp->dc_tbl_no;
650 parms.components[component_idx].ac_table_selector = comp->ac_tbl_no;
651 if (parms.components[component_idx].dc_table_selector > 1 ||
652 parms.components[component_idx].ac_table_selector > 1) {
653 fprintf(stderr, "Uses too many Huffman tables\n");
657 parms.num_components = cinfo.num_components;
658 parms.restart_interval = cinfo.restart_interval;
660 jpeg_destroy_compress(&cinfo);
663 ret.jpeg_header = move(jpeg_header);
664 ret.pic_param = pic_param;
668 va_data_for_resolution[key] = ret;
672 void MJPEGEncoder::encode_jpeg_va(QueuedFrame &&qf)
674 PBOFrameAllocator::Userdata *userdata = (PBOFrameAllocator::Userdata *)qf.frame->userdata;
675 unsigned width = qf.video_format.width;
676 unsigned height = qf.video_format.height;
678 VAResources resources;
679 ReleaseVAResources release;
680 if (userdata->data_copy_current_src == PBOFrameAllocator::Userdata::FROM_VA_API) {
681 resources = move(userdata->va_resources);
682 release = move(userdata->va_resources_release);
684 assert(userdata->data_copy_current_src == PBOFrameAllocator::Userdata::FROM_MALLOC);
685 resources = get_va_resources(width, height);
686 release = ReleaseVAResources(this, resources);
689 VAData va_data = get_va_data_for_resolution(width, height);
690 va_data.pic_param.coded_buf = resources.data_buffer;
692 VABufferID pic_param_buffer;
693 VAStatus va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAEncPictureParameterBufferType, sizeof(va_data.pic_param), 1, &va_data.pic_param, &pic_param_buffer);
694 CHECK_VASTATUS(va_status, "vaCreateBuffer");
695 VABufferDestroyer destroy_pic_param(va_dpy->va_dpy, pic_param_buffer);
698 va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAQMatrixBufferType, sizeof(va_data.q), 1, &va_data.q, &q_buffer);
699 CHECK_VASTATUS(va_status, "vaCreateBuffer");
700 VABufferDestroyer destroy_iq(va_dpy->va_dpy, q_buffer);
702 VABufferID huff_buffer;
703 va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAHuffmanTableBufferType, sizeof(va_data.huff), 1, &va_data.huff, &huff_buffer);
704 CHECK_VASTATUS(va_status, "vaCreateBuffer");
705 VABufferDestroyer destroy_huff(va_dpy->va_dpy, huff_buffer);
707 VABufferID slice_param_buffer;
708 va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAEncSliceParameterBufferType, sizeof(va_data.parms), 1, &va_data.parms, &slice_param_buffer);
709 CHECK_VASTATUS(va_status, "vaCreateBuffer");
710 VABufferDestroyer destroy_slice_param(va_dpy->va_dpy, slice_param_buffer);
712 if (userdata->data_copy_current_src == PBOFrameAllocator::Userdata::FROM_VA_API) {
713 // The pixel data is already put into the image by the caller.
714 va_status = vaUnmapBuffer(va_dpy->va_dpy, resources.image.buf);
715 CHECK_VASTATUS(va_status, "vaUnmapBuffer");
717 assert(userdata->data_copy_current_src == PBOFrameAllocator::Userdata::FROM_MALLOC);
719 // Upload the pixel data.
720 uint8_t *surface_p = nullptr;
721 vaMapBuffer(va_dpy->va_dpy, resources.image.buf, (void **)&surface_p);
723 size_t field_start_line = qf.video_format.extra_lines_top; // No interlacing support.
724 size_t field_start = qf.cbcr_offset * 2 + qf.video_format.width * field_start_line * 2;
727 const uint8_t *src = qf.frame->data_copy + field_start;
728 uint8_t *dst = (unsigned char *)surface_p + resources.image.offsets[0];
729 memcpy_with_pitch(dst, src, qf.video_format.width * 2, resources.image.pitches[0], qf.video_format.height);
732 va_status = vaUnmapBuffer(va_dpy->va_dpy, resources.image.buf);
733 CHECK_VASTATUS(va_status, "vaUnmapBuffer");
736 qf.frame->data_copy = nullptr;
738 // Seemingly vaPutImage() (which triggers a GPU copy) is much nicer to the
739 // CPU than vaDeriveImage() and copying directly into the GPU's buffers.
740 // Exactly why is unclear, but it seems to involve L3 cache usage when there
741 // are many high-res (1080p+) images in play.
742 va_status = vaPutImage(va_dpy->va_dpy, resources.surface, resources.image.image_id, 0, 0, width, height, 0, 0, width, height);
743 CHECK_VASTATUS(va_status, "vaPutImage");
745 // Finally, stick in the JPEG header.
746 VAEncPackedHeaderParameterBuffer header_parm;
747 header_parm.type = VAEncPackedHeaderRawData;
748 header_parm.bit_length = 8 * va_data.jpeg_header.size();
750 VABufferID header_parm_buffer;
751 va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAEncPackedHeaderParameterBufferType, sizeof(header_parm), 1, &header_parm, &header_parm_buffer);
752 CHECK_VASTATUS(va_status, "vaCreateBuffer");
753 VABufferDestroyer destroy_header(va_dpy->va_dpy, header_parm_buffer);
755 VABufferID header_data_buffer;
756 va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAEncPackedHeaderDataBufferType, va_data.jpeg_header.size(), 1, va_data.jpeg_header.data(), &header_data_buffer);
757 CHECK_VASTATUS(va_status, "vaCreateBuffer");
758 VABufferDestroyer destroy_header_data(va_dpy->va_dpy, header_data_buffer);
760 va_status = vaBeginPicture(va_dpy->va_dpy, resources.context, resources.surface);
761 CHECK_VASTATUS(va_status, "vaBeginPicture");
762 va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &pic_param_buffer, 1);
763 CHECK_VASTATUS(va_status, "vaRenderPicture(pic_param)");
764 va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &q_buffer, 1);
765 CHECK_VASTATUS(va_status, "vaRenderPicture(q)");
766 va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &huff_buffer, 1);
767 CHECK_VASTATUS(va_status, "vaRenderPicture(huff)");
768 va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &slice_param_buffer, 1);
769 CHECK_VASTATUS(va_status, "vaRenderPicture(slice_param)");
770 va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &header_parm_buffer, 1);
771 CHECK_VASTATUS(va_status, "vaRenderPicture(header_parm)");
772 va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &header_data_buffer, 1);
773 CHECK_VASTATUS(va_status, "vaRenderPicture(header_data)");
774 va_status = vaEndPicture(va_dpy->va_dpy, resources.context);
775 CHECK_VASTATUS(va_status, "vaEndPicture");
777 qf.resources = move(resources);
778 qf.resource_releaser = move(release);
780 lock_guard<mutex> lock(mu);
781 frames_encoding.push(move(qf));
782 any_frames_encoding.notify_all();
785 void MJPEGEncoder::va_receiver_thread_func()
787 pthread_setname_np(pthread_self(), "MJPEG_Receive");
791 unique_lock<mutex> lock(mu);
792 any_frames_encoding.wait(lock, [this] { return !frames_encoding.empty() || should_quit; });
793 if (should_quit) return;
794 qf = move(frames_encoding.front());
795 frames_encoding.pop();
798 // Write audio before video, since Futatabi expects it.
799 if (qf.audio.size() > 0) {
800 write_audio_packet(qf.pts, qf.card_index, qf.audio);
803 VAStatus va_status = vaSyncSurface(va_dpy->va_dpy, qf.resources.surface);
804 CHECK_VASTATUS(va_status, "vaSyncSurface");
806 VACodedBufferSegment *segment;
807 va_status = vaMapBuffer(va_dpy->va_dpy, qf.resources.data_buffer, (void **)&segment);
808 CHECK_VASTATUS(va_status, "vaMapBuffer");
810 const uint8_t *coded_buf = reinterpret_cast<uint8_t *>(segment->buf);
811 write_mjpeg_packet(qf.pts, qf.card_index, coded_buf, segment->size);
813 va_status = vaUnmapBuffer(va_dpy->va_dpy, qf.resources.data_buffer);
814 CHECK_VASTATUS(va_status, "vaUnmapBuffer");
818 vector<uint8_t> MJPEGEncoder::encode_jpeg_libjpeg(const QueuedFrame &qf)
820 unsigned width = qf.video_format.width;
821 unsigned height = qf.video_format.height;
823 VectorDestinationManager dest;
824 jpeg_compress_struct cinfo;
825 init_jpeg_422(width, height, &dest, &cinfo);
827 size_t field_start_line = qf.video_format.extra_lines_top; // No interlacing support.
828 size_t field_start = qf.cbcr_offset * 2 + qf.video_format.width * field_start_line * 2;
830 JSAMPROW yptr[8], cbptr[8], crptr[8];
831 JSAMPARRAY data[3] = { yptr, cbptr, crptr };
832 for (unsigned y = 0; y < qf.video_format.height; y += 8) {
833 const uint8_t *src = qf.frame->data_copy + field_start + y * qf.video_format.width * 2;
835 memcpy_interleaved(tmp_y, tmp_cbcr, src, qf.video_format.width * 8 * 2);
836 memcpy_interleaved(tmp_cb, tmp_cr, tmp_cbcr, qf.video_format.width * 8);
837 for (unsigned yy = 0; yy < 8; ++yy) {
838 yptr[yy] = tmp_y + yy * width;
839 cbptr[yy] = tmp_cb + yy * width / 2;
840 crptr[yy] = tmp_cr + yy * width / 2;
842 jpeg_write_raw_data(&cinfo, data, /*num_lines=*/8);
844 jpeg_finish_compress(&cinfo);