44 unsigned maxWidth_,
unsigned height_,
bool canDoInterlace_)
48 , renderSettings(display_.getRenderSettings())
49 , eventDistributor(motherBoard_.getReactor().getEventDistributor())
53 , canDoInterlace(canDoInterlace_)
54 , lastRotate(motherBoard_.getCurrentTime())
57 deinterlacedFrame = std::make_unique<DeinterlacedFrame>();
58 interlacedFrame = std::make_unique<DoubledFrame>();
59 deflicker = std::make_unique<Deflicker>(lastFrames);
60 superImposedFrame = std::make_unique<SuperImposedFrame>();
69 preCalcNoise(renderSettings.
getNoise());
74 monitor3DProg.
attach(vertexShader);
75 monitor3DProg.
attach(fragmentShader);
93 "Video recording stopped, because you "
94 "changed machine or changed a video setting "
100void PostProcessor::initBuffers()
103 static constexpr std::array pos_tex = {
107 glBindBuffer(GL_ARRAY_BUFFER, vbo.
get());
108 glBufferData(GL_ARRAY_BUFFER,
sizeof(pos_tex), pos_tex.data(), GL_STATIC_DRAW);
109 glBindBuffer(GL_ARRAY_BUFFER, 0);
117unsigned PostProcessor::getLineWidth(
123void PostProcessor::executeUntil(EmuTime::param )
130using WorkBuffer = std::vector<MemBuffer<char, SSE_ALIGNMENT>>;
132 std::span<const void*> lines,
135 auto height = narrow<unsigned>(lines.size());
136 unsigned width = (height == 240) ? 320 : 640;
137 unsigned pitch = width * 4;
138 const void* linePtr =
nullptr;
139 void* work =
nullptr;
140 for (
auto i :
xrange(height)) {
141 if (linePtr == work) {
144 work = workBuffer.emplace_back(pitch).data();
146 auto* work2 =
static_cast<uint32_t*
>(work);
148 auto line = paintFrame.
getLinePtr320_240(i, std::span<uint32_t, 320>{work2, 320});
149 linePtr = line.data();
151 assert (height == 480);
152 auto line = paintFrame.
getLinePtr640_480(i, std::span<uint32_t, 640>{work2, 640});
153 linePtr = line.data();
165 VLA(
const void*, lines, height2);
167 getScaledFrame(*paintFrame, lines, workBuffer);
168 unsigned width = (height2 == 240) ? 320 : 640;
172void PostProcessor::createRegions()
176 const unsigned srcHeight = paintFrame->
getHeight();
179 unsigned g = std::gcd(srcHeight, dstHeight);
180 unsigned srcStep = srcHeight /
g;
181 unsigned dstStep = dstHeight /
g;
185 unsigned srcStartY = 0;
186 unsigned dstStartY = 0;
187 while (dstStartY < dstHeight) {
190 assert(srcStartY < srcHeight);
193 unsigned lineWidth = getLineWidth(paintFrame, srcStartY, srcStep);
194 unsigned srcEndY = srcStartY + srcStep;
195 unsigned dstEndY = dstStartY + dstStep;
196 while ((srcEndY < srcHeight) && (dstEndY < dstHeight) &&
197 (getLineWidth(paintFrame, srcEndY, srcStep) == lineWidth)) {
202 regions.emplace_back(srcStartY, srcEndY,
215 interleaveCount ^= 1;
216 if (interleaveCount) {
217 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
218 glClear(GL_COLOR_BUFFER_BIT);
225 int glow = renderSettings.
getGlow();
229 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
230 glClear(GL_COLOR_BUFFER_BIT);
238 if (scaleAlgorithm != algo) {
239 scaleAlgorithm = algo;
255 glViewport(0, 0, size.x, size.y);
256 glBindTexture(GL_TEXTURE_2D, 0);
257 auto& renderedFrame = renderedFrames[frameCounter & 1];
258 if (renderedFrame.size != size) {
259 renderedFrame.tex.bind();
260 renderedFrame.tex.setInterpolation(
true);
261 glTexImage2D(GL_TEXTURE_2D,
272 renderedFrame.fbo.push();
274 for (
auto& r : regions) {
277 auto it =
find_unguarded(textures, r.lineWidth, &TextureData::width);
278 auto* superImpose = superImposeVideoFrame
279 ? &superImposeTex :
nullptr;
280 currScaler->scaleImage(
281 it->tex, superImpose,
282 r.srcStartY, r.srcEndY, r.lineWidth,
283 r.dstStartY, r.dstEndY, size.x,
290 renderedFrame.fbo.pop();
291 renderedFrame.tex.bind();
294 glViewport(x, y, w, h);
299 float x1 = (320.0f - float(horStretch)) * (1.0f / (2.0f * 320.0f));
300 float x2 = 1.0f - x1;
306 glContext.progTex.activate();
307 glUniform4f(glContext.unifTexColor,
308 1.0f, 1.0f, 1.0f, 1.0f);
310 glUniformMatrix4fv(glContext.unifTexMvp, 1, GL_FALSE, I.
data());
312 glBindBuffer(GL_ARRAY_BUFFER, vbo.
get());
313 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0,
nullptr);
314 glEnableVertexAttribArray(0);
316 glBindBuffer(GL_ARRAY_BUFFER, stretchVBO.
get());
317 glBufferData(GL_ARRAY_BUFFER,
sizeof(tex), tex.data(), GL_STREAM_DRAW);
318 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0,
nullptr);
319 glEnableVertexAttribArray(1);
321 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
323 glDisableVertexAttribArray(1);
324 glDisableVertexAttribArray(0);
325 glBindBuffer(GL_ARRAY_BUFFER, 0);
332 std::unique_ptr<RawFrame> finishedFrame, EmuTime::param time)
335 auto delta = time - lastRotate;
336 auto middle = time + delta / 2;
344 bool doDeinterlace =
false;
345 bool doInterlace =
false;
346 bool doDeflicker =
false;
347 auto currType = finishedFrame->getField();
348 if (canDoInterlace) {
351 doDeinterlace =
true;
364 int recycleIdx = (lastFramesCount < numRequired)
367 assert(recycleIdx < 4);
368 auto recycleFrame = std::move(lastFrames[recycleIdx]);
371 std::move_backward(&lastFrames[0], &lastFrames[recycleIdx],
372 &lastFrames[recycleIdx + 1]);
373 lastFrames[0] = std::move(finishedFrame);
376 if (lastFramesCount >= numRequired) {
378 lastFramesCount = numRequired;
390 doDeinterlace =
false;
398 deinterlacedFrame->init(lastFrames[1].get(), lastFrames[0].get());
400 deinterlacedFrame->init(lastFrames[0].get(), lastFrames[1].get());
402 paintFrame = deinterlacedFrame.get();
403 }
else if (doInterlace) {
404 interlacedFrame->init(
407 paintFrame = interlacedFrame.get();
408 }
else if (doDeflicker) {
410 paintFrame = deflicker.get();
412 paintFrame = lastFrames[0].get();
414 if (superImposeVdpFrame) {
415 superImposedFrame->init(paintFrame, superImposeVdpFrame);
416 paintFrame = superImposedFrame.get();
422 recorder->
addImage(paintFrame, time);
425 "Recording stopped with error: ",
433 std::unique_ptr<RawFrame> reuseFrame = [&] {
434 if (canDoInterlace) {
435 if (!recycleFrame) [[unlikely]] {
436 recycleFrame = std::make_unique<RawFrame>(maxWidth, height);
438 return std::move(recycleFrame);
440 return std::move(lastFrames[0]);
454 auto& noiseSetting = renderSettings.getNoiseSetting();
455 auto& horizontalStretch = renderSettings.getHorizontalStretchSetting();
456 if (&
setting == &noiseSetting) {
457 preCalcNoise(noiseSetting.getFloat());
458 }
else if (&
setting == &horizontalStretch) {
459 preCalcMonitor3D(horizontalStretch.getFloat());
463void PostProcessor::uploadFrame()
467 const unsigned srcHeight = paintFrame->
getHeight();
468 for (
auto& r : regions) {
473 uploadBlock(narrow<unsigned>(std::max(0, narrow<int>(r.srcStartY) - before)),
474 std::min(srcHeight, r.srcEndY + after),
478 if (superImposeVideoFrame) {
479 int w = narrow<GLsizei>(superImposeVideoFrame->
getWidth());
480 int h = narrow<GLsizei>(superImposeVideoFrame->
getHeight());
481 if (superImposeTex.
getWidth() != w ||
483 superImposeTex.
resize(w, h);
486 superImposeTex.
bind();
496 const_cast<RawFrame*
>(superImposeVideoFrame)->getLineDirect(0).data());
500void PostProcessor::uploadBlock(
501 unsigned srcStartY,
unsigned srcEndY,
unsigned lineWidth)
504 auto it =
ranges::find(textures, lineWidth, &TextureData::width);
505 if (it ==
end(textures)) {
506 TextureData textureData;
508 textureData.tex.resize(narrow<GLsizei>(lineWidth),
509 narrow<GLsizei>(height * 2));
510 textureData.pbo.setImage(lineWidth, height * 2);
511 textures.push_back(std::move(textureData));
512 it =
end(textures) - 1;
522 uint32_t* mapped = pbo.mapWrite();
523 for (
auto y :
xrange(srcStartY, srcEndY)) {
524 auto* dest = mapped + y * size_t(lineWidth);
525 auto line = paintFrame->
getLine(narrow<int>(y), std::span{dest, lineWidth});
526 if (line.data() != dest) {
531#if defined(__APPLE__)
535 if (lineWidth == 1 && srcStartY != 0 && srcStartY % 16 == 0) {
543 narrow<GLint>(srcStartY),
544 narrow<GLint>(lineWidth),
545 narrow<GLint>(srcEndY - srcStartY),
548 pbo.getOffset(0, srcStartY));
553 currScaler->uploadBlock(srcStartY, srcEndY, lineWidth, *paintFrame);
557void PostProcessor::drawGlow(
int glow)
559 if ((glow == 0) || !storedFrame)
return;
562 glContext.progTex.activate();
564 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
565 renderedFrames[(frameCounter & 1) ^ 1].tex.bind();
566 glUniform4f(glContext.unifTexColor,
567 1.0f, 1.0f, 1.0f, narrow<float>(glow) * (31.0f / 3200.0f));
569 glUniformMatrix4fv(glContext.unifTexMvp, 1, GL_FALSE, I.
data());
571 glBindBuffer(GL_ARRAY_BUFFER, vbo.
get());
573 const vec2* offset =
nullptr;
574 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, offset);
576 glEnableVertexAttribArray(0);
578 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, offset);
579 glEnableVertexAttribArray(1);
581 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
583 glDisableVertexAttribArray(1);
584 glDisableVertexAttribArray(0);
585 glBindBuffer(GL_ARRAY_BUFFER, 0);
589void PostProcessor::preCalcNoise(
float factor)
591 std::array<uint8_t, 256 * 256> buf1;
592 std::array<uint8_t, 256 * 256> buf2;
594 std::normal_distribution<float> distribution(0.0f, 1.0f);
595 for (
auto i :
xrange(256 * 256)) {
596 float r = distribution(generator);
597 int s = std::clamp(
int(roundf(r * factor)), -255, 255);
598 buf1[i] = narrow<uint8_t>((s > 0) ? s : 0);
599 buf2[i] = narrow<uint8_t>((s < 0) ? -s : 0);
604 noiseTextureA.
bind();
615#if OPENGL_VERSION >= OPENGL_3_3
616 GLint swizzleMask1[] = {GL_RED, GL_RED, GL_RED, GL_ONE};
617 glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask1);
620 noiseTextureB.
bind();
631#if OPENGL_VERSION >= OPENGL_3_3
632 GLint swizzleMask2[] = {GL_RED, GL_RED, GL_RED, GL_ONE};
633 glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask2);
637void PostProcessor::drawNoise()
639 if (renderSettings.
getNoise() == 0.0f)
return;
643 static constexpr std::array pos = {
653 vec2 noise(noiseX, noiseY);
654 const std::array tex = {
655 noise +
vec2(0.0f, 1.875f),
656 noise +
vec2(2.0f, 1.875f),
657 noise +
vec2(2.0f, 0.0f ),
658 noise +
vec2(0.0f, 0.0f ),
662 glContext.progTex.activate();
665 glBlendFunc(GL_ONE, GL_ONE);
666 glUniform4f(glContext.unifTexColor, 1.0f, 1.0f, 1.0f, 1.0f);
668 glUniformMatrix4fv(glContext.unifTexMvp, 1, GL_FALSE, I.
data());
670 unsigned seq = frameCounter & 7;
671 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, pos[seq].data());
672 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, tex.data());
673 glEnableVertexAttribArray(0);
674 glEnableVertexAttribArray(1);
676 noiseTextureA.
bind();
677 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
678 glBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
679 noiseTextureB.
bind();
680 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
682 glDisableVertexAttribArray(1);
683 glDisableVertexAttribArray(0);
684 glBlendEquation(GL_FUNC_ADD);
688static constexpr int GRID_SIZE = 16;
689static constexpr int GRID_SIZE1 = GRID_SIZE + 1;
690static constexpr int NUM_INDICES = (GRID_SIZE1 * 2 + 2) * GRID_SIZE - 2;
697void PostProcessor::preCalcMonitor3D(
float width)
700 std::array<std::array<Vertex, GRID_SIZE1>, GRID_SIZE1> vertices;
702 constexpr float GRID_SIZE2 = float(GRID_SIZE) * 0.5f;
703 float s = width * (1.0f / 320.0f);
704 float b = (320.0f - width) * (1.0f / (2.0f * 320.0f));
706 for (
auto sx :
xrange(GRID_SIZE1)) {
707 for (
auto sy :
xrange(GRID_SIZE1)) {
708 Vertex& v = vertices[sx][sy];
709 float x = (narrow<float>(sx) - GRID_SIZE2) / GRID_SIZE2;
710 float y = (narrow<float>(sy) - GRID_SIZE2) / GRID_SIZE2;
712 v.
position =
vec3(x, y, (x * x + y * y) * (1.0f / -12.0f));
714 v.
tex =
vec2((
float(sx) / GRID_SIZE) * s + b,
715 float(sy) / GRID_SIZE);
720 std::array<uint16_t, NUM_INDICES> indices;
722 uint16_t* ind = indices.data();
723 for (
auto y :
xrange(GRID_SIZE)) {
724 for (
auto x :
xrange(GRID_SIZE1)) {
725 *ind++ = narrow<uint16_t>((y + 0) * GRID_SIZE1 + x);
726 *ind++ = narrow<uint16_t>((y + 1) * GRID_SIZE1 + x);
731 assert((ind - indices.data()) == NUM_INDICES + 2);
732 ind = indices.data();
733 repeat(GRID_SIZE - 1, [&] {
734 ind += 2 * GRID_SIZE1;
742 glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer.
get());
743 glBufferData(GL_ARRAY_BUFFER,
sizeof(vertices), vertices.data(),
745 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBuffer.
get());
746 glBufferData(GL_ELEMENT_ARRAY_BUFFER,
sizeof(indices), indices.data(),
748 glBindBuffer(GL_ARRAY_BUFFER, 0);
749 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
758 mat4 mvp = proj * tran * rotX * scal;
764 1, GL_FALSE, mvp.
data());
766 1, GL_FALSE, normal.
data());
769void PostProcessor::drawMonitor3D()
773 char* base =
nullptr;
774 glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer.
get());
775 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBuffer.
get());
776 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE,
sizeof(Vertex),
778 glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE,
sizeof(Vertex),
779 base +
sizeof(
vec3));
780 glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE,
sizeof(Vertex),
781 base +
sizeof(
vec3) +
sizeof(
vec3));
782 glEnableVertexAttribArray(0);
783 glEnableVertexAttribArray(1);
784 glEnableVertexAttribArray(2);
786 glDrawElements(GL_TRIANGLE_STRIP, NUM_INDICES, GL_UNSIGNED_SHORT,
nullptr);
787 glDisableVertexAttribArray(2);
788 glDisableVertexAttribArray(1);
789 glDisableVertexAttribArray(0);
791 glBindBuffer(GL_ARRAY_BUFFER, 0);
792 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
GLsizei getHeight() const
void resize(GLsizei width, GLsizei height)
Wrapper around an OpenGL fragment shader: a program executed on the GPU that computes the colors of p...
void activate() const
Makes this program the active shader program.
void attach(const Shader &shader)
Adds a given shader to this program.
void link()
Links all attached shaders together into one program.
void bindAttribLocation(unsigned index, const char *name)
Bind the given name for a vertex shader attribute to the given location.
GLint getUniformLocation(const char *name) const
Gets a reference to a uniform variable declared in the shader source.
void setInterpolation(bool interpolation)
Enable/disable bilinear interpolation for this texture.
void bind()
Makes this texture the active GL texture.
Wrapper around an OpenGL vertex shader: a program executed on the GPU that computes per-vertex stuff.
constexpr const T * data() const
void addImage(FrameSource *frame, EmuTime::param time)
void printWarning(std::string_view message)
Represents the output window/screen of openMSX.
CliComm & getCliComm() const
void distributeEvent(Event &&event)
Schedule the given event for delivery.
Interface for getting lines from a video frame.
std::span< const Pixel > getLine(int line, std::span< Pixel > buf) const
Gets a pointer to the pixels of the given line number.
virtual unsigned getLineWidth(unsigned line) const =0
Gets the number of display pixels on the given line.
std::span< const Pixel, 320 > getLinePtr320_240(unsigned line, std::span< Pixel, 320 > buf) const
Get a pointer to a given line in this frame, the frame is scaled to 320x240 pixels.
unsigned getWidth() const
Get the width of (all) lines in this frame.
std::span< const Pixel, 640 > getLinePtr640_480(unsigned line, std::span< Pixel, 640 > buf) const
Get a pointer to a given line in this frame, the frame is scaled to 640x480 pixels.
unsigned getHeight() const
Gets the number of lines in this frame.
@ FIELD_NONINTERLACED
Interlacing is off for this frame.
@ FIELD_ODD
Interlacing is on and this is an odd frame.
A frame buffer where pixels can be written to.
gl::ivec2 getLogicalSize() const
gl::ivec2 getViewOffset() const
gl::ivec2 getViewSize() const
int getLogicalHeight() const
std::unique_ptr< RawFrame > rotateFrames(std::unique_ptr< RawFrame > finishedFrame, EmuTime::param time)
Sets up the "abcdFrame" variables for a new frame.
PostProcessor(MSXMotherBoard &motherBoard, Display &display, OutputSurface &screen, const std::string &videoSource, unsigned maxWidth, unsigned height, bool canDoInterlace)
void takeRawScreenShot(unsigned height, const std::string &filename) override
Create a raw (=non-post-processed) screenshot.
void paint(OutputSurface &output) override
Paint this layer.
~PostProcessor() override
bool getDeflicker() const
bool getDeinterlace() const
bool getInterleaveBlackFrame() const
Is black frame interleaving enabled?
FloatSetting & getNoiseSetting()
The amount of noise to add to the frame.
float getHorizontalStretch() const
DisplayDeform getDisplayDeform() const
FloatSetting & getHorizontalStretchSetting()
Amount of horizontal stretch.
ScaleAlgorithm getScaleAlgorithm() const
Every class that wants to get scheduled at some point must inherit from this class.
void setSyncPoint(EmuTime::param timestamp)
void detach(Observer< T > &observer)
void attach(Observer< T > &observer)
int getVideoSource() const
Returns the ID for this VideoLayer.
int getVideoSourceSetting() const
void update(const Setting &setting) noexcept override
mat4 rotateX(float angle)
matMxN< 3, 3, float > mat3
std::optional< Context > context
constexpr mat4 frustum(float left, float right, float bottom, float top, float nearVal, float farVal)
vecN< N, T > normalize(const vecN< N, T > &x)
constexpr mat4 translate(const vec3 &xyz)
constexpr mat4 scale(const vec3 &xyz)
void format(SectorAccessibleDisk &disk, MSXBootSectorType bootType)
Format the given disk (= a single partition).
std::unique_ptr< GLScaler > createScaler(RenderSettings &renderSettings)
Instantiates a Scaler.
void saveRGBA(size_t width, std::span< const void * > rowPointers, const std::string &filename)
This file implemented 3 utility functions:
std::vector< MemBuffer< char, SSE_ALIGNMENT > > WorkBuffer
auto copy(InputRange &&range, OutputIter out)
auto find(InputRange &&range, const T &value)
auto & global_urng()
Return reference to a (shared) global random number generator.
float random_float(float from, float upto)
Return a random float in the range [from, upto) (note: half-open interval).
ITER find_unguarded(ITER first, ITER last, const VAL &val, Proj proj={})
Faster alternative to 'find' when it's guaranteed that the value will be found (if not the behavior i...
auto max_value(InputIterator first, InputIterator last, Proj proj={})
#define VLA(TYPE, NAME, LENGTH)
constexpr void repeat(T n, Op op)
Repeat the given operation 'op' 'n' times.
constexpr auto xrange(T e)
constexpr auto end(const zstring_view &x)