Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/guide/media/media-files.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 11 additions & 5 deletions webrtc-media/src/main/cpp/include/media/VideoDecoder.h
Original file line number Diff line number Diff line change
Expand Up @@ -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 <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
Expand All @@ -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.
Expand Down Expand Up @@ -119,7 +123,8 @@ namespace ffmpeg

void ResolveColor(AVFrame * frame) const;

// Resolves color properties and retains I420 or converts other formats.
// Resolves color properties and retains I420 of square pixels, or
// converts anything else.
int MakeI420(AVFrame * source, AVFrame ** frame);
// How many packets are kept, until the hardware has produced a
// frame, to be decoded again in software if it fails by then.
Expand Down Expand Up @@ -176,9 +181,10 @@ 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 a decoded frame to I420, at the given size. The returned
// frame is a new reference the caller owns, with the properties and
// the side data of the source, the display matrix among them.
int ConvertToI420(const AVFrame * source, 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
Expand Down
53 changes: 53 additions & 0 deletions webrtc-media/src/main/cpp/include/media/VideoGeometry.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
* 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 <libavformat/avformat.h>
#include <libavutil/frame.h>
}

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. Without a
// stream, the frame is all there is to go by.
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
3 changes: 2 additions & 1 deletion webrtc-media/src/main/cpp/src/media/MediaPacer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
#include "media/MediaPacer.h"
#include "media/AudioDecoder.h"
#include "media/PlaybackProbe.h"
#include "media/VideoGeometry.h"

#include <algorithm>
#include <limits>
Expand Down Expand Up @@ -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;
Expand Down
5 changes: 3 additions & 2 deletions webrtc-media/src/main/cpp/src/media/MediaReader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

#include "media/MediaReader.h"
#include "media/AllocationFault.h"
#include "media/VideoGeometry.h"

#include <algorithm>
#include <cstring>
Expand Down Expand Up @@ -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
Expand Down
10 changes: 6 additions & 4 deletions webrtc-media/src/main/cpp/src/media/VideoDecoder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -764,7 +764,9 @@ namespace ffmpeg
{
ResolveColor(source);

if (IsI420(source->format)) {
const VideoSize size = GetSquarePixelSize(stream_, source);

if (IsI420(source->format) && size.width == source->width && size.height == source->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();
Expand All @@ -785,7 +787,7 @@ namespace ffmpeg
return 0;
}

return ConvertToI420(source, frame);
return ConvertToI420(source, size, frame);
}

void VideoDecoder::ResolveColor(AVFrame * frame) const
Expand Down Expand Up @@ -826,7 +828,7 @@ namespace ffmpeg
}
}

int VideoDecoder::ConvertToI420(const AVFrame * source, AVFrame ** result)
int VideoDecoder::ConvertToI420(const AVFrame * source, VideoSize size, AVFrame ** result)
{
// Dynamic swscale reads matrix/range from the frames and rebuilds its
// graph when they change, even if dimensions and pixel format do not.
Expand All @@ -843,7 +845,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;
Expand Down
144 changes: 144 additions & 0 deletions webrtc-media/src/main/cpp/src/media/VideoGeometry.cpp
Original file line number Diff line number Diff line change
@@ -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 <libavutil/display.h>
#include <libavutil/mathematics.h>
}

#include <cmath>
#include <cstddef>
#include <cstdint>
#include <utility>

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<const int32_t *>(data);

// A negative determinant is a mirror image.
const int64_t determinant = static_cast<int64_t>(matrix[0]) * matrix[4]
- static_cast<int64_t>(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<int>((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 (stream != nullptr && 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<int>(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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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.
*/
Expand All @@ -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.
*/
Expand Down
Loading
Loading