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