#include "flags.h"
#include "shared/httpd.h"
#include "shared/memcpy_interleaved.h"
+#include "shared/metrics.h"
#include "pbo_frame_allocator.h"
#include "shared/timebase.h"
#include "va_display_with_cleanup.h"
using namespace bmusb;
using namespace std;
-extern void memcpy_with_pitch(uint8_t *dst, const uint8_t *src, size_t src_width, size_t dst_pitch, size_t height);
+static VAImageFormat uyvy_format;
-#define CHECK_VASTATUS(va_status, func) \
- if (va_status != VA_STATUS_SUCCESS) { \
- fprintf(stderr, "%s:%d (%s) failed with %d\n", __func__, __LINE__, func, va_status); \
- exit(1); \
- }
+extern void memcpy_with_pitch(uint8_t *dst, const uint8_t *src, size_t src_width, size_t dst_pitch, size_t height);
// From libjpeg (although it's of course identical between implementations).
static const int jpeg_natural_order[DCTSIZE2] = {
MJPEGEncoder::MJPEGEncoder(HTTPD *httpd, const string &va_display)
: httpd(httpd)
{
- encoder_thread = thread(&MJPEGEncoder::encoder_thread_func, this);
-
// Set up the mux. We don't use the Mux wrapper, because it's geared towards
// a situation with only one video stream (and possibly one audio stream)
// with known width/height, and we don't need the extra functionality it provides.
avctx.reset(avformat_alloc_context());
- avctx->oformat = av_guess_format("mp4", nullptr, nullptr);
+ avctx->oformat = av_guess_format("nut", nullptr, nullptr);
uint8_t *buf = (uint8_t *)av_malloc(MUX_BUFFER_SIZE);
avctx->pb = avio_alloc_context(buf, MUX_BUFFER_SIZE, 1, this, nullptr, nullptr, nullptr);
avctx->pb->write_data_type = &MJPEGEncoder::write_packet2_thunk;
avctx->flags = AVFMT_FLAG_CUSTOM_IO;
- for (int card_idx = 0; card_idx < global_flags.num_cards; ++card_idx) {
+ 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");
- exit(1);
+ abort();
}
- stream->time_base = AVRational{ 1, TIMEBASE };
+
+ // 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;
stream->codecpar->chroma_location = AVCHROMA_LOC_LEFT;
stream->codecpar->field_order = AV_FIELD_PROGRESSIVE;
}
+ 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;
}
if (avformat_write_header(avctx.get(), &options) < 0) {
fprintf(stderr, "avformat_write_header() failed\n");
- exit(1);
+ abort();
}
// Initialize VA-API.
fprintf(stderr, "Could not initialize VA-API for MJPEG encoding: %s. JPEGs will be encoded in software if needed.\n", error.c_str());
}
+ encoder_thread = thread(&MJPEGEncoder::encoder_thread_func, this);
+ if (va_dpy != nullptr) {
+ va_receiver_thread = thread(&MJPEGEncoder::va_receiver_thread_func, this);
+ }
+
+ global_metrics.add("mjpeg_frames", {{ "status", "dropped" }, { "reason", "zero_size" }}, &metric_mjpeg_frames_zero_size_dropped);
+ global_metrics.add("mjpeg_frames", {{ "status", "dropped" }, { "reason", "interlaced" }}, &metric_mjpeg_frames_interlaced_dropped);
+ global_metrics.add("mjpeg_frames", {{ "status", "dropped" }, { "reason", "unsupported_pixel_format" }}, &metric_mjpeg_frames_unsupported_pixel_format_dropped);
+ global_metrics.add("mjpeg_frames", {{ "status", "dropped" }, { "reason", "oversized" }}, &metric_mjpeg_frames_oversized_dropped);
+ global_metrics.add("mjpeg_frames", {{ "status", "dropped" }, { "reason", "overrun" }}, &metric_mjpeg_overrun_dropped);
+ global_metrics.add("mjpeg_frames", {{ "status", "submitted" }}, &metric_mjpeg_overrun_submitted);
+
running = true;
}
+MJPEGEncoder::~MJPEGEncoder()
+{
+ av_free(avctx->pb->buffer);
+
+ global_metrics.remove("mjpeg_frames", {{ "status", "dropped" }, { "reason", "zero_size" }});
+ global_metrics.remove("mjpeg_frames", {{ "status", "dropped" }, { "reason", "interlaced" }});
+ global_metrics.remove("mjpeg_frames", {{ "status", "dropped" }, { "reason", "unsupported_pixel_format" }});
+ global_metrics.remove("mjpeg_frames", {{ "status", "dropped" }, { "reason", "oversized" }});
+ global_metrics.remove("mjpeg_frames", {{ "status", "dropped" }, { "reason", "overrun" }});
+ global_metrics.remove("mjpeg_frames", {{ "status", "submitted" }});
+}
+
void MJPEGEncoder::stop()
{
if (!running) {
running = false;
should_quit = true;
any_frames_to_be_encoded.notify_all();
+ any_frames_encoding.notify_all();
encoder_thread.join();
+ if (va_dpy != nullptr) {
+ va_receiver_thread.join();
+ }
}
unique_ptr<VADisplayWithCleanup> MJPEGEncoder::try_open_va(const string &va_display, string *error, VAConfigID *config_id)
return nullptr;
}
+ // TODO: Unify with the code in Futatabi.
int num_formats = vaMaxNumImageFormats(va_dpy->va_dpy);
assert(num_formats > 0);
return nullptr;
}
+ bool found = false;
+ for (int i = 0; i < num_formats; ++i) {
+ if (formats[i].fourcc == VA_FOURCC_UYVY) {
+ memcpy(&uyvy_format, &formats[i], sizeof(VAImageFormat));
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ if (error != nullptr) *error = "UYVY format not found";
+ return nullptr;
+ }
+
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)
+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)
{
PBOFrameAllocator::Userdata *userdata = (PBOFrameAllocator::Userdata *)frame->userdata;
if (video_format.width == 0 || video_format.height == 0) {
+ ++metric_mjpeg_frames_zero_size_dropped;
return;
}
if (video_format.interlaced) {
fprintf(stderr, "Card %u: Ignoring JPEG encoding for interlaced frame\n", card_index);
+ ++metric_mjpeg_frames_interlaced_dropped;
return;
}
if (userdata->pixel_format != PixelFormat_8BitYCbCr ||
!frame->interleaved) {
fprintf(stderr, "Card %u: Ignoring JPEG encoding for unsupported pixel format\n", card_index);
+ ++metric_mjpeg_frames_unsupported_pixel_format_dropped;
return;
}
if (video_format.width > 4096 || video_format.height > 4096) {
fprintf(stderr, "Card %u: Ignoring JPEG encoding for oversized frame\n", card_index);
+ ++metric_mjpeg_frames_oversized_dropped;
return;
}
lock_guard<mutex> lock(mu);
- frames_to_be_encoded.push(QueuedFrame{ pts, card_index, frame, video_format, y_offset, cbcr_offset });
+ if (frames_to_be_encoded.size() + frames_encoding.size() > 50) {
+ fprintf(stderr, "WARNING: MJPEG encoding doesn't keep up, discarding frame.\n");
+ ++metric_mjpeg_overrun_dropped;
+ return;
+ }
+ ++metric_mjpeg_overrun_submitted;
+ frames_to_be_encoded.push(QueuedFrame{ pts, card_index, frame, video_format, y_offset, cbcr_offset, move(audio) });
any_frames_to_be_encoded.notify_all();
}
+int MJPEGEncoder::get_mjpeg_stream_for_card(unsigned card_index)
+{
+ // Only bother doing MJPEG encoding if there are any connected clients
+ // that want the stream.
+ if (httpd->get_num_connected_multicam_clients() == 0) {
+ return -1;
+ }
+
+ auto it = global_flags.card_to_mjpeg_stream_export.find(card_index);
+ if (it == global_flags.card_to_mjpeg_stream_export.end()) {
+ return -1;
+ }
+ return it->second;
+}
+
void MJPEGEncoder::encoder_thread_func()
{
pthread_setname_np(pthread_self(), "MJPEG_Encode");
posix_memalign((void **)&tmp_cb, 4096, 4096 * 8);
posix_memalign((void **)&tmp_cr, 4096, 4096 * 8);
- unique_lock<mutex> lock(mu);
for (;;) {
- any_frames_to_be_encoded.wait(lock, [this] { return !frames_to_be_encoded.empty() || should_quit; });
- if (should_quit) return;
- QueuedFrame qf = move(frames_to_be_encoded.front());
- frames_to_be_encoded.pop();
-
- vector<uint8_t> jpeg = encode_jpeg(qf);
-
- AVPacket pkt;
- memset(&pkt, 0, sizeof(pkt));
- pkt.buf = nullptr;
- pkt.data = &jpeg[0];
- pkt.size = jpeg.size();
- pkt.stream_index = qf.card_index;
- pkt.flags = AV_PKT_FLAG_KEY;
- pkt.pts = pkt.dts = qf.pts;
-
- if (av_write_frame(avctx.get(), &pkt) < 0) {
- fprintf(stderr, "av_write_frame() failed\n");
- exit(1);
+ QueuedFrame qf;
+ {
+ unique_lock<mutex> lock(mu);
+ any_frames_to_be_encoded.wait(lock, [this] { return !frames_to_be_encoded.empty() || should_quit; });
+ if (should_quit) break;
+ qf = move(frames_to_be_encoded.front());
+ frames_to_be_encoded.pop();
+ }
+
+ if (va_dpy != nullptr) {
+ // Will call back in the receiver thread.
+ encode_jpeg_va(move(qf));
+ } else {
+ // Write audio before video, since Futatabi expects it.
+ if (qf.audio.size() > 0) {
+ write_audio_packet(qf.pts, qf.card_index, qf.audio);
+ }
+
+ // Encode synchronously, in the same thread.
+ vector<uint8_t> jpeg = encode_jpeg_libjpeg(qf);
+ write_mjpeg_packet(qf.pts, qf.card_index, jpeg.data(), jpeg.size());
}
}
+
+ free(tmp_y);
+ free(tmp_cbcr);
+ free(tmp_cb);
+ free(tmp_cr);
+}
+
+void MJPEGEncoder::write_mjpeg_packet(int64_t pts, unsigned card_index, const uint8_t *jpeg, size_t jpeg_size)
+{
+ AVPacket pkt;
+ memset(&pkt, 0, sizeof(pkt));
+ pkt.buf = nullptr;
+ pkt.data = const_cast<uint8_t *>(jpeg);
+ pkt.size = jpeg_size;
+ pkt.stream_index = card_index;
+ pkt.flags = AV_PKT_FLAG_KEY;
+ AVRational time_base = avctx->streams[pkt.stream_index]->time_base;
+ pkt.pts = pkt.dts = av_rescale_q(pts, AVRational{ 1, TIMEBASE }, time_base);
+ pkt.duration = 0;
+
+ if (av_write_frame(avctx.get(), &pkt) < 0) {
+ fprintf(stderr, "av_write_frame() failed\n");
+ abort();
+ }
+}
+
+void MJPEGEncoder::write_audio_packet(int64_t pts, unsigned card_index, const vector<int32_t> &audio)
+{
+ AVPacket pkt;
+ memset(&pkt, 0, sizeof(pkt));
+ pkt.buf = nullptr;
+ pkt.data = reinterpret_cast<uint8_t *>(const_cast<int32_t *>(&audio[0]));
+ pkt.size = audio.size() * sizeof(audio[0]);
+ pkt.stream_index = card_index + global_flags.card_to_mjpeg_stream_export.size();
+ pkt.flags = AV_PKT_FLAG_KEY;
+ AVRational time_base = avctx->streams[pkt.stream_index]->time_base;
+ pkt.pts = pkt.dts = av_rescale_q(pts, AVRational{ 1, TIMEBASE }, time_base);
+ size_t num_stereo_samples = audio.size() / 2;
+ pkt.duration = av_rescale_q(num_stereo_samples, AVRational{ 1, OUTPUT_FREQUENCY }, time_base);
+
+ if (av_write_frame(avctx.get(), &pkt) < 0) {
+ fprintf(stderr, "av_write_frame() failed\n");
+ abort();
+ }
}
class VABufferDestroyer {
va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAEncCodedBufferType, width * height * 3 + 8192, 1, nullptr, &ret.data_buffer);
CHECK_VASTATUS(va_status, "vaCreateBuffer");
+ va_status = vaCreateImage(va_dpy->va_dpy, &uyvy_format, width, height, &ret.image);
+ CHECK_VASTATUS(va_status, "vaCreateImage");
+
return ret;
}
void MJPEGEncoder::release_va_resources(MJPEGEncoder::VAResources resources)
{
lock_guard<mutex> lock(va_resources_mutex);
- if (va_resources_freelist.size() > 10) {
+ if (va_resources_freelist.size() > 50) {
auto it = va_resources_freelist.end();
--it;
va_status = vaDestroySurfaces(va_dpy->va_dpy, &it->surface, 1);
CHECK_VASTATUS(va_status, "vaDestroySurfaces");
+ va_status = vaDestroyImage(va_dpy->va_dpy, it->image.image_id);
+ CHECK_VASTATUS(va_status, "vaDestroyImage");
+
va_resources_freelist.erase(it);
}
cinfo->comp_info[2].v_samp_factor = 1;
cinfo->CCIR601_sampling = true; // Seems to be mostly ignored by libjpeg, though.
jpeg_start_compress(cinfo, true);
+
+ // 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)
return ret;
}
-vector<uint8_t> MJPEGEncoder::encode_jpeg(const QueuedFrame &qf)
-{
- if (va_dpy != nullptr) {
- return encode_jpeg_va(qf);
- } else {
- return encode_jpeg_libjpeg(qf);
- }
-}
-
-vector<uint8_t> MJPEGEncoder::encode_jpeg_va(const QueuedFrame &qf)
+void MJPEGEncoder::encode_jpeg_va(QueuedFrame &&qf)
{
+ PBOFrameAllocator::Userdata *userdata = (PBOFrameAllocator::Userdata *)qf.frame->userdata;
unsigned width = qf.video_format.width;
unsigned height = qf.video_format.height;
- VAResources resources = get_va_resources(width, height);
- ReleaseVAResources release(this, resources);
+ VAResources resources;
+ ReleaseVAResources release;
+ if (userdata->data_copy_current_src == PBOFrameAllocator::Userdata::FROM_VA_API) {
+ resources = move(userdata->va_resources);
+ release = move(userdata->va_resources_release);
+ } else {
+ assert(userdata->data_copy_current_src == PBOFrameAllocator::Userdata::FROM_MALLOC);
+ resources = get_va_resources(width, height);
+ release = ReleaseVAResources(this, resources);
+ }
VAData va_data = get_va_data_for_resolution(width, height);
va_data.pic_param.coded_buf = resources.data_buffer;
CHECK_VASTATUS(va_status, "vaCreateBuffer");
VABufferDestroyer destroy_slice_param(va_dpy->va_dpy, slice_param_buffer);
- VAImage image;
- va_status = vaDeriveImage(va_dpy->va_dpy, resources.surface, &image);
- CHECK_VASTATUS(va_status, "vaDeriveImage");
+ if (userdata->data_copy_current_src == PBOFrameAllocator::Userdata::FROM_VA_API) {
+ // The pixel data is already put into the image by the caller.
+ va_status = vaUnmapBuffer(va_dpy->va_dpy, resources.image.buf);
+ CHECK_VASTATUS(va_status, "vaUnmapBuffer");
+ } else {
+ assert(userdata->data_copy_current_src == PBOFrameAllocator::Userdata::FROM_MALLOC);
- // Upload the pixel data.
- uint8_t *surface_p = nullptr;
- vaMapBuffer(va_dpy->va_dpy, image.buf, (void **)&surface_p);
+ // Upload the pixel data.
+ uint8_t *surface_p = nullptr;
+ vaMapBuffer(va_dpy->va_dpy, resources.image.buf, (void **)&surface_p);
- 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;
+ 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;
- {
- const uint8_t *src = qf.frame->data_copy + field_start;
- uint8_t *dst = (unsigned char *)surface_p + image.offsets[0];
- memcpy_with_pitch(dst, src, qf.video_format.width * 2, image.pitches[0], qf.video_format.height);
+ {
+ const uint8_t *src = qf.frame->data_copy + field_start;
+ uint8_t *dst = (unsigned char *)surface_p + resources.image.offsets[0];
+ memcpy_with_pitch(dst, src, qf.video_format.width * 2, resources.image.pitches[0], qf.video_format.height);
+ }
+
+ va_status = vaUnmapBuffer(va_dpy->va_dpy, resources.image.buf);
+ CHECK_VASTATUS(va_status, "vaUnmapBuffer");
}
- va_status = vaUnmapBuffer(va_dpy->va_dpy, image.buf);
- CHECK_VASTATUS(va_status, "vaUnmapBuffer");
- va_status = vaDestroyImage(va_dpy->va_dpy, image.image_id);
- CHECK_VASTATUS(va_status, "vaDestroyImage");
+ qf.frame->data_copy = nullptr;
+
+ // Seemingly vaPutImage() (which triggers a GPU copy) is much nicer to the
+ // CPU than vaDeriveImage() and copying directly into the GPU's buffers.
+ // Exactly why is unclear, but it seems to involve L3 cache usage when there
+ // are many high-res (1080p+) images in play.
+ va_status = vaPutImage(va_dpy->va_dpy, resources.surface, resources.image.image_id, 0, 0, width, height, 0, 0, width, height);
+ CHECK_VASTATUS(va_status, "vaPutImage");
// Finally, stick in the JPEG header.
VAEncPackedHeaderParameterBuffer header_parm;
va_status = vaEndPicture(va_dpy->va_dpy, resources.context);
CHECK_VASTATUS(va_status, "vaEndPicture");
- va_status = vaSyncSurface(va_dpy->va_dpy, resources.surface);
- CHECK_VASTATUS(va_status, "vaSyncSurface");
+ qf.resources = move(resources);
+ qf.resource_releaser = move(release);
- VACodedBufferSegment *segment;
- va_status = vaMapBuffer(va_dpy->va_dpy, resources.data_buffer, (void **)&segment);
- CHECK_VASTATUS(va_status, "vaMapBuffer");
+ lock_guard<mutex> lock(mu);
+ frames_encoding.push(move(qf));
+ any_frames_encoding.notify_all();
+}
- const char *coded_buf = reinterpret_cast<char *>(segment->buf);
- vector<uint8_t> jpeg(coded_buf, coded_buf + segment->size);
+void MJPEGEncoder::va_receiver_thread_func()
+{
+ pthread_setname_np(pthread_self(), "MJPEG_Receive");
+ for (;;) {
+ QueuedFrame qf;
+ {
+ unique_lock<mutex> lock(mu);
+ any_frames_encoding.wait(lock, [this] { return !frames_encoding.empty() || should_quit; });
+ if (should_quit) return;
+ qf = move(frames_encoding.front());
+ frames_encoding.pop();
+ }
- va_status = vaUnmapBuffer(va_dpy->va_dpy, resources.data_buffer);
- CHECK_VASTATUS(va_status, "vaUnmapBuffer");
+ // Write audio before video, since Futatabi expects it.
+ if (qf.audio.size() > 0) {
+ write_audio_packet(qf.pts, qf.card_index, qf.audio);
+ }
- return jpeg;
+ VAStatus va_status = vaSyncSurface(va_dpy->va_dpy, qf.resources.surface);
+ CHECK_VASTATUS(va_status, "vaSyncSurface");
+
+ VACodedBufferSegment *segment;
+ va_status = vaMapBuffer(va_dpy->va_dpy, qf.resources.data_buffer, (void **)&segment);
+ CHECK_VASTATUS(va_status, "vaMapBuffer");
+
+ const uint8_t *coded_buf = reinterpret_cast<uint8_t *>(segment->buf);
+ write_mjpeg_packet(qf.pts, qf.card_index, coded_buf, segment->size);
+
+ va_status = vaUnmapBuffer(va_dpy->va_dpy, qf.resources.data_buffer);
+ CHECK_VASTATUS(va_status, "vaUnmapBuffer");
+ }
}
vector<uint8_t> MJPEGEncoder::encode_jpeg_libjpeg(const QueuedFrame &qf)