]> git.sesse.net Git - nageru/blobdiff - nageru/mjpeg_encoder.cpp
Split out some work from the MJPEG encoder constructor.
[nageru] / nageru / mjpeg_encoder.cpp
index e39e802c843cbef0bcd6f130db17702d722c2ce3..867414d44127d5019cca822102de519ef3f6bcf8 100644 (file)
@@ -21,11 +21,15 @@ extern "C" {
 #include "shared/timebase.h"
 #include "va_display_with_cleanup.h"
 
+#include <movit/colorspace_conversion_effect.h>
+
 #include <va/va.h>
 #include <va/va_drm.h>
 #include <va/va_x11.h>
 
+using namespace Eigen;
 using namespace bmusb;
+using namespace movit;
 using namespace std;
 
 static VAImageFormat uyvy_format;
@@ -113,6 +117,68 @@ int MJPEGEncoder::write_packet2(uint8_t *buf, int buf_size, AVIODataMarkerType t
        return buf_size;
 }
 
+namespace {
+
+void add_video_stream(AVFormatContext *avctx)
+{
+       AVStream *stream = avformat_new_stream(avctx, nullptr);
+       if (stream == nullptr) {
+               fprintf(stderr, "avformat_new_stream() failed\n");
+               abort();
+       }
+
+       // FFmpeg is very picky about having audio at 1/48000 timebase,
+       // no matter what we write. Even though we'd prefer our usual 1/120000,
+       // put the video on the same one, so that we can have locked audio.
+       stream->time_base = AVRational{ 1, OUTPUT_FREQUENCY };
+       stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
+       stream->codecpar->codec_id = AV_CODEC_ID_MJPEG;
+
+       // Used for aspect ratio only. Can change without notice (the mux won't care).
+       stream->codecpar->width = global_flags.width;
+       stream->codecpar->height = global_flags.height;
+
+       // TODO: We could perhaps use the interpretation for each card here
+       // (or at least the command-line flags) instead of the defaults,
+       // but what would we do when they change?
+       stream->codecpar->color_primaries = AVCOL_PRI_BT709;
+       stream->codecpar->color_trc = AVCOL_TRC_IEC61966_2_1;
+       stream->codecpar->color_space = AVCOL_SPC_BT709;
+       stream->codecpar->color_range = AVCOL_RANGE_MPEG;
+       stream->codecpar->chroma_location = AVCHROMA_LOC_LEFT;
+       stream->codecpar->field_order = AV_FIELD_PROGRESSIVE;
+}
+
+void add_audio_stream(AVFormatContext *avctx)
+{
+       AVStream *stream = avformat_new_stream(avctx, nullptr);
+       if (stream == nullptr) {
+               fprintf(stderr, "avformat_new_stream() failed\n");
+               abort();
+       }
+       stream->time_base = AVRational{ 1, OUTPUT_FREQUENCY };
+       stream->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
+       stream->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
+       stream->codecpar->channel_layout = AV_CH_LAYOUT_STEREO;
+       stream->codecpar->channels = 2;
+       stream->codecpar->sample_rate = OUTPUT_FREQUENCY;
+}
+
+void finalize_mux(AVFormatContext *avctx)
+{
+       AVDictionary *options = NULL;
+       vector<pair<string, string>> opts = MUX_OPTS;
+       for (pair<string, string> opt : opts) {
+               av_dict_set(&options, opt.first.c_str(), opt.second.c_str(), 0);
+       }
+       if (avformat_write_header(avctx, &options) < 0) {
+               fprintf(stderr, "avformat_write_header() failed\n");
+               abort();
+       }
+}
+
+}  // namespace
+
 MJPEGEncoder::MJPEGEncoder(HTTPD *httpd, const string &va_display)
        : httpd(httpd)
 {
@@ -128,56 +194,12 @@ MJPEGEncoder::MJPEGEncoder(HTTPD *httpd, const string &va_display)
        avctx->flags = AVFMT_FLAG_CUSTOM_IO;
 
        for (unsigned card_idx = 0; card_idx < global_flags.card_to_mjpeg_stream_export.size(); ++card_idx) {
-               AVStream *stream = avformat_new_stream(avctx.get(), nullptr);
-               if (stream == nullptr) {
-                       fprintf(stderr, "avformat_new_stream() failed\n");
-                       abort();
-               }
-
-               // FFmpeg is very picky about having audio at 1/48000 timebase,
-               // no matter what we write. Even though we'd prefer our usual 1/120000,
-               // put the video on the same one, so that we can have locked audio.
-               stream->time_base = AVRational{ 1, OUTPUT_FREQUENCY };
-               stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
-               stream->codecpar->codec_id = AV_CODEC_ID_MJPEG;
-
-               // Used for aspect ratio only. Can change without notice (the mux won't care).
-               stream->codecpar->width = global_flags.width;
-               stream->codecpar->height = global_flags.height;
-
-               // TODO: We could perhaps use the interpretation for each card here
-               // (or at least the command-line flags) instead of the defaults,
-               // but what would we do when they change?
-               stream->codecpar->color_primaries = AVCOL_PRI_BT709;
-               stream->codecpar->color_trc = AVCOL_TRC_IEC61966_2_1;
-               stream->codecpar->color_space = AVCOL_SPC_BT709;
-               stream->codecpar->color_range = AVCOL_RANGE_MPEG;
-               stream->codecpar->chroma_location = AVCHROMA_LOC_LEFT;
-               stream->codecpar->field_order = AV_FIELD_PROGRESSIVE;
+               add_video_stream(avctx.get());
        }
        for (unsigned card_idx = 0; card_idx < global_flags.card_to_mjpeg_stream_export.size(); ++card_idx) {
-               AVStream *stream = avformat_new_stream(avctx.get(), nullptr);
-               if (stream == nullptr) {
-                       fprintf(stderr, "avformat_new_stream() failed\n");
-                       abort();
-               }
-               stream->time_base = AVRational{ 1, OUTPUT_FREQUENCY };
-               stream->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
-               stream->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
-               stream->codecpar->channel_layout = AV_CH_LAYOUT_STEREO;
-               stream->codecpar->channels = 2;
-               stream->codecpar->sample_rate = OUTPUT_FREQUENCY;
-       }
-
-       AVDictionary *options = NULL;
-       vector<pair<string, string>> opts = MUX_OPTS;
-       for (pair<string, string> opt : opts) {
-               av_dict_set(&options, opt.first.c_str(), opt.second.c_str(), 0);
-       }
-       if (avformat_write_header(avctx.get(), &options) < 0) {
-               fprintf(stderr, "avformat_write_header() failed\n");
-               abort();
+               add_audio_stream(avctx.get());
        }
+       finalize_mux(avctx.get());
 
        // Initialize VA-API.
        string error;
@@ -286,7 +308,7 @@ unique_ptr<VADisplayWithCleanup> MJPEGEncoder::try_open_va(const string &va_disp
        return va_dpy;
 }
 
-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)
+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)
 {
        PBOFrameAllocator::Userdata *userdata = (PBOFrameAllocator::Userdata *)frame->userdata;
        if (video_format.width == 0 || video_format.height == 0) {
@@ -317,7 +339,7 @@ void MJPEGEncoder::upload_frame(int64_t pts, unsigned card_index, RefCountedFram
                return;
        }
        ++metric_mjpeg_overrun_submitted;
-       frames_to_be_encoded.push(QueuedFrame{ pts, card_index, frame, video_format, y_offset, cbcr_offset, move(audio) });
+       frames_to_be_encoded.push(QueuedFrame{ pts, card_index, frame, video_format, y_offset, cbcr_offset, move(audio), white_balance });
        any_frames_to_be_encoded.notify_all();
 }
 
@@ -495,7 +517,25 @@ void MJPEGEncoder::release_va_resources(MJPEGEncoder::VAResources resources)
        va_resources_freelist.push_front(resources);
 }
 
