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