From 1db0c8bac3fd4f09800f8ede336858cd4c10fff3 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Thu, 5 Nov 2026 15:22:35 +0100 Subject: [PATCH] fix: honor video rotation metadata and non-square pixels in playback --- docs/guide/media/media-files.md | 2 + .../src/main/cpp/include/media/VideoDecoder.h | 14 +- .../main/cpp/include/media/VideoGeometry.h | 52 ++++ .../src/main/cpp/src/media/MediaPacer.cpp | 3 +- .../src/main/cpp/src/media/MediaReader.cpp | 5 +- .../src/main/cpp/src/media/VideoDecoder.cpp | 29 +- .../src/main/cpp/src/media/VideoGeometry.cpp | 144 +++++++++ .../onvoid/webrtc/media/player/MediaInfo.java | 12 +- .../onvoid/webrtc/media/player/TestMedia.java | 134 ++++++++ .../media/player/VideoGeometryTest.java | 294 ++++++++++++++++++ 10 files changed, 672 insertions(+), 17 deletions(-) create mode 100644 webrtc-media/src/main/cpp/include/media/VideoGeometry.h create mode 100644 webrtc-media/src/main/cpp/src/media/VideoGeometry.cpp create mode 100644 webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/VideoGeometryTest.java diff --git a/docs/guide/media/media-files.md b/docs/guide/media/media-files.md index 0fc534d01..17d014a66 100644 --- a/docs/guide/media/media-files.md +++ b/docs/guide/media/media-files.md @@ -121,6 +121,8 @@ try (MediaReader reader = new MediaReader(Path.of("movie.mp4"))) { } ``` +The width and height are those of the video as it is shown, which can differ from what the file stores. A phone stores a portrait video sideways with a rotation next to it: its frames keep the stored size and carry the rotation in `VideoFrame.rotation`, which the video views and the receiving peers apply, and `MediaInfo` reports the upright size. A video of pixels that are not square, such as 720x576 PAL with 16:15 pixels, is scaled to square ones while it plays, to 768x576 in that case, because WebRTC has no way to describe them. One side grows so that no detail is lost, at the price of one copy of each picture. Only quarter turns are applied: a video that is to be shown mirrored, or turned by another angle, plays as it is stored. So does one whose pixels are said to be more than four times as wide as high, or the other way round. + A `MediaFileSource` already has this, so there is no need to open the file twice: ```java diff --git a/webrtc-media/src/main/cpp/include/media/VideoDecoder.h b/webrtc-media/src/main/cpp/include/media/VideoDecoder.h index 667a83dab..9c3a64d38 100644 --- a/webrtc-media/src/main/cpp/include/media/VideoDecoder.h +++ b/webrtc-media/src/main/cpp/include/media/VideoDecoder.h @@ -17,6 +17,8 @@ #ifndef WEBRTC_JAVA_MEDIA_VIDEO_DECODER_H_ #define WEBRTC_JAVA_MEDIA_VIDEO_DECODER_H_ +#include "media/VideoGeometry.h" + extern "C" { #include #include @@ -37,7 +39,9 @@ namespace ffmpeg // already, and such a frame is handed on untouched, so the decoded picture // reaches the encoder without a single copy. Anything else is converted // with swscale first, which costs one copy and is the price of the format - // rather than of this design. + // rather than of this design. So is a picture of pixels that are not + // square, which WebRTC has no way to describe, and which is scaled to + // square ones on the way. A frame keeps the display matrix of its picture. // // Asked to, it decodes H.264, HEVC, VP9 and AV1 on the media engine or GPU // instead. @@ -170,9 +174,11 @@ namespace ffmpeg void DropKeptPackets(); void DropPending(); - // Converts a decoded frame to I420. The returned frame is a new - // reference the caller owns. - int ConvertToI420(const AVFrame * source, AVFrame ** result); + // Converts the pixels of a frame to I420, at the given size. The + // returned frame is a new reference the caller owns, with the + // display matrix of the decoded picture, which is the source + // itself unless that was brought back from the hardware. + int ConvertToI420(const AVFrame * source, const AVFrame * picture, VideoSize size, AVFrame ** result); // A new I420 frame of the given size, whose buffer comes from a // pool, so that the picture lands in memory that is already diff --git a/webrtc-media/src/main/cpp/include/media/VideoGeometry.h b/webrtc-media/src/main/cpp/include/media/VideoGeometry.h new file mode 100644 index 000000000..3a812e21d --- /dev/null +++ b/webrtc-media/src/main/cpp/include/media/VideoGeometry.h @@ -0,0 +1,52 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WEBRTC_JAVA_MEDIA_VIDEO_GEOMETRY_H_ +#define WEBRTC_JAVA_MEDIA_VIDEO_GEOMETRY_H_ + +extern "C" { +#include +#include +} + +namespace ffmpeg +{ + struct VideoSize + { + int width; + int height; + }; + + // How far a picture has to be turned clockwise to stand upright, as its + // display matrix says: 0, 90, 180 or 270. WebRTC carries a quarter turn + // and nothing else, so a matrix that mirrors the picture or turns it by + // another angle counts as 0: read as a turn, a mirrored picture would + // end up on its head. + int GetFrameRotation(const AVFrame * frame); + + // The size that shows the pixels of a picture of the stream as squares, + // which is all WebRTC knows. It is the size of the picture itself if its + // pixels are square. Otherwise one side grows, so that no detail is lost, + // to an even number of pixels. A ratio beyond 4:1 is taken for a broken + // one and ignored, as it would only make for a huge picture. + VideoSize GetSquarePixelSize(const AVStream * stream, const AVFrame * frame); + + // The size of the video of a stream as it is shown, with square pixels + // and turned upright. + VideoSize GetDisplaySize(const AVStream * stream); +} + +#endif diff --git a/webrtc-media/src/main/cpp/src/media/MediaPacer.cpp b/webrtc-media/src/main/cpp/src/media/MediaPacer.cpp index ad879afef..7cb523d74 100644 --- a/webrtc-media/src/main/cpp/src/media/MediaPacer.cpp +++ b/webrtc-media/src/main/cpp/src/media/MediaPacer.cpp @@ -17,6 +17,7 @@ #include "media/MediaPacer.h" #include "media/AudioDecoder.h" #include "media/PlaybackProbe.h" +#include "media/VideoGeometry.h" #include #include @@ -495,7 +496,7 @@ namespace ffmpeg pushed.stride_y = frame->linesize[0]; pushed.stride_u = frame->linesize[1]; pushed.stride_v = frame->linesize[2]; - pushed.rotation = 0; + pushed.rotation = GetFrameRotation(frame); pushed.timestamp_us = mapped_us; pushed.release = ReleaseVideoFrame; pushed.opaque = frame; diff --git a/webrtc-media/src/main/cpp/src/media/MediaReader.cpp b/webrtc-media/src/main/cpp/src/media/MediaReader.cpp index 30b678c71..e1a2a1608 100644 --- a/webrtc-media/src/main/cpp/src/media/MediaReader.cpp +++ b/webrtc-media/src/main/cpp/src/media/MediaReader.cpp @@ -16,6 +16,7 @@ #include "media/MediaReader.h" #include "media/AllocationFault.h" +#include "media/VideoGeometry.h" #include #include @@ -224,14 +225,14 @@ namespace ffmpeg { const AVStream * stream = GetVideoStream(); - return stream != nullptr ? stream->codecpar->width : 0; + return stream != nullptr ? GetDisplaySize(stream).width : 0; } int MediaReader::GetVideoHeight() const { const AVStream * stream = GetVideoStream(); - return stream != nullptr ? stream->codecpar->height : 0; + return stream != nullptr ? GetDisplaySize(stream).height : 0; } double MediaReader::GetFrameRate() const diff --git a/webrtc-media/src/main/cpp/src/media/VideoDecoder.cpp b/webrtc-media/src/main/cpp/src/media/VideoDecoder.cpp index 6d32c7894..41bd76b6b 100644 --- a/webrtc-media/src/main/cpp/src/media/VideoDecoder.cpp +++ b/webrtc-media/src/main/cpp/src/media/VideoDecoder.cpp @@ -558,6 +558,8 @@ namespace ffmpeg return 0; } + const VideoSize size = GetSquarePixelSize(stream_, decoded_); + if (hardware_frame) { // The picture is in the memory of the hardware decoder. Bring it // into system memory, as NV12, and convert it like any other @@ -588,12 +590,13 @@ namespace ffmpeg transfer_height_ = frames->height; } - result = ConvertToI420(transferred_, frame); + // The transferred frame has the pixels and nothing else. + result = ConvertToI420(transferred_, decoded_, size, frame); } av_frame_unref(decoded_); } - else if (IsI420(decoded_->format)) { + else if (IsI420(decoded_->format) && size.width == decoded_->width && size.height == decoded_->height) { // Hand over a reference to the decoded picture rather than a copy // of it. The caller drops that reference once WebRTC is done. AVFrame * reference = av_frame_alloc(); @@ -618,7 +621,7 @@ namespace ffmpeg result = 0; } else { - result = ConvertToI420(decoded_, frame); + result = ConvertToI420(decoded_, decoded_, size, frame); av_frame_unref(decoded_); } @@ -777,12 +780,12 @@ namespace ffmpeg return hardware_.load(); } - int VideoDecoder::ConvertToI420(const AVFrame * source, AVFrame ** result) + int VideoDecoder::ConvertToI420(const AVFrame * source, const AVFrame * picture, VideoSize size, AVFrame ** result) { sws_context_ = sws_getCachedContext(sws_context_, source->width, source->height, static_cast(source->format), - source->width, source->height, AV_PIX_FMT_YUV420P, + size.width, size.height, AV_PIX_FMT_YUV420P, SWS_BILINEAR, nullptr, nullptr, nullptr); if (sws_context_ == nullptr) { @@ -791,7 +794,7 @@ namespace ffmpeg AVFrame * converted = nullptr; - int error = AllocateI420(source->width, source->height, &converted); + int error = AllocateI420(size.width, size.height, &converted); if (error < 0) { return error; @@ -806,6 +809,20 @@ namespace ffmpeg return error; } + // The rotation goes on with the frame, as it does on a decoded picture + // that is handed on as it is. + const AVFrameSideData * matrix = av_frame_get_side_data(picture, AV_FRAME_DATA_DISPLAYMATRIX); + + if (matrix != nullptr) { + error = av_frame_side_data_clone(&converted->side_data, &converted->nb_side_data, matrix, 0); + + if (error < 0) { + av_frame_free(&converted); + + return error; + } + } + *result = converted; return 0; diff --git a/webrtc-media/src/main/cpp/src/media/VideoGeometry.cpp b/webrtc-media/src/main/cpp/src/media/VideoGeometry.cpp new file mode 100644 index 000000000..c9e674c81 --- /dev/null +++ b/webrtc-media/src/main/cpp/src/media/VideoGeometry.cpp @@ -0,0 +1,144 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "media/VideoGeometry.h" + +extern "C" { +#include +#include +} + +#include +#include +#include +#include + +namespace +{ + // The size of a display matrix. + constexpr size_t kMatrixSize = 9 * sizeof(int32_t); + + // How far a pixel may be from square, either way. + constexpr int64_t kMaxPixelAspect = 4; + + // How far from a quarter turn an angle may be, in degrees, and still count + // as one: the matrix holds fixed-point numbers. + constexpr double kAngleTolerance = 2.0; + + int GetRotation(const uint8_t * data, size_t size) + { + if (data == nullptr || size < kMatrixSize) { + return 0; + } + + const int32_t * matrix = reinterpret_cast(data); + + // A negative determinant is a mirror image. + const int64_t determinant = static_cast(matrix[0]) * matrix[4] + - static_cast(matrix[1]) * matrix[3]; + + if (determinant <= 0) { + return 0; + } + + // Counter-clockwise, in the range of -180 to 180. + const double angle = av_display_rotation_get(matrix); + + if (std::isnan(angle)) { + return 0; + } + + const long quarters = std::lround(angle / 90.0); + + if (std::fabs(angle - quarters * 90.0) > kAngleTolerance) { + return 0; + } + + return static_cast((4 - quarters % 4) % 4) * 90; + } + + bool IsNonSquare(AVRational ratio) + { + return ratio.num > 0 && ratio.den > 0 && ratio.num != ratio.den; + } + + // The container goes first, as it does everywhere in FFmpeg: that is where + // a wrong value in the stream gets corrected. But where it has 1:1, that + // need not be a statement: Matroska gives it to any track without a display + // size, whatever the stream says. + AVRational GetPixelAspect(const AVStream * stream, const AVFrame * frame) + { + if (IsNonSquare(stream->sample_aspect_ratio)) { + return stream->sample_aspect_ratio; + } + + return frame != nullptr ? frame->sample_aspect_ratio : stream->codecpar->sample_aspect_ratio; + } + + // Rounded to the nearest even number, for the chroma planes of I420. + int ScaleToEven(int size, int64_t num, int64_t den) + { + return static_cast(2 * av_rescale(size, num, 2 * den)); + } + + ffmpeg::VideoSize ToSquarePixels(int width, int height, AVRational aspect) + { + const int64_t num = aspect.num; + const int64_t den = aspect.den; + + if (!IsNonSquare(aspect) || num > kMaxPixelAspect * den || den > kMaxPixelAspect * num) { + return { width, height }; + } + + if (num > den) { + return { ScaleToEven(width, num, den), height }; + } + + return { width, ScaleToEven(height, den, num) }; + } +} + +namespace ffmpeg +{ + int GetFrameRotation(const AVFrame * frame) + { + const AVFrameSideData * matrix = av_frame_get_side_data(frame, AV_FRAME_DATA_DISPLAYMATRIX); + + return matrix != nullptr ? GetRotation(matrix->data, matrix->size) : 0; + } + + VideoSize GetSquarePixelSize(const AVStream * stream, const AVFrame * frame) + { + return ToSquarePixels(frame->width, frame->height, GetPixelAspect(stream, frame)); + } + + VideoSize GetDisplaySize(const AVStream * stream) + { + const AVCodecParameters * parameters = stream->codecpar; + + VideoSize size = ToSquarePixels(parameters->width, parameters->height, + GetPixelAspect(stream, nullptr)); + + const AVPacketSideData * matrix = av_packet_side_data_get(parameters->coded_side_data, + parameters->nb_coded_side_data, AV_PKT_DATA_DISPLAYMATRIX); + + if (matrix != nullptr && GetRotation(matrix->data, matrix->size) % 180 != 0) { + std::swap(size.width, size.height); + } + + return size; + } +} diff --git a/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaInfo.java b/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaInfo.java index b9d42269e..9edd809f1 100644 --- a/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaInfo.java +++ b/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaInfo.java @@ -31,10 +31,10 @@ public class MediaInfo { /** How long the source runs in microseconds, or 0 if it is not known. */ private final long durationUs; - /** The width of the video in pixels, or 0 if there is no video. */ + /** The width of the video as it is shown, or 0 if there is no video. */ private final int videoWidth; - /** The height of the video in pixels, or 0 if there is no video. */ + /** The height of the video as it is shown, or 0 if there is no video. */ private final int videoHeight; /** The frame rate of the video, or 0 if there is no video. */ @@ -99,7 +99,9 @@ public boolean hasVideo() { } /** - * Returns the width of the video in pixels. + * Returns the width of the video as it is shown, in square pixels and + * turned upright. A video stored sideways reports its stored height here, + * while its frames keep their stored size and carry the rotation. * * @return The width, or {@code 0} if there is no video. */ @@ -108,7 +110,9 @@ public int getVideoWidth() { } /** - * Returns the height of the video in pixels. + * Returns the height of the video as it is shown, in square pixels and + * turned upright. A video stored sideways reports its stored width here, + * while its frames keep their stored size and carry the rotation. * * @return The height, or {@code 0} if there is no video. */ diff --git a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/TestMedia.java b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/TestMedia.java index bd6de7b35..4d0af5f85 100644 --- a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/TestMedia.java +++ b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/TestMedia.java @@ -264,6 +264,105 @@ static Path shiftedMatroska(Path directory, Path source, long videoStartMs, matroska(content.tracks, frames, content.videoTrack, endMs)); } + /** + * Copies a Matroska file and has the copy say that its video is shown + * turned clockwise by the given angle, which is what makes FFmpeg give it + * a display matrix. + * + * @param directory Where to write the file. + * @param source The file to copy. + * @param degrees The clockwise angle. + * + * @return The file written. + */ + static Path rotatedMatroska(Path directory, Path source, double degrees) + throws IOException { + return videoSettingsMatroska(directory, source, projection(0, -degrees)); + } + + /** + * Copies a Matroska file and has the copy say that its video is shown + * mirrored from left to right. + * + * @param directory Where to write the file. + * @param source The file to copy. + * + * @return The file written. + */ + static Path mirroredMatroska(Path directory, Path source) throws IOException { + return videoSettingsMatroska(directory, source, projection(180, 0)); + } + + /** + * Copies a Matroska file and has the copy give a display size, from which + * the shape of a pixel follows: the display width over the display height, + * against the width over the height of the picture. + * + * @param directory Where to write the file. + * @param source The file to copy. + * @param width The display width. + * @param height The display height. + * + * @return The file written. + */ + static Path displaySizeMatroska(Path directory, Path source, int width, int height) + throws IOException { + ByteArrayOutputStream settings = new ByteArrayOutputStream(); + + writeBytes(settings, ebmlUInt(0x54B0, width)); + writeBytes(settings, ebmlUInt(0x54BA, height)); + + return videoSettingsMatroska(directory, source, settings.toByteArray()); + } + + /** + * Copies a Matroska file of JFIF pictures, as MJPEG holds them, with the + * given pixel density in each of them. That makes the shape of a pixel + * something only the decoder knows, and the frames that come out of it. + * + * @param directory Where to write the file. + * @param source The file to copy. + * @param x The horizontal density. + * @param y The vertical density. + * + * @return The file written. + */ + static Path pixelDensityMatroska(Path directory, Path source, int x, int y) + throws IOException { + MatroskaContent content = new MatroskaContent(Files.readAllBytes(source)); + + for (Frame frame : content.frames) { + if (frame.track == content.videoTrack) { + // The start of the picture, the marker of its APP0 segment and + // the length of that, its name, a version and the unit. + ByteBuffer.wrap(frame.data, 14, 4).putShort((short) x).putShort((short) y); + } + } + + return Files.write(directory.resolve("density.mkv"), + matroska(content.tracks, content.frames, content.videoTrack, -1)); + } + + /** + * Copies a Matroska file with further elements in the settings of its + * video track. + */ + private static Path videoSettingsMatroska(Path directory, Path source, byte[] settings) + throws IOException { + MatroskaContent content = new MatroskaContent(Files.readAllBytes(source)); + + return Files.write(directory.resolve("video-settings.mkv"), + matroska(content.tracksWith(settings), content.frames, content.videoTrack, -1)); + } + + /** The Projection of a flat picture, in the angles Matroska gives it. */ + private static byte[] projection(double yaw, double roll) { + return ebml(0x7670, + ebmlUInt(0x7671, 0), // ProjectionType, rectangular + ebml(0x7673, ByteBuffer.allocate(8).putDouble(yaw).array()), + ebml(0x7675, ByteBuffer.allocate(8).putDouble(roll).array())); + } + /** * Copies a Matroska file holding a video and an audio track so that its * video comes late. The audio is repeated until it runs for the given @@ -740,6 +839,7 @@ private static final class MatroskaContent { int videoTrack; private final ByteBuffer data; + private int tracksStart; private long clusterTime; private long trackNumber; @@ -766,6 +866,7 @@ private void read(int end) { break; case 0x1654AE6B: // Tracks tracks = Arrays.copyOfRange(data.array(), start, stop); + tracksStart = start; read(stop); break; case 0xD7: // TrackNumber @@ -791,6 +892,39 @@ private void read(int end) { } } + /** The tracks, with the given elements added to the video settings. */ + byte[] tracksWith(byte[] settings) { + data.position(tracksStart); + + return copyWith(tracksStart + tracks.length, settings); + } + + private byte[] copyWith(int end, byte[] settings) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + while (data.position() < end) { + int element = data.position(); + int id = readId(); + long size = readSize(); + int start = data.position(); + int stop = (int) (start + size); + + if (id == 0xAE) { // TrackEntry + writeBytes(out, ebml(id, copyWith(stop, settings))); + } + else if (id == 0xE0) { // Video + writeBytes(out, ebml(id, Arrays.copyOfRange(data.array(), start, stop), settings)); + } + else { + out.write(data.array(), element, stop - element); + } + + data.position(stop); + } + + return out.toByteArray(); + } + private void readBlock(int end, boolean simple) { int track = data.get() & 0x7F; long time = clusterTime + data.getShort(); diff --git a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/VideoGeometryTest.java b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/VideoGeometryTest.java new file mode 100644 index 000000000..33e33dd46 --- /dev/null +++ b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/VideoGeometryTest.java @@ -0,0 +1,294 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dev.onvoid.webrtc.media.player; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.ByteBuffer; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +import dev.onvoid.webrtc.PeerConnectionFactory; +import dev.onvoid.webrtc.media.audio.AudioDeviceModule; +import dev.onvoid.webrtc.media.audio.AudioLayer; +import dev.onvoid.webrtc.media.video.I420Buffer; +import dev.onvoid.webrtc.media.video.VideoFrame; +import dev.onvoid.webrtc.media.video.VideoTrack; +import dev.onvoid.webrtc.media.video.VideoTrackSink; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; + +/** + * Tests that a video is shown the way its file says, whatever the shape in + * which the pictures are stored: turned by a display matrix, and with pixels + * that are not square. + * + * @author Alex Andres + */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@Execution(ExecutionMode.SAME_THREAD) +class VideoGeometryTest { + + /** 320x240 H.264 in yuv420p, whose frames are handed on as they are. */ + private static final String H264 = "/media-test-h264.mkv"; + + /** 320x240 H.264 in yuv444p, whose frames are converted. */ + private static final String H264_444 = "/media-test-h264-444.mkv"; + + /** 160x120 MJPEG in JFIF pictures. */ + private static final String MJPEG = "/media-test-coarse.mkv"; + + private AudioDeviceModule audioModule; + private PeerConnectionFactory factory; + + @TempDir + Path directory; + + + @BeforeAll + void initFactory() { + audioModule = new AudioDeviceModule(AudioLayer.kDummyAudio); + factory = new PeerConnectionFactory(audioModule); + } + + @AfterAll + void disposeFactory() { + factory.dispose(); + audioModule.dispose(); + } + + @Test + void plainVideoStaysAsItIs() throws Exception { + assertPlays(path(H264), false, 320, 240, 0, 320, 240); + } + + @Test + void quarterTurnsReachTheSink() throws Exception { + Path source = path(H264); + + assertPlays(TestMedia.rotatedMatroska(directory, source, 90), false, 320, 240, 90, 240, 320); + assertPlays(TestMedia.rotatedMatroska(directory, source, 180), false, 320, 240, 180, 320, 240); + assertPlays(TestMedia.rotatedMatroska(directory, source, 270), false, 320, 240, 270, 240, 320); + } + + @Test + void convertedFramesKeepTheirRotation() throws Exception { + Path file = TestMedia.rotatedMatroska(directory, path(H264_444), 90); + + assertPlays(file, false, 320, 240, 90, 240, 320); + } + + @Test + void otherAnglesPlayAsStored() throws Exception { + Path file = TestMedia.rotatedMatroska(directory, path(H264), 45); + + assertPlays(file, false, 320, 240, 0, 320, 240); + } + + // A mirror image is a half turn to the matrix. Read as one, it would play + // on its head. + @Test + void mirroredVideoIsNotTurned() throws Exception { + Path file = TestMedia.mirroredMatroska(directory, path(H264)); + + assertPlays(file, false, 320, 240, 0, 320, 240); + } + + // H.264 replaces the ratio of the container with that of its own headers, + // which here say nothing, so the frames do not have it. + @Test + void containerRatioCounts() throws Exception { + // 16:15, as in PAL, but for a picture of 320x240. + Path file = TestMedia.displaySizeMatroska(directory, path(H264), 1024, 720); + + assertPlays(file, false, 342, 240, 0, 342, 240); + } + + @Test + void narrowPixelsGrowTheHeight() throws Exception { + // 4:5. + Path file = TestMedia.displaySizeMatroska(directory, path(H264), 320, 300); + + assertPlays(file, false, 320, 300, 0, 320, 300); + } + + // Matroska reports 1:1 for a track without a display size, which is not to + // hide what the pictures say. + @Test + void pictureRatioCounts() throws Exception { + Path file = TestMedia.pixelDensityMatroska(directory, path(MJPEG), 2, 1); + + assertPlays(file, false, 320, 120, 0, 320, 120); + } + + @Test + void convertedFramesAreScaled() throws Exception { + Path file = TestMedia.displaySizeMatroska(directory, path(H264_444), 640, 240); + + assertPlays(file, false, 640, 240, 0, 640, 240); + } + + @Test + void brokenRatioIsIgnored() throws Exception { + Path file = TestMedia.displaySizeMatroska(directory, path(H264), 32000, 1); + + assertPlays(file, false, 320, 240, 0, 320, 240); + } + + // Without hardware this is decoded in software, which is as good a result. + @Test + void hardwareDecodingKeepsTheShape() throws Exception { + Path source = path(H264); + + assertPlays(TestMedia.rotatedMatroska(directory, source, 90), true, 320, 240, 90, 240, 320); + assertPlays(TestMedia.displaySizeMatroska(directory, source, 640, 240), true, 640, 240, 0, 640, 240); + } + + @Test + void scalingKeepsThePicture() throws Exception { + Picture plain = play(path(H264), false); + Picture wide = play(TestMedia.displaySizeMatroska(directory, path(H264), 640, 240), false); + + int blocks = 8; + + for (int y = 0; y < blocks; y++) { + for (int x = 0; x < blocks; x++) { + double expected = plain.meanLuma(x, y, blocks); + double actual = wide.meanLuma(x, y, blocks); + + assertTrue(Math.abs(expected - actual) < 8, + "block " + x + "," + y + ": " + expected + " became " + actual); + } + } + } + + private void assertPlays(Path file, boolean hardware, int width, int height, int rotation, + int shownWidth, int shownHeight) throws Exception { + Picture picture = play(file, hardware); + + assertEquals(width, picture.width, "frame width"); + assertEquals(height, picture.height, "frame height"); + assertEquals(rotation, picture.rotation, "frame rotation"); + assertEquals(shownWidth, picture.shownWidth, "reported width"); + assertEquals(shownHeight, picture.shownHeight, "reported height"); + } + + /** Plays a file up to its first picture, as a sink on its track sees it. */ + private Picture play(Path file, boolean hardware) throws Exception { + CompletableFuture first = new CompletableFuture<>(); + + try (MediaFileSource source = new MediaFileSource(file, hardware)) { + VideoTrack track = factory.createVideoTrack("video", source.getVideoSource()); + VideoTrackSink sink = frame -> { + if (!first.isDone()) { + first.complete(new VideoFrameCopy(frame)); + } + }; + + track.addSink(sink); + + source.play(); + + VideoFrameCopy frame = first.get(15, TimeUnit.SECONDS); + + track.removeSink(sink); + track.dispose(); + + return new Picture(frame, source.getInfo()); + } + } + + private static Path path(String asset) throws Exception { + return Paths.get(VideoGeometryTest.class.getResource(asset).toURI()); + } + + /** What outlives the frame a sink is given. */ + private static final class VideoFrameCopy { + + final int width; + final int height; + final int rotation; + final byte[] luma; + + + VideoFrameCopy(VideoFrame frame) { + I420Buffer buffer = frame.buffer.toI420(); + + width = buffer.getWidth(); + height = buffer.getHeight(); + rotation = frame.rotation; + luma = new byte[width * height]; + + ByteBuffer plane = buffer.getDataY(); + + for (int y = 0; y < height; y++) { + ByteBuffer line = plane.duplicate(); + + line.position(y * buffer.getStrideY()); + line.get(luma, y * width, width); + } + + buffer.release(); + } + } + + private static final class Picture { + + final int width; + final int height; + final int rotation; + final int shownWidth; + final int shownHeight; + final byte[] luma; + + + Picture(VideoFrameCopy frame, MediaInfo info) { + width = frame.width; + height = frame.height; + rotation = frame.rotation; + luma = frame.luma; + shownWidth = info.getVideoWidth(); + shownHeight = info.getVideoHeight(); + } + + /** The mean luma of one block of a picture cut into equal blocks. */ + double meanLuma(int blockX, int blockY, int blocks) { + int left = width * blockX / blocks; + int right = width * (blockX + 1) / blocks; + int top = height * blockY / blocks; + int bottom = height * (blockY + 1) / blocks; + long sum = 0; + + for (int y = top; y < bottom; y++) { + for (int x = left; x < right; x++) { + sum += luma[y * width + x] & 0xFF; + } + } + + return (double) sum / ((right - left) * (bottom - top)); + } + } +}