-void MJPEGEncoder::init_jpeg_422(unsigned width, unsigned height, VectorDestinationManager *dest, jpeg_compress_struct *cinfo)
+namespace {
+
+void push16(uint16_t val, string *str)
+{
+       str->push_back(val >> 8);
+       str->push_back(val & 0xff);
+}
+
+void push32(uint32_t val, string *str)
+{
+       str->push_back(val >> 24);
+       str->push_back((val >> 16) & 0xff);
+       str->push_back((val >> 8) & 0xff);
+       str->push_back(val & 0xff);
+}
+
+}  // namespace
+
+void MJPEGEncoder::init_jpeg_422(unsigned width, unsigned height, const RGBTriplet &white_balance, VectorDestinationManager *dest, jpeg_compress_struct *cinfo)
 {
        jpeg_error_mgr jerr;
        cinfo->err = jpeg_std_error(&jerr);
@@ -520,15 +560,70 @@ void MJPEGEncoder::init_jpeg_422(unsigned width, unsigned height, VectorDestinat
        cinfo->CCIR601_sampling = true;  // Seems to be mostly ignored by libjpeg, though.
        jpeg_start_compress(cinfo, true);
 
+       if (fabs(white_balance.r - 1.0f) > 1e-3 ||
+           fabs(white_balance.g - 1.0f) > 1e-3 ||
+           fabs(white_balance.b - 1.0f) > 1e-3) {
+               // Convert from (linear) RGB to XYZ.
+               Matrix3d rgb_to_xyz_matrix = movit::ColorspaceConversionEffect::get_xyz_matrix(COLORSPACE_sRGB);
+               Vector3d xyz = rgb_to_xyz_matrix * Vector3d(white_balance.r, white_balance.g, white_balance.b);
+
+               // Convert from XYZ to xyz by normalizing.
+               xyz /= (xyz[0] + xyz[1] + xyz[2]);
+
+               // Create a very rudimentary EXIF header to hold our white point.
+               string exif;
+
+               // Exif header, followed by some padding.
+               exif = "Exif";
+               push16(0, &exif);
+
+               // TIFF header first:
+               exif += "MM";  // Big endian.
+
+               // Magic number.
+               push16(42, &exif);
+
+               // Offset of first IFD (relative to the MM, immediately after the header).
+               push32(exif.size() - 6 + 4, &exif);
+
+               // Now the actual IFD.
+
+               // One entry.
+               push16(1, &exif);
+
+               // WhitePoint tag ID.
+               push16(0x13e, &exif);
+
+               // Rational type.
+               push16(5, &exif);
+
+               // Two values (x and y; z is implicit due to normalization).
+               push32(2, &exif);
+
+               // Offset (relative to the MM, immediately after the last IFD).
+               push32(exif.size() - 6 + 8, &exif);
+
+               // No more IFDs.
+               push32(0, &exif);
+
+               // The actual values.
+               push32(lrintf(xyz[0] * 10000.0f), &exif);
+               push32(10000, &exif);
+               push32(lrintf(xyz[1] * 10000.0f), &exif);
+               push32(10000, &exif);
+
+               jpeg_write_marker(cinfo, JPEG_APP0 + 1, (const JOCTET *)exif.data(), exif.size());
+       }
+
        // This comment marker is private to FFmpeg. It signals limited Y'CbCr range
        // (and nothing else).
        jpeg_write_marker(cinfo, JPEG_COM, (const JOCTET *)"CS=ITU601", strlen("CS=ITU601"));
 }
 
-vector<uint8_t> MJPEGEncoder::get_jpeg_header(unsigned width, unsigned height, jpeg_compress_struct *cinfo)
+vector<uint8_t> MJPEGEncoder::get_jpeg_header(unsigned width, unsigned height, const RGBTriplet &white_balance, jpeg_compress_struct *cinfo)
 {
        VectorDestinationManager dest;
-       init_jpeg_422(width, height, &dest, cinfo);
+       init_jpeg_422(width, height, white_balance, &dest, cinfo);
 
        // Make a dummy black image; there's seemingly no other easy way of
        // making libjpeg outputting all of its headers.
@@ -560,7 +655,7 @@ vector<uint8_t> MJPEGEncoder::get_jpeg_header(unsigned width, unsigned height, j
        return dest.dest;
 }
 
-MJPEGEncoder::VAData MJPEGEncoder::get_va_data_for_resolution(unsigned width, unsigned height)
+MJPEGEncoder::VAData MJPEGEncoder::get_va_data_for_resolution(unsigned width, unsigned height, const RGBTriplet &white_balance)
 {
        pair<unsigned, unsigned> key(width, height);
        if (va_data_for_resolution.count(key)) {
@@ -570,7 +665,7 @@ MJPEGEncoder::VAData MJPEGEncoder::get_va_data_for_resolution(unsigned width, un
        // Use libjpeg to generate a header and set sane defaults for e.g.
        // quantization tables. Then do the actual encode with VA-API.
        jpeg_compress_struct cinfo;
-       vector<uint8_t> jpeg_header = get_jpeg_header(width, height, &cinfo);
+       vector<uint8_t> jpeg_header = get_jpeg_header(width, height, white_balance, &cinfo);
 
        // Picture parameters.
        VAEncPictureParameterBufferJPEG pic_param;
@@ -686,7 +781,7 @@ void MJPEGEncoder::encode_jpeg_va(QueuedFrame &&qf)
                release = ReleaseVAResources(this, resources);
        }
 
-       VAData va_data = get_va_data_for_resolution(width, height);
+       VAData va_data = get_va_data_for_resolution(width, height, qf.white_balance);
        va_data.pic_param.coded_buf = resources.data_buffer;
 
        VABufferID pic_param_buffer;
@@ -822,7 +917,7 @@ vector<uint8_t> MJPEGEncoder::encode_jpeg_libjpeg(const QueuedFrame &qf)
 
        VectorDestinationManager dest;
        jpeg_compress_struct cinfo;
-       init_jpeg_422(width, height, &dest, &cinfo);
+       init_jpeg_422(width, height, qf.white_balance, &dest, &cinfo);
 
        size_t field_start_line = qf.video_format.extra_lines_top;  // No interlacing support.
        size_t field_start = qf.cbcr_offset * 2 + qf.video_format.width * field_start_line * 2;