1 #include "mjpeg_encoder.h"
11 #include <libavformat/avformat.h>
15 #include "ffmpeg_raii.h"
18 #include "memcpy_interleaved.h"
19 #include "pbo_frame_allocator.h"
21 #include "va_display_with_cleanup.h"
24 #include <va/va_drm.h>
25 #include <va/va_x11.h>
27 using namespace bmusb;
30 extern void memcpy_with_pitch(uint8_t *dst, const uint8_t *src, size_t src_width, size_t dst_pitch, size_t height);
32 #define CHECK_VASTATUS(va_status, func) \
33 if (va_status != VA_STATUS_SUCCESS) { \
34 fprintf(stderr, "%s:%d (%s) failed with %d\n", __func__, __LINE__, func, va_status); \
38 // From libjpeg (although it's of course identical between implementations).
39 static const int jpeg_natural_order[DCTSIZE2] = {
40 0, 1, 8, 16, 9, 2, 3, 10,
41 17, 24, 32, 25, 18, 11, 4, 5,
42 12, 19, 26, 33, 40, 48, 41, 34,
43 27, 20, 13, 6, 7, 14, 21, 28,
44 35, 42, 49, 56, 57, 50, 43, 36,
45 29, 22, 15, 23, 30, 37, 44, 51,
46 58, 59, 52, 45, 38, 31, 39, 46,
47 53, 60, 61, 54, 47, 55, 62, 63,
50 struct VectorDestinationManager {
51 jpeg_destination_mgr pub;
52 std::vector<uint8_t> dest;
54 VectorDestinationManager()
56 pub.init_destination = init_destination_thunk;
57 pub.empty_output_buffer = empty_output_buffer_thunk;
58 pub.term_destination = term_destination_thunk;
61 static void init_destination_thunk(j_compress_ptr ptr)
63 ((VectorDestinationManager *)(ptr->dest))->init_destination();
66 inline void init_destination()
71 static boolean empty_output_buffer_thunk(j_compress_ptr ptr)
73 return ((VectorDestinationManager *)(ptr->dest))->empty_output_buffer();
76 inline bool empty_output_buffer()
78 make_room(dest.size()); // Should ignore pub.free_in_buffer!
82 inline void make_room(size_t bytes_used)
84 dest.resize(bytes_used + 4096);
85 dest.resize(dest.capacity());
86 pub.next_output_byte = dest.data() + bytes_used;
87 pub.free_in_buffer = dest.size() - bytes_used;
90 static void term_destination_thunk(j_compress_ptr ptr)
92 ((VectorDestinationManager *)(ptr->dest))->term_destination();
95 inline void term_destination()
97 dest.resize(dest.size() - pub.free_in_buffer);
100 static_assert(std::is_standard_layout<VectorDestinationManager>::value, "");
102 int MJPEGEncoder::write_packet2_thunk(void *opaque, uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
104 MJPEGEncoder *engine = (MJPEGEncoder *)opaque;
105 return engine->write_packet2(buf, buf_size, type, time);
108 int MJPEGEncoder::write_packet2(uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
110 if (type == AVIO_DATA_MARKER_HEADER) {
111 mux_header.append((char *)buf, buf_size);
112 httpd->set_header(HTTPD::MULTICAM_STREAM, mux_header);
114 httpd->add_data(HTTPD::MULTICAM_STREAM, (char *)buf, buf_size, /*keyframe=*/true, AV_NOPTS_VALUE, AVRational{ AV_TIME_BASE, 1 });
119 MJPEGEncoder::MJPEGEncoder(HTTPD *httpd, const string &va_display)
122 // Set up the mux. We don't use the Mux wrapper, because it's geared towards
123 // a situation with only one video stream (and possibly one audio stream)
124 // with known width/height, and we don't need the extra functionality it provides.
125 avctx.reset(avformat_alloc_context());
126 avctx->oformat = av_guess_format("mp4", nullptr, nullptr);
128 uint8_t *buf = (uint8_t *)av_malloc(MUX_BUFFER_SIZE);
129 avctx->pb = avio_alloc_context(buf, MUX_BUFFER_SIZE, 1, this, nullptr, nullptr, nullptr);
130 avctx->pb->write_data_type = &MJPEGEncoder::write_packet2_thunk;
131 avctx->flags = AVFMT_FLAG_CUSTOM_IO;
133 for (int card_idx = 0; card_idx < global_flags.num_cards; ++card_idx) {
134 AVStream *stream = avformat_new_stream(avctx.get(), nullptr);
135 if (stream == nullptr) {
136 fprintf(stderr, "avformat_new_stream() failed\n");
139 stream->time_base = AVRational{ 1, TIMEBASE };
140 stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
141 stream->codecpar->codec_id = AV_CODEC_ID_MJPEG;
143 // Used for aspect ratio only. Can change without notice (the mux won't care).
144 stream->codecpar->width = global_flags.width;
145 stream->codecpar->height = global_flags.height;
147 // TODO: We could perhaps use the interpretation for each card here
148 // (or at least the command-line flags) instead of the defaults,
149 // but what would we do when they change?
150 stream->codecpar->color_primaries = AVCOL_PRI_BT709;
151 stream->codecpar->color_trc = AVCOL_TRC_IEC61966_2_1;
152 stream->codecpar->color_space = AVCOL_SPC_BT709;
153 stream->codecpar->color_range = AVCOL_RANGE_MPEG;
154 stream->codecpar->chroma_location = AVCHROMA_LOC_LEFT;
155 stream->codecpar->field_order = AV_FIELD_PROGRESSIVE;
158 AVDictionary *options = NULL;
159 vector<pair<string, string>> opts = MUX_OPTS;
160 for (pair<string, string> opt : opts) {
161 av_dict_set(&options, opt.first.c_str(), opt.second.c_str(), 0);
163 if (avformat_write_header(avctx.get(), &options) < 0) {
164 fprintf(stderr, "avformat_write_header() failed\n");
168 // Initialize VA-API.
170 va_dpy = try_open_va(va_display, &error, &config_id);
171 if (va_dpy == nullptr) {
172 fprintf(stderr, "Could not initialize VA-API for MJPEG encoding: %s. JPEGs will be encoded in software if needed.\n", error.c_str());
175 encoder_thread = thread(&MJPEGEncoder::encoder_thread_func, this);
176 if (va_dpy != nullptr) {
177 va_receiver_thread = thread(&MJPEGEncoder::va_receiver_thread_func, this);
183 void MJPEGEncoder::stop()
190 any_frames_to_be_encoded.notify_all();
191 encoder_thread.join();
192 if (va_dpy != nullptr) {
193 va_receiver_thread.join();
197 unique_ptr<VADisplayWithCleanup> MJPEGEncoder::try_open_va(const string &va_display, string *error, VAConfigID *config_id)
199 unique_ptr<VADisplayWithCleanup> va_dpy = va_open_display(va_display);
200 if (va_dpy == nullptr) {
201 if (error) *error = "Opening VA display failed";
204 int major_ver, minor_ver;
205 VAStatus va_status = vaInitialize(va_dpy->va_dpy, &major_ver, &minor_ver);
206 if (va_status != VA_STATUS_SUCCESS) {
208 snprintf(buf, sizeof(buf), "vaInitialize() failed with status %d\n", va_status);
209 if (error != nullptr) *error = buf;
213 VAConfigAttrib attr = { VAConfigAttribRTFormat, VA_RT_FORMAT_YUV422 };
214 va_status = vaCreateConfig(va_dpy->va_dpy, VAProfileJPEGBaseline, VAEntrypointEncPicture,
215 &attr, 1, config_id);
216 if (va_status == VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT) {
217 if (error != nullptr) *error = "No hardware support";
219 } else if (va_status != VA_STATUS_SUCCESS) {
221 snprintf(buf, sizeof(buf), "vaCreateConfig() failed with status %d\n", va_status);
222 if (error != nullptr) *error = buf;
226 int num_formats = vaMaxNumImageFormats(va_dpy->va_dpy);
227 assert(num_formats > 0);
229 unique_ptr<VAImageFormat[]> formats(new VAImageFormat[num_formats]);
230 va_status = vaQueryImageFormats(va_dpy->va_dpy, formats.get(), &num_formats);
231 if (va_status != VA_STATUS_SUCCESS) {
233 snprintf(buf, sizeof(buf), "vaQueryImageFormats() failed with status %d\n", va_status);
234 if (error != nullptr) *error = buf;
241 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)
243 PBOFrameAllocator::Userdata *userdata = (PBOFrameAllocator::Userdata *)frame->userdata;
244 if (video_format.width == 0 || video_format.height == 0) {
247 if (video_format.interlaced) {
248 fprintf(stderr, "Card %u: Ignoring JPEG encoding for interlaced frame\n", card_index);
251 if (userdata->pixel_format != PixelFormat_8BitYCbCr ||
252 !frame->interleaved) {
253 fprintf(stderr, "Card %u: Ignoring JPEG encoding for unsupported pixel format\n", card_index);
256 if (video_format.width > 4096 || video_format.height > 4096) {
257 fprintf(stderr, "Card %u: Ignoring JPEG encoding for oversized frame\n", card_index);
261 lock_guard<mutex> lock(mu);
262 if (frames_to_be_encoded.size() + frames_encoding.size() > 10) {
263 fprintf(stderr, "WARNING: MJPEG encoding doesn't keep up, discarding frame.\n");
266 frames_to_be_encoded.push(QueuedFrame{ pts, card_index, frame, video_format, y_offset, cbcr_offset });
267 any_frames_to_be_encoded.notify_all();
270 void MJPEGEncoder::encoder_thread_func()
272 pthread_setname_np(pthread_self(), "MJPEG_Encode");
273 posix_memalign((void **)&tmp_y, 4096, 4096 * 8);
274 posix_memalign((void **)&tmp_cbcr, 4096, 4096 * 8);
275 posix_memalign((void **)&tmp_cb, 4096, 4096 * 8);
276 posix_memalign((void **)&tmp_cr, 4096, 4096 * 8);
281 unique_lock<mutex> lock(mu);
282 any_frames_to_be_encoded.wait(lock, [this] { return !frames_to_be_encoded.empty() || should_quit; });
283 if (should_quit) return;
284 qf = move(frames_to_be_encoded.front());
285 frames_to_be_encoded.pop();
288 if (va_dpy != nullptr) {
289 // Will call back in the receiver thread.
290 encode_jpeg_va(move(qf));
292 // Encode synchronously, in the same thread.
293 vector<uint8_t> jpeg = encode_jpeg_libjpeg(qf);
294 write_mjpeg_packet(qf.pts, qf.card_index, jpeg);
299 void MJPEGEncoder::write_mjpeg_packet(int64_t pts, unsigned card_index, const vector<uint8_t> &jpeg)
302 memset(&pkt, 0, sizeof(pkt));
304 pkt.data = const_cast<uint8_t *>(&jpeg[0]);
305 pkt.size = jpeg.size();
306 pkt.stream_index = card_index;
307 pkt.flags = AV_PKT_FLAG_KEY;
308 pkt.pts = pkt.dts = pts;
310 if (av_write_frame(avctx.get(), &pkt) < 0) {
311 fprintf(stderr, "av_write_frame() failed\n");
316 class VABufferDestroyer {
318 VABufferDestroyer(VADisplay dpy, VABufferID buf)
319 : dpy(dpy), buf(buf) {}
321 ~VABufferDestroyer() {
322 VAStatus va_status = vaDestroyBuffer(dpy, buf);
323 CHECK_VASTATUS(va_status, "vaDestroyBuffer");
331 MJPEGEncoder::VAResources MJPEGEncoder::get_va_resources(unsigned width, unsigned height)
334 lock_guard<mutex> lock(va_resources_mutex);
335 for (auto it = va_resources_freelist.begin(); it != va_resources_freelist.end(); ++it) {
336 if (it->width == width && it->height == height) {
337 VAResources ret = *it;
338 va_resources_freelist.erase(it);
349 VASurfaceAttrib attrib;
350 attrib.flags = VA_SURFACE_ATTRIB_SETTABLE;
351 attrib.type = VASurfaceAttribPixelFormat;
352 attrib.value.type = VAGenericValueTypeInteger;
353 attrib.value.value.i = VA_FOURCC_UYVY;
355 VAStatus va_status = vaCreateSurfaces(va_dpy->va_dpy, VA_RT_FORMAT_YUV422,
357 &ret.surface, 1, &attrib, 1);
358 CHECK_VASTATUS(va_status, "vaCreateSurfaces");
360 va_status = vaCreateContext(va_dpy->va_dpy, config_id, width, height, 0, &ret.surface, 1, &ret.context);
361 CHECK_VASTATUS(va_status, "vaCreateContext");
363 va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAEncCodedBufferType, width * height * 3 + 8192, 1, nullptr, &ret.data_buffer);
364 CHECK_VASTATUS(va_status, "vaCreateBuffer");
369 void MJPEGEncoder::release_va_resources(MJPEGEncoder::VAResources resources)
371 lock_guard<mutex> lock(va_resources_mutex);
372 if (va_resources_freelist.size() > 10) {
373 auto it = va_resources_freelist.end();
376 VAStatus va_status = vaDestroyBuffer(va_dpy->va_dpy, it->data_buffer);
377 CHECK_VASTATUS(va_status, "vaDestroyBuffer");
379 va_status = vaDestroyContext(va_dpy->va_dpy, it->context);
380 CHECK_VASTATUS(va_status, "vaDestroyContext");
382 va_status = vaDestroySurfaces(va_dpy->va_dpy, &it->surface, 1);
383 CHECK_VASTATUS(va_status, "vaDestroySurfaces");
385 va_resources_freelist.erase(it);
388 va_resources_freelist.push_front(resources);
391 void MJPEGEncoder::init_jpeg_422(unsigned width, unsigned height, VectorDestinationManager *dest, jpeg_compress_struct *cinfo)
394 cinfo->err = jpeg_std_error(&jerr);
395 jpeg_create_compress(cinfo);
397 cinfo->dest = (jpeg_destination_mgr *)dest;
399 cinfo->input_components = 3;
400 jpeg_set_defaults(cinfo);
401 jpeg_set_quality(cinfo, quality, /*force_baseline=*/false);
403 cinfo->image_width = width;
404 cinfo->image_height = height;
405 cinfo->raw_data_in = true;
406 jpeg_set_colorspace(cinfo, JCS_YCbCr);
407 cinfo->comp_info[0].h_samp_factor = 2;
408 cinfo->comp_info[0].v_samp_factor = 1;
409 cinfo->comp_info[1].h_samp_factor = 1;
410 cinfo->comp_info[1].v_samp_factor = 1;
411 cinfo->comp_info[2].h_samp_factor = 1;
412 cinfo->comp_info[2].v_samp_factor = 1;
413 cinfo->CCIR601_sampling = true; // Seems to be mostly ignored by libjpeg, though.
414 jpeg_start_compress(cinfo, true);
417 vector<uint8_t> MJPEGEncoder::get_jpeg_header(unsigned width, unsigned height, jpeg_compress_struct *cinfo)
419 VectorDestinationManager dest;
420 init_jpeg_422(width, height, &dest, cinfo);
422 // Make a dummy black image; there's seemingly no other easy way of
423 // making libjpeg outputting all of its headers.
424 JSAMPROW yptr[8], cbptr[8], crptr[8];
425 JSAMPARRAY data[3] = { yptr, cbptr, crptr };
426 memset(tmp_y, 0, 4096);
427 memset(tmp_cb, 0, 4096);
428 memset(tmp_cr, 0, 4096);
429 for (unsigned yy = 0; yy < 8; ++yy) {
434 for (unsigned y = 0; y < height; y += 8) {
435 jpeg_write_raw_data(cinfo, data, /*num_lines=*/8);
437 jpeg_finish_compress(cinfo);
439 // We're only interested in the header, not the data after it.
440 dest.term_destination();
441 for (size_t i = 0; i < dest.dest.size() - 1; ++i) {
442 if (dest.dest[i] == 0xff && dest.dest[i + 1] == 0xda) { // Start of scan (SOS).
443 unsigned len = dest.dest[i + 2] * 256 + dest.dest[i + 3];
444 dest.dest.resize(i + len + 2);
452 MJPEGEncoder::VAData MJPEGEncoder::get_va_data_for_resolution(unsigned width, unsigned height)
454 pair<unsigned, unsigned> key(width, height);
455 if (va_data_for_resolution.count(key)) {
456 return va_data_for_resolution[key];
459 // Use libjpeg to generate a header and set sane defaults for e.g.
460 // quantization tables. Then do the actual encode with VA-API.
461 jpeg_compress_struct cinfo;
462 vector<uint8_t> jpeg_header = get_jpeg_header(width, height, &cinfo);
464 // Picture parameters.
465 VAEncPictureParameterBufferJPEG pic_param;
466 memset(&pic_param, 0, sizeof(pic_param));
467 pic_param.reconstructed_picture = VA_INVALID_ID;
468 pic_param.picture_width = cinfo.image_width;
469 pic_param.picture_height = cinfo.image_height;
470 for (int component_idx = 0; component_idx < cinfo.num_components; ++component_idx) {
471 const jpeg_component_info *comp = &cinfo.comp_info[component_idx];
472 pic_param.component_id[component_idx] = comp->component_id;
473 pic_param.quantiser_table_selector[component_idx] = comp->quant_tbl_no;
475 pic_param.num_components = cinfo.num_components;
476 pic_param.num_scan = 1;
477 pic_param.sample_bit_depth = 8;
478 pic_param.coded_buf = VA_INVALID_ID; // To be filled out by caller.
479 pic_param.pic_flags.bits.huffman = 1;
480 pic_param.quality = 50; // Don't scale the given quantization matrices. (See gen8_mfc_jpeg_fqm_state)
482 // Quantization matrices.
483 VAQMatrixBufferJPEG q;
484 memset(&q, 0, sizeof(q));
486 q.load_lum_quantiser_matrix = true;
487 q.load_chroma_quantiser_matrix = true;
488 for (int quant_tbl_idx = 0; quant_tbl_idx < min(4, NUM_QUANT_TBLS); ++quant_tbl_idx) {
489 const JQUANT_TBL *qtbl = cinfo.quant_tbl_ptrs[quant_tbl_idx];
490 assert((qtbl == nullptr) == (quant_tbl_idx >= 2));
491 if (qtbl == nullptr) continue;
493 uint8_t *qmatrix = (quant_tbl_idx == 0) ? q.lum_quantiser_matrix : q.chroma_quantiser_matrix;
494 for (int i = 0; i < 64; ++i) {
495 if (qtbl->quantval[i] > 255) {
496 fprintf(stderr, "Baseline JPEG only!\n");
499 qmatrix[i] = qtbl->quantval[jpeg_natural_order[i]];
503 // Huffman tables (arithmetic is not supported).
504 VAHuffmanTableBufferJPEGBaseline huff;
505 memset(&huff, 0, sizeof(huff));
507 for (int huff_tbl_idx = 0; huff_tbl_idx < min(2, NUM_HUFF_TBLS); ++huff_tbl_idx) {
508 const JHUFF_TBL *ac_hufftbl = cinfo.ac_huff_tbl_ptrs[huff_tbl_idx];
509 const JHUFF_TBL *dc_hufftbl = cinfo.dc_huff_tbl_ptrs[huff_tbl_idx];
510 if (ac_hufftbl == nullptr) {
511 assert(dc_hufftbl == nullptr);
512 huff.load_huffman_table[huff_tbl_idx] = 0;
514 assert(dc_hufftbl != nullptr);
515 huff.load_huffman_table[huff_tbl_idx] = 1;
517 for (int i = 0; i < 16; ++i) {
518 huff.huffman_table[huff_tbl_idx].num_dc_codes[i] = dc_hufftbl->bits[i + 1];
520 for (int i = 0; i < 12; ++i) {
521 huff.huffman_table[huff_tbl_idx].dc_values[i] = dc_hufftbl->huffval[i];
523 for (int i = 0; i < 16; ++i) {
524 huff.huffman_table[huff_tbl_idx].num_ac_codes[i] = ac_hufftbl->bits[i + 1];
526 for (int i = 0; i < 162; ++i) {
527 huff.huffman_table[huff_tbl_idx].ac_values[i] = ac_hufftbl->huffval[i];
532 // Slice parameters (metadata about the slice).
533 VAEncSliceParameterBufferJPEG parms;
534 memset(&parms, 0, sizeof(parms));
535 for (int component_idx = 0; component_idx < cinfo.num_components; ++component_idx) {
536 const jpeg_component_info *comp = &cinfo.comp_info[component_idx];
537 parms.components[component_idx].component_selector = comp->component_id;
538 parms.components[component_idx].dc_table_selector = comp->dc_tbl_no;
539 parms.components[component_idx].ac_table_selector = comp->ac_tbl_no;
540 if (parms.components[component_idx].dc_table_selector > 1 ||
541 parms.components[component_idx].ac_table_selector > 1) {
542 fprintf(stderr, "Uses too many Huffman tables\n");
546 parms.num_components = cinfo.num_components;
547 parms.restart_interval = cinfo.restart_interval;
549 jpeg_destroy_compress(&cinfo);
552 ret.jpeg_header = move(jpeg_header);
553 ret.pic_param = pic_param;
557 va_data_for_resolution[key] = ret;
561 void MJPEGEncoder::encode_jpeg_va(QueuedFrame &&qf)
563 unsigned width = qf.video_format.width;
564 unsigned height = qf.video_format.height;
566 VAResources resources = get_va_resources(width, height);
567 ReleaseVAResources release(this, resources);
569 VAData va_data = get_va_data_for_resolution(width, height);
570 va_data.pic_param.coded_buf = resources.data_buffer;
572 VABufferID pic_param_buffer;
573 VAStatus va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAEncPictureParameterBufferType, sizeof(va_data.pic_param), 1, &va_data.pic_param, &pic_param_buffer);
574 CHECK_VASTATUS(va_status, "vaCreateBuffer");
575 VABufferDestroyer destroy_pic_param(va_dpy->va_dpy, pic_param_buffer);
578 va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAQMatrixBufferType, sizeof(va_data.q), 1, &va_data.q, &q_buffer);
579 CHECK_VASTATUS(va_status, "vaCreateBuffer");
580 VABufferDestroyer destroy_iq(va_dpy->va_dpy, q_buffer);
582 VABufferID huff_buffer;
583 va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAHuffmanTableBufferType, sizeof(va_data.huff), 1, &va_data.huff, &huff_buffer);
584 CHECK_VASTATUS(va_status, "vaCreateBuffer");
585 VABufferDestroyer destroy_huff(va_dpy->va_dpy, huff_buffer);
587 VABufferID slice_param_buffer;
588 va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAEncSliceParameterBufferType, sizeof(va_data.parms), 1, &va_data.parms, &slice_param_buffer);
589 CHECK_VASTATUS(va_status, "vaCreateBuffer");
590 VABufferDestroyer destroy_slice_param(va_dpy->va_dpy, slice_param_buffer);
593 va_status = vaDeriveImage(va_dpy->va_dpy, resources.surface, &image);
594 CHECK_VASTATUS(va_status, "vaDeriveImage");
596 // Upload the pixel data.
597 uint8_t *surface_p = nullptr;
598 vaMapBuffer(va_dpy->va_dpy, image.buf, (void **)&surface_p);
600 size_t field_start_line = qf.video_format.extra_lines_top; // No interlacing support.
601 size_t field_start = qf.cbcr_offset * 2 + qf.video_format.width * field_start_line * 2;
604 const uint8_t *src = qf.frame->data_copy + field_start;
605 uint8_t *dst = (unsigned char *)surface_p + image.offsets[0];
606 memcpy_with_pitch(dst, src, qf.video_format.width * 2, image.pitches[0], qf.video_format.height);
609 va_status = vaUnmapBuffer(va_dpy->va_dpy, image.buf);
610 CHECK_VASTATUS(va_status, "vaUnmapBuffer");
611 va_status = vaDestroyImage(va_dpy->va_dpy, image.image_id);
612 CHECK_VASTATUS(va_status, "vaDestroyImage");
614 // Finally, stick in the JPEG header.
615 VAEncPackedHeaderParameterBuffer header_parm;
616 header_parm.type = VAEncPackedHeaderRawData;
617 header_parm.bit_length = 8 * va_data.jpeg_header.size();
619 VABufferID header_parm_buffer;
620 va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAEncPackedHeaderParameterBufferType, sizeof(header_parm), 1, &header_parm, &header_parm_buffer);
621 CHECK_VASTATUS(va_status, "vaCreateBuffer");
622 VABufferDestroyer destroy_header(va_dpy->va_dpy, header_parm_buffer);
624 VABufferID header_data_buffer;
625 va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAEncPackedHeaderDataBufferType, va_data.jpeg_header.size(), 1, va_data.jpeg_header.data(), &header_data_buffer);
626 CHECK_VASTATUS(va_status, "vaCreateBuffer");
627 VABufferDestroyer destroy_header_data(va_dpy->va_dpy, header_data_buffer);
629 va_status = vaBeginPicture(va_dpy->va_dpy, resources.context, resources.surface);
630 CHECK_VASTATUS(va_status, "vaBeginPicture");
631 va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &pic_param_buffer, 1);
632 CHECK_VASTATUS(va_status, "vaRenderPicture(pic_param)");
633 va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &q_buffer, 1);
634 CHECK_VASTATUS(va_status, "vaRenderPicture(q)");
635 va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &huff_buffer, 1);
636 CHECK_VASTATUS(va_status, "vaRenderPicture(huff)");
637 va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &slice_param_buffer, 1);
638 CHECK_VASTATUS(va_status, "vaRenderPicture(slice_param)");
639 va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &header_parm_buffer, 1);
640 CHECK_VASTATUS(va_status, "vaRenderPicture(header_parm)");
641 va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &header_data_buffer, 1);
642 CHECK_VASTATUS(va_status, "vaRenderPicture(header_data)");
643 va_status = vaEndPicture(va_dpy->va_dpy, resources.context);
644 CHECK_VASTATUS(va_status, "vaEndPicture");
646 qf.resources = move(resources);
647 qf.resource_releaser = move(release);
649 lock_guard<mutex> lock(mu);
650 frames_encoding.push(move(qf));
651 any_frames_encoding.notify_all();
654 void MJPEGEncoder::va_receiver_thread_func()
656 pthread_setname_np(pthread_self(), "MJPEG_Receive");
660 unique_lock<mutex> lock(mu);
661 any_frames_encoding.wait(lock, [this] { return !frames_encoding.empty() || should_quit; });
662 if (should_quit) return;
663 qf = move(frames_encoding.front());
664 frames_encoding.pop();
667 VAStatus va_status = vaSyncSurface(va_dpy->va_dpy, qf.resources.surface);
668 CHECK_VASTATUS(va_status, "vaSyncSurface");
670 VACodedBufferSegment *segment;
671 va_status = vaMapBuffer(va_dpy->va_dpy, qf.resources.data_buffer, (void **)&segment);
672 CHECK_VASTATUS(va_status, "vaMapBuffer");
674 const char *coded_buf = reinterpret_cast<char *>(segment->buf);
675 vector<uint8_t> jpeg(coded_buf, coded_buf + segment->size);
677 va_status = vaUnmapBuffer(va_dpy->va_dpy, qf.resources.data_buffer);
678 CHECK_VASTATUS(va_status, "vaUnmapBuffer");
680 write_mjpeg_packet(qf.pts, qf.card_index, jpeg);
684 vector<uint8_t> MJPEGEncoder::encode_jpeg_libjpeg(const QueuedFrame &qf)
686 unsigned width = qf.video_format.width;
687 unsigned height = qf.video_format.height;
689 VectorDestinationManager dest;
690 jpeg_compress_struct cinfo;
691 init_jpeg_422(width, height, &dest, &cinfo);
693 size_t field_start_line = qf.video_format.extra_lines_top; // No interlacing support.
694 size_t field_start = qf.cbcr_offset * 2 + qf.video_format.width * field_start_line * 2;
696 JSAMPROW yptr[8], cbptr[8], crptr[8];
697 JSAMPARRAY data[3] = { yptr, cbptr, crptr };
698 for (unsigned y = 0; y < qf.video_format.height; y += 8) {
699 const uint8_t *src = qf.frame->data_copy + field_start + y * qf.video_format.width * 2;
701 memcpy_interleaved(tmp_y, tmp_cbcr, src, qf.video_format.width * 8 * 2);
702 memcpy_interleaved(tmp_cb, tmp_cr, tmp_cbcr, qf.video_format.width * 8);
703 for (unsigned yy = 0; yy < 8; ++yy) {
704 yptr[yy] = tmp_y + yy * width;
705 cbptr[yy] = tmp_cb + yy * width / 2;
706 crptr[yy] = tmp_cr + yy * width / 2;
708 jpeg_write_raw_data(&cinfo, data, /*num_lines=*/8);
710 jpeg_finish_compress(&cinfo);