diff --git a/examples/WebRTCExamples/UnityAudioVideoSource/Assets/Editor/AutoPlaySmokeTest.cs b/examples/WebRTCExamples/UnityAudioVideoSource/Assets/Editor/AutoPlaySmokeTest.cs new file mode 100644 index 0000000000..7dfcf63e8b --- /dev/null +++ b/examples/WebRTCExamples/UnityAudioVideoSource/Assets/Editor/AutoPlaySmokeTest.cs @@ -0,0 +1,18 @@ +// Automation hook: prepares and opens the game scene, then enters play mode, so the +// WebRTC stream can be tested without the editor window: +// +// Unity.exe -batchmode -projectPath -executeMethod AutoPlaySmokeTest.Run +// +// (no -quit: the editor keeps playing until the process is stopped). Safe to delete. +using UnityEditor; +using UnityEditor.SceneManagement; + +public static class AutoPlaySmokeTest +{ + public static void Run() + { + SIPSorcerySceneSetup.EnsureScene(); + EditorSceneManager.OpenScene(SIPSorcerySceneSetup.ScenePath); + EditorApplication.EnterPlaymode(); + } +} diff --git a/examples/WebRTCExamples/UnityAudioVideoSource/Assets/Editor/SIPSorcerySceneSetup.cs b/examples/WebRTCExamples/UnityAudioVideoSource/Assets/Editor/SIPSorcerySceneSetup.cs new file mode 100644 index 0000000000..ef30f0703b --- /dev/null +++ b/examples/WebRTCExamples/UnityAudioVideoSource/Assets/Editor/SIPSorcerySceneSetup.cs @@ -0,0 +1,140 @@ +//----------------------------------------------------------------------------- +// Filename: SIPSorcerySceneSetup.cs +// +// Description: Prepares the "Get Started With Unity" template's scene for +// streaming. The template ships GetStarted_Scene without the player robot +// (placing it is one of the tutorial's steps) and the robot carries the camera +// and the AudioListener, so an untouched template project has nothing to stream +// and its Game view says "No cameras rendering". This places the PlayerRobot and +// the template's background music in the scene and saves it. +// +// It runs once by itself, the first time the editor loads the project after +// setup.ps1 copied it in, and again on demand from the menu +// SIPSorcery > Add Robot And Music To Scene. +// +// Author(s): +// Aaron Clauson (aaron@sipsorcery.com) +// +// License: +// BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file. +//----------------------------------------------------------------------------- + +using System.IO; +using UnityEditor; +using UnityEditor.SceneManagement; +using UnityEngine; +using UnityEngine.SceneManagement; + +[InitializeOnLoad] +public static class SIPSorcerySceneSetup +{ + public const string ScenePath = "Assets/Scenes/GetStarted_Scene.unity"; + private const string RobotPrefabPath = "Assets/Prefabs/PlayerRobot.prefab"; + private const string MusicPrefabPath = "Assets/Audio/Background_Music_Ethereal.prefab"; + + // Where the robot stood in the original working project of this example. + private static readonly Vector3 RobotPosition = new Vector3(10f, 5f, 0f); + + // Recorded once the template's scene has been checked, so the automatic run never + // re-adds a robot that was removed on purpose. UserSettings is per project and per user. + private const string MarkerPath = "UserSettings/SIPSorcerySceneSetup.txt"; + + static SIPSorcerySceneSetup() + { + if (!File.Exists(MarkerPath)) + { + EditorApplication.delayCall += AutoSetup; + } + } + + private static void AutoSetup() + { + if (EditorApplication.isPlayingOrWillChangePlaymode || File.Exists(MarkerPath)) + { + return; + } + if (EditorApplication.isCompiling || EditorApplication.isUpdating) + { + EditorApplication.delayCall += AutoSetup; + return; + } + EnsureScene(fromMenu: false); + } + + [MenuItem("SIPSorcery/Add Robot And Music To Scene")] + private static void AddFromMenu() => EnsureScene(fromMenu: true); + + /// + /// Adds the PlayerRobot and the background music to GetStarted_Scene if they are + /// missing, and saves the scene. Returns false if the project isn't from the template. + /// + public static bool EnsureScene(bool fromMenu = false) + { + var robotPrefab = AssetDatabase.LoadAssetAtPath(RobotPrefabPath); + if (robotPrefab == null || AssetDatabase.LoadAssetAtPath(ScenePath) == null) + { + if (fromMenu) + { + Debug.LogWarning($"SIPSorcery: this project isn't from the Get Started template ({ScenePath} or " + + $"{RobotPrefabPath} is missing). Any scene with a camera tagged MainCamera can be streamed."); + } + return false; + } + + // Edit the scene where it is if it's open, else open it alongside so the scene the + // user has open is left alone. + var scene = SceneManager.GetSceneByPath(ScenePath); + bool openedHere = !scene.isLoaded; + if (openedHere) + { + scene = EditorSceneManager.OpenScene(ScenePath, OpenSceneMode.Additive); + } + + bool changed = false; + if (!ContainsInstanceOf(scene, robotPrefab)) + { + var robot = (GameObject)PrefabUtility.InstantiatePrefab(robotPrefab, scene); + robot.transform.position = RobotPosition; + changed = true; + } + + var musicPrefab = AssetDatabase.LoadAssetAtPath(MusicPrefabPath); + if (musicPrefab != null && !ContainsInstanceOf(scene, musicPrefab)) + { + PrefabUtility.InstantiatePrefab(musicPrefab, scene); + changed = true; + } + + if (changed) + { + EditorSceneManager.MarkSceneDirty(scene); + EditorSceneManager.SaveScene(scene); + Debug.Log($"SIPSorcery: added the PlayerRobot (camera and AudioListener) and background music to {ScenePath} and saved it."); + } + else if (fromMenu) + { + Debug.Log($"SIPSorcery: {ScenePath} already has the PlayerRobot and background music."); + } + + if (openedHere) + { + EditorSceneManager.CloseScene(scene, removeScene: true); + } + + Directory.CreateDirectory(Path.GetDirectoryName(MarkerPath)); + File.WriteAllText(MarkerPath, $"Checked {ScenePath} for the PlayerRobot and background music.\n"); + return true; + } + + private static bool ContainsInstanceOf(Scene scene, GameObject prefab) + { + foreach (var root in scene.GetRootGameObjects()) + { + if (PrefabUtility.GetCorrespondingObjectFromSource(root) == prefab) + { + return true; + } + } + return false; + } +} diff --git a/examples/WebRTCExamples/UnityAudioVideoSource/Assets/Scripts/WebRTCVideoSource.cs b/examples/WebRTCExamples/UnityAudioVideoSource/Assets/Scripts/WebRTCVideoSource.cs new file mode 100644 index 0000000000..60d2f9f2e5 --- /dev/null +++ b/examples/WebRTCExamples/UnityAudioVideoSource/Assets/Scripts/WebRTCVideoSource.cs @@ -0,0 +1,681 @@ +//----------------------------------------------------------------------------- +// Filename: WebRTCVideoSource.cs +// +// Description: Streams the game's main camera view and audio to a browser over +// WebRTC using SIPSorcery - the modern (Unity 6 / URP / Cinemachine) successor +// to the original 2019 UnityVideoSource example. It is written for a project +// created from Unity's "Get Started With Unity" template, see README.md. +// +// mirror camera tracks Camera.main (so the Game view is untouched) +// v renders to a fixed-size RenderTexture +// v ReadPixels each frame period -> RGBA32 -> flipped BGR24 +// v background encode thread -> VP9Codec (SIPSorcery.VP9, managed: no native libraries) +// v RTCPeerConnection.SendVideo +// +// game audio: the AudioListener's final mix (OnAudioFilterRead, GameAudioTap) +// v mono 16-bit PCM in 20ms frames on the Unity audio thread +// v background audio thread -> AudioEncoder (Opus) +// v RTCPeerConnection.SendAudio +// +// Setup is zero-touch: a RuntimeInitializeOnLoadMethod bootstraps the component +// when the scene starts, so just press Play, browse to http://localhost:8081 +// and click Connect. +// +// Author(s): +// Aaron Clauson (aaron@sipsorcery.com) +// +// License: +// BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file. +//----------------------------------------------------------------------------- + +using System; +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Net; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using SIPSorcery.Media; +using SIPSorcery.Net; +using SIPSorcery.VP9; +using SIPSorceryMedia.Abstractions; +using UnityEngine; +using UnityEngine.Rendering; +using Debug = UnityEngine.Debug; +using ILogger = Microsoft.Extensions.Logging.ILogger; + +public class WebRTCVideoSource : MonoBehaviour +{ + // The stream's size. Unity's Mono runs SIPSorcery.VP9's netstandard2.1 build, which has no + // SIMD: 640x360 encodes in about 15ms on 4 threads, well inside 25fps's 40ms, and 960x540 in + // about 27ms on 8. Both need the editor's Release code optimisation (README.md). + public const int WIDTH = 640; + public const int HEIGHT = 360; + public const int FPS = 25; + public const int HTTP_PORT = 8081; + + // VP9 target bitrate, libvpx's realtime speed (5 to 9, higher is faster and a little lower in + // quality) and the encoder's threads. + private const int VIDEO_BITRATE_KBPS = 1000; + private const int VP9_SPEED = 9; + private static readonly int VP9_THREADS = Math.Min(4, Environment.ProcessorCount); + + private const int VIDEO_CLOCK = 90000; // RTP video sampling rate. + private static readonly List VideoFormats = new() + { + new VideoFormat(VideoCodecsEnum.VP9, VP9Codec.VP9_SUGGESTED_FORMAT_ID, VIDEO_CLOCK) + }; + + // Opus only: every WebRTC browser must support it (RFC 7874). Adding PCMU as a fallback + // backfires - SIPSorcery's answer lists static payload IDs first, so PCMU (0) would win + // over Opus (111) and the game audio would be sent at telephone quality. + private static readonly List AudioFormats = new() + { + AudioCommonlyUsedFormats.OpusWebRTC + }; + + private static ILogger logger; + + // Rendering / capture. + private Camera _mirrorCamera; + private RenderTexture _renderTexture; + private Texture2D _readbackTexture; + private float _nextCaptureTime; + private bool _warnedNoCamera; + + // Encode pipeline (background thread - encoding must not stall the Unity main thread). + private VP9Codec _encoder; + private VideoCodecsEnum _negotiatedCodec = VideoCodecsEnum.VP9; + private RTCPeerConnection _pcForEncode; // captured for SendVideo off-thread. + private readonly BlockingCollection<(byte[] bgr, long captured)> _encodeQueue = + new(new ConcurrentQueue<(byte[] bgr, long captured)>(), boundedCapacity: 2); + private Thread _encodeThread; + + // Audio pipeline: 20ms PCM frames from the game's AudioListener, encoded off the audio thread. + private GameAudioTap _audioTap; + private readonly AudioEncoder _audioEncoder = new AudioEncoder(includeOpus: true); + private AudioFormat _negotiatedAudioFormat; + private readonly BlockingCollection _audioQueue = + new(new ConcurrentQueue(), boundedCapacity: 10); + private Thread _audioThread; + + // WebRTC / signaling. + private RTCPeerConnection _pc; + private HttpListener _http; + private CancellationTokenSource _cts; + + /// + /// Creates the streaming GameObject automatically when the scene loads so no manual + /// scene wiring is needed. Remove this method if you'd rather place the component + /// in the scene yourself. + /// + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)] + private static void Bootstrap() + { + if (FindAnyObjectByType() == null) + { + var go = new GameObject("WebRTCVideoSource"); + DontDestroyOnLoad(go); + go.AddComponent(); + } + } + + void Awake() + { + // Each stage reports its own failure - a silent exception here otherwise leaves the + // scene playing with no listener and no clue why. + try + { + // A streaming source must keep producing frames when the app (or the editor + // in play mode) loses focus - e.g. the moment the user switches to the browser + // to click Connect. Without this the player loop suspends and the video freezes. + Application.runInBackground = true; + + SIPSorcery.LogFactory.Set(new UnityLoggerFactory()); + logger = SIPSorcery.LogFactory.CreateLogger("webrtc"); + + BuildMirrorCamera(); + + _readbackTexture = new Texture2D(WIDTH, HEIGHT, TextureFormat.RGBA32, mipChain: false); + + // Pure C# VP9 (SIPSorcery.VP9): nothing native to install or find. + _encoder = new VP9Codec(VIDEO_BITRATE_KBPS, VP9_SPEED, threads: VP9_THREADS); + + _cts = new CancellationTokenSource(); + _encodeThread = new Thread(EncodeLoop) { IsBackground = true, Name = "vp9-encode" }; + _encodeThread.Start(); + + AttachAudioTap(); + _audioThread = new Thread(AudioSendLoop) { IsBackground = true, Name = "audio-encode" }; + _audioThread.Start(); + + StartHttpListener(); + StartCoroutine(CaptureLoop()); + + logger.LogInformation($"WebRTC audio/video source running. Browse to http://localhost:{HTTP_PORT} and click Connect."); + +#if UNITY_EDITOR + // In Debug code optimisation (the editor's default) the debugger keeps Mono's JIT from + // optimising, and the managed encoder runs about 4x slower: too slow for 25fps. + if (UnityEditor.Compilation.CompilationPipeline.codeOptimization == UnityEditor.Compilation.CodeOptimization.Debug) + { + Debug.LogWarning("The editor is in Debug code optimisation, so VP9 encodes about 4x slower and the video " + + "runs below 25fps. Switch to Release with the bug icon at the right of the status bar."); + } +#endif + } + catch (Exception excp) + { + Debug.LogError($"WebRTCVideoSource failed to initialise: {excp}"); + } + } + + // --- Mirror camera --------------------------------------------------------------------- + + /// + /// A second camera renders the stream so the player's Game view is untouched. It stays + /// disabled - CaptureLoop renders it on demand with a render request, which keeps the + /// stream alive even when the editor is unfocused or the Game view hidden (an enabled + /// camera or WaitForEndOfFrame capture only runs when the editor repaints). + /// + private void BuildMirrorCamera() + { + _renderTexture = new RenderTexture(WIDTH, HEIGHT, 24); + var camGo = new GameObject("WebRTCMirrorCamera"); + camGo.transform.SetParent(transform, false); + _mirrorCamera = camGo.AddComponent(); + _mirrorCamera.targetTexture = _renderTexture; + _mirrorCamera.enabled = false; + SyncMirrorCamera(); + } + + private void SyncMirrorCamera() + { + var main = Camera.main; + if (main == null || _mirrorCamera == null) + { + if (main == null && !_warnedNoCamera) + { + // The Get Started template's scene ships without the player robot, and the + // robot carries the camera - so an untouched template streams (and the Game + // view shows) nothing. SIPSorcerySceneSetup places it in the editor. + _warnedNoCamera = true; + Debug.LogWarning("No camera tagged MainCamera in the scene, so there is nothing to stream. " + + "In the Get Started template the camera comes with the PlayerRobot prefab: use the editor menu " + + "SIPSorcery > Add Robot And Music To Scene, or drag Assets/Prefabs/PlayerRobot into the scene."); + } + return; + } + + _mirrorCamera.transform.SetPositionAndRotation(main.transform.position, main.transform.rotation); + _mirrorCamera.fieldOfView = main.fieldOfView; + _mirrorCamera.nearClipPlane = main.nearClipPlane; + _mirrorCamera.farClipPlane = main.farClipPlane; + _mirrorCamera.clearFlags = main.clearFlags; + _mirrorCamera.backgroundColor = main.backgroundColor; + _mirrorCamera.cullingMask = main.cullingMask; + } + + // --- Capture -> encode ---------------------------------------------------------------- + + private IEnumerator CaptureLoop() + { + float nextKeyFrameTime = 0f; + var renderRequest = new RenderPipeline.StandardRequest(); + + while (!_cts.IsCancellationRequested) + { + yield return null; + + if (Time.realtimeSinceStartup < _nextCaptureTime || _pc == null || + _pc.connectionState != RTCPeerConnectionState.connected) + { + continue; + } + _nextCaptureTime = Time.realtimeSinceStartup + 1f / FPS; + + // Periodic keyframe insurance: caps how long any decode glitch can freeze the + // picture, at a small bitrate cost. + if (Time.realtimeSinceStartup >= nextKeyFrameTime) + { + nextKeyFrameTime = Time.realtimeSinceStartup + 3f; + _encoder.ForceKeyFrame(); + } + + SyncMirrorCamera(); + if (RenderPipeline.SupportsRenderRequest(_mirrorCamera, renderRequest)) + { + renderRequest.destination = _renderTexture; + RenderPipeline.SubmitRenderRequest(_mirrorCamera, renderRequest); + } + + var prevActive = RenderTexture.active; + RenderTexture.active = _renderTexture; + _readbackTexture.ReadPixels(new Rect(0, 0, WIDTH, HEIGHT), 0, 0, recalculateMipMaps: false); + RenderTexture.active = prevActive; + + var bgr = ToBgrFlipped(_readbackTexture.GetRawTextureData()); + if (!_encodeQueue.TryAdd((bgr, Stopwatch.GetTimestamp()))) + { + // Encoder still busy with the previous frame - drop this one. + } + } + } + + /// Unity textures are bottom-up RGBA; the encoder wants top-down BGR24. + private static byte[] ToBgrFlipped(Unity.Collections.NativeArray rgba) + { + var bgr = new byte[WIDTH * HEIGHT * 3]; + int d = 0; + for (int y = HEIGHT - 1; y >= 0; y--) + { + int row = y * WIDTH; + for (int x = 0; x < WIDTH; x++) + { + var px = rgba[row + x]; + bgr[d++] = px.b; + bgr[d++] = px.g; + bgr[d++] = px.r; + } + } + return bgr; + } + + private void EncodeLoop() + { + // Encoder throughput, logged every 5s, to show whether it keeps up with FPS. + var report = Stopwatch.StartNew(); + var encodeTime = new Stopwatch(); + int frames = 0; + long bytes = 0; + long firstSent = 0, lastRtp = 0; + try + { + foreach (var (bgr, captured) in _encodeQueue.GetConsumingEnumerable(_cts.Token)) + { + if (frames == 0) + { + report.Restart(); // frames only come while a browser is connected + } + encodeTime.Start(); + var encoded = _encoder.EncodeVideo(WIDTH, HEIGHT, bgr, VideoPixelFormatsEnum.Bgr, _negotiatedCodec); + encodeTime.Stop(); + frames++; + bytes += encoded?.Length ?? 0; + + var pc = _pcForEncode; + if (encoded != null && pc != null && pc.connectionState == RTCPeerConnectionState.connected) + { + // The RTP duration is the time since the last frame sent was captured, in + // 90kHz units: 3600 at a steady 25fps, more after a frame the capture loop + // dropped because the encoder was busy, so the browser plays in real time. + if (firstSent == 0) + { + firstSent = captured - Stopwatch.Frequency / FPS; + } + long rtp = (captured - firstSent) * VIDEO_CLOCK / Stopwatch.Frequency; + pc.SendVideo((uint)(rtp - lastRtp), encoded); + lastRtp = rtp; + } + + if (report.Elapsed.TotalSeconds >= 5) + { + double secs = report.Elapsed.TotalSeconds; + logger.LogInformation($"VP9: {frames / secs:0.0} fps encoded at {encodeTime.Elapsed.TotalMilliseconds / frames:0.0} ms a frame, " + + $"{bytes * 8 / secs / 1000:0} kbps."); + report.Restart(); + encodeTime.Reset(); + frames = 0; + bytes = 0; + } + } + } + catch (OperationCanceledException) { } + catch (Exception excp) + { + logger.LogError($"Encode loop failed: {excp}"); + } + } + + // --- Game audio -> encode ------------------------------------------------------------ + + /// + /// Taps the game's final audio mix: Unity routes everything the AudioListener hears + /// through OnAudioFilterRead on components beside it, so the tap goes on that GameObject + /// (the player Robot in this scene). + /// + private void AttachAudioTap() + { + var listener = FindAnyObjectByType(); + if (listener == null) + { + logger.LogWarning("No AudioListener in the scene - adding one so game audio can be streamed."); + listener = gameObject.AddComponent(); + } + + if (!listener.TryGetComponent(out _audioTap)) + { + _audioTap = listener.gameObject.AddComponent(); + } + + _audioTap.OnFrame += frame => + { + var pc = _pcForEncode; + if (pc != null && pc.connectionState == RTCPeerConnectionState.connected) + { + // Non-blocking: this runs on the Unity audio thread. A full queue means the + // sender has stalled, and dropping a 20ms frame beats glitching the game audio. + _audioQueue.TryAdd(frame); + } + }; + + logger.LogInformation($"Streaming game audio from the AudioListener on '{listener.gameObject.name}' at {_audioTap.SampleRate}Hz."); + } + + private void AudioSendLoop() + { + try + { + foreach (var frame in _audioQueue.GetConsumingEnumerable(_cts.Token)) + { + var pc = _pcForEncode; + var format = _negotiatedAudioFormat; + if (pc == null || format.IsEmpty() || pc.connectionState != RTCPeerConnectionState.connected) + { + continue; + } + + var pcm = Resample(frame, _audioTap.SampleRate, format.ClockRate); + var encoded = _audioEncoder.EncodeAudio(pcm, format); + if (encoded != null && encoded.Length > 0) + { + uint durationRtpUnits = (uint)((long)pcm.Length * format.RtpClockRate / format.ClockRate); + pc.SendAudio(durationRtpUnits, encoded); + } + } + } + catch (OperationCanceledException) { } + catch (Exception excp) + { + logger.LogError($"Audio send loop failed: {excp}"); + } + } + + /// + /// Converts one mono frame between sample rates: a pass-through when the rates match + /// (Opus at a 48kHz output, the usual case), linear interpolation when upsampling and + /// a box average when downsampling (e.g. a 96kHz output device). + /// + private static short[] Resample(short[] input, int inRate, int outRate) + { + if (inRate == outRate) + { + return input; + } + + int outLength = (int)((long)input.Length * outRate / inRate); + var output = new short[outLength]; + double step = (double)inRate / outRate; + + for (int i = 0; i < outLength; i++) + { + double pos = i * step; + if (step > 1.0) + { + int start = (int)pos; + int end = Math.Min(input.Length, (int)(pos + step)); + int sum = 0; + for (int j = start; j < end; j++) { sum += input[j]; } + output[i] = (short)(sum / Math.Max(1, end - start)); + } + else + { + int idx = (int)pos; + int next = Math.Min(idx + 1, input.Length - 1); + double frac = pos - idx; + output[i] = (short)(input[idx] + (input[next] - input[idx]) * frac); + } + } + return output; + } + + // --- WebRTC + signaling ---------------------------------------------------------------- + + private void StartHttpListener() + { + try + { + _http = new HttpListener(); + _http.Prefixes.Add($"http://localhost:{HTTP_PORT}/"); + _http.Prefixes.Add($"http://127.0.0.1:{HTTP_PORT}/"); + _http.Start(); + Task.Run(() => HttpLoop(_cts.Token)); + Debug.Log($"HTTP signaling listener STARTED on http://localhost:{HTTP_PORT}/."); + } + catch (Exception excp) + { + Debug.LogError($"HTTP signaling listener FAILED to start on port {HTTP_PORT}: {excp}"); + throw; + } + } + + private async Task HttpLoop(CancellationToken ct) + { + while (!ct.IsCancellationRequested) + { + HttpListenerContext ctx; + try { ctx = await _http.GetContextAsync().ConfigureAwait(false); } + catch { break; } + + try + { + if (ctx.Request.HttpMethod == "POST" && ctx.Request.Url.AbsolutePath == "/offer") + { + using var reader = new StreamReader(ctx.Request.InputStream); + string offerJson = await reader.ReadToEndAsync().ConfigureAwait(false); + string answerJson = await HandleOffer(offerJson).ConfigureAwait(false); + await WriteResponse(ctx, answerJson, "application/json").ConfigureAwait(false); + } + else + { + await WriteResponse(ctx, INDEX_HTML, "text/html").ConfigureAwait(false); + } + } + catch (Exception excp) + { + logger.LogError($"HTTP handler error: {excp.Message}"); + try { ctx.Response.StatusCode = 500; ctx.Response.Close(); } catch { } + } + } + } + + private static async Task WriteResponse(HttpListenerContext ctx, string body, string contentType) + { + var bytes = Encoding.UTF8.GetBytes(body); + ctx.Response.ContentType = contentType; + ctx.Response.ContentLength64 = bytes.Length; + await ctx.Response.OutputStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false); + ctx.Response.Close(); + } + + private async Task HandleOffer(string offerJson) + { + if (!RTCSessionDescriptionInit.TryParse(offerJson, out var offer)) + { + throw new ApplicationException("Could not parse SDP offer."); + } + + _pc?.Close("replaced"); + var pc = new RTCPeerConnection(); + + var videoTrack = new MediaStreamTrack(VideoFormats, MediaStreamStatusEnum.SendOnly); + pc.addTrack(videoTrack); + var audioTrack = new MediaStreamTrack(AudioFormats, MediaStreamStatusEnum.SendOnly); + pc.addTrack(audioTrack); + + pc.OnVideoFormatsNegotiated += formats => _negotiatedCodec = formats[0].Codec; + pc.OnAudioFormatsNegotiated += formats => + { + _negotiatedAudioFormat = formats[0]; + logger.LogInformation($"Audio format negotiated: {formats[0].FormatName}/{formats[0].ClockRate}."); + }; + // Video and audio are encoded on the EncodeLoop and AudioSendLoop background threads + // and sent with pc.SendVideo and pc.SendAudio directly. + + // Answer the browser's picture-loss requests (PLI) with a keyframe - without this + // a single undecodable inter-frame freezes the video permanently. + pc.OnReceiveReport += (ep, media, report) => + { + if (media == SDPMediaTypesEnum.video && + report?.Feedback?.Header.PayloadFeedbackMessageType == PSFBFeedbackTypesEnum.PLI) + { + logger.LogInformation("PLI received - forcing a keyframe."); + _encoder.ForceKeyFrame(); + } + }; + + pc.onconnectionstatechange += state => + { + logger.LogInformation($"Peer connection state: {state}."); + if (state == RTCPeerConnectionState.connected) + { + _encoder.ForceKeyFrame(); + } + }; + + pc.setRemoteDescription(offer); + var answer = pc.createAnswer(); + await pc.setLocalDescription(answer).ConfigureAwait(false); + + _pc = pc; + _pcForEncode = pc; + return answer.toJSON(); + } + + void OnDestroy() + { + _cts?.Cancel(); + _encodeQueue.CompleteAdding(); + _audioQueue.CompleteAdding(); + if (_audioTap != null) + { + Destroy(_audioTap); + } + try { _http?.Stop(); } catch { } + _pc?.Close("component destroyed"); + _encoder?.Dispose(); + _renderTexture?.Release(); + } + + private const string INDEX_HTML = @" +Unity Audio/Video Source + +

Unity game camera and audio over SIPSorcery WebRTC

+
+ +"; +} + +// --- Unity logging bridge (same pattern as the UnityVideoSink example) -------------------- + +public class UnityLoggerFactory : ILoggerFactory +{ + public ILogger CreateLogger(string categoryName) => new UnityLogger(categoryName); + public void AddProvider(ILoggerProvider provider) { } + public void Dispose() { } +} + +public class UnityLogger : ILogger +{ + private readonly string _category; + public UnityLogger(string category) { _category = category; } + public IDisposable BeginScope(TState state) => null; + public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Debug; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, + Func formatter) + { + var msg = $"[{_category}] {formatter(state, exception)}"; + if (logLevel >= LogLevel.Error) { Debug.LogError(msg); } + else if (logLevel == LogLevel.Warning) { Debug.LogWarning(msg); } + else { Debug.Log(msg); } + } +} + +/// +/// Sits on the AudioListener's GameObject and copies the game's final audio mix as it is +/// rendered: downmixed to mono 16-bit PCM and handed out in fixed 20ms frames. It only +/// reads the buffer, so local playback is unaffected. +/// +public class GameAudioTap : MonoBehaviour +{ + /// Raised on the Unity audio thread with each complete 20ms frame. + public event Action OnFrame; + + public int SampleRate { get; private set; } + + private short[] _frame; + private int _frameFill; + + void Awake() + { + // AudioSettings must be read on the main thread, so cache it before the audio thread + // starts calling OnAudioFilterRead. + SampleRate = AudioSettings.outputSampleRate; + _frame = new short[SampleRate / 50]; + } + + void OnAudioFilterRead(float[] data, int channels) + { + if (_frame == null) + { + return; + } + + for (int i = 0; i + channels <= data.Length; i += channels) + { + float sum = 0f; + for (int c = 0; c < channels; c++) + { + sum += data[i + c]; + } + + float sample = sum / channels; + if (sample > 1f) { sample = 1f; } else if (sample < -1f) { sample = -1f; } + _frame[_frameFill++] = (short)(sample * short.MaxValue); + + if (_frameFill == _frame.Length) + { + OnFrame?.Invoke(_frame); + _frame = new short[_frame.Length]; + _frameFill = 0; + } + } + } +} diff --git a/examples/WebRTCExamples/UnityAudioVideoSource/README.md b/examples/WebRTCExamples/UnityAudioVideoSource/README.md new file mode 100644 index 0000000000..00a6814ee2 --- /dev/null +++ b/examples/WebRTCExamples/UnityAudioVideoSource/README.md @@ -0,0 +1,128 @@ +# Unity Audio/Video Source + +Streams a Unity game's camera view and audio to a browser over WebRTC using SIPSorcery. +The game is the robot from Unity's **Get Started With Unity** template. Video is +VP9-encoded with `SIPSorcery.VP9`, a pure C# port of libvpx. Audio is Opus-encoded with +SIPSorcery's managed `AudioEncoder` (Concentus). Everything is managed code, so there is +nothing native to install. + +This folder is an **overlay**, not a whole Unity project. The template's models, +textures and tutorial videos come to about 250 MB, so they stay out of the repo. You +create a project from the template in Unity Hub, and `setup.ps1` adds this example to it. + +Tested with Unity **6000.6.12f1** and template `com.unity.template.get-started` 2.1.1. + +## Prerequisites + +- Unity 6 and Unity Hub. +- The .NET SDK, to build the SIPSorcery libraries. + +## Run + +1. In Unity Hub, create a new project from the **Get Started With Unity** template. + Close the editor once the project has opened. +2. Add this example to it: + + ```powershell + ./setup.ps1 -ProjectPath "C:\Users\me\My project" + ``` + + This builds SIPSorcery and SIPSorcery.VP9 for netstandard2.1 into + `Assets/Plugins/SIPSorcery` and copies this folder's `Assets` into the project. + Run it again after changing the library source. It also removes plugins earlier + copies of this example used: the FFmpeg ones, and DLLs kept directly in + `Assets/Plugins`, which Unity would refuse as duplicate assemblies. +3. Open the project. The first time, `SIPSorcerySceneSetup` places the PlayerRobot and + the background music in `GetStarted_Scene` and saves the scene. The template ships + that scene without the robot, and the robot carries the camera and the + AudioListener. Run it again from the menu **SIPSorcery > Add Robot And Music To + Scene**. +4. Open `GetStarted_Scene` and press Play. +5. Browse to and click **Connect**. The game view and audio play + in the page. The line beside the button shows the received video frames and audio + level. + +## How it works + +The code is in [WebRTCVideoSource.cs](Assets/Scripts/WebRTCVideoSource.cs). + +- **Startup:** a `RuntimeInitializeOnLoadMethod` creates the component when the scene + starts, so no scene wiring is needed. +- **Mirror camera:** a second camera copies the main camera's pose (the Cinemachine-driven + camera on the robot). It renders to a fixed 640x360 `RenderTexture`, so the Game view + is untouched. + - It renders on demand with `RenderPipeline.SubmitRenderRequest`, not as an enabled + camera and not on `WaitForEndOfFrame`. That keeps the stream going when the editor + is unfocused or the Game view is hidden. +- **Video encoding:** the texture is read back at 25fps and converted to top-down BGR24. + A background thread VP9-encodes each frame with `VP9Codec` (libvpx's realtime encoder at + speed 9, on up to 4 threads) and sends it with `RTCPeerConnection.SendVideo`. Each + frame's RTP timestamp comes from the time it was captured, so a slow encode doesn't + make the video run slow. Every 5 seconds the console shows the encoded frame rate, the + time per frame and the bitrate. +- **Audio:** a `GameAudioTap` component goes beside the scene's `AudioListener`. Unity + passes the final game mix through its `OnAudioFilterRead`. The tap downmixes it to mono + 16-bit PCM in 20ms frames. A background thread Opus-encodes the frames and sends them + with `RTCPeerConnection.SendAudio`. +- **Signaling:** a small in-process `HttpListener` serves the browser page and answers + `POST /offer`. + +## Speed + +Unity runs SIPSorcery.VP9's netstandard2.1 build on its Mono runtime. That build has no +SIMD, so it is slower than on .NET 8 and later. Steady-state encode times on an i9-10900 +(speed 9, about 1 Mbit/s): + +| Size | Threads | Release code optimisation | Debug code optimisation | +|---|---|---|---| +| 640x360 | 2 | 21 ms | 85 ms | +| 640x360 | 4 | 15 ms (the example: 25fps) | 57 ms (17fps) | +| 960x540 | 4 | 35 ms | 160 ms | +| 960x540 | 8 | 27 ms | 111 ms | + +- **Switch the editor to Release.** The editor starts in Debug code optimisation by + default. There the attached debugger stops Mono's JIT from optimising, and the encoder + runs about 4x slower. The example then streams at about 17fps and logs a warning. The + bug icon at the right of the editor's status bar switches to Release. (Only the + editor has been tested, not player builds.) +- **Changing the size:** set `WIDTH` and `HEIGHT` at the top of `WebRTCVideoSource.cs`, and + `VP9_THREADS` for more threads. Keep the time a frame, shown in the console every + 5 seconds, under 40ms for 25fps. + +## Files + +| File | Purpose | +|---|---| +| `setup.ps1` | Builds the plugins into a template project and copies the files below into it. | +| `Assets/Scripts/WebRTCVideoSource.cs` | The capture, encode and WebRTC code, plus the browser page. | +| `Assets/Editor/SIPSorcerySceneSetup.cs` | Places the robot and music in the template's scene. | +| `Assets/Editor/AutoPlaySmokeTest.cs` | Starts play mode without the editor window, for testing. Safe to delete. | + +## Notes + +- **Opus only:** the audio track offers Opus and no fallback, because every WebRTC browser + supports Opus. If PCMU were also offered, SIPSorcery's answer would list the static + payload ID first, and PCMU would be sent at telephone quality. +- **Microsoft.Extensions versions:** Unity 6000.5 and later ship their own + `Microsoft.Extensions.*` assemblies (v8.0, in `Editor\Data\BCLExtensions`). These + always win over copies in `Assets/Plugins` at compile time. SIPSorcery's netstandard2.1 + build references the same 8.0 packages (see `src/Directory.Packages.props`). If it + referenced the 10.x ones, every script would fail to compile with CS1705. +- **Run in background:** `Application.runInBackground = true` is essential. Without it, + the player loop suspends when the editor loses focus. That happens exactly when you + switch to the browser to click Connect, so the video freezes. +- **Upgrading a project:** Unity 6000.6 moves `com.unity.learn.iet-framework` to 6.x, + which renames the namespace `Unity.Tutorials.Core.Editor` to `Unity.Tutorials.Editor`. + - For a new project, Unity's script updater rewrites the template's two tutorial + scripts by itself while it creates the project. + - For a project made by an older editor, accept the editor's offer to update the + scripts. Otherwise the errors stop every script in the project from compiling, + including this example's. Or fix the `using` lines in + `Assets/Tutorials/Styles/ApplyCustomThemeHelper.cs` and + `Assets/Tutorials/Settings/Editor/TutorialCallbacks.cs` by hand. +- **Editor log noise:** the console message "Unable to join player connection multicast + group" is Unity's own player discovery and is harmless. +- **Overlay UI:** screen-space overlay UI (the collectible counter) renders to the + screen, not to the mirror camera, so it does not appear in the stream. +- **ReadPixels:** capture uses synchronous `ReadPixels` for simplicity. Switch to + `AsyncGPUReadback` if the main-thread stall matters in a heavier scene. diff --git a/examples/WebRTCExamples/UnityAudioVideoSource/setup.ps1 b/examples/WebRTCExamples/UnityAudioVideoSource/setup.ps1 new file mode 100644 index 0000000000..353f87f405 --- /dev/null +++ b/examples/WebRTCExamples/UnityAudioVideoSource/setup.ps1 @@ -0,0 +1,86 @@ +# Adds the SIPSorcery WebRTC audio/video source to a Unity project created from Unity's +# "Get Started With Unity" template: +# +# - builds SIPSorcery and SIPSorcery.VP9 (the pure C# VP9 codec) for netstandard2.1, the +# profile Unity's player consumes, and copies them, with their dependencies, into +# Assets/Plugins/SIPSorcery. All managed: nothing native to install; +# - copies this folder's Assets (the streaming script and the scene setup editor script) +# into the project. +# +# ./setup.ps1 -ProjectPath "C:\Users\me\My project" [-SipsorceryRoot C:\dev\sipsorcery] +# +# Run it with the project closed in Unity, and again after changing the library source. + +param( + [Parameter(Mandatory = $true)] + [string]$ProjectPath, + [string]$SipsorceryRoot = "$PSScriptRoot\..\..\.." +) + +$ErrorActionPreference = "Stop" +$project = (Resolve-Path $ProjectPath).Path +$repoRoot = (Resolve-Path $SipsorceryRoot).Path + +if (-not (Test-Path "$project\Assets") -or -not (Test-Path "$project\ProjectSettings")) { + throw "'$project' is not a Unity project (no Assets and ProjectSettings folders)." +} +if (-not (Test-Path "$project\Assets\Prefabs\PlayerRobot.prefab")) { + Write-Warning ("'$project' doesn't look like it came from the Get Started template (no Assets\Prefabs\PlayerRobot.prefab). " + + "The stream works from any scene with a camera tagged MainCamera, but the scene setup won't apply.") +} + +$plugins = "$project\Assets\Plugins\SIPSorcery" +$staging = Join-Path ([IO.Path]::GetTempPath()) "sipsorcery-unity-plugins" + +New-Item -ItemType Directory -Force $plugins | Out-Null +Remove-Item $staging -Recurse -Force -ErrorAction SilentlyContinue +New-Item -ItemType Directory -Force $staging | Out-Null + +# The netstandard2.1 build references the 8.0 Microsoft.Extensions.* packages (see +# src/Directory.Packages.props). That matters here: Unity 6000.5 and later ship their own v8.0 +# Microsoft.Extensions.* / System.Diagnostics.DiagnosticSource (Editor\Data\BCLExtensions), +# which always win over Assets/Plugins copies at compile time, and a 10.x reference would make +# every script fail to compile with CS1705. +Write-Host "Publishing SIPSorcery (netstandard2.1) with dependencies..." +dotnet publish "$repoRoot\src\SIPSorcery\SIPSorcery.csproj" -c Release -f netstandard2.1 -o "$staging\out" | Out-Null +if ($LASTEXITCODE -ne 0) { throw "dotnet publish of SIPSorcery failed." } + +Write-Host "Publishing SIPSorcery.VP9 (netstandard2.1)..." +dotnet publish "$repoRoot\src\Codecs\SIPSorcery.VP9\SIPSorcery.VP9.csproj" -c Release -f netstandard2.1 -o "$staging\out" | Out-Null +if ($LASTEXITCODE -ne 0) { throw "dotnet publish of SIPSorcery.VP9 failed." } + +# Copy the managed assemblies, skipping reference/facade assemblies Unity provides itself. +$skip = @("netstandard.dll", "Microsoft.CSharp.dll") +$newSet = Get-ChildItem "$staging\out" -Filter "*.dll" | Where-Object { $skip -notcontains $_.Name } +$newSet | ForEach-Object { Copy-Item $_.FullName $plugins -Force } + +# Assets/Plugins/SIPSorcery belongs to this script: remove DLLs from a previous run that are +# no longer in the dependency closure (FFmpeg.AutoGen and SIPSorceryMedia.FFmpeg, from when this +# example encoded VP8 with FFmpeg). Older copies of this example put the DLLs straight into +# Assets/Plugins; Unity refuses duplicate assemblies, so remove those too (by name: the current +# set, and the ones SIPSorcery has since dropped). +$keep = @($newSet.Name) +$formerFlat = $keep + @("Common.Logging.dll", "Common.Logging.Core.dll", "Makaretu.Dns.dll", "Makaretu.Dns.Multicast.dll", + "SimpleBase.dll", "System.Net.IPNetwork.dll", "System.Reflection.TypeExtensions.dll", "Tmds.LibC.dll", "SIPSorcery.VP8.dll", + "FFmpeg.AutoGen.dll", "SIPSorceryMedia.FFmpeg.dll") +$stale = @(Get-ChildItem $plugins -Filter "*.dll" | Where-Object { $keep -notcontains $_.Name }) + + @(Get-ChildItem "$project\Assets\Plugins" -Filter "*.dll" | Where-Object { $formerFlat -contains $_.Name }) +foreach ($dll in $stale) { + Write-Host "Removing old plugin $($dll.FullName.Substring($dll.FullName.LastIndexOf('\Assets\') + 1))." + Remove-Item $dll.FullName -Force + Remove-Item "$($dll.FullName).meta" -Force -ErrorAction SilentlyContinue +} + +# Copy the example's own files. +$overlay = "$PSScriptRoot\Assets" +Get-ChildItem $overlay -Recurse -File | ForEach-Object { + $relative = $_.FullName.Substring($overlay.Length + 1) + $target = Join-Path "$project\Assets" $relative + New-Item -ItemType Directory -Force (Split-Path $target) | Out-Null + Copy-Item $_.FullName $target -Force + Write-Host "Copied Assets\$relative" +} + +Write-Host "Plugins in ${plugins}:" +Get-ChildItem $plugins -Filter "*.dll" | ForEach-Object { Write-Host " $($_.Name)" } +Write-Host "Done. Open the project in Unity, press Play in GetStarted_Scene, then browse to http://localhost:8081." diff --git a/examples/WebRTCExamples/UnityVideoSource/ProjectSettings/MemorySettings.asset b/examples/WebRTCExamples/UnityVideoSource/ProjectSettings/MemorySettings.asset new file mode 100644 index 0000000000..517e60eabc --- /dev/null +++ b/examples/WebRTCExamples/UnityVideoSource/ProjectSettings/MemorySettings.asset @@ -0,0 +1,35 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!387306366 &1 +MemorySettings: + m_ObjectHideFlags: 0 + m_EditorMemorySettings: + m_MainAllocatorBlockSize: -1 + m_ThreadAllocatorBlockSize: -1 + m_MainGfxBlockSize: -1 + m_ThreadGfxBlockSize: -1 + m_CacheBlockSize: -1 + m_TypetreeBlockSize: -1 + m_ProfilerBlockSize: -1 + m_ProfilerEditorBlockSize: -1 + m_BucketAllocatorGranularity: -1 + m_BucketAllocatorBucketsCount: -1 + m_BucketAllocatorBlockSize: -1 + m_BucketAllocatorBlockCount: -1 + m_ProfilerBucketAllocatorGranularity: -1 + m_ProfilerBucketAllocatorBucketsCount: -1 + m_ProfilerBucketAllocatorBlockSize: -1 + m_ProfilerBucketAllocatorBlockCount: -1 + m_TempAllocatorSizeMain: -1 + m_JobTempAllocatorBlockSize: -1 + m_BackgroundJobTempAllocatorBlockSize: -1 + m_JobTempAllocatorReducedBlockSize: -1 + m_TempAllocatorSizeGIBakingWorker: -1 + m_TempAllocatorSizeNavMeshWorker: -1 + m_TempAllocatorSizeAudioWorker: -1 + m_TempAllocatorSizeCloudWorker: -1 + m_TempAllocatorSizeGfx: -1 + m_TempAllocatorSizeJobWorker: -1 + m_TempAllocatorSizeBackgroundWorker: -1 + m_TempAllocatorSizePreloadManager: -1 + m_PlatformMemorySettings: [] diff --git a/examples/WebRTCExamples/UnityVideoSource/ProjectSettings/MultiplayerManager.asset b/examples/WebRTCExamples/UnityVideoSource/ProjectSettings/MultiplayerManager.asset new file mode 100644 index 0000000000..c19bcd739d --- /dev/null +++ b/examples/WebRTCExamples/UnityVideoSource/ProjectSettings/MultiplayerManager.asset @@ -0,0 +1,9 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!655991488 &1 +MultiplayerManager: + m_ObjectHideFlags: 0 + m_EnableMultiplayerRoles: 0 + m_EnablePlayModeLocalDeployment: 0 + m_EnablePlayModeRemoteDeployment: 0 + m_StrippingTypes: {} diff --git a/examples/WebRTCExamples/UnityVideoSource/ProjectSettings/VersionControlSettings.asset b/examples/WebRTCExamples/UnityVideoSource/ProjectSettings/VersionControlSettings.asset new file mode 100644 index 0000000000..979fd8eca8 --- /dev/null +++ b/examples/WebRTCExamples/UnityVideoSource/ProjectSettings/VersionControlSettings.asset @@ -0,0 +1,7 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!890905787 &1 +VersionControlSettings: + m_ObjectHideFlags: 0 + m_Mode: Visible Meta Files + m_TrackPackagesOutsideProject: 0 diff --git a/src/Codecs/SIPSorcery.VP9/GlobalUsings.cs b/src/Codecs/SIPSorcery.VP9/GlobalUsings.cs index 29070df17e..7ef0cc50d1 100644 --- a/src/Codecs/SIPSorcery.VP9/GlobalUsings.cs +++ b/src/Codecs/SIPSorcery.VP9/GlobalUsings.cs @@ -36,10 +36,12 @@ global using uint32_t = System.UInt32; global using int64_t = System.Int64; global using uint64_t = System.UInt64; -global using size_t = System.UIntPtr; -global using ptrdiff_t = System.IntPtr; -global using intptr_t = System.IntPtr; -global using uintptr_t = System.UIntPtr; +// nuint and nint, not UIntPtr and IntPtr: the same types, but only .NET 7 and later give +// IntPtr and UIntPtr nint's arithmetic and constants, and the netstandard2.1 build needs them. +global using size_t = nuint; +global using ptrdiff_t = nint; +global using intptr_t = nint; +global using uintptr_t = nuint; // vpx_dsp/vpx_dsp_common.h (CONFIG_VP9_HIGHBITDEPTH=0) global using tran_high_t = System.Int32; @@ -49,7 +51,7 @@ global using vpx_prob = System.Byte; global using vpx_tree_index = System.SByte; // vpx_dsp/bitreader.h -global using BD_VALUE = System.UIntPtr; +global using BD_VALUE = nuint; // vpx/vpx_codec.h, vpx_image.h, vpx_encoder.h enums (C enums are int) global using vpx_codec_err_t = System.Int32; diff --git a/src/Codecs/SIPSorcery.VP9/README.md b/src/Codecs/SIPSorcery.VP9/README.md index da5db8ce6d..534742bf32 100644 --- a/src/Codecs/SIPSorcery.VP9/README.md +++ b/src/Codecs/SIPSorcery.VP9/README.md @@ -177,6 +177,18 @@ frame, and 40 s runs at 1080p (VP8 or VP9 in) and a 30 s run at 720p pass read tens to hundreds of frames a run, as with Chromium's own libvpx encoder set up the same way. +### netstandard2.1 (Unity) + +The library also builds for netstandard2.1, which Unity's Mono runtime loads. That +build has no SIMD (`Vector128` isn't there), and its inline arrays are nested +structs, since Mono has no `[InlineArray]` (`netstandard/`, written by the tools). +It gives the same bytes as the other builds. In the Unity 6 editor (x64 Mono, +Release code optimisation), 640x360 at speed 9 encodes in about 15 ms a frame on 4 +threads and 960x540 in about 27 ms on 8. With the editor's default Debug code +optimisation it is about 4x slower. The +[`UnityAudioVideoSource`](../../../examples/WebRTCExamples/UnityAudioVideoSource) +example streams a game with it. + ## Port conventions - **File for file.** Each `.cs` file ports one libvpx source file (and its @@ -197,8 +209,9 @@ set up the same way. ## Tests -- `test/SIPSorcery.VP9.UnitTest`: the kernel fixtures, and the SIMD kernels - against the C kernels. +- `test/SIPSorcery.VP9.UnitTest`: the kernel fixtures, the SIMD kernels + against the C kernels, and a check of the IL for whole-struct loads that are + thrown away (`StackFrameTests`: Mono copies them onto the stack). - `test/SIPSorcery.VP9.TestVectors`: the decoder corpus, the encoder scripts (byte-exact and decodable, with leak checks), tile column threads against one thread and row based multithreading on 3 to 8 threads against 2, diff --git a/src/Codecs/SIPSorcery.VP9/SIPSorcery.VP9.csproj b/src/Codecs/SIPSorcery.VP9/SIPSorcery.VP9.csproj index 1a01365a83..b2cf97c6fe 100644 --- a/src/Codecs/SIPSorcery.VP9/SIPSorcery.VP9.csproj +++ b/src/Codecs/SIPSorcery.VP9/SIPSorcery.VP9.csproj @@ -1,8 +1,9 @@ - - net8.0;net9.0;net10.0 + + netstandard2.1;net8.0;net9.0;net10.0 12.0 @@ -55,6 +56,16 @@ A pure .NET (no native code) port of the libvpx VP9 video codec: the full 8-bit + + + + + + + + diff --git a/src/Codecs/SIPSorcery.VP9/VP9Codec.cs b/src/Codecs/SIPSorcery.VP9/VP9Codec.cs index 74fcb4cb74..79fc0aa883 100644 --- a/src/Codecs/SIPSorcery.VP9/VP9Codec.cs +++ b/src/Codecs/SIPSorcery.VP9/VP9Codec.cs @@ -315,7 +315,11 @@ private byte[] Encode(int width, int height, byte* i420, int length) } else { +#if NETSTANDARD2_1 + pts = (long)((Stopwatch.GetTimestamp() - _created) * (TimeSpan.TicksPerSecond / (double)Stopwatch.Frequency)) * 9 / 1000; +#else pts = Stopwatch.GetElapsedTime(_created).Ticks * 9 / 1000; // 90 kHz +#endif if (pts <= _lastPts) { pts = _lastPts + 1; diff --git a/src/Codecs/SIPSorcery.VP9/VP9NetVideoEndPoint.cs b/src/Codecs/SIPSorcery.VP9/VP9NetVideoEndPoint.cs index 0ded5d291e..70d90a10b8 100644 --- a/src/Codecs/SIPSorcery.VP9/VP9NetVideoEndPoint.cs +++ b/src/Codecs/SIPSorcery.VP9/VP9NetVideoEndPoint.cs @@ -117,7 +117,11 @@ public void GotVideoFrame(IPEndPoint remoteEndPoint, uint timestamp, byte[] fram if (_codec.KeyFrameRequired) { +#if NETSTANDARD2_1 + long now = Stopwatch.GetTimestamp() * 1000 / Stopwatch.Frequency; +#else long now = Environment.TickCount64; +#endif if (now - _lastKeyFrameRequest >= KEY_FRAME_REQUEST_INTERVAL_MS) { _lastKeyFrameRequest = now; diff --git a/src/Codecs/SIPSorcery.VP9/common/vp9_alloccommon.cs b/src/Codecs/SIPSorcery.VP9/common/vp9_alloccommon.cs index 79b0727e79..f00081ff33 100644 --- a/src/Codecs/SIPSorcery.VP9/common/vp9_alloccommon.cs +++ b/src/Codecs/SIPSorcery.VP9/common/vp9_alloccommon.cs @@ -104,13 +104,13 @@ internal static void vp9_free_ref_frame_buffers(BufferPool* pool) for (i = 0; i < FRAME_BUFFERS; ++i) { if (((pool->frame_bufs[i].released) == 0) && pool->frame_bufs[i].raw_frame_buffer.data != null) { - pool->release_fb_cb(pool->cb_priv, &pool->frame_bufs[i].raw_frame_buffer); + pool->release_fb_cb(pool->cb_priv, addr(ref pool->frame_bufs[i].raw_frame_buffer)); pool->frame_bufs[i].ref_count = 0; pool->frame_bufs[i].released = 1; } vpx_free(pool->frame_bufs[i].mvs); pool->frame_bufs[i].mvs = null; - vpx_free_frame_buffer(&pool->frame_bufs[i].buf); + vpx_free_frame_buffer(addr(ref pool->frame_bufs[i].buf)); } } diff --git a/src/Codecs/SIPSorcery.VP9/common/vp9_blockd.cs b/src/Codecs/SIPSorcery.VP9/common/vp9_blockd.cs index 3229359de9..06266abbc3 100644 --- a/src/Codecs/SIPSorcery.VP9/common/vp9_blockd.cs +++ b/src/Codecs/SIPSorcery.VP9/common/vp9_blockd.cs @@ -141,7 +141,7 @@ internal static void reset_skip_context(MACROBLOCKD* xd, BLOCK_SIZE bsize) { int i; for (i = 0; i < MAX_MB_PLANE; i++) { - macroblockd_plane* pd = &xd->plane[i]; + macroblockd_plane* pd = addr(ref xd->plane[i]); BLOCK_SIZE plane_bsize = get_plane_block_size(bsize, pd); memset(pd->above_context, 0, sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide_lookup[plane_bsize]); @@ -154,7 +154,7 @@ internal static void reset_skip_context(MACROBLOCKD* xd, BLOCK_SIZE bsize) { PREDICTION_MODE above = vp9_above_block_mode(mi, above_mi, block); PREDICTION_MODE left = vp9_left_block_mode(mi, left_mi, block); - return (byte*)&vp9_kf_y_mode_prob[above][left]; + return (byte*)addr(ref vp9_kf_y_mode_prob[above][left]); } // ---- vp9_blockd.c ---- @@ -185,7 +185,7 @@ internal static PREDICTION_MODE vp9_above_block_mode(MODE_INFO* cur_mi, MODE_INF internal static void vp9_foreach_transformed_block_in_plane(MACROBLOCKD* xd, BLOCK_SIZE bsize, int plane, foreach_transformed_block_visitor visit, void* arg) { - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); MODE_INFO* mi = xd->mi[0]; // block and transform sizes, in number of 4x4 blocks log 2 ("*_b") // 4x4=0, 8x8=2, 16x16=4, 32x32=6, 64x64=8 diff --git a/src/Codecs/SIPSorcery.VP9/common/vp9_entropy.cs b/src/Codecs/SIPSorcery.VP9/common/vp9_entropy.cs index b5c559d83a..1f653fe405 100644 --- a/src/Codecs/SIPSorcery.VP9/common/vp9_entropy.cs +++ b/src/Codecs/SIPSorcery.VP9/common/vp9_entropy.cs @@ -524,19 +524,19 @@ internal static void vp9_default_coef_probs(VP9_COMMON* cm) { do { Debug.Assert((2 * sizeof(vp9_coeff_probs_model)) == (2 * sizeof(vp9_coeff_probs_model))); - memcpy((void*)&(cm->fc->coef_probs[TX_4X4]), default_coef_probs_4x4, ((nuint)(2 * sizeof(vp9_coeff_probs_model)))); + memcpy((void*)addr(ref cm->fc->coef_probs[TX_4X4]), default_coef_probs_4x4, ((nuint)(2 * sizeof(vp9_coeff_probs_model)))); } while (0 != 0); do { Debug.Assert((2 * sizeof(vp9_coeff_probs_model)) == (2 * sizeof(vp9_coeff_probs_model))); - memcpy((void*)&(cm->fc->coef_probs[TX_8X8]), default_coef_probs_8x8, ((nuint)(2 * sizeof(vp9_coeff_probs_model)))); + memcpy((void*)addr(ref cm->fc->coef_probs[TX_8X8]), default_coef_probs_8x8, ((nuint)(2 * sizeof(vp9_coeff_probs_model)))); } while (0 != 0); do { Debug.Assert((2 * sizeof(vp9_coeff_probs_model)) == (2 * sizeof(vp9_coeff_probs_model))); - memcpy((void*)&(cm->fc->coef_probs[TX_16X16]), default_coef_probs_16x16, ((nuint)(2 * sizeof(vp9_coeff_probs_model)))); + memcpy((void*)addr(ref cm->fc->coef_probs[TX_16X16]), default_coef_probs_16x16, ((nuint)(2 * sizeof(vp9_coeff_probs_model)))); } while (0 != 0); do { Debug.Assert((2 * sizeof(vp9_coeff_probs_model)) == (2 * sizeof(vp9_coeff_probs_model))); - memcpy((void*)&(cm->fc->coef_probs[TX_32X32]), default_coef_probs_32x32, ((nuint)(2 * sizeof(vp9_coeff_probs_model)))); + memcpy((void*)addr(ref cm->fc->coef_probs[TX_32X32]), default_coef_probs_32x32, ((nuint)(2 * sizeof(vp9_coeff_probs_model)))); } while (0 != 0); } @@ -551,10 +551,10 @@ private static void adapt_coef_probs(VP9_COMMON* cm, TX_SIZE tx_size, uint count { A2* branch_ct = stackalloc A2[UNCONSTRAINED_NODES]; FRAME_CONTEXT* pre_fc = &cm->frame_contexts[cm->frame_context_idx]; - vp9_coeff_probs_model* probs = (A2>>>*)&(cm->fc->coef_probs[tx_size]); - vp9_coeff_probs_model* pre_probs = (A2>>>*)&(pre_fc->coef_probs[tx_size]); - vp9_coeff_count_model* counts = (A2>>>*)&(cm->counts.coef[tx_size]); - A2>>* eob_counts = (A2>>*)&(cm->counts.eob_branch[tx_size]); + vp9_coeff_probs_model* probs = (A2>>>*)addr(ref cm->fc->coef_probs[tx_size]); + vp9_coeff_probs_model* pre_probs = (A2>>>*)addr(ref pre_fc->coef_probs[tx_size]); + vp9_coeff_count_model* counts = (A2>>>*)addr(ref cm->counts.coef[tx_size]); + A2>>* eob_counts = (A2>>*)addr(ref cm->counts.eob_branch[tx_size]); int i; int j; int k; int l; int m; for (i = 0; i < PLANE_TYPES; ++i) diff --git a/src/Codecs/SIPSorcery.VP9/common/vp9_entropymode.cs b/src/Codecs/SIPSorcery.VP9/common/vp9_entropymode.cs index 2bbbbed33d..c8adaae9fc 100644 --- a/src/Codecs/SIPSorcery.VP9/common/vp9_entropymode.cs +++ b/src/Codecs/SIPSorcery.VP9/common/vp9_entropymode.cs @@ -256,39 +256,39 @@ internal static void vp9_adapt_mode_probs(VP9_COMMON* cm) for (i = 0; i < INTRA_INTER_CONTEXTS; i++) fc->intra_inter_prob[i] = mode_mv_merge_probs(pre_fc->intra_inter_prob[i], - (uint*)&(counts->intra_inter[i])); + (uint*)addr(ref counts->intra_inter[i])); for (i = 0; i < COMP_INTER_CONTEXTS; i++) fc->comp_inter_prob[i] = - mode_mv_merge_probs(pre_fc->comp_inter_prob[i], (uint*)&(counts->comp_inter[i])); + mode_mv_merge_probs(pre_fc->comp_inter_prob[i], (uint*)addr(ref counts->comp_inter[i])); for (i = 0; i < REF_CONTEXTS; i++) fc->comp_ref_prob[i] = - mode_mv_merge_probs(pre_fc->comp_ref_prob[i], (uint*)&(counts->comp_ref[i])); + mode_mv_merge_probs(pre_fc->comp_ref_prob[i], (uint*)addr(ref counts->comp_ref[i])); for (i = 0; i < REF_CONTEXTS; i++) for (j = 0; j < 2; j++) fc->single_ref_prob[i][j] = mode_mv_merge_probs( - pre_fc->single_ref_prob[i][j], (uint*)&(counts->single_ref[i][j])); + pre_fc->single_ref_prob[i][j], (uint*)addr(ref counts->single_ref[i][j])); for (i = 0; i < INTER_MODE_CONTEXTS; i++) - vpx_tree_merge_probs(vp9_inter_mode_tree, (byte*)&(pre_fc->inter_mode_probs[i]), - (uint*)&(counts->inter_mode[i]), (byte*)&(fc->inter_mode_probs[i])); + vpx_tree_merge_probs(vp9_inter_mode_tree, (byte*)addr(ref pre_fc->inter_mode_probs[i]), + (uint*)addr(ref counts->inter_mode[i]), (byte*)addr(ref fc->inter_mode_probs[i])); for (i = 0; i < BLOCK_SIZE_GROUPS; i++) - vpx_tree_merge_probs(vp9_intra_mode_tree, (byte*)&(pre_fc->y_mode_prob[i]), - (uint*)&(counts->y_mode[i]), (byte*)&(fc->y_mode_prob[i])); + vpx_tree_merge_probs(vp9_intra_mode_tree, (byte*)addr(ref pre_fc->y_mode_prob[i]), + (uint*)addr(ref counts->y_mode[i]), (byte*)addr(ref fc->y_mode_prob[i])); for (i = 0; i < INTRA_MODES; ++i) - vpx_tree_merge_probs(vp9_intra_mode_tree, (byte*)&(pre_fc->uv_mode_prob[i]), - (uint*)&(counts->uv_mode[i]), (byte*)&(fc->uv_mode_prob[i])); + vpx_tree_merge_probs(vp9_intra_mode_tree, (byte*)addr(ref pre_fc->uv_mode_prob[i]), + (uint*)addr(ref counts->uv_mode[i]), (byte*)addr(ref fc->uv_mode_prob[i])); for (i = 0; i < PARTITION_CONTEXTS; i++) - vpx_tree_merge_probs(vp9_partition_tree, (byte*)&(pre_fc->partition_prob[i]), - (uint*)&(counts->partition[i]), (byte*)&(fc->partition_prob[i])); + vpx_tree_merge_probs(vp9_partition_tree, (byte*)addr(ref pre_fc->partition_prob[i]), + (uint*)addr(ref counts->partition[i]), (byte*)addr(ref fc->partition_prob[i])); if (cm->interp_filter == SWITCHABLE) { for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) vpx_tree_merge_probs( - vp9_switchable_interp_tree, (byte*)&(pre_fc->switchable_interp_prob[i]), - (uint*)&(counts->switchable_interp[i]), (byte*)&(fc->switchable_interp_prob[i])); + vp9_switchable_interp_tree, (byte*)addr(ref pre_fc->switchable_interp_prob[i]), + (uint*)addr(ref counts->switchable_interp[i]), (byte*)addr(ref fc->switchable_interp_prob[i])); } if (cm->tx_mode == TX_MODE_SELECT) { @@ -297,17 +297,17 @@ internal static void vp9_adapt_mode_probs(VP9_COMMON* cm) for (i = 0; i < TX_SIZE_CONTEXTS; ++i) { - tx_counts_to_branch_counts_8x8((uint*)&(counts->tx.p8x8[i]), branch_ct_8x8p); + tx_counts_to_branch_counts_8x8((uint*)addr(ref counts->tx.p8x8[i]), branch_ct_8x8p); for (j = 0; j < TX_SIZES - 3; ++j) fc->tx_probs.p8x8[i][j] = mode_mv_merge_probs(pre_fc->tx_probs.p8x8[i][j], (uint*)&branch_ct_8x8p[j]); - tx_counts_to_branch_counts_16x16((uint*)&(counts->tx.p16x16[i]), branch_ct_16x16p); + tx_counts_to_branch_counts_16x16((uint*)addr(ref counts->tx.p16x16[i]), branch_ct_16x16p); for (j = 0; j < TX_SIZES - 2; ++j) fc->tx_probs.p16x16[i][j] = mode_mv_merge_probs( pre_fc->tx_probs.p16x16[i][j], (uint*)&branch_ct_16x16p[j]); - tx_counts_to_branch_counts_32x32((uint*)&(counts->tx.p32x32[i]), branch_ct_32x32p); + tx_counts_to_branch_counts_32x32((uint*)addr(ref counts->tx.p32x32[i]), branch_ct_32x32p); for (j = 0; j < TX_SIZES - 1; ++j) fc->tx_probs.p32x32[i][j] = mode_mv_merge_probs( pre_fc->tx_probs.p32x32[i][j], (uint*)&branch_ct_32x32p[j]); @@ -316,7 +316,7 @@ internal static void vp9_adapt_mode_probs(VP9_COMMON* cm) for (i = 0; i < SKIP_CONTEXTS; ++i) fc->skip_probs[i] = - mode_mv_merge_probs(pre_fc->skip_probs[i], (uint*)&(counts->skip[i])); + mode_mv_merge_probs(pre_fc->skip_probs[i], (uint*)addr(ref counts->skip[i])); } private static void set_default_lf_deltas(loopfilter* lf) diff --git a/src/Codecs/SIPSorcery.VP9/common/vp9_entropymv.cs b/src/Codecs/SIPSorcery.VP9/common/vp9_entropymv.cs index 5bc5cbe91d..4bbe9c5dc2 100644 --- a/src/Codecs/SIPSorcery.VP9/common/vp9_entropymv.cs +++ b/src/Codecs/SIPSorcery.VP9/common/vp9_entropymv.cs @@ -240,11 +240,11 @@ internal static void vp9_inc_mv(MV* mv, nmv_context_counts* counts) ++counts->joints[j]; if ((mv_joint_vertical(j)) != 0) { - inc_mv_component(mv->row, &counts->comps[0], 1, 1); + inc_mv_component(mv->row, addr(ref counts->comps[0]), 1, 1); } if ((mv_joint_horizontal(j)) != 0) { - inc_mv_component(mv->col, &counts->comps[1], 1, 1); + inc_mv_component(mv->col, addr(ref counts->comps[1]), 1, 1); } } } @@ -261,9 +261,9 @@ internal static void vp9_adapt_mv_probs(VP9_COMMON* cm, int allow_hp) fc->joints); for (i = 0; i < 2; ++i) { - nmv_component* comp = &fc->comps[i]; - nmv_component* pre_comp = &pre_fc->comps[i]; - nmv_component_counts* c = &counts->comps[i]; + nmv_component* comp = addr(ref fc->comps[i]); + nmv_component* pre_comp = addr(ref pre_fc->comps[i]); + nmv_component_counts* c = addr(ref counts->comps[i]); comp->sign = mode_mv_merge_probs(pre_comp->sign, c->sign); vpx_tree_merge_probs(vp9_mv_class_tree, pre_comp->classes, c->classes, @@ -272,11 +272,11 @@ internal static void vp9_adapt_mv_probs(VP9_COMMON* cm, int allow_hp) comp->class0); for (j = 0; j < MV_OFFSET_BITS; ++j) - comp->bits[j] = mode_mv_merge_probs(pre_comp->bits[j], (uint*)&(c->bits[j])); + comp->bits[j] = mode_mv_merge_probs(pre_comp->bits[j], (uint*)addr(ref c->bits[j])); for (j = 0; j < CLASS0_SIZE; ++j) - vpx_tree_merge_probs(vp9_mv_fp_tree, (byte*)&(pre_comp->class0_fp[j]), - (uint*)&(c->class0_fp[j]), (byte*)&(comp->class0_fp[j])); + vpx_tree_merge_probs(vp9_mv_fp_tree, (byte*)addr(ref pre_comp->class0_fp[j]), + (uint*)addr(ref c->class0_fp[j]), (byte*)addr(ref comp->class0_fp[j])); vpx_tree_merge_probs(vp9_mv_fp_tree, pre_comp->fp, c->fp, comp->fp); diff --git a/src/Codecs/SIPSorcery.VP9/common/vp9_loopfilter.cs b/src/Codecs/SIPSorcery.VP9/common/vp9_loopfilter.cs index 54d385453a..75d446104d 100644 --- a/src/Codecs/SIPSorcery.VP9/common/vp9_loopfilter.cs +++ b/src/Codecs/SIPSorcery.VP9/common/vp9_loopfilter.cs @@ -181,8 +181,8 @@ private static void update_sharpness(loop_filter_info_n* lfi, int sharpness_lvl) if (block_inside_limit < 1) block_inside_limit = 1; - memset(lfi->lfthr[lvl].lim, block_inside_limit, SIMD_WIDTH); - memset(lfi->lfthr[lvl].mblim, (2 * (lvl + 2) + block_inside_limit), + memset(addr(ref lfi->lfthr[lvl])->lim, block_inside_limit, SIMD_WIDTH); + memset(addr(ref lfi->lfthr[lvl])->mblim, (2 * (lvl + 2) + block_inside_limit), SIMD_WIDTH); } } @@ -204,7 +204,7 @@ internal static void vp9_loop_filter_init(VP9_COMMON* cm) // init hev threshold const vectors for (lvl = 0; lvl <= MAX_LOOP_FILTER; lvl++) - memset(lfi->lfthr[lvl].hev_thr, (lvl >> 4), SIMD_WIDTH); + memset(addr(ref lfi->lfthr[lvl])->hev_thr, (lvl >> 4), SIMD_WIDTH); } internal static void vp9_loop_filter_frame_init(VP9_COMMON* cm, int default_filt_lvl) @@ -236,7 +236,7 @@ internal static void vp9_loop_filter_frame_init(VP9_COMMON* cm, int default_filt if ((lf->mode_ref_delta_enabled) == 0) { // we could get rid of this if we assume that deltas are set to // zero when not in use; encoder always uses deltas - memset((void*)&(lfi->lvl[seg_id]), lvl_seg, (8 * sizeof(uint8_t))); + memset((void*)addr(ref lfi->lvl[seg_id]), lvl_seg, (8 * sizeof(uint8_t))); } else { int @ref; int mode; int intra_lvl = lvl_seg + lf->ref_deltas[INTRA_FRAME] * scale; diff --git a/src/Codecs/SIPSorcery.VP9/common/vp9_onyxc_int.cs b/src/Codecs/SIPSorcery.VP9/common/vp9_onyxc_int.cs index a4f778e4c1..c19b563447 100644 --- a/src/Codecs/SIPSorcery.VP9/common/vp9_onyxc_int.cs +++ b/src/Codecs/SIPSorcery.VP9/common/vp9_onyxc_int.cs @@ -93,7 +93,7 @@ internal static void init_frame_info(FRAME_INFO* frame_info, VP9_COMMON* cm) { if (index < 0 || index >= FRAME_BUFFERS) return null; if (cm->error.error_code != VPX_CODEC_OK) return null; - return &cm->buffer_pool->frame_bufs[index].buf; + return addr(ref cm->buffer_pool->frame_bufs[index].buf); } internal static YV12_BUFFER_CONFIG* get_ref_frame(VP9_COMMON* cm, int index) @@ -101,12 +101,12 @@ internal static void init_frame_info(FRAME_INFO* frame_info, VP9_COMMON* cm) if (index < 0 || index >= REF_FRAMES) return null; if (cm->ref_frame_map[index] < 0) return null; Debug.Assert(cm->ref_frame_map[index] < FRAME_BUFFERS); - return &cm->buffer_pool->frame_bufs[cm->ref_frame_map[index]].buf; + return addr(ref cm->buffer_pool->frame_bufs[cm->ref_frame_map[index]].buf); } internal static YV12_BUFFER_CONFIG* get_frame_new_buffer(VP9_COMMON* cm) { - return &cm->buffer_pool->frame_bufs[cm->new_fb_idx].buf; + return addr(ref cm->buffer_pool->frame_bufs[cm->new_fb_idx].buf); } internal static int get_free_fb(VP9_COMMON* cm) @@ -168,9 +168,9 @@ internal static void vp9_init_macroblockd(VP9_COMMON* cm, MACROBLOCKD* xd, tran_ i * sizeof(ENTROPY_CONTEXT) * 2 * mi_cols_aligned_to_sb(cm->mi_cols); if (get_plane_type(i) == PLANE_TYPE_Y) { - memcpy((void*)&(xd->plane[i].seg_dequant), (void*)&(cm->y_dequant), (16 * sizeof(int16_t))); + memcpy((void*)addr(ref xd->plane[i].seg_dequant), (void*)&(cm->y_dequant), (16 * sizeof(int16_t))); } else { - memcpy((void*)&(xd->plane[i].seg_dequant), (void*)&(cm->uv_dequant), (16 * sizeof(int16_t))); + memcpy((void*)addr(ref xd->plane[i].seg_dequant), (void*)&(cm->uv_dequant), (16 * sizeof(int16_t))); } xd->fc = cm->fc; } @@ -193,9 +193,9 @@ internal static void set_skip_context(MACROBLOCKD* xd, int mi_row, int mi_col) int left_idx = (mi_row * 2) & 15; int i; for (i = 0; i < MAX_MB_PLANE; ++i) { - macroblockd_plane* pd = &xd->plane[i]; + macroblockd_plane* pd = addr(ref xd->plane[i]); pd->above_context = &xd->above_context[i][above_idx >> pd->subsampling_x]; - pd->left_context = &xd->left_context[i][left_idx >> pd->subsampling_y]; + pd->left_context = addr(ref xd->left_context[i][left_idx >> pd->subsampling_y]); } } diff --git a/src/Codecs/SIPSorcery.VP9/common/vp9_pred_common.cs b/src/Codecs/SIPSorcery.VP9/common/vp9_pred_common.cs index 227303523f..5900189eb6 100644 --- a/src/Codecs/SIPSorcery.VP9/common/vp9_pred_common.cs +++ b/src/Codecs/SIPSorcery.VP9/common/vp9_pred_common.cs @@ -176,9 +176,9 @@ internal static int get_tx_size_context(MACROBLOCKD* xd) internal static vpx_prob* get_tx_probs(TX_SIZE max_tx_size, int ctx, tx_probs* tx_probs) { switch (max_tx_size) { - case TX_8X8: return (byte*)&(tx_probs->p8x8[ctx]); - case TX_16X16: return (byte*)&(tx_probs->p16x16[ctx]); - case TX_32X32: return (byte*)&(tx_probs->p32x32[ctx]); + case TX_8X8: return (byte*)addr(ref tx_probs->p8x8[ctx]); + case TX_16X16: return (byte*)addr(ref tx_probs->p16x16[ctx]); + case TX_32X32: return (byte*)addr(ref tx_probs->p32x32[ctx]); default: Debug.Assert(false, "Invalid max_tx_size."); return null; } } @@ -186,9 +186,9 @@ internal static int get_tx_size_context(MACROBLOCKD* xd) internal static uint* get_tx_counts(TX_SIZE max_tx_size, int ctx, tx_counts* tx_counts) { switch (max_tx_size) { - case TX_8X8: return (uint*)&(tx_counts->p8x8[ctx]); - case TX_16X16: return (uint*)&(tx_counts->p16x16[ctx]); - case TX_32X32: return (uint*)&(tx_counts->p32x32[ctx]); + case TX_8X8: return (uint*)addr(ref tx_counts->p8x8[ctx]); + case TX_16X16: return (uint*)addr(ref tx_counts->p16x16[ctx]); + case TX_32X32: return (uint*)addr(ref tx_counts->p32x32[ctx]); default: Debug.Assert(false, "Invalid max_tx_size."); return null; } } diff --git a/src/Codecs/SIPSorcery.VP9/common/vp9_reconinter.cs b/src/Codecs/SIPSorcery.VP9/common/vp9_reconinter.cs index 56af2bc427..8d4d734b10 100644 --- a/src/Codecs/SIPSorcery.VP9/common/vp9_reconinter.cs +++ b/src/Codecs/SIPSorcery.VP9/common/vp9_reconinter.cs @@ -134,7 +134,7 @@ private static void build_inter_predictors(MACROBLOCKD* xd, int plane, int block { uint8_t** buf_array = stackalloc uint8_t*[3]; int* stride_array = stackalloc int[3]; - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); MODE_INFO* mi = xd->mi[0]; int is_compound = has_second_ref(mi); InterpKernel* kernel = vp9_filter_kernels[mi->interp_filter]; @@ -142,7 +142,7 @@ private static void build_inter_predictors(MACROBLOCKD* xd, int plane, int block for (@ref = 0; @ref < 1 + is_compound; ++@ref) { scale_factors* sf = &xd->block_refs[@ref]->sf; - buf_2d* pre_buf = &pd->pre[@ref]; + buf_2d* pre_buf = addr(ref pd->pre[@ref]); buf_2d* dst_buf = &pd->dst; uint8_t* dst = dst_buf->buf + (int64_t)dst_buf->stride * y + x; MV mv = mi->sb_type < BLOCK_8X8 @@ -200,7 +200,7 @@ private static void build_inter_predictors_for_planes(MACROBLOCKD* xd, BLOCK_SIZ int mi_x = mi_col * MI_SIZE; int mi_y = mi_row * MI_SIZE; for (plane = plane_from; plane <= plane_to; ++plane) { - BLOCK_SIZE plane_bsize = get_plane_block_size(bsize, &xd->plane[plane]); + BLOCK_SIZE plane_bsize = get_plane_block_size(bsize, addr(ref xd->plane[plane])); int num_4x4_w = num_4x4_blocks_wide_lookup[plane_bsize]; int num_4x4_h = num_4x4_blocks_high_lookup[plane_bsize]; int bw = 4 * num_4x4_w; @@ -261,8 +261,8 @@ internal static void vp9_setup_pre_planes(MACROBLOCKD* xd, int idx, YV12_BUFFER_ uint8_t** buffers = stackalloc uint8_t*[3] { src->y_buffer, src->u_buffer, src->v_buffer }; int* strides = stackalloc int[3] { src->y_stride, src->uv_stride, src->uv_stride }; for (i = 0; i < MAX_MB_PLANE; ++i) { - macroblockd_plane* pd = &xd->plane[i]; - setup_pred_plane(&pd->pre[idx], buffers[i], strides[i], mi_row, mi_col, + macroblockd_plane* pd = addr(ref xd->plane[i]); + setup_pred_plane(addr(ref pd->pre[idx]), buffers[i], strides[i], mi_row, mi_col, sf, pd->subsampling_x, pd->subsampling_y); } } diff --git a/src/Codecs/SIPSorcery.VP9/common/vp9_reconintra.cs b/src/Codecs/SIPSorcery.VP9/common/vp9_reconintra.cs index d62e06c869..d0aba90f1a 100644 --- a/src/Codecs/SIPSorcery.VP9/common/vp9_reconintra.cs +++ b/src/Codecs/SIPSorcery.VP9/common/vp9_reconintra.cs @@ -120,7 +120,7 @@ private static void build_intra_predictors(MACROBLOCKD* xd, uint8_t* @ref, int r int bs = 4 << tx_size; int frame_width; int frame_height; int x0; int y0; - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); // 127 127 127 .. 127 127 127 127 127 127 // 129 A B .. Y Z diff --git a/src/Codecs/SIPSorcery.VP9/common/vp9_scan.cs b/src/Codecs/SIPSorcery.VP9/common/vp9_scan.cs index 39beffc7eb..5e525e1c08 100644 --- a/src/Codecs/SIPSorcery.VP9/common/vp9_scan.cs +++ b/src/Codecs/SIPSorcery.VP9/common/vp9_scan.cs @@ -52,7 +52,7 @@ internal static int get_coef_context(int16_t* neighbors, uint8_t* token_cache, i return &vp9_default_scan_orders[tx_size]; } else { PREDICTION_MODE mode = get_y_mode(mi, block_idx); - return &vp9_scan_orders[tx_size][intra_mode_to_tx_type_lookup[mode]]; + return addr(ref vp9_scan_orders[tx_size][intra_mode_to_tx_type_lookup[mode]]); } } diff --git a/src/Codecs/SIPSorcery.VP9/common/vp9_thread_common.cs b/src/Codecs/SIPSorcery.VP9/common/vp9_thread_common.cs index 050206c618..459395906b 100644 --- a/src/Codecs/SIPSorcery.VP9/common/vp9_thread_common.cs +++ b/src/Codecs/SIPSorcery.VP9/common/vp9_thread_common.cs @@ -127,7 +127,6 @@ private static void loop_filter_rows_mt(YV12_BUFFER_CONFIG* frame, VP9_COMMON* c VPxWorkerInterface* winterface = vpx_get_worker_interface(); // Number of superblock rows and cols int sb_rows = mi_cols_aligned_to_sb(cm->mi_rows) >> MI_BLOCK_SIZE_LOG2; - int num_tile_cols = 1 << cm->log2_tile_cols; // Limit the number of workers to prevent changes in frame dimensions from // causing incorrect sync calculations when sb_rows < threads/tile_cols. // Further restrict them by the number of tile columns should the user @@ -400,8 +399,8 @@ internal static void vp9_accumulate_frame_counts(FRAME_COUNTS* accum, FRAME_COUN for (i = 0; i < MV_JOINTS; i++) accum->mv.joints[i] += counts->mv.joints[i]; for (k = 0; k < 2; k++) { - nmv_component_counts* comps = &accum->mv.comps[k]; - nmv_component_counts* comps_t = &counts->mv.comps[k]; + nmv_component_counts* comps = addr(ref accum->mv.comps[k]); + nmv_component_counts* comps_t = addr(ref counts->mv.comps[k]); for (i = 0; i < 2; i++) { comps->sign[i] += comps_t->sign[i]; diff --git a/src/Codecs/SIPSorcery.VP9/decoder/vp9_decodeframe.cs b/src/Codecs/SIPSorcery.VP9/decoder/vp9_decodeframe.cs index a3522b0fa5..0a9c95663b 100644 --- a/src/Codecs/SIPSorcery.VP9/decoder/vp9_decodeframe.cs +++ b/src/Codecs/SIPSorcery.VP9/decoder/vp9_decodeframe.cs @@ -63,15 +63,15 @@ private static void read_tx_mode_probs(tx_probs* tx_probs, vpx_reader* r) for (i = 0; i < TX_SIZE_CONTEXTS; ++i) for (j = 0; j < TX_SIZES - 3; ++j) - vp9_diff_update_prob(r, &tx_probs->p8x8[i][j]); + vp9_diff_update_prob(r, addr(ref tx_probs->p8x8[i][j])); for (i = 0; i < TX_SIZE_CONTEXTS; ++i) for (j = 0; j < TX_SIZES - 2; ++j) - vp9_diff_update_prob(r, &tx_probs->p16x16[i][j]); + vp9_diff_update_prob(r, addr(ref tx_probs->p16x16[i][j])); for (i = 0; i < TX_SIZE_CONTEXTS; ++i) for (j = 0; j < TX_SIZES - 1; ++j) - vp9_diff_update_prob(r, &tx_probs->p32x32[i][j]); + vp9_diff_update_prob(r, addr(ref tx_probs->p32x32[i][j])); } private static void read_switchable_interp_probs(FRAME_CONTEXT* fc, vpx_reader* r) @@ -79,7 +79,7 @@ private static void read_switchable_interp_probs(FRAME_CONTEXT* fc, vpx_reader* int i; int j; for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; ++j) for (i = 0; i < SWITCHABLE_FILTERS - 1; ++i) - vp9_diff_update_prob(r, &fc->switchable_interp_prob[j][i]); + vp9_diff_update_prob(r, addr(ref fc->switchable_interp_prob[j][i])); } private static void read_inter_mode_probs(FRAME_CONTEXT* fc, vpx_reader* r) @@ -87,7 +87,7 @@ private static void read_inter_mode_probs(FRAME_CONTEXT* fc, vpx_reader* r) int i; int j; for (i = 0; i < INTER_MODE_CONTEXTS; ++i) for (j = 0; j < INTER_MODES - 1; ++j) - vp9_diff_update_prob(r, &fc->inter_mode_probs[i][j]); + vp9_diff_update_prob(r, addr(ref fc->inter_mode_probs[i][j])); } private static REFERENCE_MODE read_frame_reference_mode(VP9_COMMON* cm, vpx_reader* r) @@ -112,8 +112,8 @@ private static void read_frame_reference_mode_probs(VP9_COMMON* cm, vpx_reader* if (cm->reference_mode != COMPOUND_REFERENCE) for (i = 0; i < REF_CONTEXTS; ++i) { - vp9_diff_update_prob(r, &fc->single_ref_prob[i][0]); - vp9_diff_update_prob(r, &fc->single_ref_prob[i][1]); + vp9_diff_update_prob(r, addr(ref fc->single_ref_prob[i][0])); + vp9_diff_update_prob(r, addr(ref fc->single_ref_prob[i][1])); } if (cm->reference_mode != SINGLE_REFERENCE) @@ -135,7 +135,7 @@ private static void read_mv_probs(nmv_context* ctx, int allow_hp, vpx_reader* r) update_mv_probs(ctx->joints, MV_JOINTS - 1, r); for (i = 0; i < 2; ++i) { - nmv_component* comp_ctx = &ctx->comps[i]; + nmv_component* comp_ctx = addr(ref ctx->comps[i]); update_mv_probs(&comp_ctx->sign, 1, r); update_mv_probs(comp_ctx->classes, MV_CLASSES - 1, r); update_mv_probs(comp_ctx->class0, CLASS0_SIZE - 1, r); @@ -143,15 +143,15 @@ private static void read_mv_probs(nmv_context* ctx, int allow_hp, vpx_reader* r) } for (i = 0; i < 2; ++i) { - nmv_component* comp_ctx = &ctx->comps[i]; + nmv_component* comp_ctx = addr(ref ctx->comps[i]); for (j = 0; j < CLASS0_SIZE; ++j) - update_mv_probs((byte*)&(comp_ctx->class0_fp[j]), MV_FP_SIZE - 1, r); + update_mv_probs((byte*)addr(ref comp_ctx->class0_fp[j]), MV_FP_SIZE - 1, r); update_mv_probs(comp_ctx->fp, 3, r); } if (allow_hp != 0) { for (i = 0; i < 2; ++i) { - nmv_component* comp_ctx = &ctx->comps[i]; + nmv_component* comp_ctx = addr(ref ctx->comps[i]); update_mv_probs(&comp_ctx->class0_hp, 1, r); update_mv_probs(&comp_ctx->hp, 1, r); } @@ -160,7 +160,7 @@ private static void read_mv_probs(nmv_context* ctx, int allow_hp, vpx_reader* r) private static void inverse_transform_block_inter(MACROBLOCKD* xd, int plane, TX_SIZE tx_size, uint8_t* dst, int stride, int eob) { - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); tran_low_t* dqcoeff = pd->dqcoeff; Debug.Assert(eob > 0); if ((xd->lossless) != 0) { @@ -189,7 +189,7 @@ private static void inverse_transform_block_inter(MACROBLOCKD* xd, int plane, TX private static void inverse_transform_block_intra(MACROBLOCKD* xd, int plane, TX_TYPE tx_type, TX_SIZE tx_size, uint8_t* dst, int stride, int eob) { - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); tran_low_t* dqcoeff = pd->dqcoeff; Debug.Assert(eob > 0); if ((xd->lossless) != 0) { @@ -221,7 +221,7 @@ private static void inverse_transform_block_intra(MACROBLOCKD* xd, int plane, TX private static void predict_and_reconstruct_intra_block(TileWorkerData* twd, MODE_INFO* mi, int plane, int row, int col, TX_SIZE tx_size) { MACROBLOCKD* xd = &twd->xd; - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); PREDICTION_MODE mode = (plane == 0) ? mi->mode : mi->uv_mode; uint8_t* dst; dst = &pd->dst.buf[4 * row * pd->dst.stride + 4 * col]; @@ -236,7 +236,7 @@ private static void predict_and_reconstruct_intra_block(TileWorkerData* twd, MOD TX_TYPE tx_type = ((plane != 0) || ((xd->lossless) != 0)) ? DCT_DCT : intra_mode_to_tx_type_lookup[mode]; ScanOrder* sc = ((plane != 0) || ((xd->lossless) != 0)) ? &vp9_default_scan_orders[tx_size] - : &vp9_scan_orders[tx_size][tx_type]; + : addr(ref vp9_scan_orders[tx_size][tx_type]); int eob = vp9_decode_block_tokens(twd, plane, sc, col, row, tx_size, mi->segment_id); if (eob > 0) { @@ -255,11 +255,11 @@ private static void parse_intra_block_row_mt(TileWorkerData* twd, MODE_INFO* mi, if (plane == 0) mode = xd->mi[0]->bmi[(row << 1) + col].as_mode; if ((mi->skip) == 0) { - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); TX_TYPE tx_type = ((plane != 0) || ((xd->lossless) != 0)) ? DCT_DCT : intra_mode_to_tx_type_lookup[mode]; ScanOrder* sc = ((plane != 0) || ((xd->lossless) != 0)) ? &vp9_default_scan_orders[tx_size] - : &vp9_scan_orders[tx_size][tx_type]; + : addr(ref vp9_scan_orders[tx_size][tx_type]); *pd->eob = vp9_decode_block_tokens(twd, plane, sc, col, row, tx_size, mi->segment_id); /* Keep the alignment to 16 */ @@ -271,7 +271,7 @@ private static void parse_intra_block_row_mt(TileWorkerData* twd, MODE_INFO* mi, private static void predict_and_reconstruct_intra_block_row_mt(TileWorkerData* twd, MODE_INFO* mi, int plane, int row, int col, TX_SIZE tx_size) { MACROBLOCKD* xd = &twd->xd; - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); PREDICTION_MODE mode = (plane == 0) ? mi->mode : mi->uv_mode; uint8_t* dst = &pd->dst.buf[4 * row * pd->dst.stride + 4 * col]; @@ -296,7 +296,7 @@ private static void predict_and_reconstruct_intra_block_row_mt(TileWorkerData* t private static int reconstruct_inter_block(TileWorkerData* twd, MODE_INFO* mi, int plane, int row, int col, TX_SIZE tx_size, int mi_row, int mi_col) { MACROBLOCKD* xd = &twd->xd; - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); ScanOrder* sc = &vp9_default_scan_orders[tx_size]; int eob = vp9_decode_block_tokens(twd, plane, sc, col, row, tx_size, mi->segment_id); @@ -313,7 +313,7 @@ private static int reconstruct_inter_block(TileWorkerData* twd, MODE_INFO* mi, i private static int parse_inter_block_row_mt(TileWorkerData* twd, MODE_INFO* mi, int plane, int row, int col, TX_SIZE tx_size) { MACROBLOCKD* xd = &twd->xd; - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); ScanOrder* sc = &vp9_default_scan_orders[tx_size]; int eob = vp9_decode_block_tokens(twd, plane, sc, col, row, tx_size, mi->segment_id); @@ -328,7 +328,7 @@ private static int parse_inter_block_row_mt(TileWorkerData* twd, MODE_INFO* mi, private static int reconstruct_inter_block_row_mt(TileWorkerData* twd, MODE_INFO* mi, int plane, int row, int col, TX_SIZE tx_size) { MACROBLOCKD* xd = &twd->xd; - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); int eob = *pd->eob; _ = mi; @@ -393,7 +393,7 @@ private static void extend_and_predict(TileWorkerData* twd, uint8_t* buf_ptr1, i private static void dec_build_inter_predictors(TileWorkerData* twd, MACROBLOCKD* xd, int plane, int bw, int bh, int x, int y, int w, int h, int mi_x, int mi_y, InterpKernel* kernel, scale_factors* sf, buf_2d* pre_buf, buf_2d* dst_buf, MV* mv, RefCntBuffer* ref_frame_buf, int is_scaled, int @ref) { - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); uint8_t* dst = dst_buf->buf + dst_buf->stride * y + x; MV32 scaled_mv; int xs; int ys; int x0; int y0; int x0_16; int y0_16; int frame_width; int frame_height; int buf_stride; int subpel_x; int subpel_y; @@ -518,11 +518,11 @@ private static void dec_build_inter_predictors_sb(TileWorkerData* twd, VP9Decode for (@ref = 0; @ref < 1 + is_compound; ++@ref) { MV_REFERENCE_FRAME frame = mi->ref_frame[@ref]; - RefBuffer* ref_buf = &pbi->common.frame_refs[frame - LAST_FRAME]; + RefBuffer* ref_buf = addr(ref pbi->common.frame_refs[frame - LAST_FRAME]); scale_factors* sf = &ref_buf->sf; int idx = ref_buf->idx; BufferPool* pool = pbi->common.buffer_pool; - RefCntBuffer* ref_frame_buf = &pool->frame_bufs[idx]; + RefCntBuffer* ref_frame_buf = addr(ref pool->frame_bufs[idx]); if ((vp9_is_valid_scale(sf)) == 0) vpx_internal_error(xd->error_info, VPX_CODEC_UNSUP_BITSTREAM, @@ -535,13 +535,13 @@ private static void dec_build_inter_predictors_sb(TileWorkerData* twd, VP9Decode if (sb_type < BLOCK_8X8) { for (plane = 0; plane < MAX_MB_PLANE; ++plane) { - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); buf_2d* dst_buf = &pd->dst; int num_4x4_w = pd->n4_w; int num_4x4_h = pd->n4_h; int n4w_x4 = 4 * num_4x4_w; int n4h_x4 = 4 * num_4x4_h; - buf_2d* pre_buf = &pd->pre[@ref]; + buf_2d* pre_buf = addr(ref pd->pre[@ref]); int i = 0; int x; int y; for (y = 0; y < num_4x4_h; ++y) { for (x = 0; x < num_4x4_w; ++x) { @@ -556,13 +556,13 @@ private static void dec_build_inter_predictors_sb(TileWorkerData* twd, VP9Decode } else { MV mv = mi->mv[@ref].as_mv; for (plane = 0; plane < MAX_MB_PLANE; ++plane) { - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); buf_2d* dst_buf = &pd->dst; int num_4x4_w = pd->n4_w; int num_4x4_h = pd->n4_h; int n4w_x4 = 4 * num_4x4_w; int n4h_x4 = 4 * num_4x4_h; - buf_2d* pre_buf = &pd->pre[@ref]; + buf_2d* pre_buf = addr(ref pd->pre[@ref]); dec_build_inter_predictors(twd, xd, plane, n4w_x4, n4h_x4, 0, 0, n4w_x4, n4h_x4, mi_x, mi_y, kernel, sf, pre_buf, dst_buf, &mv, ref_frame_buf, is_scaled, @ref); @@ -575,7 +575,7 @@ private static void dec_reset_skip_context(MACROBLOCKD* xd) { int i; for (i = 0; i < MAX_MB_PLANE; i++) { - macroblockd_plane* pd = &xd->plane[i]; + macroblockd_plane* pd = addr(ref xd->plane[i]); memset(pd->above_context, 0, sizeof(ENTROPY_CONTEXT) * pd->n4_w); memset(pd->left_context, 0, sizeof(ENTROPY_CONTEXT) * pd->n4_h); } @@ -643,7 +643,7 @@ private static int predict_recon_inter(MACROBLOCKD* xd, MODE_INFO* mi, TileWorke int eobtotal = 0; int plane; for (plane = 0; plane < MAX_MB_PLANE; ++plane) { - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); TX_SIZE tx_size = (plane != 0) ? get_uv_tx_size(mi, pd) : mi->tx_size; int num_4x4_w = pd->n4_w; int num_4x4_h = pd->n4_h; @@ -670,7 +670,7 @@ private static void predict_recon_intra(MACROBLOCKD* xd, MODE_INFO* mi, TileWork { int plane; for (plane = 0; plane < MAX_MB_PLANE; ++plane) { - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); TX_SIZE tx_size = (plane != 0) ? get_uv_tx_size(mi, pd) : mi->tx_size; int num_4x4_w = pd->n4_w; int num_4x4_h = pd->n4_h; @@ -722,7 +722,7 @@ private static void decode_block(TileWorkerData* twd, VP9Decoder* pbi, int mi_ro if ((is_inter_block(mi)) == 0) { int plane; for (plane = 0; plane < MAX_MB_PLANE; ++plane) { - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); TX_SIZE tx_size = (plane != 0) ? get_uv_tx_size(mi, pd) : mi->tx_size; int num_4x4_w = pd->n4_w; int num_4x4_h = pd->n4_h; @@ -753,7 +753,7 @@ private static void decode_block(TileWorkerData* twd, VP9Decoder* pbi, int mi_ro int plane; for (plane = 0; plane < MAX_MB_PLANE; ++plane) { - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); TX_SIZE tx_size = (plane != 0) ? get_uv_tx_size(mi, pd) : mi->tx_size; int num_4x4_w = pd->n4_w; int num_4x4_h = pd->n4_h; @@ -857,7 +857,7 @@ private static void parse_block(TileWorkerData* twd, VP9Decoder* pbi, int mi_row // In that case dqcoeff and eob need to be backed up and restored as // recon_block will not increment these pointers for skip cases for (plane = 0; plane < MAX_MB_PLANE; ++plane) { - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); dqcoeff[plane] = pd->dqcoeff; eob[plane] = pd->eob; } @@ -866,7 +866,7 @@ private static void parse_block(TileWorkerData* twd, VP9Decoder* pbi, int mi_row if (bsize >= BLOCK_8X8 && eobtotal == 0) { mi->skip = 1; // skip loopfilter for (plane = 0; plane < MAX_MB_PLANE; ++plane) { - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); pd->dqcoeff = dqcoeff[plane]; pd->eob = eob[plane]; } @@ -1068,7 +1068,7 @@ private static void read_coef_probs_common(vp9_coeff_probs_model* coef_probs, vp for (k = 0; k < COEF_BANDS; ++k) for (l = 0; l < ((k) == 0 ? 3 : COEFF_CONTEXTS); ++l) for (m = 0; m < UNCONSTRAINED_NODES; ++m) - vp9_diff_update_prob(r, &coef_probs[i][j][k][l][m]); + vp9_diff_update_prob(r, addr(ref coef_probs[i][j][k][l][m])); } private static void read_coef_probs(FRAME_CONTEXT* fc, TX_MODE tx_mode, vpx_reader* r) @@ -1076,7 +1076,7 @@ private static void read_coef_probs(FRAME_CONTEXT* fc, TX_MODE tx_mode, vpx_read TX_SIZE max_tx_size = tx_mode_to_biggest_tx_size[tx_mode]; TX_SIZE tx_size; for (tx_size = TX_4X4; tx_size <= max_tx_size; ++tx_size) - read_coef_probs_common((A2>>>*)&(fc->coef_probs[tx_size]), r); + read_coef_probs_common((A2>>>*)addr(ref fc->coef_probs[tx_size]), r); } private static void setup_segmentation(segmentation* seg, vpx_read_bit_buffer* rb) @@ -1266,7 +1266,7 @@ private static void setup_frame_size(VP9_COMMON* cm, vpx_read_bit_buffer* rb) get_frame_new_buffer(cm), cm->width, cm->height, cm->subsampling_x, cm->subsampling_y, VP9_DEC_BORDER_IN_PIXELS, cm->byte_alignment, - &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb, + addr(ref pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer), pool->get_fb_cb, pool->cb_priv)) != 0) { vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR, "Failed to allocate frame buffer"); @@ -1318,7 +1318,7 @@ private static void setup_frame_size_with_refs(VP9_COMMON* cm, vpx_read_bit_buff // Check to make sure at least one of frames that this frame references // has valid dimensions. for (i = 0; i < REFS_PER_FRAME; ++i) { - RefBuffer* ref_frame = &cm->frame_refs[i]; + RefBuffer* ref_frame = addr(ref cm->frame_refs[i]); has_valid_ref_frame |= ((ref_frame->idx != INVALID_IDX && ((valid_ref_frame_size(ref_frame->buf->y_crop_width, @@ -1328,7 +1328,7 @@ private static void setup_frame_size_with_refs(VP9_COMMON* cm, vpx_read_bit_buff vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME, "Referenced frame has invalid size"); for (i = 0; i < REFS_PER_FRAME; ++i) { - RefBuffer* ref_frame = &cm->frame_refs[i]; + RefBuffer* ref_frame = addr(ref cm->frame_refs[i]); if (ref_frame->idx == INVALID_IDX || ((valid_ref_frame_img_fmt((int)(ref_frame->buf->bit_depth), ref_frame->buf->subsampling_x, @@ -1345,7 +1345,7 @@ private static void setup_frame_size_with_refs(VP9_COMMON* cm, vpx_read_bit_buff get_frame_new_buffer(cm), cm->width, cm->height, cm->subsampling_x, cm->subsampling_y, VP9_DEC_BORDER_IN_PIXELS, cm->byte_alignment, - &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb, + addr(ref pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer), pool->get_fb_cb, pool->cb_priv)) != 0) { vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR, "Failed to allocate frame buffer"); @@ -1420,7 +1420,7 @@ private static void get_tile_buffers(VP9Decoder* pbi, uint8_t* data, uint8_t* da for (r = 0; r < tile_rows; ++r) { for (c = 0; c < tile_cols; ++c) { int is_last = (((r == tile_rows - 1) && (c == tile_cols - 1)) ? 1 : 0); - TileBuffer* buf = &tile_buffers[r][c]; + TileBuffer* buf = addr(ref tile_buffers[r][c]); buf->col = c; get_tile_buffer(data_end, is_last, &pbi->common.error, &data, pbi->decrypt_cb, pbi->decrypt_state, buf); @@ -1544,7 +1544,7 @@ private static void parse_tile_row(TileWorkerData* tile_data, VP9Decoder* pbi, i VP9_COMMON* cm = &pbi->common; RowMTWorkerData* row_mt_worker_data = pbi->row_mt_worker_data; TileInfo* tile = &tile_data->xd.tile; - TileBuffer* buf = &pbi->tile_buffers[cur_tile_col]; + TileBuffer* buf = addr(ref pbi->tile_buffers[cur_tile_col]); int aligned_cols = mi_cols_aligned_to_sb(cm->mi_cols); memset(tile_data->dqcoeff, 0, (32 * 32) * sizeof(tran_low_t)); @@ -1757,7 +1757,7 @@ private static int row_decode_worker_hook(void* arg1, void* arg2) // Load all tile information into tile_data. for (tile_row = 0; tile_row < tile_rows; ++tile_row) { for (tile_col = 0; tile_col < tile_cols; ++tile_col) { - TileBuffer* buf = &tile_buffers[tile_row][tile_col]; + TileBuffer* buf = addr(ref tile_buffers[tile_row][tile_col]); tile_data = pbi->tile_worker_data + tile_cols * tile_row + tile_col; tile_data->xd = pbi->mb; tile_data->xd.corrupted = 0; @@ -2423,7 +2423,7 @@ private static size_t read_uncompressed_header(VP9Decoder* pbi, vpx_read_bit_buf for (i = 0; i < REFS_PER_FRAME; ++i) { int @ref = vpx_rb_read_literal(rb, REF_FRAMES_LOG2); int idx = cm->ref_frame_map[@ref]; - RefBuffer* ref_frame = &cm->frame_refs[i]; + RefBuffer* ref_frame = addr(ref cm->frame_refs[i]); ref_frame->idx = idx; ref_frame->buf = &frame_bufs[idx].buf; cm->ref_frame_sign_bias[LAST_FRAME + i] = vpx_rb_read_bit(rb); @@ -2435,7 +2435,7 @@ private static size_t read_uncompressed_header(VP9Decoder* pbi, vpx_read_bit_buf cm->interp_filter = read_interp_filter(rb); for (i = 0; i < REFS_PER_FRAME; ++i) { - RefBuffer* ref_buf = &cm->frame_refs[i]; + RefBuffer* ref_buf = addr(ref cm->frame_refs[i]); vp9_setup_scale_factors_for_frame( &ref_buf->sf, ref_buf->buf->y_crop_width, ref_buf->buf->y_crop_height, cm->width, cm->height); @@ -2568,11 +2568,11 @@ private static int read_compressed_header(VP9Decoder* pbi, uint8_t* data, size_t for (j = 0; j < BLOCK_SIZE_GROUPS; j++) for (i = 0; i < INTRA_MODES - 1; ++i) - vp9_diff_update_prob(&r, &fc->y_mode_prob[j][i]); + vp9_diff_update_prob(&r, addr(ref fc->y_mode_prob[j][i])); for (j = 0; j < PARTITION_CONTEXTS; ++j) for (i = 0; i < PARTITION_TYPES - 1; ++i) - vp9_diff_update_prob(&r, &fc->partition_prob[j][i]); + vp9_diff_update_prob(&r, addr(ref fc->partition_prob[j][i])); read_mv_probs(nmvc, cm->allow_high_precision_mv, &r); } diff --git a/src/Codecs/SIPSorcery.VP9/decoder/vp9_decodemv.cs b/src/Codecs/SIPSorcery.VP9/decoder/vp9_decodemv.cs index ad6eed779a..306436dfcc 100644 --- a/src/Codecs/SIPSorcery.VP9/decoder/vp9_decodemv.cs +++ b/src/Codecs/SIPSorcery.VP9/decoder/vp9_decodemv.cs @@ -43,7 +43,7 @@ private static PREDICTION_MODE read_intra_mode(vpx_reader* r, vpx_prob* p) private static PREDICTION_MODE read_intra_mode_y(VP9_COMMON* cm, MACROBLOCKD* xd, vpx_reader* r, int size_group) { - PREDICTION_MODE y_mode = read_intra_mode(r, (byte*)&(cm->fc->y_mode_prob[size_group])); + PREDICTION_MODE y_mode = read_intra_mode(r, (byte*)addr(ref cm->fc->y_mode_prob[size_group])); FRAME_COUNTS* counts = xd->counts; if (counts != null) ++counts->y_mode[size_group][y_mode]; return y_mode; @@ -51,7 +51,7 @@ private static PREDICTION_MODE read_intra_mode_y(VP9_COMMON* cm, MACROBLOCKD* xd private static PREDICTION_MODE read_intra_mode_uv(VP9_COMMON* cm, MACROBLOCKD* xd, vpx_reader* r, PREDICTION_MODE y_mode) { - PREDICTION_MODE uv_mode = read_intra_mode(r, (byte*)&(cm->fc->uv_mode_prob[y_mode])); + PREDICTION_MODE uv_mode = read_intra_mode(r, (byte*)addr(ref cm->fc->uv_mode_prob[y_mode])); FRAME_COUNTS* counts = xd->counts; if (counts != null) ++counts->uv_mode[y_mode][uv_mode]; return uv_mode; @@ -59,7 +59,7 @@ private static PREDICTION_MODE read_intra_mode_uv(VP9_COMMON* cm, MACROBLOCKD* x private static PREDICTION_MODE read_inter_mode(VP9_COMMON* cm, MACROBLOCKD* xd, vpx_reader* r, int ctx) { - int mode = vpx_read_tree(r, vp9_inter_mode_tree, (byte*)&(cm->fc->inter_mode_probs[ctx])); + int mode = vpx_read_tree(r, vp9_inter_mode_tree, (byte*)addr(ref cm->fc->inter_mode_probs[ctx])); FRAME_COUNTS* counts = xd->counts; if (counts != null) ++counts->inter_mode[ctx][mode]; @@ -259,7 +259,7 @@ private static int read_mv_component(vpx_reader* r, nmv_component* mvcomp, int u // Fractional part fr = vpx_read_tree(r, vp9_mv_fp_tree, - class0 != 0 ? (vpx_prob*)&mvcomp->class0_fp[d] : (vpx_prob*)mvcomp->fp); + class0 != 0 ? (vpx_prob*)addr(ref mvcomp->class0_fp[d]) : (vpx_prob*)mvcomp->fp); // High precision part (if hp is not used, the default value of the hp is 1) hp = (usehp != 0) ? vpx_read(r, (class0 != 0) ? mvcomp->class0_hp : mvcomp->hp) : 1; @@ -276,10 +276,10 @@ private static void read_mv(vpx_reader* r, MV* mv, MV* @ref, nmv_context* ctx, n MV diff = new MV { row = 0, col = 0 }; if ((mv_joint_vertical(joint_type)) != 0) - diff.row = (short)(read_mv_component(r, &ctx->comps[0], use_hp)); + diff.row = (short)(read_mv_component(r, addr(ref ctx->comps[0]), use_hp)); if ((mv_joint_horizontal(joint_type)) != 0) - diff.col = (short)(read_mv_component(r, &ctx->comps[1], use_hp)); + diff.col = (short)(read_mv_component(r, addr(ref ctx->comps[1]), use_hp)); vp9_inc_mv(&diff, counts); @@ -344,7 +344,7 @@ private static INTERP_FILTER read_switchable_interp_filter(VP9_COMMON* cm, MACRO { int ctx = get_pred_context_switchable_interp(xd); INTERP_FILTER type = (INTERP_FILTER)vpx_read_tree( - r, vp9_switchable_interp_tree, (byte*)&(cm->fc->switchable_interp_prob[ctx])); + r, vp9_switchable_interp_tree, (byte*)addr(ref cm->fc->switchable_interp_prob[ctx])); FRAME_COUNTS* counts = xd->counts; if (counts != null) ++counts->switchable_interp[ctx][type]; return type; @@ -849,7 +849,7 @@ private static void read_inter_block_mode_info(VP9Decoder* pbi, MACROBLOCKD* xd, } } - if ((assign_mv(cm, xd, b_mode, (int_mv*)&(mi->bmi[j].as_mv), best_ref_mvs, + if ((assign_mv(cm, xd, b_mode, (int_mv*)addr(ref mi->bmi[j].as_mv), best_ref_mvs, best_sub8x8, is_compound, allow_hp, r)) == 0) { xd->corrupted |= 1; return; @@ -862,7 +862,7 @@ private static void read_inter_block_mode_info(VP9Decoder* pbi, MACROBLOCKD* xd, mi->mode = b_mode; - copy_mv_pair((int_mv*)&(mi->mv), (int_mv*)&(mi->bmi[3].as_mv)); + copy_mv_pair((int_mv*)&(mi->mv), (int_mv*)addr(ref mi->bmi[3].as_mv)); } else { if (mi->mode != ZEROMV) { for (@ref = 0; @ref < 1 + is_compound; ++@ref) { diff --git a/src/Codecs/SIPSorcery.VP9/decoder/vp9_decoder.cs b/src/Codecs/SIPSorcery.VP9/decoder/vp9_decoder.cs index 3f257f1daf..551506856b 100644 --- a/src/Codecs/SIPSorcery.VP9/decoder/vp9_decoder.cs +++ b/src/Codecs/SIPSorcery.VP9/decoder/vp9_decoder.cs @@ -315,7 +315,7 @@ internal static vpx_codec_err_t vp9_set_reference_dec(VP9_COMMON* cm, VP9_REFFRA } // Get the destination reference buffer. - ref_buf = &cm->buffer_pool->frame_bufs[idx].buf; + ref_buf = addr(ref cm->buffer_pool->frame_bufs[idx].buf); if ((equal_dimensions(ref_buf, sd)) == 0) { vpx_internal_error(&cm->error, VPX_CODEC_ERROR, @@ -450,7 +450,7 @@ internal static int vp9_receive_compressed_data(VP9Decoder* pbi, size_t size, ui } // Assign a MV array to the frame buffer. - cm->cur_frame = &pool->frame_bufs[cm->new_fb_idx]; + cm->cur_frame = addr(ref pool->frame_bufs[cm->new_fb_idx]); pbi->hold_ref_buf = 0; pbi->cur_buf = &frame_bufs[cm->new_fb_idx]; @@ -499,7 +499,6 @@ internal static int vp9_get_raw_frame(VP9Decoder* pbi, YV12_BUFFER_CONFIG* sd, v { VP9_COMMON* cm = &pbi->common; int ret = -1; - _ = *flags; if (pbi->ready_for_new_data == 1) return ret; diff --git a/src/Codecs/SIPSorcery.VP9/decoder/vp9_detokenize.cs b/src/Codecs/SIPSorcery.VP9/decoder/vp9_detokenize.cs index a8db2c3c88..eb21d619df 100644 --- a/src/Codecs/SIPSorcery.VP9/decoder/vp9_detokenize.cs +++ b/src/Codecs/SIPSorcery.VP9/decoder/vp9_detokenize.cs @@ -89,7 +89,7 @@ private static int decode_coefs(MACROBLOCKD* xd, PLANE_TYPE type, tran_low_t* dq FRAME_CONTEXT* fc = xd->fc; int @ref = is_inter_block(xd->mi[0]); int band; int c = 0; - A6>* coef_probs = (A6>*)&(fc->coef_probs[tx_size][type][@ref]); + A6>* coef_probs = (A6>*)addr(ref fc->coef_probs[tx_size][type][@ref]); vpx_prob* prob; A6>* coef_counts = default; A6* eob_branch_count = default; @@ -107,14 +107,14 @@ private static int decode_coefs(MACROBLOCKD* xd, PLANE_TYPE type, tran_low_t* dq int count = r->count; if (counts != null) { - coef_counts = (A6>*)&(counts->coef[tx_size][type][@ref]); - eob_branch_count = (A6*)&(counts->eob_branch[tx_size][type][@ref]); + coef_counts = (A6>*)addr(ref counts->coef[tx_size][type][@ref]); + eob_branch_count = (A6*)addr(ref counts->eob_branch[tx_size][type][@ref]); } while (c < max_eob) { int val = -1; band = *band_translate++; - prob = (byte*)&coef_probs[band][ctx]; + prob = (byte*)addr(ref coef_probs[band][ctx]); if (counts != null) ++eob_branch_count[band][ctx]; if ((read_bool(r, prob[EOB_CONTEXT_NODE], &value, &count, &range)) == 0) { do { @@ -138,7 +138,7 @@ private static int decode_coefs(MACROBLOCKD* xd, PLANE_TYPE type, tran_low_t* dq } ctx = get_coef_context(nb, token_cache, c); band = *band_translate++; - prob = (byte*)&coef_probs[band][ctx]; + prob = (byte*)addr(ref coef_probs[band][ctx]); } if ((read_bool(r, prob[ONE_CONTEXT_NODE], &value, &count, &range)) != 0) { @@ -224,8 +224,8 @@ internal static int vp9_decode_block_tokens(TileWorkerData* twd, int plane, Scan { vpx_reader* r = &twd->bit_reader; MACROBLOCKD* xd = &twd->xd; - macroblockd_plane* pd = &xd->plane[plane]; - int16_t* dequant = (short*)&(pd->seg_dequant[seg_id]); + macroblockd_plane* pd = addr(ref xd->plane[plane]); + int16_t* dequant = (short*)addr(ref pd->seg_dequant[seg_id]); int eob; ENTROPY_CONTEXT* a = pd->above_context + x; ENTROPY_CONTEXT* l = pd->left_context + y; diff --git a/src/Codecs/SIPSorcery.VP9/encoder/vp9_bitstream.cs b/src/Codecs/SIPSorcery.VP9/encoder/vp9_bitstream.cs index 92636d43ab..10dddd1ce5 100644 --- a/src/Codecs/SIPSorcery.VP9/encoder/vp9_bitstream.cs +++ b/src/Codecs/SIPSorcery.VP9/encoder/vp9_bitstream.cs @@ -114,7 +114,7 @@ private static void update_skip_probs(VP9_COMMON* cm, vpx_writer* w, FRAME_COUNT int k; for (k = 0; k < SKIP_CONTEXTS; ++k) - vp9_cond_prob_diff_update(w, &cm->fc->skip_probs[k], (uint*)&(counts->skip[k])); + vp9_cond_prob_diff_update(w, &cm->fc->skip_probs[k], (uint*)addr(ref counts->skip[k])); } private static void update_switchable_interp_probs(VP9_COMMON* cm, vpx_writer* w, FRAME_COUNTS* counts) @@ -122,8 +122,8 @@ private static void update_switchable_interp_probs(VP9_COMMON* cm, vpx_writer* w int j; for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; ++j) prob_diff_update(vp9_switchable_interp_tree, - (byte*)&(cm->fc->switchable_interp_prob[j]), - (uint*)&(counts->switchable_interp[j]), SWITCHABLE_FILTERS, w); + (byte*)addr(ref cm->fc->switchable_interp_prob[j]), + (uint*)addr(ref counts->switchable_interp[j]), SWITCHABLE_FILTERS, w); } private static void pack_mb_tokens(vpx_writer* w, TOKENEXTRA** tp, TOKENEXTRA* stop, vpx_bit_depth_t bit_depth) @@ -263,7 +263,7 @@ private static void pack_inter_mode_mvs(VP9_COMP* cpi, MACROBLOCKD* xd, MB_MODE_ if (is_inter == 0) { if (bsize >= BLOCK_8X8) { - write_intra_mode(w, mode, (byte*)&(cm->fc->y_mode_prob[size_group_lookup[bsize]])); + write_intra_mode(w, mode, (byte*)addr(ref cm->fc->y_mode_prob[size_group_lookup[bsize]])); } else { int idx; int idy; int num_4x4_w = num_4x4_blocks_wide_lookup[bsize]; @@ -271,14 +271,14 @@ private static void pack_inter_mode_mvs(VP9_COMP* cpi, MACROBLOCKD* xd, MB_MODE_ for (idy = 0; idy < 2; idy += num_4x4_h) { for (idx = 0; idx < 2; idx += num_4x4_w) { PREDICTION_MODE b_mode = mi->bmi[idy * 2 + idx].as_mode; - write_intra_mode(w, b_mode, (byte*)&(cm->fc->y_mode_prob[0])); + write_intra_mode(w, b_mode, (byte*)addr(ref cm->fc->y_mode_prob[0])); } } } - write_intra_mode(w, mi->uv_mode, (byte*)&(cm->fc->uv_mode_prob[mode])); + write_intra_mode(w, mi->uv_mode, (byte*)addr(ref cm->fc->uv_mode_prob[mode])); } else { int mode_ctx = mbmi_ext->mode_context[mi->ref_frame[0]]; - vpx_prob* inter_probs = (byte*)&(cm->fc->inter_mode_probs[mode_ctx]); + vpx_prob* inter_probs = (byte*)addr(ref cm->fc->inter_mode_probs[mode_ctx]); write_ref_frames(cm, xd, w); // If segment skip is not enabled code the mode. @@ -291,7 +291,7 @@ private static void pack_inter_mode_mvs(VP9_COMP* cpi, MACROBLOCKD* xd, MB_MODE_ if (cm->interp_filter == SWITCHABLE) { int ctx = get_pred_context_switchable_interp(xd); vp9_write_token(w, vp9_switchable_interp_tree, - (byte*)&(cm->fc->switchable_interp_prob[ctx]), + (byte*)addr(ref cm->fc->switchable_interp_prob[ctx]), &switchable_interp_encodings[mi->interp_filter]); ++interp_filter_selected[0][mi->interp_filter]; } else { @@ -309,8 +309,8 @@ private static void pack_inter_mode_mvs(VP9_COMP* cpi, MACROBLOCKD* xd, MB_MODE_ write_inter_mode(w, b_mode, inter_probs); if (b_mode == NEWMV) { for (@ref = 0; @ref < 1 + is_compound; ++@ref) - vp9_encode_mv(cpi, w, &mi->bmi[j].as_mv[@ref].as_mv, - &mbmi_ext->ref_mvs[mi->ref_frame[@ref]][0].as_mv, + vp9_encode_mv(cpi, w, addr(ref mi->bmi[j].as_mv[@ref].as_mv), + addr(ref mbmi_ext->ref_mvs[mi->ref_frame[@ref]][0].as_mv), nmvc, allow_hp, max_mv_magnitude); } } @@ -318,8 +318,8 @@ private static void pack_inter_mode_mvs(VP9_COMP* cpi, MACROBLOCKD* xd, MB_MODE_ } else { if (mode == NEWMV) { for (@ref = 0; @ref < 1 + is_compound; ++@ref) - vp9_encode_mv(cpi, w, &mi->mv[@ref].as_mv, - &mbmi_ext->ref_mvs[mi->ref_frame[@ref]][0].as_mv, nmvc, + vp9_encode_mv(cpi, w, addr(ref mi->mv[@ref].as_mv), + addr(ref mbmi_ext->ref_mvs[mi->ref_frame[@ref]][0].as_mv), nmvc, allow_hp, max_mv_magnitude); } } @@ -490,8 +490,8 @@ private static void write_modes(VP9_COMP* cpi, MACROBLOCKD* xd, TileInfo* tile, private static void build_tree_distribution(VP9_COMP* cpi, TX_SIZE tx_size, vp9_coeff_stats* coef_branch_ct, vp9_coeff_probs_model* coef_probs) { - vp9_coeff_count* coef_counts = (A2>>>*)&(cpi->td.rd_counts.coef_counts[tx_size]); - A2>>* eob_branch_ct = (A2>>*)&(cpi->common.counts.eob_branch[tx_size]); + vp9_coeff_count* coef_counts = (A2>>>*)addr(ref cpi->td.rd_counts.coef_counts[tx_size]); + A2>>* eob_branch_ct = (A2>>*)addr(ref cpi->common.counts.eob_branch[tx_size]); int i; int j; int k; int l; int m; for (i = 0; i < PLANE_TYPES; ++i) { @@ -499,8 +499,8 @@ private static void build_tree_distribution(VP9_COMP* cpi, TX_SIZE tx_size, vp9_ for (k = 0; k < COEF_BANDS; ++k) { for (l = 0; l < ((k) == 0 ? 3 : COEFF_CONTEXTS); ++l) { vp9_tree_probs_from_distribution(vp9_coef_tree, - (A2*)&coef_branch_ct[i][j][k][l], - (uint*)&coef_counts[i][j][k][l]); + (A2*)addr(ref coef_branch_ct[i][j][k][l]), + (uint*)addr(ref coef_counts[i][j][k][l])); coef_branch_ct[i][j][k][l][0][1] = eob_branch_ct[i][j][k][l] - coef_branch_ct[i][j][k][l][0][0]; for (m = 0; m < UNCONSTRAINED_NODES; ++m) @@ -515,7 +515,7 @@ private static void build_tree_distribution(VP9_COMP* cpi, TX_SIZE tx_size, vp9_ private static void update_coef_probs_common(vpx_writer* bc, VP9_COMP* cpi, TX_SIZE tx_size, vp9_coeff_stats* frame_branch_ct, vp9_coeff_probs_model* new_coef_probs) { - vp9_coeff_probs_model* old_coef_probs = (A2>>>*)&(cpi->common.fc->coef_probs[tx_size]); + vp9_coeff_probs_model* old_coef_probs = (A2>>>*)addr(ref cpi->common.fc->coef_probs[tx_size]); vpx_prob upd = DIFF_UPDATE_PROB; int entropy_nodes_update = UNCONSTRAINED_NODES; int i; int j; int k; int l; int t; @@ -537,11 +537,11 @@ private static void update_coef_probs_common(vpx_writer* bc, VP9_COMP* cpi, TX_S int u = 0; if (t == PIVOT_NODE) s = vp9_prob_diff_update_savings_search_model( - (uint*)&frame_branch_ct[i][j][k][l][0], oldp, &newp, upd, + (uint*)addr(ref frame_branch_ct[i][j][k][l][0]), oldp, &newp, upd, stepsize); else s = vp9_prob_diff_update_savings_search( - (uint*)&frame_branch_ct[i][j][k][l][t], oldp, &newp, upd); + (uint*)addr(ref frame_branch_ct[i][j][k][l][t]), oldp, &newp, upd); if (s > 0 && newp != oldp) u = 1; if (u != 0) savings += s - (int)((vp9_prob_cost[upd])); @@ -568,16 +568,16 @@ private static void update_coef_probs_common(vpx_writer* bc, VP9_COMP* cpi, TX_S // calc probs and branch cts for this frame only for (t = 0; t < entropy_nodes_update; ++t) { vpx_prob newp = new_coef_probs[i][j][k][l][t]; - vpx_prob* oldp = ((byte*)&old_coef_probs[i][j][k][l]) + t; + vpx_prob* oldp = ((byte*)addr(ref old_coef_probs[i][j][k][l])) + t; int64_t s; int u = 0; if (t == PIVOT_NODE) s = vp9_prob_diff_update_savings_search_model( - (uint*)&frame_branch_ct[i][j][k][l][0], *oldp, &newp, upd, + (uint*)addr(ref frame_branch_ct[i][j][k][l][0]), *oldp, &newp, upd, stepsize); else s = vp9_prob_diff_update_savings_search( - (uint*)&frame_branch_ct[i][j][k][l][t], *oldp, &newp, upd); + (uint*)addr(ref frame_branch_ct[i][j][k][l][t]), *oldp, &newp, upd); if (s > 0 && newp != *oldp) u = 1; vpx_write(bc, u, upd); if (u != 0) { @@ -604,17 +604,17 @@ private static void update_coef_probs_common(vpx_writer* bc, VP9_COMP* cpi, TX_S // calc probs and branch cts for this frame only for (t = 0; t < entropy_nodes_update; ++t) { vpx_prob newp = new_coef_probs[i][j][k][l][t]; - vpx_prob* oldp = ((byte*)&old_coef_probs[i][j][k][l]) + t; + vpx_prob* oldp = ((byte*)addr(ref old_coef_probs[i][j][k][l])) + t; int64_t s; int u = 0; if (t == PIVOT_NODE) { s = vp9_prob_diff_update_savings_search_model( - (uint*)&frame_branch_ct[i][j][k][l][0], *oldp, &newp, upd, + (uint*)addr(ref frame_branch_ct[i][j][k][l][0]), *oldp, &newp, upd, stepsize); } else { s = vp9_prob_diff_update_savings_search( - (uint*)&frame_branch_ct[i][j][k][l][t], *oldp, &newp, upd); + (uint*)addr(ref frame_branch_ct[i][j][k][l][t]), *oldp, &newp, upd); } if (s > 0 && newp != *oldp) u = 1; @@ -803,22 +803,22 @@ private static void encode_txfm_probs(VP9_COMMON* cm, vpx_writer* w, FRAME_COUNT A2* ct_32x32p = stackalloc A2[TX_SIZES-1]; for (i = 0; i < TX_SIZE_CONTEXTS; i++) { - tx_counts_to_branch_counts_8x8((uint*)&(counts->tx.p8x8[i]), ct_8x8p); + tx_counts_to_branch_counts_8x8((uint*)addr(ref counts->tx.p8x8[i]), ct_8x8p); for (j = 0; j < TX_SIZES - 3; j++) - vp9_cond_prob_diff_update(w, &cm->fc->tx_probs.p8x8[i][j], (uint*)&ct_8x8p[j]); + vp9_cond_prob_diff_update(w, addr(ref cm->fc->tx_probs.p8x8[i][j]), (uint*)&ct_8x8p[j]); } for (i = 0; i < TX_SIZE_CONTEXTS; i++) { - tx_counts_to_branch_counts_16x16((uint*)&(counts->tx.p16x16[i]), ct_16x16p); + tx_counts_to_branch_counts_16x16((uint*)addr(ref counts->tx.p16x16[i]), ct_16x16p); for (j = 0; j < TX_SIZES - 2; j++) - vp9_cond_prob_diff_update(w, &cm->fc->tx_probs.p16x16[i][j], + vp9_cond_prob_diff_update(w, addr(ref cm->fc->tx_probs.p16x16[i][j]), (uint*)&ct_16x16p[j]); } for (i = 0; i < TX_SIZE_CONTEXTS; i++) { - tx_counts_to_branch_counts_32x32((uint*)&(counts->tx.p32x32[i]), ct_32x32p); + tx_counts_to_branch_counts_32x32((uint*)addr(ref counts->tx.p32x32[i]), ct_32x32p); for (j = 0; j < TX_SIZES - 1; j++) - vp9_cond_prob_diff_update(w, &cm->fc->tx_probs.p32x32[i][j], + vp9_cond_prob_diff_update(w, addr(ref cm->fc->tx_probs.p32x32[i][j]), (uint*)&ct_32x32p[j]); } } @@ -1321,15 +1321,15 @@ private static size_t write_compressed_header(VP9_COMP* cpi, uint8_t* data, size int i; for (i = 0; i < INTER_MODE_CONTEXTS; ++i) - prob_diff_update(vp9_inter_mode_tree, (byte*)&(cm->fc->inter_mode_probs[i]), - (uint*)&(counts->inter_mode[i]), INTER_MODES, &header_bc); + prob_diff_update(vp9_inter_mode_tree, (byte*)addr(ref cm->fc->inter_mode_probs[i]), + (uint*)addr(ref counts->inter_mode[i]), INTER_MODES, &header_bc); if (cm->interp_filter == SWITCHABLE) update_switchable_interp_probs(cm, &header_bc, counts); for (i = 0; i < INTRA_INTER_CONTEXTS; i++) vp9_cond_prob_diff_update(&header_bc, &fc->intra_inter_prob[i], - (uint*)&(counts->intra_inter[i])); + (uint*)addr(ref counts->intra_inter[i])); if ((cpi->allow_comp_inter_inter) != 0) { int use_compound_pred = ((cm->reference_mode != SINGLE_REFERENCE) ? 1 : 0); @@ -1341,31 +1341,31 @@ private static size_t write_compressed_header(VP9_COMP* cpi, uint8_t* data, size if (use_hybrid_pred != 0) for (i = 0; i < COMP_INTER_CONTEXTS; i++) vp9_cond_prob_diff_update(&header_bc, &fc->comp_inter_prob[i], - (uint*)&(counts->comp_inter[i])); + (uint*)addr(ref counts->comp_inter[i])); } } if (cm->reference_mode != COMPOUND_REFERENCE) { for (i = 0; i < REF_CONTEXTS; i++) { - vp9_cond_prob_diff_update(&header_bc, &fc->single_ref_prob[i][0], - (uint*)&(counts->single_ref[i][0])); - vp9_cond_prob_diff_update(&header_bc, &fc->single_ref_prob[i][1], - (uint*)&(counts->single_ref[i][1])); + vp9_cond_prob_diff_update(&header_bc, addr(ref fc->single_ref_prob[i][0]), + (uint*)addr(ref counts->single_ref[i][0])); + vp9_cond_prob_diff_update(&header_bc, addr(ref fc->single_ref_prob[i][1]), + (uint*)addr(ref counts->single_ref[i][1])); } } if (cm->reference_mode != SINGLE_REFERENCE) for (i = 0; i < REF_CONTEXTS; i++) vp9_cond_prob_diff_update(&header_bc, &fc->comp_ref_prob[i], - (uint*)&(counts->comp_ref[i])); + (uint*)addr(ref counts->comp_ref[i])); for (i = 0; i < BLOCK_SIZE_GROUPS; ++i) - prob_diff_update(vp9_intra_mode_tree, (byte*)&(cm->fc->y_mode_prob[i]), - (uint*)&(counts->y_mode[i]), INTRA_MODES, &header_bc); + prob_diff_update(vp9_intra_mode_tree, (byte*)addr(ref cm->fc->y_mode_prob[i]), + (uint*)addr(ref counts->y_mode[i]), INTRA_MODES, &header_bc); for (i = 0; i < PARTITION_CONTEXTS; ++i) - prob_diff_update(vp9_partition_tree, (byte*)&(fc->partition_prob[i]), - (uint*)&(counts->partition[i]), PARTITION_TYPES, &header_bc); + prob_diff_update(vp9_partition_tree, (byte*)addr(ref fc->partition_prob[i]), + (uint*)addr(ref counts->partition[i]), PARTITION_TYPES, &header_bc); vp9_write_nmv_probs(cm, cm->allow_high_precision_mv, &header_bc, &counts->mv); diff --git a/src/Codecs/SIPSorcery.VP9/encoder/vp9_context_tree.cs b/src/Codecs/SIPSorcery.VP9/encoder/vp9_context_tree.cs index c9bb3468b8..94c480352e 100644 --- a/src/Codecs/SIPSorcery.VP9/encoder/vp9_context_tree.cs +++ b/src/Codecs/SIPSorcery.VP9/encoder/vp9_context_tree.cs @@ -86,25 +86,25 @@ private static void free_mode_context(PICK_MODE_CONTEXT* ctx) private static void alloc_tree_contexts(VP9_COMMON* cm, PC_TREE* tree, int num_4x4_blk) { alloc_mode_context(cm, num_4x4_blk, &tree->none); - alloc_mode_context(cm, num_4x4_blk / 2, &tree->horizontal[0]); - alloc_mode_context(cm, num_4x4_blk / 2, &tree->vertical[0]); + alloc_mode_context(cm, num_4x4_blk / 2, addr(ref tree->horizontal[0])); + alloc_mode_context(cm, num_4x4_blk / 2, addr(ref tree->vertical[0])); if (num_4x4_blk > 4) { - alloc_mode_context(cm, num_4x4_blk / 2, &tree->horizontal[1]); - alloc_mode_context(cm, num_4x4_blk / 2, &tree->vertical[1]); + alloc_mode_context(cm, num_4x4_blk / 2, addr(ref tree->horizontal[1])); + alloc_mode_context(cm, num_4x4_blk / 2, addr(ref tree->vertical[1])); } else { - memset(&tree->horizontal[1], 0, sizeof(PICK_MODE_CONTEXT)); - memset(&tree->vertical[1], 0, sizeof(PICK_MODE_CONTEXT)); + memset(addr(ref tree->horizontal[1]), 0, sizeof(PICK_MODE_CONTEXT)); + memset(addr(ref tree->vertical[1]), 0, sizeof(PICK_MODE_CONTEXT)); } } private static void free_tree_contexts(PC_TREE* tree) { free_mode_context(&tree->none); - free_mode_context(&tree->horizontal[0]); - free_mode_context(&tree->horizontal[1]); - free_mode_context(&tree->vertical[0]); - free_mode_context(&tree->vertical[1]); + free_mode_context(addr(ref tree->horizontal[0])); + free_mode_context(addr(ref tree->horizontal[1])); + free_mode_context(addr(ref tree->vertical[0])); + free_mode_context(addr(ref tree->vertical[1])); } // This function sets up a tree of contexts such that at each square diff --git a/src/Codecs/SIPSorcery.VP9/encoder/vp9_encodeframe.cs b/src/Codecs/SIPSorcery.VP9/encoder/vp9_encodeframe.cs index 211fa70e2b..85980497b1 100644 --- a/src/Codecs/SIPSorcery.VP9/encoder/vp9_encodeframe.cs +++ b/src/Codecs/SIPSorcery.VP9/encoder/vp9_encodeframe.cs @@ -231,35 +231,35 @@ private static void tree_to_node(void* data, BLOCK_SIZE bsize, variance_node* no v64x64* vt = (v64x64 *)data; node->part_variances = &vt->part_variances; for (i = 0; i < 4; i++) - node->split[i] = &vt->split[i].part_variances.none; + node->split[i] = addr(ref vt->split[i].part_variances.none); break; } case BLOCK_32X32: { v32x32* vt = (v32x32 *)data; node->part_variances = &vt->part_variances; for (i = 0; i < 4; i++) - node->split[i] = &vt->split[i].part_variances.none; + node->split[i] = addr(ref vt->split[i].part_variances.none); break; } case BLOCK_16X16: { v16x16* vt = (v16x16 *)data; node->part_variances = &vt->part_variances; for (i = 0; i < 4; i++) - node->split[i] = &vt->split[i].part_variances.none; + node->split[i] = addr(ref vt->split[i].part_variances.none); break; } case BLOCK_8X8: { v8x8* vt = (v8x8 *)data; node->part_variances = &vt->part_variances; for (i = 0; i < 4; i++) - node->split[i] = &vt->split[i].part_variances.none; + node->split[i] = addr(ref vt->split[i].part_variances.none); break; } default: { v4x4* vt = (v4x4 *)data; Debug.Assert(bsize == BLOCK_4X4); node->part_variances = &vt->part_variances; - for (i = 0; i < 4; i++) node->split[i] = &vt->split[i]; + for (i = 0; i < 4; i++) node->split[i] = addr(ref vt->split[i]); break; } } @@ -294,11 +294,11 @@ private static void fill_variance_tree(void* data, BLOCK_SIZE bsize) variance_node node; memset(&node, 0, sizeof(variance_node)); tree_to_node(data, bsize, &node); - sum_2_variances(node.split[0], node.split[1], &node.part_variances->horz[0]); - sum_2_variances(node.split[2], node.split[3], &node.part_variances->horz[1]); - sum_2_variances(node.split[0], node.split[2], &node.part_variances->vert[0]); - sum_2_variances(node.split[1], node.split[3], &node.part_variances->vert[1]); - sum_2_variances(&node.part_variances->vert[0], &node.part_variances->vert[1], + sum_2_variances(node.split[0], node.split[1], addr(ref node.part_variances->horz[0])); + sum_2_variances(node.split[2], node.split[3], addr(ref node.part_variances->horz[1])); + sum_2_variances(node.split[0], node.split[2], addr(ref node.part_variances->vert[0])); + sum_2_variances(node.split[1], node.split[3], addr(ref node.part_variances->vert[1])); + sum_2_variances(addr(ref node.part_variances->vert[0]), addr(ref node.part_variances->vert[1]), &node.part_variances->none); } @@ -347,11 +347,11 @@ private static int set_vt_partitioning(VP9_COMP* cpi, MACROBLOCK* x, MACROBLOCKD // Check vertical split. if (mi_row + block_height / 2 < cm->mi_rows) { BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_VERT); - get_variance(&vt.part_variances->vert[0]); - get_variance(&vt.part_variances->vert[1]); + get_variance(addr(ref vt.part_variances->vert[0])); + get_variance(addr(ref vt.part_variances->vert[1])); if (vt.part_variances->vert[0].variance < threshold && vt.part_variances->vert[1].variance < threshold && - get_plane_block_size(subsize, &xd->plane[1]) < BLOCK_INVALID) { + get_plane_block_size(subsize, addr(ref xd->plane[1])) < BLOCK_INVALID) { set_block_size(cpi, x, xd, mi_row, mi_col, subsize); set_block_size(cpi, x, xd, mi_row, mi_col + block_width / 2, subsize); return 1; @@ -360,11 +360,11 @@ private static int set_vt_partitioning(VP9_COMP* cpi, MACROBLOCK* x, MACROBLOCKD // Check horizontal split. if (mi_col + block_width / 2 < cm->mi_cols) { BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_HORZ); - get_variance(&vt.part_variances->horz[0]); - get_variance(&vt.part_variances->horz[1]); + get_variance(addr(ref vt.part_variances->horz[0])); + get_variance(addr(ref vt.part_variances->horz[1])); if (vt.part_variances->horz[0].variance < threshold && vt.part_variances->horz[1].variance < threshold && - get_plane_block_size(subsize, &xd->plane[1]) < BLOCK_INVALID) { + get_plane_block_size(subsize, addr(ref xd->plane[1])) < BLOCK_INVALID) { set_block_size(cpi, x, xd, mi_row, mi_col, subsize); set_block_size(cpi, x, xd, mi_row + block_height / 2, mi_col, subsize); return 1; @@ -527,7 +527,7 @@ private static void fill_variance_4x4avg(uint8_t* s, int sp, uint8_t* d, int dp, sum = s_avg - d_avg; sse = (uint)(sum * sum); } - fill_variance(sse, sum, 0, &vst->split[k].part_variances.none); + fill_variance(sse, sum, 0, addr(ref vst->split[k].part_variances.none)); } } @@ -547,7 +547,7 @@ private static void fill_variance_8x8avg(uint8_t* s, int sp, uint8_t* d, int dp, sum = s_avg - d_avg; sse = (uint)(sum * sum); } - fill_variance(sse, sum, 0, &vst->split[k].part_variances.none); + fill_variance(sse, sum, 0, addr(ref vst->split[k].part_variances.none)); } } @@ -704,9 +704,8 @@ private static int copy_partitioning(VP9_COMP* cpi, MACROBLOCK* x, MACROBLOCKD* if ((cpi->use_svc) != 0) { // For SVC, don't allow copy if base spatial layer is key frame, or if // frame is not a temporal enhancement layer frame. - int layer = ((0) * ( - cpi->svc.number_temporal_layers) + ( cpi->svc.temporal_layer_id)); - LAYER_CONTEXT* lc = &cpi->svc.layer_context[layer]; + int layer = ((0) + ( cpi->svc.temporal_layer_id)); + LAYER_CONTEXT* lc = addr(ref cpi->svc.layer_context[layer]); if (((lc->is_key_frame) != 0) || ((cpi->svc.non_reference_frame) == 0)) svc_copy_allowed = 0; frames_since_key_thresh = cpi->svc.number_spatial_layers << 1; } @@ -943,8 +942,8 @@ private static void chroma_check(VP9_COMP* cpi, MACROBLOCK* x, int bsize, uint y for (i = 1; i <= 2; ++i) { uint uv_sad = UINT_MAX; - macroblock_plane* p = &x->plane[i]; - macroblockd_plane* pd = &xd->plane[i]; + macroblock_plane* p = addr(ref x->plane[i]); + macroblockd_plane* pd = addr(ref xd->plane[i]); BLOCK_SIZE bs = get_plane_block_size((byte)bsize, pd); if (bs != BLOCK_INVALID) @@ -1170,7 +1169,7 @@ private static int choose_partitioning(VP9_COMP* cpi, TileInfo* tile, MACROBLOCK if (cpi->oxcf.speed < 8 && (yv12_g != null) && yv12_g != yv12 && ((cpi->ref_frame_flags & VP9_GOLD_FLAG) != 0)) { vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col, - &cm->frame_refs[GOLDEN_FRAME - 1].sf); + addr(ref cm->frame_refs[GOLDEN_FRAME - 1].sf)); y_sad_g = cpi->fn_ptr[bsize].sdf( x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf, xd->plane[0].pre[0].stride); @@ -1182,12 +1181,12 @@ private static int choose_partitioning(VP9_COMP* cpi, TileInfo* tile, MACROBLOCK ((cpi->rc.is_src_frame_alt_ref) != 0)) { yv12 = get_ref_frame_buffer(cpi, ALTREF_FRAME); vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col, - &cm->frame_refs[ALTREF_FRAME - 1].sf); + addr(ref cm->frame_refs[ALTREF_FRAME - 1].sf)); mi->ref_frame[0] = ALTREF_FRAME; y_sad_g = UINT_MAX; } else { vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col, - &cm->frame_refs[LAST_FRAME - 1].sf); + addr(ref cm->frame_refs[LAST_FRAME - 1].sf)); mi->ref_frame[0] = LAST_FRAME; } mi->ref_frame[1] = NO_REF_FRAME; @@ -1231,7 +1230,7 @@ private static int choose_partitioning(VP9_COMP* cpi, TileInfo* tile, MACROBLOCK y_sad_thr = ((cpi->sf.short_circuit_low_temp_var) != 0) ? (y_sad * 7) >> 3 : y_sad; if (y_sad_g < y_sad_thr) { vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col, - &cm->frame_refs[GOLDEN_FRAME - 1].sf); + addr(ref cm->frame_refs[GOLDEN_FRAME - 1].sf)); mi->ref_frame[0] = GOLDEN_FRAME; mi->mv[0].as_int = 0; y_sad = y_sad_g; @@ -1303,14 +1302,14 @@ private static int choose_partitioning(VP9_COMP* cpi, TileInfo* tile, MACROBLOCK int x16_idx = x32_idx + ((j & 1) << 4); int y16_idx = y32_idx + ((j >> 1) << 4); int split_index = 5 + i2 + j; - v16x16* vst = &vt.split[i].split[j]; + v16x16* vst = addr(ref vt.split[i].split[j]); force_split[split_index] = 0; variance4x4downsample[i2 + j] = 0; if (is_key_frame == 0) { fill_variance_8x8avg(s, sp, d, dp, x16_idx, y16_idx, vst, pixels_wide, pixels_high, is_key_frame); - fill_variance_tree(&vt.split[i].split[j], BLOCK_16X16); - get_variance(&vt.split[i].split[j].part_variances.none); + fill_variance_tree(addr(ref vt.split[i].split[j]), BLOCK_16X16); + get_variance(addr(ref vt.split[i].split[j].part_variances.none)); avg_16x16[i] += vt.split[i].split[j].part_variances.none.variance; if (vt.split[i].split[j].part_variances.none.variance < minvar_16x16[i]) minvar_16x16[i] = vt.split[i].split[j].part_variances.none.variance; @@ -1350,7 +1349,7 @@ private static int choose_partitioning(VP9_COMP* cpi, TileInfo* tile, MACROBLOCK for (k = 0; k < 4; k++) { int x8_idx = x16_idx + ((k & 1) << 3); int y8_idx = y16_idx + ((k >> 1) << 3); - v8x8* vst2 = (is_key_frame != 0) ? &vst->split[k] : &vt2[i2 + j].split[k]; + v8x8* vst2 = (is_key_frame != 0) ? addr(ref vst->split[k]) : addr(ref vt2[i2 + j].split[k]); fill_variance_4x4avg(s, sp, d, dp, x8_idx, y8_idx, vst2, pixels_wide, pixels_high, is_key_frame); } @@ -1365,8 +1364,8 @@ private static int choose_partitioning(VP9_COMP* cpi, TileInfo* tile, MACROBLOCK int i2 = i << 2; for (j = 0; j < 4; j++) { if (variance4x4downsample[i2 + j] == 1) { - v16x16* vtemp = (is_key_frame == 0) ? &vt2[i2 + j] : &vt.split[i].split[j]; - for (m = 0; m < 4; m++) fill_variance_tree(&vtemp->split[m], BLOCK_8X8); + v16x16* vtemp = (is_key_frame == 0) ? &vt2[i2 + j] : addr(ref vt.split[i].split[j]); + for (m = 0; m < 4; m++) fill_variance_tree(addr(ref vtemp->split[m]), BLOCK_8X8); fill_variance_tree(vtemp, BLOCK_16X16); // If variance of this 16x16 block is above the threshold, force block // to split. This also forces a split on the upper levels. @@ -1378,13 +1377,13 @@ private static int choose_partitioning(VP9_COMP* cpi, TileInfo* tile, MACROBLOCK } } } - fill_variance_tree(&vt.split[i], BLOCK_32X32); + fill_variance_tree(addr(ref vt.split[i]), BLOCK_32X32); // If variance of this 32x32 block is above the threshold, or if its above // (some threshold of) the average variance over the sub-16x16 blocks, then // force this block to split. This also forces a split on the upper // (64x64) level. if (force_split[i + 1] == 0) { - get_variance(&vt.split[i].part_variances.none); + get_variance(addr(ref vt.split[i].part_variances.none)); var_32x32 = vt.split[i].part_variances.none.variance; max_var_32x32 = VPXMAX(var_32x32, max_var_32x32); min_var_32x32 = VPXMIN(var_32x32, min_var_32x32); @@ -1431,7 +1430,7 @@ private static int choose_partitioning(VP9_COMP* cpi, TileInfo* tile, MACROBLOCK int x32_idx = ((i & 1) << 2); int y32_idx = ((i >> 1) << 2); int i2 = i << 2; - if ((set_vt_partitioning(cpi, x, xd, &vt.split[i], BLOCK_32X32, + if ((set_vt_partitioning(cpi, x, xd, addr(ref vt.split[i]), BLOCK_32X32, (mi_row + y32_idx), (mi_col + x32_idx), thresholds[1], BLOCK_16X16, force_split[i + 1])) == 0) { @@ -1443,7 +1442,7 @@ private static int choose_partitioning(VP9_COMP* cpi, TileInfo* tile, MACROBLOCK // in set_vt_partitioning(), otherwise use vt. v16x16* vtemp = ((is_key_frame == 0) && variance4x4downsample[i2 + j] == 1) ? &vt2[i2 + j] - : &vt.split[i].split[j]; + : addr(ref vt.split[i].split[j]); if ((set_vt_partitioning( cpi, x, xd, vtemp, BLOCK_16X16, mi_row + y32_idx + y16_idx, mi_col + x32_idx + x16_idx, thresholds[2], cpi->vbp_bsize_min, @@ -1452,7 +1451,7 @@ private static int choose_partitioning(VP9_COMP* cpi, TileInfo* tile, MACROBLOCK int x8_idx = (k & 1); int y8_idx = (k >> 1); if (use_4x4_partition != 0) { - if ((set_vt_partitioning(cpi, x, xd, &vtemp->split[k], + if ((set_vt_partitioning(cpi, x, xd, addr(ref vtemp->split[k]), BLOCK_8X8, mi_row + y32_idx + y16_idx + y8_idx, mi_col + x32_idx + x16_idx + x8_idx, @@ -1501,7 +1500,7 @@ internal static void vp9_setup_src_planes(MACROBLOCK* x, YV12_BUFFER_CONFIG* src x->e_mbd.cur_buf = src; for (i = 0; i < MAX_MB_PLANE; i++) - setup_pred_plane(&x->plane[i].src, buffers[i], strides[i], mi_row, mi_col, + setup_pred_plane(addr(ref x->plane[i].src), buffers[i], strides[i], mi_row, mi_col, null, x->e_mbd.plane[i].subsampling_x, x->e_mbd.plane[i].subsampling_y); } @@ -1865,18 +1864,18 @@ private static void encode_sb_rt(VP9_COMP* cpi, ThreadData* td, TileInfo* tile, break; case PARTITION_VERT: encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize, - &pc_tree->vertical[0]); + addr(ref pc_tree->vertical[0])); if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) { encode_b_rt(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled, - subsize, &pc_tree->vertical[1]); + subsize, addr(ref pc_tree->vertical[1])); } break; case PARTITION_HORZ: encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize, - &pc_tree->horizontal[0]); + addr(ref pc_tree->horizontal[0])); if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) { encode_b_rt(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled, - subsize, &pc_tree->horizontal[1]); + subsize, addr(ref pc_tree->horizontal[1])); } break; default: @@ -2129,7 +2128,7 @@ private static void nonrd_pick_sb_modes(VP9_COMP* cpi, TileDataEnc* tile_data, M mi->sb_type = bsize; for (plane = 0; plane < MAX_MB_PLANE; ++plane) { - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); memcpy(a + num_4x4_blocks_wide * plane, pd->above_context, (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >> pd->subsampling_x); memcpy(l + num_4x4_blocks_high * plane, pd->left_context, @@ -2161,7 +2160,7 @@ private static void nonrd_pick_sb_modes(VP9_COMP* cpi, TileDataEnc* tile_data, M duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize); for (plane = 0; plane < MAX_MB_PLANE; ++plane) { - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); memcpy(pd->above_context, a + num_4x4_blocks_wide * plane, (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >> pd->subsampling_x); memcpy(pd->left_context, l + num_4x4_blocks_high * plane, @@ -2337,7 +2336,6 @@ private static void nonrd_pick_partition(VP9_COMP* cpi, ThreadData* td, TileData int partition_vert_allowed = (((force_horz_split == 0) && xss <= yss && bsize >= BLOCK_8X8) ? 1 : 0); int use_ml_based_partitioning = ((sf->partition_search_type == ML_BASED_PARTITION) ? 1 : 0); - _ = *tp_orig; // Avoid checking for rectangular partitions for speed >= 5. if (cpi->oxcf.speed >= 5) do_rect = 0; @@ -2460,7 +2458,7 @@ private static void nonrd_pick_partition(VP9_COMP* cpi, ThreadData* td, TileData load_pred_mv(x, ctx); pc_tree->horizontal[0].pred_pixel_ready = 1; nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize, - &pc_tree->horizontal[0]); + addr(ref pc_tree->horizontal[0])); pc_tree->horizontal[0].mic = *xd->mi[0]; pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext; @@ -2471,7 +2469,7 @@ private static void nonrd_pick_partition(VP9_COMP* cpi, ThreadData* td, TileData load_pred_mv(x, ctx); pc_tree->horizontal[1].pred_pixel_ready = 1; nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + ms, mi_col, &this_rdc, - subsize, &pc_tree->horizontal[1]); + subsize, addr(ref pc_tree->horizontal[1])); pc_tree->horizontal[1].mic = *xd->mi[0]; pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext; @@ -2504,7 +2502,7 @@ private static void nonrd_pick_partition(VP9_COMP* cpi, ThreadData* td, TileData load_pred_mv(x, ctx); pc_tree->vertical[0].pred_pixel_ready = 1; nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize, - &pc_tree->vertical[0]); + addr(ref pc_tree->vertical[0])); pc_tree->vertical[0].mic = *xd->mi[0]; pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext; pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0]; @@ -2514,7 +2512,7 @@ private static void nonrd_pick_partition(VP9_COMP* cpi, ThreadData* td, TileData load_pred_mv(x, ctx); pc_tree->vertical[1].pred_pixel_ready = 1; nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + ms, &this_rdc, - subsize, &pc_tree->vertical[1]); + subsize, addr(ref pc_tree->vertical[1])); pc_tree->vertical[1].mic = *xd->mi[0]; pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext; pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0]; @@ -2614,7 +2612,7 @@ private static void nonrd_select_partition(VP9_COMP* cpi, ThreadData* td, TileDa case PARTITION_VERT: pc_tree->vertical[0].pred_pixel_ready = 1; nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize, - &pc_tree->vertical[0]); + addr(ref pc_tree->vertical[0])); pc_tree->vertical[0].mic = *xd->mi[0]; pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext; pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0]; @@ -2622,7 +2620,7 @@ private static void nonrd_select_partition(VP9_COMP* cpi, ThreadData* td, TileDa if (mi_col + hbs < cm->mi_cols) { pc_tree->vertical[1].pred_pixel_ready = 1; nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs, - &this_rdc, subsize, &pc_tree->vertical[1]); + &this_rdc, subsize, addr(ref pc_tree->vertical[1])); pc_tree->vertical[1].mic = *xd->mi[0]; pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext; pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0]; @@ -2637,7 +2635,7 @@ private static void nonrd_select_partition(VP9_COMP* cpi, ThreadData* td, TileDa case PARTITION_HORZ: pc_tree->horizontal[0].pred_pixel_ready = 1; nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize, - &pc_tree->horizontal[0]); + addr(ref pc_tree->horizontal[0])); pc_tree->horizontal[0].mic = *xd->mi[0]; pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext; pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0]; @@ -2645,7 +2643,7 @@ private static void nonrd_select_partition(VP9_COMP* cpi, ThreadData* td, TileDa if (mi_row + hbs < cm->mi_rows) { pc_tree->horizontal[1].pred_pixel_ready = 1; nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col, - &this_rdc, subsize, &pc_tree->horizontal[1]); + &this_rdc, subsize, addr(ref pc_tree->horizontal[1])); pc_tree->horizontal[1].mic = *xd->mi[0]; pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext; pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0]; @@ -2731,46 +2729,46 @@ private static void nonrd_use_partition(VP9_COMP* cpi, ThreadData* td, TileDataE case PARTITION_VERT: pc_tree->vertical[0].pred_pixel_ready = 1; nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost, - subsize, &pc_tree->vertical[0]); + subsize, addr(ref pc_tree->vertical[0])); pc_tree->vertical[0].mic = *xd->mi[0]; pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext; pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0]; pc_tree->vertical[0].skip = x->skip; encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, - subsize, &pc_tree->vertical[0]); + subsize, addr(ref pc_tree->vertical[0])); if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) { pc_tree->vertical[1].pred_pixel_ready = 1; nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs, dummy_cost, - subsize, &pc_tree->vertical[1]); + subsize, addr(ref pc_tree->vertical[1])); pc_tree->vertical[1].mic = *xd->mi[0]; pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext; pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0]; pc_tree->vertical[1].skip = x->skip; encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col + hbs, - output_enabled, subsize, &pc_tree->vertical[1]); + output_enabled, subsize, addr(ref pc_tree->vertical[1])); } break; case PARTITION_HORZ: pc_tree->horizontal[0].pred_pixel_ready = 1; nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost, - subsize, &pc_tree->horizontal[0]); + subsize, addr(ref pc_tree->horizontal[0])); pc_tree->horizontal[0].mic = *xd->mi[0]; pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext; pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0]; pc_tree->horizontal[0].skip = x->skip; encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, - subsize, &pc_tree->horizontal[0]); + subsize, addr(ref pc_tree->horizontal[0])); if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) { pc_tree->horizontal[1].pred_pixel_ready = 1; nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col, dummy_cost, - subsize, &pc_tree->horizontal[1]); + subsize, addr(ref pc_tree->horizontal[1])); pc_tree->horizontal[1].mic = *xd->mi[0]; pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext; pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0]; pc_tree->horizontal[1].skip = x->skip; encode_b_rt(cpi, td, tile_info, tp, mi_row + hbs, mi_col, - output_enabled, subsize, &pc_tree->horizontal[1]); + output_enabled, subsize, addr(ref pc_tree->horizontal[1])); } break; default: @@ -2832,7 +2830,7 @@ private static void get_estimated_pred(VP9_COMP* cpi, TileInfo* tile, MACROBLOCK if (cpi->oxcf.speed < 8 && (yv12_g != null) && yv12_g != yv12 && ((cpi->ref_frame_flags & VP9_GOLD_FLAG) != 0)) { vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col, - &cm->frame_refs[GOLDEN_FRAME - 1].sf); + addr(ref cm->frame_refs[GOLDEN_FRAME - 1].sf)); y_sad_g = cpi->fn_ptr[bsize].sdf( x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf, xd->plane[0].pre[0].stride); @@ -2844,12 +2842,12 @@ private static void get_estimated_pred(VP9_COMP* cpi, TileInfo* tile, MACROBLOCK ((cpi->rc.is_src_frame_alt_ref) != 0)) { yv12 = get_ref_frame_buffer(cpi, ALTREF_FRAME); vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col, - &cm->frame_refs[ALTREF_FRAME - 1].sf); + addr(ref cm->frame_refs[ALTREF_FRAME - 1].sf)); mi->ref_frame[0] = ALTREF_FRAME; y_sad_g = UINT_MAX; } else { vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col, - &cm->frame_refs[LAST_FRAME - 1].sf); + addr(ref cm->frame_refs[LAST_FRAME - 1].sf)); mi->ref_frame[0] = LAST_FRAME; } mi->ref_frame[1] = NO_REF_FRAME; @@ -2871,7 +2869,7 @@ private static void get_estimated_pred(VP9_COMP* cpi, TileInfo* tile, MACROBLOCK y_sad_thr = ((cpi->sf.short_circuit_low_temp_var) != 0) ? (y_sad * 7) >> 3 : y_sad; if (y_sad_g < y_sad_thr) { vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col, - &cm->frame_refs[GOLDEN_FRAME - 1].sf); + addr(ref cm->frame_refs[GOLDEN_FRAME - 1].sf)); mi->ref_frame[0] = GOLDEN_FRAME; mi->mv[0].as_int = 0; } else { @@ -3456,7 +3454,7 @@ private static void encode_frame_internal(VP9_COMP* cpi) source_var_based_partition_search_method(cpi); } else if ((gf_group_index != 0) && gf_group_index < MAX_ARF_GOP_SIZE && ((cpi->sf.enable_tpl_model) != 0)) { - TplDepFrame* tpl_frame = &cpi->tpl_stats[cpi->twopass.gf_group.index]; + TplDepFrame* tpl_frame = addr(ref cpi->tpl_stats[cpi->twopass.gf_group.index]); TplDepStats* tpl_stats = tpl_frame->tpl_stats_ptr; int tpl_stride = tpl_frame->stride; @@ -3617,8 +3615,8 @@ internal static void vp9_encode_frame(VP9_COMP* cpi) // that for subsequent frames. // It also does the same analysis for transform size selection. MV_REFERENCE_FRAME frame_type = get_frame_type(cpi); - int64_t* mode_thrs = (long*)&(rd_opt->prediction_type_threshes[frame_type]); - int64_t* filter_thrs = (long*)&(rd_opt->filter_threshes[frame_type]); + int64_t* mode_thrs = (long*)addr(ref rd_opt->prediction_type_threshes[frame_type]); + int64_t* filter_thrs = (long*)addr(ref rd_opt->filter_threshes[frame_type]); int is_alt_ref = ((frame_type == ALTREF_FRAME) ? 1 : 0); /* prediction (compound, single or hybrid) mode selection */ @@ -3849,7 +3847,7 @@ private static void encode_superblock(VP9_COMP* cpi, ThreadData* td, TOKENEXTRA* } ++td->counts->tx.tx_totals[mi->tx_size]; - ++td->counts->tx.tx_totals[get_uv_tx_size(mi, &xd->plane[1])]; + ++td->counts->tx.tx_totals[get_uv_tx_size(mi, addr(ref xd->plane[1]))]; if (((cm->seg.enabled) != 0) && cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && ((cpi->cyclic_refresh->content_mode) != 0)) vp9_cyclic_refresh_update_sb_postencode(cpi, mi, mi_row, mi_col, bsize); diff --git a/src/Codecs/SIPSorcery.VP9/encoder/vp9_encodemb.cs b/src/Codecs/SIPSorcery.VP9/encoder/vp9_encodemb.cs index db13af5a0d..6b4e3ab525 100644 --- a/src/Codecs/SIPSorcery.VP9/encoder/vp9_encodemb.cs +++ b/src/Codecs/SIPSorcery.VP9/encoder/vp9_encodemb.cs @@ -40,8 +40,8 @@ internal static unsafe partial class vp9_encodemb internal static void vp9_subtract_plane(MACROBLOCK* x, BLOCK_SIZE bsize, int plane) { - macroblock_plane* p = &x->plane[plane]; - macroblockd_plane* pd = &x->e_mbd.plane[plane]; + macroblock_plane* p = addr(ref x->plane[plane]); + macroblockd_plane* pd = addr(ref x->e_mbd.plane[plane]); BLOCK_SIZE plane_bsize = get_plane_block_size(bsize, pd); int bw = 4 * num_4x4_blocks_wide_lookup[plane_bsize]; int bh = 4 * num_4x4_blocks_high_lookup[plane_bsize]; @@ -58,8 +58,8 @@ internal static void vp9_subtract_plane(MACROBLOCK* x, BLOCK_SIZE bsize, int pla internal static int vp9_optimize_b(MACROBLOCK* mb, int plane, int block, TX_SIZE tx_size, int ctx) { MACROBLOCKD* xd = &mb->e_mbd; - macroblock_plane* p = &mb->plane[plane]; - macroblockd_plane* pd = &xd->plane[plane]; + macroblock_plane* p = addr(ref mb->plane[plane]); + macroblockd_plane* pd = addr(ref xd->plane[plane]); int @ref = is_inter_block(xd->mi[0]); uint8_t* token_cache = stackalloc uint8_t[1024]; tran_low_t* coeff = ((p->coeff) + ( block)*16); @@ -87,7 +87,7 @@ internal static int vp9_optimize_b(MACROBLOCK* mb, int plane, int block, TX_SIZE int i; int final_eob; int count_high_values_after_eob = 0; uint16_t* cat6_high_cost = vp9_get_high_cost_table(8); - A2>>* token_costs = (A2>>*)&(mb->token_costs[tx_size][plane_type][@ref]); + A2>>* token_costs = (A2>>*)addr(ref mb->token_costs[tx_size][plane_type][@ref]); A2>>* token_costs_cur; int64_t eob_cost0; int64_t eob_cost1; int ctx0 = ctx; @@ -303,8 +303,8 @@ private static void fdct32x32(int rd_transform, int16_t* src, tran_low_t* dst, i internal static void vp9_xform_quant_fp(MACROBLOCK* x, int plane, int block, int row, int col, BLOCK_SIZE plane_bsize, TX_SIZE tx_size) { MACROBLOCKD* xd = &x->e_mbd; - macroblock_plane* p = &x->plane[plane]; - macroblockd_plane* pd = &xd->plane[plane]; + macroblock_plane* p = addr(ref x->plane[plane]); + macroblockd_plane* pd = addr(ref xd->plane[plane]); ScanOrder* scan_order = &vp9_default_scan_orders[tx_size]; tran_low_t* coeff = ((p->coeff) + ( block)*16); tran_low_t* qcoeff = ((p->qcoeff) + ( block)*16); @@ -345,8 +345,8 @@ internal static void vp9_xform_quant_fp(MACROBLOCK* x, int plane, int block, int internal static void vp9_xform_quant_dc(MACROBLOCK* x, int plane, int block, int row, int col, BLOCK_SIZE plane_bsize, TX_SIZE tx_size) { MACROBLOCKD* xd = &x->e_mbd; - macroblock_plane* p = &x->plane[plane]; - macroblockd_plane* pd = &xd->plane[plane]; + macroblock_plane* p = addr(ref x->plane[plane]); + macroblockd_plane* pd = addr(ref xd->plane[plane]); tran_low_t* coeff = ((p->coeff) + ( block)*16); tran_low_t* qcoeff = ((p->qcoeff) + ( block)*16); tran_low_t* dqcoeff = ((pd->dqcoeff) + ( block)*16); @@ -385,8 +385,8 @@ internal static void vp9_xform_quant_dc(MACROBLOCK* x, int plane, int block, int internal static void vp9_xform_quant(MACROBLOCK* x, int plane, int block, int row, int col, BLOCK_SIZE plane_bsize, TX_SIZE tx_size) { MACROBLOCKD* xd = &x->e_mbd; - macroblock_plane* p = &x->plane[plane]; - macroblockd_plane* pd = &xd->plane[plane]; + macroblock_plane* p = addr(ref x->plane[plane]); + macroblockd_plane* pd = addr(ref xd->plane[plane]); ScanOrder* scan_order = &vp9_default_scan_orders[tx_size]; tran_low_t* coeff = ((p->coeff) + ( block)*16); tran_low_t* qcoeff = ((p->qcoeff) + ( block)*16); @@ -428,8 +428,8 @@ private static void encode_block(int plane, int block, int row, int col, BLOCK_S encode_b_args* args = (encode_b_args*)arg; MACROBLOCK* x = args->x; MACROBLOCKD* xd = &x->e_mbd; - macroblock_plane* p = &x->plane[plane]; - macroblockd_plane* pd = &xd->plane[plane]; + macroblock_plane* p = addr(ref x->plane[plane]); + macroblockd_plane* pd = addr(ref xd->plane[plane]); tran_low_t* dqcoeff = ((pd->dqcoeff) + ( block)*16); uint8_t* dst; ENTROPY_CONTEXT* a; ENTROPY_CONTEXT* l; @@ -514,8 +514,8 @@ private static void encode_block_pass1(int plane, int block, int row, int col, B { MACROBLOCK* x = (MACROBLOCK *)arg; MACROBLOCKD* xd = &x->e_mbd; - macroblock_plane* p = &x->plane[plane]; - macroblockd_plane* pd = &xd->plane[plane]; + macroblock_plane* p = addr(ref x->plane[plane]); + macroblockd_plane* pd = addr(ref xd->plane[plane]); tran_low_t* dqcoeff = ((pd->dqcoeff) + ( block)*16); uint8_t* dst; dst = &pd->dst.buf[4 * row * pd->dst.stride + 4 * col]; @@ -553,16 +553,16 @@ internal static void vp9_encode_sb(MACROBLOCK* x, BLOCK_SIZE bsize, int mi_row, if ((x->skip_recode) == 0) vp9_subtract_plane(x, bsize, plane); if (((x->optimize) != 0) && (((x->skip_recode) == 0) || ((x->skip_optimize) == 0))) { - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); TX_SIZE tx_size = (plane != 0) ? get_uv_tx_size(mi, pd) : mi->tx_size; - vp9_get_entropy_contexts(bsize, tx_size, pd, (byte*)&ctx.ta[plane], - (byte*)&ctx.tl[plane]); + vp9_get_entropy_contexts(bsize, tx_size, pd, (byte*)addr(ref ctx.ta[plane]), + (byte*)addr(ref ctx.tl[plane])); arg.enable_trellis_opt = 1; } else { arg.enable_trellis_opt = 0; } - arg.ta = (byte*)&ctx.ta[plane]; - arg.tl = (byte*)&ctx.tl[plane]; + arg.ta = (byte*)addr(ref ctx.ta[plane]); + arg.tl = (byte*)addr(ref ctx.tl[plane]); vp9_foreach_transformed_block_in_plane(xd, bsize, plane, &encode_block, &arg); @@ -575,8 +575,8 @@ internal static void vp9_encode_block_intra(int plane, int block, int row, int c MACROBLOCK* x = args->x; MACROBLOCKD* xd = &x->e_mbd; MODE_INFO* mi = xd->mi[0]; - macroblock_plane* p = &x->plane[plane]; - macroblockd_plane* pd = &xd->plane[plane]; + macroblock_plane* p = addr(ref x->plane[plane]); + macroblockd_plane* pd = addr(ref xd->plane[plane]); tran_low_t* coeff = ((p->coeff) + ( block)*16); tran_low_t* qcoeff = ((p->qcoeff) + ( block)*16); tran_low_t* dqcoeff = ((pd->dqcoeff) + ( block)*16); @@ -600,7 +600,7 @@ internal static void vp9_encode_block_intra(int plane, int block, int row, int c if (tx_size == TX_4X4) { tx_type = get_tx_type_4x4(get_plane_type(plane), xd, block); - scan_order = &vp9_scan_orders[TX_4X4][tx_type]; + scan_order = addr(ref vp9_scan_orders[TX_4X4][tx_type]); mode = plane == 0 ? get_y_mode(xd->mi[0], block) : mi->uv_mode; } else { mode = plane == 0 ? mi->mode : mi->uv_mode; @@ -608,7 +608,7 @@ internal static void vp9_encode_block_intra(int plane, int block, int row, int c scan_order = &vp9_default_scan_orders[TX_32X32]; } else { tx_type = get_tx_type(get_plane_type(plane), xd); - scan_order = &vp9_scan_orders[tx_size][tx_type]; + scan_order = addr(ref vp9_scan_orders[tx_size][tx_type]); } } @@ -702,13 +702,13 @@ internal static void vp9_encode_intra_block_plane(MACROBLOCK* x, BLOCK_SIZE bsiz { MACROBLOCKD* xd = &x->e_mbd; optimize_ctx ctx; Unsafe.SkipInit(out ctx); - encode_b_args arg = new encode_b_args { x = x, enable_trellis_opt = enable_trellis_opt, trellis_opt_thresh = 0.0, sse_calc_done = null, sse = null, ta = (byte*)&ctx.ta[plane], tl = (byte*)&ctx.tl[plane], skip = &xd->mi[0]->skip }; + encode_b_args arg = new encode_b_args { x = x, enable_trellis_opt = enable_trellis_opt, trellis_opt_thresh = 0.0, sse_calc_done = null, sse = null, ta = (byte*)addr(ref ctx.ta[plane]), tl = (byte*)addr(ref ctx.tl[plane]), skip = &xd->mi[0]->skip }; if ((enable_trellis_opt != 0) && ((x->optimize) != 0) && (((x->skip_recode) == 0) || ((x->skip_optimize) == 0))) { - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); TX_SIZE tx_size = (plane != 0) ? get_uv_tx_size(xd->mi[0], pd) : xd->mi[0]->tx_size; - vp9_get_entropy_contexts(bsize, tx_size, pd, (byte*)&ctx.ta[plane], (byte*)&ctx.tl[plane]); + vp9_get_entropy_contexts(bsize, tx_size, pd, (byte*)addr(ref ctx.ta[plane]), (byte*)addr(ref ctx.tl[plane])); } else { arg.enable_trellis_opt = 0; } diff --git a/src/Codecs/SIPSorcery.VP9/encoder/vp9_encodemv.cs b/src/Codecs/SIPSorcery.VP9/encoder/vp9_encodemv.cs index 2b968fcf53..8bfbb14712 100644 --- a/src/Codecs/SIPSorcery.VP9/encoder/vp9_encodemv.cs +++ b/src/Codecs/SIPSorcery.VP9/encoder/vp9_encodemv.cs @@ -77,7 +77,7 @@ private static void encode_mv_component(vpx_writer* w, int comp, nmv_component* // Fractional bits vp9_write_token(w, vp9_mv_fp_tree, - mv_class == MV_CLASS_0 ? (vpx_prob*)&mvcomp->class0_fp[d] : mvcomp->fp, + mv_class == MV_CLASS_0 ? (vpx_prob*)addr(ref mvcomp->class0_fp[d]) : mvcomp->fp, &mv_fp_encodings[fr]); // High precision bit @@ -104,7 +104,7 @@ private static void build_nmv_component_cost_table(int* mvcost, nmv_component* m } for (i = 0; i < CLASS0_SIZE; ++i) - vp9_cost_tokens((int*)&class0_fp_cost[i], (byte*)&(mvcomp->class0_fp[i]), vp9_mv_fp_tree); + vp9_cost_tokens((int*)&class0_fp_cost[i], (byte*)addr(ref mvcomp->class0_fp[i]), vp9_mv_fp_tree); vp9_cost_tokens(fp_cost, mvcomp->fp, vp9_mv_fp_tree); // Always build the hp costs to avoid an uninitialized warning from gcc @@ -193,8 +193,8 @@ internal static void vp9_write_nmv_probs(VP9_COMMON* cm, int usehp, vpx_writer* write_mv_update(vp9_mv_joint_tree, mvc->joints, counts->joints, MV_JOINTS, w); for (i = 0; i < 2; ++i) { - nmv_component* comp = &mvc->comps[i]; - nmv_component_counts* comp_counts = &counts->comps[i]; + nmv_component* comp = addr(ref mvc->comps[i]); + nmv_component_counts* comp_counts = addr(ref counts->comps[i]); update_mv(w, comp_counts->sign, &comp->sign, MV_UPDATE_PROB); write_mv_update(vp9_mv_class_tree, comp->classes, comp_counts->classes, @@ -202,23 +202,23 @@ internal static void vp9_write_nmv_probs(VP9_COMMON* cm, int usehp, vpx_writer* write_mv_update(vp9_mv_class0_tree, comp->class0, comp_counts->class0, CLASS0_SIZE, w); for (j = 0; j < MV_OFFSET_BITS; ++j) - update_mv(w, (uint*)&(comp_counts->bits[j]), &comp->bits[j], MV_UPDATE_PROB); + update_mv(w, (uint*)addr(ref comp_counts->bits[j]), &comp->bits[j], MV_UPDATE_PROB); } for (i = 0; i < 2; ++i) { for (j = 0; j < CLASS0_SIZE; ++j) - write_mv_update(vp9_mv_fp_tree, (byte*)&(mvc->comps[i].class0_fp[j]), - (uint*)&(counts->comps[i].class0_fp[j]), MV_FP_SIZE, w); + write_mv_update(vp9_mv_fp_tree, (byte*)addr(ref mvc->comps[i].class0_fp[j]), + (uint*)addr(ref counts->comps[i].class0_fp[j]), MV_FP_SIZE, w); - write_mv_update(vp9_mv_fp_tree, mvc->comps[i].fp, counts->comps[i].fp, + write_mv_update(vp9_mv_fp_tree, addr(ref mvc->comps[i])->fp, addr(ref counts->comps[i])->fp, MV_FP_SIZE, w); } if (usehp != 0) { for (i = 0; i < 2; ++i) { - update_mv(w, counts->comps[i].class0_hp, &mvc->comps[i].class0_hp, + update_mv(w, addr(ref counts->comps[i])->class0_hp, addr(ref mvc->comps[i].class0_hp), MV_UPDATE_PROB); - update_mv(w, counts->comps[i].hp, &mvc->comps[i].hp, MV_UPDATE_PROB); + update_mv(w, addr(ref counts->comps[i])->hp, addr(ref mvc->comps[i].hp), MV_UPDATE_PROB); } } } @@ -231,10 +231,10 @@ internal static void vp9_encode_mv(VP9_COMP* cpi, vpx_writer* w, MV* mv, MV* @re vp9_write_token(w, vp9_mv_joint_tree, mvctx->joints, &mv_joint_encodings[j]); if ((mv_joint_vertical(j)) != 0) - encode_mv_component(w, diff.row, &mvctx->comps[0], usehp); + encode_mv_component(w, diff.row, addr(ref mvctx->comps[0]), usehp); if ((mv_joint_horizontal(j)) != 0) - encode_mv_component(w, diff.col, &mvctx->comps[1], usehp); + encode_mv_component(w, diff.col, addr(ref mvctx->comps[1]), usehp); // If auto_mv_step_size is enabled then keep track of the largest // motion vector component used. @@ -247,8 +247,8 @@ internal static void vp9_encode_mv(VP9_COMP* cpi, vpx_writer* w, MV* mv, MV* @re internal static void vp9_build_nmv_cost_table(int* mvjoint, int** mvcost, nmv_context* ctx, int usehp) { vp9_cost_tokens(mvjoint, ctx->joints, vp9_mv_joint_tree); - build_nmv_component_cost_table(mvcost[0], &ctx->comps[0], usehp); - build_nmv_component_cost_table(mvcost[1], &ctx->comps[1], usehp); + build_nmv_component_cost_table(mvcost[0], addr(ref ctx->comps[0]), usehp); + build_nmv_component_cost_table(mvcost[1], addr(ref ctx->comps[1]), usehp); } private static void inc_mvs(MODE_INFO* mi, MB_MODE_INFO_EXT* mbmi_ext, int_mv* mvs, nmv_context_counts* counts) @@ -256,7 +256,7 @@ private static void inc_mvs(MODE_INFO* mi, MB_MODE_INFO_EXT* mbmi_ext, int_mv* m int i; for (i = 0; i < 1 + has_second_ref(mi); ++i) { - MV* @ref = &mbmi_ext->ref_mvs[mi->ref_frame[i]][0].as_mv; + MV* @ref = addr(ref mbmi_ext->ref_mvs[mi->ref_frame[i]][0].as_mv); MV diff = new MV { row = (short)(mvs[i].as_mv.row-@ref->row), col = (short)(mvs[i].as_mv.col-@ref->col) }; vp9_inc_mv(&diff, counts); } @@ -277,7 +277,7 @@ internal static void vp9_update_mv_count(ThreadData* td) for (idx = 0; idx < 2; idx += num_4x4_w) { int i = idy * 2 + idx; if (mi->bmi[i].as_mode == NEWMV) - inc_mvs(mi, mbmi_ext, (int_mv*)&(mi->bmi[i].as_mv), &td->counts->mv); + inc_mvs(mi, mbmi_ext, (int_mv*)addr(ref mi->bmi[i].as_mv), &td->counts->mv); } } } else { diff --git a/src/Codecs/SIPSorcery.VP9/encoder/vp9_encoder.cs b/src/Codecs/SIPSorcery.VP9/encoder/vp9_encoder.cs index 49df76b4d3..7d4f163a37 100644 --- a/src/Codecs/SIPSorcery.VP9/encoder/vp9_encoder.cs +++ b/src/Codecs/SIPSorcery.VP9/encoder/vp9_encoder.cs @@ -230,7 +230,7 @@ internal static int get_ref_frame_buf_idx(VP9_COMP* cpi, int ref_frame) internal static RefCntBuffer* get_ref_cnt_buffer(VP9_COMMON* cm, int fb_idx) { - return fb_idx != INVALID_IDX ? &cm->buffer_pool->frame_bufs[fb_idx] : null; + return fb_idx != INVALID_IDX ? addr(ref cm->buffer_pool->frame_bufs[fb_idx]) : null; } internal static void get_ref_frame_bufs(VP9_COMP* cpi, RefCntBuffer** ref_frame_bufs) @@ -248,7 +248,7 @@ internal static void get_ref_frame_bufs(VP9_COMP* cpi, RefCntBuffer** ref_frame_ { VP9_COMMON* cm = &cpi->common; int buf_idx = get_ref_frame_buf_idx(cpi, ref_frame); - return buf_idx != INVALID_IDX ? &cm->buffer_pool->frame_bufs[buf_idx].buf + return buf_idx != INVALID_IDX ? addr(ref cm->buffer_pool->frame_bufs[buf_idx].buf) : null; } @@ -306,9 +306,9 @@ internal static int is_altref_enabled(VP9_COMP* cpi) internal static void set_ref_ptrs(VP9_COMMON* cm, MACROBLOCKD* xd, MV_REFERENCE_FRAME ref0, MV_REFERENCE_FRAME ref1) { xd->block_refs[0] = - &cm->frame_refs[ref0 >= LAST_FRAME ? ref0 - LAST_FRAME : 0]; + addr(ref cm->frame_refs[ref0 >= LAST_FRAME ? ref0 - LAST_FRAME : 0]); xd->block_refs[1] = - &cm->frame_refs[ref1 >= LAST_FRAME ? ref1 - LAST_FRAME : 0]; + addr(ref cm->frame_refs[ref1 >= LAST_FRAME ? ref1 - LAST_FRAME : 0]); } internal static int get_chessboard_index(int frame_index) @@ -360,7 +360,7 @@ internal static int log_tile_cols_from_picsize_level(uint32_t width, uint32_t he internal static void alloc_frame_mvs(VP9_COMMON* cm, int buffer_idx) { - RefCntBuffer* new_fb_ptr = &cm->buffer_pool->frame_bufs[buffer_idx]; + RefCntBuffer* new_fb_ptr = addr(ref cm->buffer_pool->frame_bufs[buffer_idx]); if (new_fb_ptr->mvs == null || new_fb_ptr->mi_rows < cm->mi_rows || new_fb_ptr->mi_cols < cm->mi_cols) { vpx_free(new_fb_ptr->mvs); @@ -1220,7 +1220,7 @@ private static void dealloc_compressor_data(VP9_COMP* cpi) vp9_free_pc_tree(&cpi->td); for (i = 0; i < cpi->svc.number_spatial_layers; ++i) { - LAYER_CONTEXT* lc = &cpi->svc.layer_context[i]; + LAYER_CONTEXT* lc = addr(ref cpi->svc.layer_context[i]); vpx_free(lc->rc_twopass_stats_in.buf); lc->rc_twopass_stats_in.buf = null; lc->rc_twopass_stats_in.sz = 0; @@ -1232,9 +1232,9 @@ private static void dealloc_compressor_data(VP9_COMP* cpi) } for (i = 0; i < MAX_LAG_BUFFERS; ++i) { - vpx_free_frame_buffer(&cpi->svc.scaled_frames[i]); + vpx_free_frame_buffer(addr(ref cpi->svc.scaled_frames[i])); } - memset(&cpi->svc.scaled_frames[0], 0, + memset(addr(ref cpi->svc.scaled_frames[0]), 0, MAX_LAG_BUFFERS * sizeof(YV12_BUFFER_CONFIG)); vpx_free_frame_buffer(&cpi->svc.scaled_temp); @@ -1260,13 +1260,13 @@ private static void save_coding_context(VP9_COMP* cpi) memcpy(cc->nmvjointcost, cpi->td.mb.nmvjointcost, (4 * sizeof(int))); } while (0 != 0); - memcpy((void*)&(cc->nmvcosts[0]), cpi->nmvcosts[0], + memcpy((void*)addr(ref cc->nmvcosts[0]), cpi->nmvcosts[0], MV_VALS * sizeof(int)); - memcpy((void*)&(cc->nmvcosts[1]), cpi->nmvcosts[1], + memcpy((void*)addr(ref cc->nmvcosts[1]), cpi->nmvcosts[1], MV_VALS * sizeof(int)); - memcpy((void*)&(cc->nmvcosts_hp[0]), cpi->nmvcosts_hp[0], + memcpy((void*)addr(ref cc->nmvcosts_hp[0]), cpi->nmvcosts_hp[0], MV_VALS * sizeof(int)); - memcpy((void*)&(cc->nmvcosts_hp[1]), cpi->nmvcosts_hp[1], + memcpy((void*)addr(ref cc->nmvcosts_hp[1]), cpi->nmvcosts_hp[1], MV_VALS * sizeof(int)); do { @@ -1301,11 +1301,11 @@ private static void restore_coding_context(VP9_COMP* cpi) memcpy(cpi->td.mb.nmvjointcost, cc->nmvjointcost, (4 * sizeof(int))); } while (0 != 0); - memcpy(cpi->nmvcosts[0], (void*)&(cc->nmvcosts[0]), MV_VALS * sizeof(int)); - memcpy(cpi->nmvcosts[1], (void*)&(cc->nmvcosts[1]), MV_VALS * sizeof(int)); - memcpy(cpi->nmvcosts_hp[0], (void*)&(cc->nmvcosts_hp[0]), + memcpy(cpi->nmvcosts[0], (void*)addr(ref cc->nmvcosts[0]), MV_VALS * sizeof(int)); + memcpy(cpi->nmvcosts[1], (void*)addr(ref cc->nmvcosts[1]), MV_VALS * sizeof(int)); + memcpy(cpi->nmvcosts_hp[0], (void*)addr(ref cc->nmvcosts_hp[0]), MV_VALS * sizeof(int)); - memcpy(cpi->nmvcosts_hp[1], (void*)&(cc->nmvcosts_hp[1]), + memcpy(cpi->nmvcosts_hp[1], (void*)addr(ref cc->nmvcosts_hp[1]), MV_VALS * sizeof(int)); do { @@ -1756,7 +1756,7 @@ internal static void vp9_change_config(VP9_COMP* cpi, VP9EncoderConfig* oxcf) if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) { for (int sl = 0; sl < cpi->svc.number_spatial_layers; ++sl) { int layer = ((sl) * ( cpi->svc.number_temporal_layers) + ( 0)); - LAYER_CONTEXT* lc = &cpi->svc.layer_context[layer]; + LAYER_CONTEXT* lc = addr(ref cpi->svc.layer_context[layer]); lc->sb_index = 0; lc->actual_num_seg1_blocks = 0; lc->actual_num_seg2_blocks = 0; @@ -2464,8 +2464,8 @@ private static void update_ref_frames(VP9_COMP* cpi) Debug.Assert(arf_idx < REF_FRAMES); ref_cnt_fb((RefCntBuffer*)&(pool->frame_bufs), &cm->ref_frame_map[arf_idx], cm->new_fb_idx); - memcpy((void*)&(cpi->interp_filter_selected[ALTREF_FRAME]), - (void*)&(cpi->interp_filter_selected[0]), + memcpy((void*)addr(ref cpi->interp_filter_selected[ALTREF_FRAME]), + (void*)addr(ref cpi->interp_filter_selected[0]), (4 * sizeof(int))); cpi->alt_fb_idx = arf_idx; @@ -2475,12 +2475,12 @@ private static void update_ref_frames(VP9_COMP* cpi) ref_cnt_fb((RefCntBuffer*)&(pool->frame_bufs), &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx); if ((cpi->rc.is_src_frame_alt_ref) == 0) - memcpy((void*)&(cpi->interp_filter_selected[GOLDEN_FRAME]), - (void*)&(cpi->interp_filter_selected[0]), + memcpy((void*)addr(ref cpi->interp_filter_selected[GOLDEN_FRAME]), + (void*)addr(ref cpi->interp_filter_selected[0]), (4 * sizeof(int))); else - memcpy((void*)&(cpi->interp_filter_selected[GOLDEN_FRAME]), - (void*)&(cpi->interp_filter_selected[ALTREF_FRAME]), + memcpy((void*)addr(ref cpi->interp_filter_selected[GOLDEN_FRAME]), + (void*)addr(ref cpi->interp_filter_selected[ALTREF_FRAME]), (4 * sizeof(int))); } } @@ -2489,8 +2489,8 @@ private static void update_ref_frames(VP9_COMP* cpi) ref_cnt_fb((RefCntBuffer*)&(pool->frame_bufs), &cm->ref_frame_map[cpi->lst_fb_idx], cm->new_fb_idx); if ((cpi->rc.is_src_frame_alt_ref) == 0) - memcpy((void*)&(cpi->interp_filter_selected[LAST_FRAME]), - (void*)&(cpi->interp_filter_selected[0]), + memcpy((void*)addr(ref cpi->interp_filter_selected[LAST_FRAME]), + (void*)addr(ref cpi->interp_filter_selected[0]), (4 * sizeof(int))); } @@ -2592,7 +2592,7 @@ internal static void vp9_scale_references(VP9_COMP* cpi) force_scaling = 1; } if (new_fb == INVALID_IDX) return; - new_fb_ptr = &pool->frame_bufs[new_fb]; + new_fb_ptr = addr(ref pool->frame_bufs[new_fb]); if ((force_scaling != 0) || new_fb_ptr->buf.y_crop_width != cm->width || new_fb_ptr->buf.y_crop_height != cm->height) { if ((vpx_realloc_frame_buffer(&new_fb_ptr->buf, cm->width, cm->height, @@ -2612,13 +2612,13 @@ internal static void vp9_scale_references(VP9_COMP* cpi) // Check for release of scaled reference. buf_idx = cpi->scaled_ref_idx[ref_frame - 1]; if (buf_idx != INVALID_IDX) { - buf = &pool->frame_bufs[buf_idx]; + buf = addr(ref pool->frame_bufs[buf_idx]); --buf->ref_count; cpi->scaled_ref_idx[ref_frame - 1] = INVALID_IDX; } } buf_idx = get_ref_frame_buf_idx(cpi, ref_frame); - buf = &pool->frame_bufs[buf_idx]; + buf = addr(ref pool->frame_bufs[buf_idx]); buf->buf.y_crop_width = @ref->y_crop_width; buf->buf.y_crop_height = @ref->y_crop_height; cpi->scaled_ref_idx[ref_frame - 1] = buf_idx; @@ -2645,7 +2645,7 @@ private static void release_scaled_references(VP9_COMP* cpi) for (i = LAST_FRAME; i <= ALTREF_FRAME; ++i) { int idx = cpi->scaled_ref_idx[i - 1]; if (idx != INVALID_IDX) { - RefCntBuffer* buf = &cm->buffer_pool->frame_bufs[idx]; + RefCntBuffer* buf = addr(ref cm->buffer_pool->frame_bufs[idx]); YV12_BUFFER_CONFIG* @ref = get_ref_frame_buffer(cpi, (sbyte)i); if ((refresh[i - 1] != 0) || (buf->buf.y_crop_width == @ref->y_crop_width && buf->buf.y_crop_height == @ref->y_crop_height)) { @@ -2658,7 +2658,7 @@ private static void release_scaled_references(VP9_COMP* cpi) for (i = 0; i < REFS_PER_FRAME; ++i) { int idx = cpi->scaled_ref_idx[i]; if (idx != INVALID_IDX) { - RefCntBuffer* buf = &cm->buffer_pool->frame_bufs[idx]; + RefCntBuffer* buf = addr(ref cm->buffer_pool->frame_bufs[idx]); --buf->ref_count; cpi->scaled_ref_idx[i] = INVALID_IDX; } @@ -2685,7 +2685,7 @@ private static void full_to_model_counts(vp9_coeff_count_model* model_count, vp9 for (j = 0; j < REF_TYPES; ++j) for (k = 0; k < COEF_BANDS; ++k) for (l = 0; l < ((k) == 0 ? 3 : COEFF_CONTEXTS); ++l) - full_to_model_count((uint*)&model_count[i][j][k][l], (uint*)&full_count[i][j][k][l]); + full_to_model_count((uint*)addr(ref model_count[i][j][k][l]), (uint*)addr(ref full_count[i][j][k][l])); } private static void set_mv_search_params(VP9_COMP* cpi) @@ -2804,13 +2804,13 @@ private static void set_frame_size(VP9_COMP* cpi) int has_valid_ref_frame = 0; for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) { - RefBuffer* ref_buf = &cm->frame_refs[ref_frame - 1]; + RefBuffer* ref_buf = addr(ref cm->frame_refs[ref_frame - 1]); int buf_idx = get_ref_frame_buf_idx(cpi, ref_frame); ref_buf->idx = buf_idx; if (buf_idx != INVALID_IDX) { - YV12_BUFFER_CONFIG* buf = &cm->buffer_pool->frame_bufs[buf_idx].buf; + YV12_BUFFER_CONFIG* buf = addr(ref cm->buffer_pool->frame_bufs[buf_idx].buf); ref_buf->buf = buf; vp9_setup_scale_factors_for_frame(&ref_buf->sf, buf->y_crop_width, buf->y_crop_height, cm->width, @@ -3619,8 +3619,8 @@ private static void encode_frame_to_data_rate(VP9_COMP* cpi, size_t* size, uint8 if ((cm->show_existing_frame) == 0) { for (t = TX_4X4; t <= TX_32X32; ++t) { - full_to_model_counts((A2>>>*)&(cpi->td.counts->coef[t]), - (A2>>>*)&(cpi->td.rd_counts.coef_counts[t])); + full_to_model_counts((A2>>>*)addr(ref cpi->td.counts->coef[t]), + (A2>>>*)addr(ref cpi->td.rd_counts.coef_counts[t])); } if (((cm->error_resilient_mode) == 0) && ((cm->frame_parallel_decoding_mode) == 0)) { @@ -4278,7 +4278,7 @@ internal static int vp9_get_compressed_data(VP9_COMP* cpi, uint* frame_flags, si cm->new_fb_idx = get_free_fb(cm); if (cm->new_fb_idx == INVALID_IDX) return -1; - cm->cur_frame = &pool->frame_bufs[cm->new_fb_idx]; + cm->cur_frame = addr(ref pool->frame_bufs[cm->new_fb_idx]); // If the frame buffer for current frame is the same as previous frame, MV in // the base layer shouldn't be used as it'll cause data race. if (cpi->svc.spatial_layer_id > 0 && cm->cur_frame == cm->prev_frame) { diff --git a/src/Codecs/SIPSorcery.VP9/encoder/vp9_mcomp.cs b/src/Codecs/SIPSorcery.VP9/encoder/vp9_mcomp.cs index 07d47172e7..74c43f52f8 100644 --- a/src/Codecs/SIPSorcery.VP9/encoder/vp9_mcomp.cs +++ b/src/Codecs/SIPSorcery.VP9/encoder/vp9_mcomp.cs @@ -793,8 +793,8 @@ private static int is_mv_in(MvLimits* mv_limits, MV* mv) private static void calc_int_cost_list(MACROBLOCK* x, MV* ref_mv, int sadpb, vp9_variance_fn_ptr_t* fn_ptr, MV* best_mv, int* cost_list) { /* static vp9_pattern_search_sad_neighbors hoisted to calc_int_cost_list_neighbors */ - buf_2d* what = &x->plane[0].src; - buf_2d* in_what = &x->e_mbd.plane[0].pre[0]; + buf_2d* what = addr(ref x->plane[0].src); + buf_2d* in_what = addr(ref x->e_mbd.plane[0].pre[0]); MV fcenter_mv = new MV { row = (short)(ref_mv->row>>3), col = (short)(ref_mv->col>>3) }; int br = best_mv->row; int bc = best_mv->col; @@ -841,8 +841,8 @@ private static int vp9_pattern_search(MACROBLOCK* x, MV* ref_mv, int search_para MACROBLOCKD* xd = &x->e_mbd; /* static vp9_pattern_search_sad_search_param_to_steps hoisted to vp9_pattern_search_search_param_to_steps */ int i; int s; int t; - buf_2d* what = &x->plane[0].src; - buf_2d* in_what = &xd->plane[0].pre[0]; + buf_2d* what = addr(ref x->plane[0].src); + buf_2d* in_what = addr(ref xd->plane[0].pre[0]); int br; int bc; int bestsad = INT_MAX; int thissad; @@ -996,8 +996,8 @@ private static int vp9_pattern_search_sad(MACROBLOCK* x, MV* ref_mv, int search_ MACROBLOCKD* xd = &x->e_mbd; /* static vp9_pattern_search_sad_search_param_to_steps hoisted to vp9_pattern_search_sad_search_param_to_steps */ int i; int s; int t; - buf_2d* what = &x->plane[0].src; - buf_2d* in_what = &xd->plane[0].pre[0]; + buf_2d* what = addr(ref x->plane[0].src); + buf_2d* in_what = addr(ref xd->plane[0].pre[0]); int br; int bc; int bestsad = INT_MAX; int thissad; @@ -1247,8 +1247,8 @@ private static int vp9_pattern_search_sad(MACROBLOCK* x, MV* ref_mv, int search_ internal static int vp9_get_mvpred_var(MACROBLOCK* x, MV* best_mv, MV* center_mv, vp9_variance_fn_ptr_t* vfp, int use_mvcost) { MACROBLOCKD* xd = &x->e_mbd; - buf_2d* what = &x->plane[0].src; - buf_2d* in_what = &xd->plane[0].pre[0]; + buf_2d* what = addr(ref x->plane[0].src); + buf_2d* in_what = addr(ref xd->plane[0].pre[0]); MV mv = new MV { row = (short)(best_mv->row*8), col = (short)(best_mv->col*8) }; uint32_t unused; return (int)(vfp->vf(what->buf, what->stride, get_buf_from_mv(in_what, best_mv), @@ -1261,8 +1261,8 @@ internal static int vp9_get_mvpred_var(MACROBLOCK* x, MV* best_mv, MV* center_mv internal static int vp9_get_mvpred_av_var(MACROBLOCK* x, MV* best_mv, MV* center_mv, uint8_t* second_pred, vp9_variance_fn_ptr_t* vfp, int use_mvcost) { MACROBLOCKD* xd = &x->e_mbd; - buf_2d* what = &x->plane[0].src; - buf_2d* in_what = &xd->plane[0].pre[0]; + buf_2d* what = addr(ref x->plane[0].src); + buf_2d* in_what = addr(ref xd->plane[0].pre[0]); MV mv = new MV { row = (short)(best_mv->row*8), col = (short)(best_mv->col*8) }; uint unused; @@ -1335,8 +1335,8 @@ private static int exhaustive_mesh_search(MACROBLOCK* x, MV* ref_mv, MV* best_mv uint* sads = stackalloc uint[4]; uint8_t** addrs = stackalloc uint8_t*[4]; MACROBLOCKD* xd = &x->e_mbd; - buf_2d* what = &x->plane[0].src; - buf_2d* in_what = &xd->plane[0].pre[0]; + buf_2d* what = addr(ref x->plane[0].src); + buf_2d* in_what = addr(ref xd->plane[0].pre[0]); MV fcenter_mv = new MV { row = center_mv->row, col = center_mv->col }; uint best_sad = INT_MAX; int r; int c; int i; @@ -1443,8 +1443,8 @@ internal static int vp9_diamond_search_sad_c(MACROBLOCK* x, search_site_config* // 1 = (MAX_FIRST_STEP/2) pel, // 2 = (MAX_FIRST_STEP/4) pel... // const search_site *ss = &cfg->ss[search_param * cfg->searches_per_step]; - MV* ss_mv = &cfg->ss_mv[search_param * cfg->searches_per_step]; - intptr_t* ss_os = &cfg->ss_os[search_param * cfg->searches_per_step]; + MV* ss_mv = addr(ref cfg->ss_mv[search_param * cfg->searches_per_step]); + intptr_t* ss_os = addr(ref cfg->ss_os[search_param * cfg->searches_per_step]); int tot_steps = cfg->total_steps - search_param; MV fcenter_mv = new MV { row = (short)(center_mv->row>>3), col = (short)(center_mv->col>>3) }; @@ -1613,7 +1613,7 @@ internal static uint vp9_int_pro_motion_estimation(VP9_COMP* cpi, MACROBLOCK* x, int src_stride = x->plane[0].src.stride; int ref_stride = xd->plane[0].pre[0].stride; uint8_t* ref_buf; uint8_t* src_buf; - MV* tmp_mv = &xd->mi[0]->mv[0].as_mv; + MV* tmp_mv = addr(ref xd->mi[0]->mv[0].as_mv); uint best_sad; uint tmp_sad; uint* this_sad = stackalloc uint[4]; MV this_mv; int norm_factor = 3 + (bw >> 5); @@ -1813,7 +1813,7 @@ private static int full_pixel_diamond(VP9_COMP* cpi, MACROBLOCK* x, BLOCK_SIZE b // If we are skipping rows when we perform the motion search, we need to // check the quality of skipping. If it's bad, then we run search with // skip row features off. - uint8_t* best_address = get_buf_from_mv(&xd->plane[0].pre[0], dst_mv); + uint8_t* best_address = get_buf_from_mv(addr(ref xd->plane[0].pre[0]), dst_mv); int sad = (int)(fn_ptr->sdf(src_buf, src_buf_stride, best_address, pred_buf_stride)); int skip_sad = (int)(fn_ptr->sdsf(src_buf, src_buf_stride, best_address, pred_buf_stride)); // We will keep the result of skipping rows if it's good enough. @@ -1894,8 +1894,8 @@ internal static int vp9_refining_search_sad(MACROBLOCK* x, MV* ref_mv, int error uint8_t** positions = stackalloc uint8_t*[4]; MACROBLOCKD* xd = &x->e_mbd; MV* vp9_pattern_search_sad_neighbors = stackalloc MV[4]; vp9_pattern_search_sad_neighbors[0].row = -1; vp9_pattern_search_sad_neighbors[0].col = 0; vp9_pattern_search_sad_neighbors[1].row = 0; vp9_pattern_search_sad_neighbors[1].col = -1; vp9_pattern_search_sad_neighbors[2].row = 0; vp9_pattern_search_sad_neighbors[2].col = 1; vp9_pattern_search_sad_neighbors[3].row = 1; vp9_pattern_search_sad_neighbors[3].col = 0; - buf_2d* what = &x->plane[0].src; - buf_2d* in_what = &xd->plane[0].pre[0]; + buf_2d* what = addr(ref x->plane[0].src); + buf_2d* in_what = addr(ref xd->plane[0].pre[0]); MV fcenter_mv = new MV { row = (short)(center_mv->row>>3), col = (short)(center_mv->col>>3) }; uint8_t* best_address = get_buf_from_mv(in_what, ref_mv); uint best_sad = (uint)(sad_fn_ptr->sdf(what->buf, what->stride, best_address, in_what->stride) + @@ -1962,8 +1962,8 @@ internal static int vp9_refining_search_8p_c(MACROBLOCK* x, MV* ref_mv, int erro { MV* vp9_pattern_search_sad_neighbors = stackalloc MV[8]; vp9_pattern_search_sad_neighbors[0].row = -1; vp9_pattern_search_sad_neighbors[0].col = 0; vp9_pattern_search_sad_neighbors[1].row = 0; vp9_pattern_search_sad_neighbors[1].col = -1; vp9_pattern_search_sad_neighbors[2].row = 0; vp9_pattern_search_sad_neighbors[2].col = 1; vp9_pattern_search_sad_neighbors[3].row = 1; vp9_pattern_search_sad_neighbors[3].col = 0; vp9_pattern_search_sad_neighbors[4].row = -1; vp9_pattern_search_sad_neighbors[4].col = -1; vp9_pattern_search_sad_neighbors[5].row = 1; vp9_pattern_search_sad_neighbors[5].col = -1; vp9_pattern_search_sad_neighbors[6].row = -1; vp9_pattern_search_sad_neighbors[6].col = 1; vp9_pattern_search_sad_neighbors[7].row = 1; vp9_pattern_search_sad_neighbors[7].col = 1; MACROBLOCKD* xd = &x->e_mbd; - buf_2d* what = &x->plane[0].src; - buf_2d* in_what = &xd->plane[0].pre[0]; + buf_2d* what = addr(ref x->plane[0].src); + buf_2d* in_what = addr(ref xd->plane[0].pre[0]); MV fcenter_mv = new MV { row = (short)(center_mv->row>>3), col = (short)(center_mv->col>>3) }; uint best_sad = INT_MAX; int i; int j; @@ -2007,7 +2007,7 @@ internal static int vp9_full_pixel_search(VP9_COMP* cpi, MACROBLOCK* x, BLOCK_SI { SPEED_FEATURES* sf = &cpi->sf; SEARCH_METHODS method = (SEARCH_METHODS)search_method; - vp9_variance_fn_ptr_t* fn_ptr = &cpi->fn_ptr[bsize]; + vp9_variance_fn_ptr_t* fn_ptr = addr(ref cpi->fn_ptr[bsize]); int var = 0; int run_exhaustive_search = 0; diff --git a/src/Codecs/SIPSorcery.VP9/encoder/vp9_multi_thread.cs b/src/Codecs/SIPSorcery.VP9/encoder/vp9_multi_thread.cs index ff3f2824c8..7aab3d480b 100644 --- a/src/Codecs/SIPSorcery.VP9/encoder/vp9_multi_thread.cs +++ b/src/Codecs/SIPSorcery.VP9/encoder/vp9_multi_thread.cs @@ -43,7 +43,7 @@ internal static unsafe partial class vp9_multi_thread void* next = null; JobNode* job_info = null; - row_mt_info = (RowMTInfo *)(&multi_thread_ctxt->row_mt_info[tile_id]); + row_mt_info = (RowMTInfo *)(addr(ref multi_thread_ctxt->row_mt_info[tile_id])); job_queue_hdl = (JobQueueHandle *)&row_mt_info->job_queue_hdl; // lock the mutex for queue access @@ -194,7 +194,7 @@ internal static int vp9_get_job_queue_status(MultiThreadHandle* multi_thread_ctx JobQueueHandle* job_queue_hndl; int num_jobs_remaining; - row_mt_info = &multi_thread_ctxt->row_mt_info[cur_tile_id]; + row_mt_info = addr(ref multi_thread_ctxt->row_mt_info[cur_tile_id]); job_queue_hndl = &row_mt_info->job_queue_hdl; num_jobs_remaining = @@ -230,7 +230,7 @@ internal static void vp9_prepare_job_queue(VP9_COMP* cpi, JOB_TYPE job_type) // Job queue preparation for (tile_col = 0; tile_col < tile_cols; tile_col++) { - RowMTInfo* tile_ctxt = &multi_thread_ctxt->row_mt_info[tile_col]; + RowMTInfo* tile_ctxt = addr(ref multi_thread_ctxt->row_mt_info[tile_col]); JobQueue* job_queue_curr; JobQueue* job_queue_temp; int tile_row = 0; diff --git a/src/Codecs/SIPSorcery.VP9/encoder/vp9_pickmode.cs b/src/Codecs/SIPSorcery.VP9/encoder/vp9_pickmode.cs index ca9e2cd55b..82463f0c9e 100644 --- a/src/Codecs/SIPSorcery.VP9/encoder/vp9_pickmode.cs +++ b/src/Codecs/SIPSorcery.VP9/encoder/vp9_pickmode.cs @@ -286,7 +286,7 @@ private static int combined_motion_search(VP9_COMP* cpi, MACROBLOCK* x, BLOCK_SI } cpi->find_fractional_mv_step( x, &tmp_mv->as_mv, &ref_mv, cpi->common.allow_high_precision_mv, - x->errorperbit, &cpi->fn_ptr[bsize], subpel_force_stop, + x->errorperbit, addr(ref cpi->fn_ptr[bsize]), subpel_force_stop, cpi->sf.mv.subpel_search_level, cond_cost_list(cpi, cost_list), x->nmvjointcost, x->mvcost, &dis, &x->pred_sse[@ref], null, 0, 0, cpi->sf.use_accurate_subpel_search); @@ -391,8 +391,8 @@ private static TX_SIZE calculate_tx_size(VP9_COMP* cpi, BLOCK_SIZE bsize, MACROB private static void compute_intra_yprediction(PREDICTION_MODE mode, BLOCK_SIZE bsize, MACROBLOCK* x, MACROBLOCKD* xd) { - macroblockd_plane* pd = &xd->plane[0]; - macroblock_plane* p = &x->plane[0]; + macroblockd_plane* pd = addr(ref xd->plane[0]); + macroblock_plane* p = addr(ref x->plane[0]); uint8_t* src_buf_base = p->src.buf; uint8_t* dst_buf_base = pd->dst.buf; int src_stride = p->src.stride; @@ -438,8 +438,8 @@ private static void model_rd_for_sb_y_large(VP9_COMP* cpi, BLOCK_SIZE bsize, MAC uint sse; int rate = default; int64_t dist = default; - macroblock_plane* p = &x->plane[0]; - macroblockd_plane* pd = &xd->plane[0]; + macroblock_plane* p = addr(ref x->plane[0]); + macroblockd_plane* pd = addr(ref xd->plane[0]); uint32_t dc_quant = (uint)(pd->dequant[0]); uint32_t ac_quant = (uint)(pd->dequant[1]); int64_t dc_thr = dc_quant * dc_quant >> 6; @@ -547,8 +547,8 @@ private static void model_rd_for_sb_y_large(VP9_COMP* cpi, BLOCK_SIZE bsize, MAC // Transform skipping test in UV planes. for (i = 1; i <= 2; i++) { - macroblock_plane* p_uv = &x->plane[i]; - macroblockd_plane* pd_uv = &xd->plane[i]; + macroblock_plane* p_uv = addr(ref x->plane[i]); + macroblockd_plane* pd_uv = addr(ref xd->plane[i]); TX_SIZE uv_tx_size = get_uv_tx_size(xd->mi[0], pd_uv); BLOCK_SIZE unit_size = txsize_to_bsize[uv_tx_size]; BLOCK_SIZE uv_bsize = get_plane_block_size(bsize, pd_uv); @@ -609,8 +609,8 @@ private static void model_rd_for_sb_y(VP9_COMP* cpi, BLOCK_SIZE bsize, MACROBLOC uint sse; int rate = default; int64_t dist = default; - macroblock_plane* p = &x->plane[0]; - macroblockd_plane* pd = &xd->plane[0]; + macroblock_plane* p = addr(ref x->plane[0]); + macroblockd_plane* pd = addr(ref xd->plane[0]); int64_t dc_thr = p->quant_thred[0] >> 6; int64_t ac_thr = p->quant_thred[1] >> 6; uint32_t dc_quant = (uint)(pd->dequant[0]); @@ -674,8 +674,8 @@ private static void model_rd_for_sb_y(VP9_COMP* cpi, BLOCK_SIZE bsize, MACROBLOC private static void block_yrd(VP9_COMP* cpi, MACROBLOCK* x, RD_COST* this_rdc, int* skippable, int64_t* sse, BLOCK_SIZE bsize, TX_SIZE tx_size, int rd_computed, int is_intra) { MACROBLOCKD* xd = &x->e_mbd; - macroblockd_plane* pd = &xd->plane[0]; - macroblock_plane* p = &x->plane[0]; + macroblockd_plane* pd = addr(ref xd->plane[0]); + macroblock_plane* p = addr(ref x->plane[0]); int num_4x4_w = num_4x4_blocks_wide_lookup[bsize]; int num_4x4_h = num_4x4_blocks_high_lookup[bsize]; int step = 1 << (tx_size << 1); @@ -801,8 +801,8 @@ private static void model_rd_for_sb_uv(VP9_COMP* cpi, BLOCK_SIZE plane_bsize, MA this_rdc->dist = 0; for (i = start_plane; i <= stop_plane; ++i) { - macroblock_plane* p = &x->plane[i]; - macroblockd_plane* pd = &xd->plane[i]; + macroblock_plane* p = addr(ref x->plane[i]); + macroblockd_plane* pd = addr(ref xd->plane[i]); uint32_t dc_quant = (uint)(pd->dequant[0]); uint32_t ac_quant = (uint)(pd->dequant[1]); BLOCK_SIZE bs = plane_bsize; @@ -854,7 +854,7 @@ private static void encode_breakout_test(VP9_COMP* cpi, MACROBLOCK* x, BLOCK_SIZ { MACROBLOCKD* xd = &x->e_mbd; MODE_INFO* mi = xd->mi[0]; - BLOCK_SIZE uv_size = get_plane_block_size(bsize, &xd->plane[1]); + BLOCK_SIZE uv_size = get_plane_block_size(bsize, addr(ref xd->plane[1])); uint var = var_y; uint sse = sse_y; // Skipping threshold for ac. uint thresh_ac; @@ -945,8 +945,8 @@ private static void estimate_block_intra(int plane, int block, int row, int col, VP9_COMP* cpi = args->cpi; MACROBLOCK* x = args->x; MACROBLOCKD* xd = &x->e_mbd; - macroblock_plane* p = &x->plane[plane]; - macroblockd_plane* pd = &xd->plane[plane]; + macroblock_plane* p = addr(ref x->plane[plane]); + macroblockd_plane* pd = addr(ref xd->plane[plane]); BLOCK_SIZE bsize_tx = txsize_to_bsize[tx_size]; uint8_t* src_buf_base = p->src.buf; uint8_t* dst_buf_base = pd->dst.buf; @@ -1029,7 +1029,7 @@ private static void update_thresh_freq_fact_row_mt(VP9_COMP* cpi, TileDataEnc* t private static void update_thresh_freq_fact(VP9_COMP* cpi, TileDataEnc* tile_data, uint source_variance, BLOCK_SIZE bsize, MV_REFERENCE_FRAME ref_frame, THR_MODES best_mode_idx, PREDICTION_MODE mode) { THR_MODES thr_mode_idx = mode_idx[ref_frame][mode_offset(mode)]; - int* freq_fact = &tile_data->thresh_freq_fact[bsize][thr_mode_idx]; + int* freq_fact = addr(ref tile_data->thresh_freq_fact[bsize][thr_mode_idx]); if (thr_mode_idx == best_mode_idx) *freq_fact -= (*freq_fact >> 4); else if (((cpi->sf.limit_newmv_early_exit) != 0) && mode == NEWMV && @@ -1056,7 +1056,7 @@ internal static void vp9_pick_intra_mode(VP9_COMP* cpi, MACROBLOCK* x, RD_COST* MODE_INFO* left_mi = xd->left_mi; PREDICTION_MODE A = vp9_above_block_mode(mic, above_mi, 0); PREDICTION_MODE L = vp9_left_block_mode(mic, left_mi, 0); - bmode_costs = (int*)&(cpi->y_mode_costs[A][L]); + bmode_costs = (int*)addr(ref cpi->y_mode_costs[A][L]); _ = ctx; vp9_rd_cost_reset(&best_rdc); @@ -1189,8 +1189,8 @@ private static void find_predictors(VP9_COMP* cpi, MACROBLOCK* x, MV_REFERENCE_F frame_mv[ZEROMV][ref_frame].as_int = 0; // this needs various further optimizations. to be continued.. if (((cpi->ref_frame_flags & ref_frame_to_flag(ref_frame)) != 0) && (yv12 != null)) { - int_mv* candidates = (int_mv*)&(x->mbmi_ext->ref_mvs[ref_frame]); - scale_factors* sf = &cm->frame_refs[ref_frame - 1].sf; + int_mv* candidates = (int_mv*)addr(ref x->mbmi_ext->ref_mvs[ref_frame]); + scale_factors* sf = addr(ref cm->frame_refs[ref_frame - 1].sf); vp9_setup_pred_block(xd, (buf_2d*)&yv12_mb[ref_frame], yv12, mi_row, mi_col, sf, sf); if (((cm->use_prev_frame_mvs) != 0) || (comp_pred_allowed != 0)) { vp9_find_mv_refs(cm, xd, xd->mi[0], ref_frame, candidates, mi_row, mi_col, @@ -1198,12 +1198,12 @@ private static void find_predictors(VP9_COMP* cpi, MACROBLOCK* x, MV_REFERENCE_F } else { const_motion[ref_frame] = mv_refs_rt(cpi, cm, x, xd, tile_info, xd->mi[0], ref_frame, - candidates, &frame_mv[NEWMV][ref_frame], mi_row, mi_col, + candidates, addr(ref frame_mv[NEWMV][ref_frame]), mi_row, mi_col, (int)((((cpi->svc.use_base_mv) != 0) && ((cpi->svc.spatial_layer_id) != 0)) ? 1 : 0)); } vp9_find_best_ref_mvs(xd, cm->allow_high_precision_mv, candidates, - &frame_mv[NEARESTMV][ref_frame], - &frame_mv[NEARMV][ref_frame]); + addr(ref frame_mv[NEARESTMV][ref_frame]), + addr(ref frame_mv[NEARMV][ref_frame])); // Early exit for golden frame if force_skip_low_temp_var is set. if (((vp9_is_scaled(sf)) == 0) && bsize >= BLOCK_8X8 && !((force_skip_low_temp_var != 0) && ref_frame == GOLDEN_FRAME)) { @@ -1322,7 +1322,7 @@ private static void search_filter_ref(VP9_COMP* cpi, MACROBLOCK* x, RD_COST* thi { MACROBLOCKD* xd = &x->e_mbd; MODE_INFO* mi = xd->mi[0]; - macroblockd_plane* pd = &xd->plane[0]; + macroblockd_plane* pd = addr(ref xd->plane[0]); int bw = num_4x4_blocks_wide_lookup[bsize] << 2; int* pf_rate = stackalloc int[3]; memset(pf_rate, 0, 3 * sizeof(int)); @@ -1417,23 +1417,23 @@ private static int search_new_mv(VP9_COMP* cpi, MACROBLOCK* x, A4* frame tmp_sad = (int)(vp9_int_pro_motion_estimation( cpi, x, bsize, mi_row, mi_col, - &x->mbmi_ext->ref_mvs[ref_frame][0].as_mv)); + addr(ref x->mbmi_ext->ref_mvs[ref_frame][0].as_mv))); if (tmp_sad > x->pred_mv_sad[LAST_FRAME]) return -1; if (tmp_sad + (num_pels_log2_lookup[bsize] << 4) > best_pred_sad) return -1; frame_mv[NEWMV][ref_frame].as_int = mi->mv[0].as_int; - *rate_mv = vp9_mv_bit_cost(&frame_mv[NEWMV][ref_frame].as_mv, - &x->mbmi_ext->ref_mvs[ref_frame][0].as_mv, + *rate_mv = vp9_mv_bit_cost(addr(ref frame_mv[NEWMV][ref_frame].as_mv), + addr(ref x->mbmi_ext->ref_mvs[ref_frame][0].as_mv), x->nmvjointcost, x->mvcost, MV_COST_WEIGHT); frame_mv[NEWMV][ref_frame].as_mv.row >>= 3; frame_mv[NEWMV][ref_frame].as_mv.col >>= 3; cpi->find_fractional_mv_step( - x, &frame_mv[NEWMV][ref_frame].as_mv, - &x->mbmi_ext->ref_mvs[ref_frame][0].as_mv, + x, addr(ref frame_mv[NEWMV][ref_frame].as_mv), + addr(ref x->mbmi_ext->ref_mvs[ref_frame][0].as_mv), cpi->common.allow_high_precision_mv, x->errorperbit, - &cpi->fn_ptr[bsize], cpi->sf.mv.subpel_force_stop, + addr(ref cpi->fn_ptr[bsize]), cpi->sf.mv.subpel_force_stop, cpi->sf.mv.subpel_search_level, cond_cost_list(cpi, cost_list), x->nmvjointcost, x->mvcost, &dis, &x->pred_sse[ref_frame], null, 0, 0, cpi->sf.use_accurate_subpel_search); @@ -1470,22 +1470,22 @@ private static int search_new_mv(VP9_COMP* cpi, MACROBLOCK* x, A4* frame frame_mv[NEWMV][ref_frame].as_mv.col == 0) return -1; if ((combined_motion_search(cpi, x, bsize, mi_row, mi_col, - &frame_mv[NEWMV][ref_frame], rate_mv, + addr(ref frame_mv[NEWMV][ref_frame]), rate_mv, best_rdc->rdcost, 1)) == 0) { return -1; } } else if ((combined_motion_search(cpi, x, bsize, mi_row, mi_col, - &frame_mv[NEWMV][ref_frame], rate_mv, + addr(ref frame_mv[NEWMV][ref_frame]), rate_mv, best_rdc->rdcost, 0)) == 0) { return -1; } } else if ((combined_motion_search(cpi, x, bsize, mi_row, mi_col, - &frame_mv[NEWMV][ref_frame], rate_mv, + addr(ref frame_mv[NEWMV][ref_frame]), rate_mv, best_rdc->rdcost, 0)) == 0) { return -1; } } else if ((combined_motion_search(cpi, x, bsize, mi_row, mi_col, - &frame_mv[NEWMV][ref_frame], rate_mv, + addr(ref frame_mv[NEWMV][ref_frame]), rate_mv, best_rdc->rdcost, 0)) == 0) { return -1; } @@ -1513,7 +1513,7 @@ internal static void vp9_pick_inter_mode(VP9_COMP* cpi, MACROBLOCK* x, TileDataE SVC* svc = &cpi->svc; MACROBLOCKD* xd = &x->e_mbd; MODE_INFO* mi = xd->mi[0]; - macroblockd_plane* pd = &xd->plane[0]; + macroblockd_plane* pd = addr(ref xd->plane[0]); BEST_PICKMODE best_pickmode; @@ -1528,12 +1528,12 @@ internal static void vp9_pick_inter_mode(VP9_COMP* cpi, MACROBLOCK* x, TileDataE uint sse_y = UINT_MAX; int intra_cost_penalty = vp9_get_intra_cost_penalty(cpi, bsize, cm->base_qindex, cm->y_dc_delta_q); int64_t inter_mode_thresh = ROUND_POWER_OF_TWO(((int64_t)( intra_cost_penalty)) * (x->rdmult), VP9_PROB_COST_SHIFT) + (( 0) << ( x->rddiv)); - int* rd_threshes = (int*)&(cpi->rd.threshes[mi->segment_id][bsize]); + int* rd_threshes = (int*)addr(ref cpi->rd.threshes[mi->segment_id][bsize]); int sb_row = mi_row >> MI_BLOCK_SIZE_LOG2; int thresh_freq_fact_idx = (sb_row * BLOCK_SIZES + bsize) * MAX_MODES; int* rd_thresh_freq_fact = ((cpi->sf.adaptive_rd_thresh_row_mt) != 0) ? &(tile_data->row_base_thresh_freq_fact[thresh_freq_fact_idx]) - : (int*)&(tile_data->thresh_freq_fact[bsize]); + : (int*)addr(ref tile_data->thresh_freq_fact[bsize]); INTERP_FILTER filter_ref; int pred_filter_search = ((cm->interp_filter == SWITCHABLE) ? 1 : 0); int* const_motion = stackalloc int[MAX_REF_FRAMES]; memset(const_motion, 0, 4 * sizeof(int)); @@ -1593,7 +1593,7 @@ internal static void vp9_pick_inter_mode(VP9_COMP* cpi, MACROBLOCK* x, TileDataE if (((cpi->use_svc) != 0) && svc->spatial_layer_id > 0) { int layer = ((svc->spatial_layer_id - 1) * ( svc->number_temporal_layers) + ( svc->temporal_layer_id)); - LAYER_CONTEXT* lc = &svc->layer_context[layer]; + LAYER_CONTEXT* lc = addr(ref svc->layer_context[layer]); if (lc->scaling_factor_num == lc->scaling_factor_den) no_scaling = 1; } if (svc->spatial_layer_id > 0 && @@ -1613,8 +1613,8 @@ internal static void vp9_pick_inter_mode(VP9_COMP* cpi, MACROBLOCK* x, TileDataE if (((cpi->use_svc) == 0) || (((svc->use_gf_temporal_ref_current_layer) != 0) && ((svc->layer_context[svc->temporal_layer_id].is_key_frame) == 0))) { - scale_factors* sf_last = &cm->frame_refs[LAST_FRAME - 1].sf; - scale_factors* sf_golden = &cm->frame_refs[GOLDEN_FRAME - 1].sf; + scale_factors* sf_last = addr(ref cm->frame_refs[LAST_FRAME - 1].sf); + scale_factors* sf_golden = addr(ref cm->frame_refs[GOLDEN_FRAME - 1].sf); gf_temporal_ref = 1; // For temporal long term prediction, check that the golden reference // is same scale as last reference, otherwise disable. @@ -1630,7 +1630,7 @@ internal static void vp9_pick_inter_mode(VP9_COMP* cpi, MACROBLOCK* x, TileDataE } init_ref_frame_cost(cm, xd, ref_frame_cost); - memset(&mode_checked[0][0], 0, MB_MODE_COUNT * MAX_REF_FRAMES); + memset(addr(ref mode_checked[0][0]), 0, MB_MODE_COUNT * MAX_REF_FRAMES); if (reuse_inter_pred != 0) { int i; @@ -1679,7 +1679,7 @@ internal static void vp9_pick_inter_mode(VP9_COMP* cpi, MACROBLOCK* x, TileDataE if (((sf->short_circuit_flat_blocks) != 0) || ((sf->limit_newmv_early_exit) != 0)) { x->source_variance = - vp9_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize); + vp9_get_sby_perpixel_variance(cpi, addr(ref x->plane[0].src), bsize); if (cpi->oxcf.content == VP9E_CONTENT_SCREEN && cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && mi->segment_id > 0 && @@ -1718,14 +1718,14 @@ internal static void vp9_pick_inter_mode(VP9_COMP* cpi, MACROBLOCK* x, TileDataE if (((cpi->use_svc) != 0) && ((svc->force_zero_mode_spatial_ref) != 0) && svc->spatial_layer_id > 0 && (gf_temporal_ref == 0)) { if ((cpi->ref_frame_flags & VP9_LAST_FLAG) != 0) { - scale_factors* ref_sf = &cm->frame_refs[LAST_FRAME - 1].sf; + scale_factors* ref_sf = addr(ref cm->frame_refs[LAST_FRAME - 1].sf); if ((vp9_is_scaled(ref_sf)) != 0) { svc_force_zero_mode[LAST_FRAME - 1] = 1; inter_layer_ref = LAST_FRAME; } } if ((cpi->ref_frame_flags & VP9_GOLD_FLAG) != 0) { - scale_factors* ref_sf = &cm->frame_refs[GOLDEN_FRAME - 1].sf; + scale_factors* ref_sf = addr(ref cm->frame_refs[GOLDEN_FRAME - 1].sf); if ((vp9_is_scaled(ref_sf)) != 0) { svc_force_zero_mode[GOLDEN_FRAME - 1] = 1; inter_layer_ref = GOLDEN_FRAME; @@ -2137,7 +2137,7 @@ internal static void vp9_pick_inter_mode(VP9_COMP* cpi, MACROBLOCK* x, TileDataE this_rdc.rate = (vp9_prob_cost[(( 1) != 0) ? 256 - (vp9_get_skip_prob(cm, xd)) : (vp9_get_skip_prob(cm, xd))]); } else { if (ROUND_POWER_OF_TWO(((int64_t)( this_rdc.rate)) * (x->rdmult), VP9_PROB_COST_SHIFT) + (( this_rdc.dist) << ( x->rddiv)) < - ROUND_POWER_OF_TWO(((int64_t)( 0)) * (x->rdmult), VP9_PROB_COST_SHIFT) + (( this_sse) << ( x->rddiv))) { + ROUND_POWER_OF_TWO(((int64_t)( 0)), VP9_PROB_COST_SHIFT) + (( this_sse) << ( x->rddiv))) { this_rdc.rate += (vp9_prob_cost[(( 0) != 0) ? 256 - (vp9_get_skip_prob(cm, xd)) : (vp9_get_skip_prob(cm, xd))]); } else { this_rdc.rate = (vp9_prob_cost[(( 1) != 0) ? 256 - (vp9_get_skip_prob(cm, xd)) : (vp9_get_skip_prob(cm, xd))]); @@ -2161,7 +2161,7 @@ internal static void vp9_pick_inter_mode(VP9_COMP* cpi, MACROBLOCK* x, TileDataE if ((this_early_term == 0) && (((x->color_sensitivity[0]) != 0) || ((x->color_sensitivity[1]) != 0))) { RD_COST rdc_uv; - BLOCK_SIZE uv_bsize = get_plane_block_size(bsize, &xd->plane[1]); + BLOCK_SIZE uv_bsize = get_plane_block_size(bsize, addr(ref xd->plane[1])); if (((x->color_sensitivity[0]) != 0) && (flag_preduv_computed[0] == 0)) { vp9_build_inter_predictors_sbp(xd, mi_row, mi_col, bsize, 1); flag_preduv_computed[0] = 1; @@ -2502,8 +2502,8 @@ internal static void vp9_pick_inter_mode_sub8x8(VP9_COMP* cpi, MACROBLOCK* x, in if (((cpi->ref_frame_flags & ref_frame_to_flag(ref_frame)) != 0) && (yv12 != null)) { - int_mv* candidates = (int_mv*)&(mbmi_ext->ref_mvs[ref_frame]); - scale_factors* ref_sf = &cm->frame_refs[ref_frame - 1].sf; + int_mv* candidates = (int_mv*)addr(ref mbmi_ext->ref_mvs[ref_frame]); + scale_factors* ref_sf = addr(ref cm->frame_refs[ref_frame - 1].sf); vp9_setup_pred_block(xd, (buf_2d*)&yv12_mb[ref_frame], yv12, mi_row, mi_col, ref_sf, ref_sf); vp9_find_mv_refs(cm, xd, xd->mi[0], ref_frame, candidates, mi_row, mi_col, @@ -2533,7 +2533,7 @@ internal static void vp9_pick_inter_mode_sub8x8(VP9_COMP* cpi, MACROBLOCK* x, in // TODO(jingning, agrange): Scaling reference frame not supported for // sub8x8 blocks. Is this supported now? if (ref_frame > INTRA_FRAME && - ((vp9_is_scaled(&cm->frame_refs[ref_frame - 1].sf)) != 0)) + ((vp9_is_scaled(addr(ref cm->frame_refs[ref_frame - 1].sf))) != 0)) continue; // If the segment reference frame feature is enabled.... @@ -2559,13 +2559,13 @@ internal static void vp9_pick_inter_mode_sub8x8(VP9_COMP* cpi, MACROBLOCK* x, in RD_COST this_rdc; uint var_y; uint sse_y; - macroblock_plane* p = &x->plane[0]; - macroblockd_plane* pd = &xd->plane[0]; + macroblock_plane* p = addr(ref x->plane[0]); + macroblockd_plane* pd = addr(ref xd->plane[0]); buf_2d orig_src = p->src; buf_2d orig_dst = pd->dst; - memcpy(orig_pre, (void*)&(xd->plane[0].pre), ((nuint)(2 * sizeof(buf_2d)))); + memcpy(orig_pre, (void*)addr(ref xd->plane[0].pre), ((nuint)(2 * sizeof(buf_2d)))); // set buffer pointers for sub8x8 motion search. p->src.buf = @@ -2603,12 +2603,12 @@ internal static void vp9_pick_inter_mode_sub8x8(VP9_COMP* cpi, MACROBLOCK* x, in } vp9_set_mv_search_range(&x->mv_limits, - &mbmi_ext->ref_mvs[ref_frame][0].as_mv); + addr(ref mbmi_ext->ref_mvs[ref_frame][0].as_mv)); vp9_full_pixel_search( cpi, x, bsize, &mvp_full, step_param, cpi->sf.mv.search_method, x->sadperbit4, cond_cost_list(cpi, cost_list), - &mbmi_ext->ref_mvs[ref_frame][0].as_mv, &tmp_mv, INT_MAX, 0); + addr(ref mbmi_ext->ref_mvs[ref_frame][0].as_mv), &tmp_mv, INT_MAX, 0); x->mv_limits = tmp_mv_limits; @@ -2617,7 +2617,7 @@ internal static void vp9_pick_inter_mode_sub8x8(VP9_COMP* cpi, MACROBLOCK* x, in mvp_full.col = (short)(tmp_mv.col * 8); b_rate += vp9_mv_bit_cost( - &mvp_full, &mbmi_ext->ref_mvs[ref_frame][0].as_mv, + &mvp_full, addr(ref mbmi_ext->ref_mvs[ref_frame][0].as_mv), x->nmvjointcost, x->mvcost, MV_COST_WEIGHT); b_rate += unchecked((int)(cpi->inter_mode_cost[x->mbmi_ext->mode_context[ref_frame]] @@ -2625,9 +2625,9 @@ internal static void vp9_pick_inter_mode_sub8x8(VP9_COMP* cpi, MACROBLOCK* x, in if (ROUND_POWER_OF_TWO(((int64_t)( b_rate)) * (x->rdmult), VP9_PROB_COST_SHIFT) + (( 0) << ( x->rddiv)) > b_best_rd) continue; cpi->find_fractional_mv_step( - x, &tmp_mv, &mbmi_ext->ref_mvs[ref_frame][0].as_mv, + x, &tmp_mv, addr(ref mbmi_ext->ref_mvs[ref_frame][0].as_mv), cpi->common.allow_high_precision_mv, x->errorperbit, - &cpi->fn_ptr[bsize], cpi->sf.mv.subpel_force_stop, + addr(ref cpi->fn_ptr[bsize]), cpi->sf.mv.subpel_force_stop, cpi->sf.mv.subpel_search_level, cond_cost_list(cpi, cost_list), x->nmvjointcost, x->mvcost, &dummy_dist, &x->pred_sse[ref_frame], null, 0, 0, @@ -2641,7 +2641,7 @@ internal static void vp9_pick_inter_mode_sub8x8(VP9_COMP* cpi, MACROBLOCK* x, in vp9_build_inter_predictor( pd->pre[0].buf, pd->pre[0].stride, pd->dst.buf, pd->dst.stride, - &xd->mi[0]->bmi[i].as_mv[0].as_mv, &xd->block_refs[0]->sf, + addr(ref xd->mi[0]->bmi[i].as_mv[0].as_mv), &xd->block_refs[0]->sf, 4 * num_4x4_blocks_wide, 4 * num_4x4_blocks_high, 0, vp9_filter_kernels[mi->interp_filter], MV_PRECISION_Q3, mi_col * MI_SIZE + 4 * (i & 0x01), diff --git a/src/Codecs/SIPSorcery.VP9/encoder/vp9_quantize.cs b/src/Codecs/SIPSorcery.VP9/encoder/vp9_quantize.cs index 21fdf34083..b4a3b81837 100644 --- a/src/Codecs/SIPSorcery.VP9/encoder/vp9_quantize.cs +++ b/src/Codecs/SIPSorcery.VP9/encoder/vp9_quantize.cs @@ -140,7 +140,7 @@ internal static void vp9_init_quantizer(VP9_COMP* cpi) // y quant = i == 0 ? vp9_dc_quant(q, cm->y_dc_delta_q, cm->bit_depth) : vp9_ac_quant(q, 0, cm->bit_depth); - invert_quant(&quants->y_quant[q][i], &quants->y_quant_shift[q][i], quant); + invert_quant(addr(ref quants->y_quant[q][i]), addr(ref quants->y_quant_shift[q][i]), quant); quants->y_quant_fp[q][i] = (short)((1 << 16) / quant); quants->y_round_fp[q][i] = (short)((qrounding_factor_fp * quant) >> 7); quants->y_zbin[q][i] = (short)(ROUND_POWER_OF_TWO(qzbin_factor * quant, 7)); @@ -150,7 +150,7 @@ internal static void vp9_init_quantizer(VP9_COMP* cpi) // uv quant = i == 0 ? vp9_dc_quant(q, cm->uv_dc_delta_q, cm->bit_depth) : vp9_ac_quant(q, cm->uv_ac_delta_q, cm->bit_depth); - invert_quant(&quants->uv_quant[q][i], &quants->uv_quant_shift[q][i], + invert_quant(addr(ref quants->uv_quant[q][i]), addr(ref quants->uv_quant_shift[q][i]), quant); quants->uv_quant_fp[q][i] = (short)((1 << 16) / quant); quants->uv_round_fp[q][i] = (short)((qrounding_factor_fp * quant) >> 7); @@ -190,25 +190,25 @@ internal static void vp9_init_plane_quantizers(VP9_COMP* cpi, MACROBLOCK* x) int i; // Y - x->plane[0].quant = (short*)&(quants->y_quant[qindex]); - x->plane[0].quant_fp = (short*)&(quants->y_quant_fp[qindex]); - x->plane[0].round_fp = (short*)&(quants->y_round_fp[qindex]); - x->plane[0].quant_shift = (short*)&(quants->y_quant_shift[qindex]); - x->plane[0].zbin = (short*)&(quants->y_zbin[qindex]); - x->plane[0].round = (short*)&(quants->y_round[qindex]); - xd->plane[0].dequant = (short*)&(cpi->y_dequant[qindex]); + x->plane[0].quant = (short*)addr(ref quants->y_quant[qindex]); + x->plane[0].quant_fp = (short*)addr(ref quants->y_quant_fp[qindex]); + x->plane[0].round_fp = (short*)addr(ref quants->y_round_fp[qindex]); + x->plane[0].quant_shift = (short*)addr(ref quants->y_quant_shift[qindex]); + x->plane[0].zbin = (short*)addr(ref quants->y_zbin[qindex]); + x->plane[0].round = (short*)addr(ref quants->y_round[qindex]); + xd->plane[0].dequant = (short*)addr(ref cpi->y_dequant[qindex]); x->plane[0].quant_thred[0] = x->plane[0].zbin[0] * x->plane[0].zbin[0]; x->plane[0].quant_thred[1] = x->plane[0].zbin[1] * x->plane[0].zbin[1]; // UV for (i = 1; i < 3; i++) { - x->plane[i].quant = (short*)&(quants->uv_quant[qindex]); - x->plane[i].quant_fp = (short*)&(quants->uv_quant_fp[qindex]); - x->plane[i].round_fp = (short*)&(quants->uv_round_fp[qindex]); - x->plane[i].quant_shift = (short*)&(quants->uv_quant_shift[qindex]); - x->plane[i].zbin = (short*)&(quants->uv_zbin[qindex]); - x->plane[i].round = (short*)&(quants->uv_round[qindex]); - xd->plane[i].dequant = (short*)&(cpi->uv_dequant[qindex]); + x->plane[i].quant = (short*)addr(ref quants->uv_quant[qindex]); + x->plane[i].quant_fp = (short*)addr(ref quants->uv_quant_fp[qindex]); + x->plane[i].round_fp = (short*)addr(ref quants->uv_round_fp[qindex]); + x->plane[i].quant_shift = (short*)addr(ref quants->uv_quant_shift[qindex]); + x->plane[i].zbin = (short*)addr(ref quants->uv_zbin[qindex]); + x->plane[i].round = (short*)addr(ref quants->uv_round[qindex]); + xd->plane[i].dequant = (short*)addr(ref cpi->uv_dequant[qindex]); x->plane[i].quant_thred[0] = x->plane[i].zbin[0] * x->plane[i].zbin[0]; x->plane[i].quant_thred[1] = x->plane[i].zbin[1] * x->plane[i].zbin[1]; } diff --git a/src/Codecs/SIPSorcery.VP9/encoder/vp9_ratectrl.cs b/src/Codecs/SIPSorcery.VP9/encoder/vp9_ratectrl.cs index 3dd677e6c4..db2aa590de 100644 --- a/src/Codecs/SIPSorcery.VP9/encoder/vp9_ratectrl.cs +++ b/src/Codecs/SIPSorcery.VP9/encoder/vp9_ratectrl.cs @@ -343,7 +343,7 @@ internal static void vp9_update_buffer_level_svc_preencode(VP9_COMP* cpi) int64_t ts_delta = svc->time_stamp_superframe - svc->time_stamp_prev[svc->spatial_layer_id]; for (i = svc->temporal_layer_id; i < svc->number_temporal_layers; ++i) { int layer = ((svc->spatial_layer_id) * ( svc->number_temporal_layers) + ( i)); - LAYER_CONTEXT* lc = &svc->layer_context[layer]; + LAYER_CONTEXT* lc = addr(ref svc->layer_context[layer]); RATE_CONTROL* lrc = &lc->rc; if ((use_timestamp != 0) && ((cpi->svc.use_set_ref_frame_config) != 0) && svc->number_temporal_layers == 1 && ts_delta > 0 && @@ -375,7 +375,7 @@ private static void update_layer_buffer_level_postencode(SVC* svc, int encoded_f int current_temporal_layer = svc->temporal_layer_id; for (i = current_temporal_layer + 1; i < svc->number_temporal_layers; ++i) { int layer = ((svc->spatial_layer_id) * ( svc->number_temporal_layers) + ( i)); - LAYER_CONTEXT* lc = &svc->layer_context[layer]; + LAYER_CONTEXT* lc = addr(ref svc->layer_context[layer]); RATE_CONTROL* lrc = &lc->rc; lrc->bits_off_target -= encoded_frame_size; // Clip buffer level to maximum buffer size for the layer. @@ -537,7 +537,7 @@ private static int check_buffer_above_thresh(VP9_COMP* cpi, int drop_mark) for (i = svc->spatial_layer_id; i < svc->number_spatial_layers; ++i) { int layer = ((i) * ( svc->number_temporal_layers) + ( svc->temporal_layer_id)); - LAYER_CONTEXT* lc = &svc->layer_context[layer]; + LAYER_CONTEXT* lc = addr(ref svc->layer_context[layer]); RATE_CONTROL* lrc = &lc->rc; // Exclude check for layer whose bitrate is 0. if (lc->target_bandwidth > 0) { @@ -566,7 +566,7 @@ private static int check_buffer_below_thresh(VP9_COMP* cpi, int drop_mark) for (i = svc->spatial_layer_id; i < svc->number_spatial_layers; ++i) { int layer = ((i) * ( svc->number_temporal_layers) + ( svc->temporal_layer_id)); - LAYER_CONTEXT* lc = &svc->layer_context[layer]; + LAYER_CONTEXT* lc = addr(ref svc->layer_context[layer]); RATE_CONTROL* lrc = &lc->rc; // Exclude check for layer whose bitrate is 0. if (lc->target_bandwidth > 0) { @@ -671,7 +671,7 @@ internal static int post_encode_drop_cbr(VP9_COMP* cpi, size_t* size) for (sl = 0; sl < svc->number_spatial_layers; ++sl) { for (tl = 0; tl < svc->number_temporal_layers; ++tl) { int layer = ((sl) * ( svc->number_temporal_layers) + ( tl)); - LAYER_CONTEXT* lc = &svc->layer_context[layer]; + LAYER_CONTEXT* lc = addr(ref svc->layer_context[layer]); RATE_CONTROL* lrc = &lc->rc; lrc->force_max_q = 1; lrc->avg_frame_qindex[INTER_FRAME] = cpi->rc.worst_quality; @@ -1049,9 +1049,8 @@ private static int calc_active_worst_quality_one_pass_cbr(VP9_COMP* cpi) // For SVC if the current base spatial layer was key frame, use the QP from // that base layer for ambient_qp. if (((cpi->use_svc) != 0) && cpi->svc.spatial_layer_id > 0) { - int layer = ((0) * ( - cpi->svc.number_temporal_layers) + ( cpi->svc.temporal_layer_id)); - LAYER_CONTEXT* lc = &cpi->svc.layer_context[layer]; + int layer = ((0) + ( cpi->svc.temporal_layer_id)); + LAYER_CONTEXT* lc = addr(ref cpi->svc.layer_context[layer]); if ((lc->is_key_frame) != 0) { RATE_CONTROL* lrc = &lc->rc; ambient_qp = VPXMIN(ambient_qp, lrc->last_q[KEY_FRAME]); @@ -1099,7 +1098,6 @@ private static int rc_pick_q_and_bounds_one_pass_cbr(VP9_COMP* cpi, int* bottom_ int q; int* rtc_minq; do { - _ = cm->bit_depth; rtc_minq = rtc_minq_8; } while (0 != 0); @@ -1238,7 +1236,6 @@ private static int rc_pick_q_and_bounds_one_pass_vbr(VP9_COMP* cpi, int* bottom_ int q; int* inter_minq; do { - _ = cm->bit_depth; inter_minq = inter_minq_8; } while (0 != 0); @@ -1549,7 +1546,6 @@ internal static int vp9_rc_pick_q_and_bounds_two_pass(VP9_COMP* cpi, int* bottom (((cpi->refresh_golden_frame) != 0) || ((cpi->refresh_alt_ref_frame) != 0))) ? 1 : 0); do { - _ = cm->bit_depth; inter_minq = inter_minq_8; } while (0 != 0); @@ -1577,13 +1573,11 @@ internal static int vp9_rc_pick_q_and_bounds_two_pass(VP9_COMP* cpi, int* bottom if (rc->arf_increase_active_best_quality == 1) { do { - _ = cm->bit_depth; arfgf_high_motion_minq = arfgf_high_motion_minq_8; } while (0 != 0); arf_active_best_quality_hl = arfgf_high_motion_minq[q]; } else if (rc->arf_increase_active_best_quality == -1) { do { - _ = cm->bit_depth; arfgf_low_motion_minq = arfgf_low_motion_minq_8; } while (0 != 0); arf_active_best_quality_hl = arfgf_low_motion_minq[q]; @@ -1918,7 +1912,7 @@ internal static void vp9_compute_frame_low_motion(VP9_COMP* cpi) for (i = 0; i < svc->number_spatial_layers - 1; ++i) { int layer = ((i) * ( svc->number_temporal_layers) + ( svc->temporal_layer_id)); - LAYER_CONTEXT* lc = &svc->layer_context[layer]; + LAYER_CONTEXT* lc = addr(ref svc->layer_context[layer]); RATE_CONTROL* lrc = &lc->rc; lrc->avg_frame_low_motion = rc->avg_frame_low_motion; } @@ -1952,7 +1946,7 @@ internal static void vp9_rc_postencode_update(VP9_COMP* cpi, uint64_t bytes_used for (i = 0; i < svc->number_temporal_layers; ++i) { int layer = ((svc->spatial_layer_id) * ( svc->number_temporal_layers) + ( i)); - LAYER_CONTEXT* lc = &svc->layer_context[layer]; + LAYER_CONTEXT* lc = addr(ref svc->layer_context[layer]); RATE_CONTROL* lrc = &lc->rc; lrc->last_q[KEY_FRAME] = rc->last_q[KEY_FRAME]; lrc->avg_frame_qindex[KEY_FRAME] = rc->avg_frame_qindex[KEY_FRAME]; @@ -2046,7 +2040,7 @@ internal static void vp9_rc_postencode_update(VP9_COMP* cpi, uint64_t bytes_used for (i = 1; i < svc->number_temporal_layers; ++i) { int layer = ((svc->spatial_layer_id) * ( svc->number_temporal_layers) + ( i)); - LAYER_CONTEXT* lc = &svc->layer_context[layer]; + LAYER_CONTEXT* lc = addr(ref svc->layer_context[layer]); RATE_CONTROL* lrc = &lc->rc; lrc->frames_since_golden = rc->frames_since_golden; } @@ -2260,7 +2254,7 @@ internal static int vp9_calc_pframe_target_size_one_pass_cbr(VP9_COMP* cpi) // layer average frame size (i.e., non-cumulative per-frame-bw). int layer = ((svc->spatial_layer_id) * ( svc->number_temporal_layers) + ( svc->temporal_layer_id)); - LAYER_CONTEXT* lc = &svc->layer_context[layer]; + LAYER_CONTEXT* lc = addr(ref svc->layer_context[layer]); target = lc->avg_frame_size; min_frame_target = VPXMAX(lc->avg_frame_size >> 4, FRAME_OVERHEAD_BITS); } @@ -2296,7 +2290,7 @@ internal static int vp9_calc_iframe_target_size_one_pass_cbr(VP9_COMP* cpi) // Use the layer framerate for temporal layers CBR mode. int layer = ((svc->spatial_layer_id) * ( svc->number_temporal_layers) + ( svc->temporal_layer_id)); - LAYER_CONTEXT* lc = &svc->layer_context[layer]; + LAYER_CONTEXT* lc = addr(ref svc->layer_context[layer]); framerate = lc->framerate; } kf_boost = VPXMAX(kf_boost, (int)round(2 * framerate - 16)); @@ -2407,7 +2401,7 @@ internal static void vp9_rc_get_svc_params(VP9_COMP* cpi) } else { cm->frame_type = INTER_FRAME; if ((is_one_pass_svc(cpi)) != 0) { - LAYER_CONTEXT* lc = &svc->layer_context[layer]; + LAYER_CONTEXT* lc = addr(ref svc->layer_context[layer]); // Add condition current_video_frame > 0 for the case where first frame // is intra only followed by overlay/copy frame. In this case we don't // want to reset is_key_frame to 0 on overlay/copy frame. @@ -2553,9 +2547,9 @@ internal static void vp9_rc_get_svc_params(VP9_COMP* cpi) int tl; int width; int height; // Apply the same scale to all temporal layers. for (tl = 0; tl < svc->number_temporal_layers; tl++) { - lc = &svc->layer_context[svc->spatial_layer_id * + lc = addr(ref svc->layer_context[svc->spatial_layer_id * svc->number_temporal_layers + - tl]; + tl]); lc->scaling_factor_num_resize = cpi->resize_scale_num * lc->scaling_factor_num; lc->scaling_factor_den_resize = @@ -2567,9 +2561,9 @@ internal static void vp9_rc_get_svc_params(VP9_COMP* cpi) rc->rate_correction_factors[INTER_FRAME]; } // Set the size for this current temporal layer. - lc = &svc->layer_context[svc->spatial_layer_id * + lc = addr(ref svc->layer_context[svc->spatial_layer_id * svc->number_temporal_layers + - svc->temporal_layer_id]; + svc->temporal_layer_id]); get_layer_resolution(cpi->oxcf.width, cpi->oxcf.height, lc->scaling_factor_num_resize, lc->scaling_factor_den_resize, &width, &height); @@ -3279,7 +3273,7 @@ internal static void vp9_scene_detection_onepass(VP9_COMP* cpi) for (sl = 0; sl < svc->number_spatial_layers; ++sl) for (tl = 0; tl < svc->number_temporal_layers; ++tl) { int layer = ((sl) * ( svc->number_temporal_layers) + ( tl)); - LAYER_CONTEXT* lc = &svc->layer_context[layer]; + LAYER_CONTEXT* lc = addr(ref svc->layer_context[layer]); RATE_CONTROL* lrc = &lc->rc; lrc->avg_source_sad[0] = rc->avg_source_sad[0]; } @@ -3417,7 +3411,7 @@ internal static int vp9_encodedframe_overshoot(VP9_COMP* cpi, int frame_size, in for (sl = 0; sl < num_spatial_layers; ++sl) { for (tl = 0; tl < svc->number_temporal_layers; ++tl) { int layer = ((sl) * ( svc->number_temporal_layers) + ( tl)); - LAYER_CONTEXT* lc = &svc->layer_context[layer]; + LAYER_CONTEXT* lc = addr(ref svc->layer_context[layer]); RATE_CONTROL* lrc = &lc->rc; lrc->avg_frame_qindex[INTER_FRAME] = *q; lrc->buffer_level = lrc->optimal_buffer_level; diff --git a/src/Codecs/SIPSorcery.VP9/encoder/vp9_rd.cs b/src/Codecs/SIPSorcery.VP9/encoder/vp9_rd.cs index c4d24c5469..b361b13d93 100644 --- a/src/Codecs/SIPSorcery.VP9/encoder/vp9_rd.cs +++ b/src/Codecs/SIPSorcery.VP9/encoder/vp9_rd.cs @@ -176,22 +176,22 @@ private static void fill_mode_costs(VP9_COMP* cpi) for (i = 0; i < INTRA_MODES; ++i) { for (j = 0; j < INTRA_MODES; ++j) { - vp9_cost_tokens((int*)&(cpi->y_mode_costs[i][j]), (byte*)&vp9_kf_y_mode_prob[i][j], + vp9_cost_tokens((int*)addr(ref cpi->y_mode_costs[i][j]), (byte*)addr(ref vp9_kf_y_mode_prob[i][j]), vp9_intra_mode_tree); } } - vp9_cost_tokens(cpi->mbmode_cost, (byte*)&(fc->y_mode_prob[1]), vp9_intra_mode_tree); + vp9_cost_tokens(cpi->mbmode_cost, (byte*)addr(ref fc->y_mode_prob[1]), vp9_intra_mode_tree); for (i = 0; i < INTRA_MODES; ++i) { - vp9_cost_tokens((int*)&(cpi->intra_uv_mode_cost[KEY_FRAME][i]), + vp9_cost_tokens((int*)addr(ref cpi->intra_uv_mode_cost[KEY_FRAME][i]), (byte*)&vp9_kf_uv_mode_prob[i], vp9_intra_mode_tree); - vp9_cost_tokens((int*)&(cpi->intra_uv_mode_cost[INTER_FRAME][i]), - (byte*)&(fc->uv_mode_prob[i]), vp9_intra_mode_tree); + vp9_cost_tokens((int*)addr(ref cpi->intra_uv_mode_cost[INTER_FRAME][i]), + (byte*)addr(ref fc->uv_mode_prob[i]), vp9_intra_mode_tree); } for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i) { - vp9_cost_tokens((int*)&(cpi->switchable_interp_costs[i]), - (byte*)&(fc->switchable_interp_prob[i]), vp9_switchable_interp_tree); + vp9_cost_tokens((int*)addr(ref cpi->switchable_interp_costs[i]), + (byte*)addr(ref fc->switchable_interp_prob[i]), vp9_switchable_interp_tree); } for (i = TX_8X8; i < TX_SIZES; ++i) { @@ -224,9 +224,9 @@ private static void fill_token_costs(vp9_coeff_cost* c, A2common; int i; for (i = 0; i < INTER_MODE_CONTEXTS; ++i) { - vp9_cost_tokens((int *)&(cpi->inter_mode_cost[i]), (byte*)&(cm->fc->inter_mode_probs[i]), + vp9_cost_tokens((int *)addr(ref cpi->inter_mode_cost[i]), (byte*)addr(ref cm->fc->inter_mode_probs[i]), vp9_inter_mode_tree); } } @@ -473,7 +473,7 @@ internal static void vp9_initialize_rd_consts(VP9_COMP* cpi) if (cpi->sf.partition_search_type != VAR_BASED_PARTITION || cm->frame_type == KEY_FRAME) { for (i = 0; i < PARTITION_CONTEXTS; ++i) - vp9_cost_tokens((int*)&(cpi->partition_cost[i]), get_partition_probs(xd, i), + vp9_cost_tokens((int*)addr(ref cpi->partition_cost[i]), get_partition_probs(xd, i), vp9_partition_tree); } @@ -700,7 +700,7 @@ internal static int vp9_raster_block_offset(BLOCK_SIZE plane_bsize, int raster_b int ref_idx = get_ref_frame_buf_idx(cpi, ref_frame); Debug.Assert(ref_frame >= LAST_FRAME && ref_frame <= ALTREF_FRAME); return (scaled_idx != ref_idx && scaled_idx != INVALID_IDX) - ? &cm->buffer_pool->frame_bufs[scaled_idx].buf + ? addr(ref cm->buffer_pool->frame_bufs[scaled_idx].buf) : null; } @@ -785,7 +785,7 @@ internal static void vp9_update_rd_thresh_fact(A30* factor_buf, int rd_thre BLOCK_SIZE max_size = (byte)(VPXMIN(bsize + 2, BLOCK_64X64)); BLOCK_SIZE bs; for (bs = min_size; bs <= max_size; ++bs) { - int* fact = &factor_buf[bs][mode]; + int* fact = addr(ref factor_buf[bs][mode]); if (mode == best_mode_index) { *fact -= (*fact >> 4); } else { diff --git a/src/Codecs/SIPSorcery.VP9/encoder/vp9_rdopt.cs b/src/Codecs/SIPSorcery.VP9/encoder/vp9_rdopt.cs index 51f950d506..44f86a02be 100644 --- a/src/Codecs/SIPSorcery.VP9/encoder/vp9_rdopt.cs +++ b/src/Codecs/SIPSorcery.VP9/encoder/vp9_rdopt.cs @@ -55,8 +55,8 @@ private static void swap_block_ptr(MACROBLOCK* x, PICK_MODE_CONTEXT* ctx, int m, int i; for (i = min_plane; i < max_plane; ++i) { - macroblock_plane* p = &x->plane[i]; - macroblockd_plane* pd = &x->e_mbd.plane[i]; + macroblock_plane* p = addr(ref x->plane[i]); + macroblockd_plane* pd = addr(ref x->e_mbd.plane[i]); p->coeff = ctx->coeff_pbuf[i][m]; p->qcoeff = ctx->qcoeff_pbuf[i][m]; @@ -115,12 +115,12 @@ private static int cost_coeffs(MACROBLOCK* x, int plane, int block, TX_SIZE tx_s { MACROBLOCKD* xd = &x->e_mbd; MODE_INFO* mi = xd->mi[0]; - macroblock_plane* p = &x->plane[plane]; + macroblock_plane* p = addr(ref x->plane[plane]); PLANE_TYPE type = get_plane_type(plane); - int16_t* band_count = &band_counts[tx_size][1]; + int16_t* band_count = addr(ref band_counts[tx_size][1]); int eob = p->eobs[block]; tran_low_t* qcoeff = ((p->qcoeff) + ( block)*16); - A2>>* token_costs = (A2>>*)&(x->token_costs[tx_size][type][is_inter_block(mi)]); + A2>>* token_costs = (A2>>*)addr(ref x->token_costs[tx_size][type][is_inter_block(mi)]); uint8_t* token_cache = stackalloc uint8_t[32*32]; int cost; uint16_t* cat6_high_cost = vp9_get_high_cost_table(8); @@ -128,7 +128,7 @@ private static int cost_coeffs(MACROBLOCK* x, int plane, int block, TX_SIZE tx_s // Check for consistency of tx_size with mode info Debug.Assert(type == PLANE_TYPE_Y ? mi->tx_size == tx_size - : get_uv_tx_size(mi, &xd->plane[plane]) == tx_size); + : get_uv_tx_size(mi, addr(ref xd->plane[plane])) == tx_size); if (eob == 0) { // single eob token @@ -179,7 +179,7 @@ private static int cost_coeffs(MACROBLOCK* x, int plane, int block, TX_SIZE tx_s token_cache[0] = vp9_pt_energy_class[tok]; ++token_costs; - tok_cost_ptr = &((*token_costs)[((tok == 0) ? 1 : 0)]); + tok_cost_ptr = addr(ref (*token_costs)[((tok == 0) ? 1 : 0)]); // ac tokens for (c = 1; c < eob; c++) { @@ -194,7 +194,7 @@ private static int cost_coeffs(MACROBLOCK* x, int plane, int block, TX_SIZE tx_s band_left = *band_count++; ++token_costs; } - tok_cost_ptr = &((*token_costs)[((tok == 0) ? 1 : 0)]); + tok_cost_ptr = addr(ref (*token_costs)[((tok == 0) ? 1 : 0)]); } // eob token @@ -283,8 +283,8 @@ private static uint pixel_sse(VP9_COMP* cpi, MACROBLOCKD* xd, macroblockd_plane* private static void dist_block(VP9_COMP* cpi, MACROBLOCK* x, int plane, BLOCK_SIZE plane_bsize, int block, int blk_row, int blk_col, TX_SIZE tx_size, int64_t* out_dist, int64_t* out_sse, buf_2d* out_recon, int sse_calc_done) { MACROBLOCKD* xd = &x->e_mbd; - macroblock_plane* p = &x->plane[plane]; - macroblockd_plane* pd = &xd->plane[plane]; + macroblock_plane* p = addr(ref x->plane[plane]); + macroblockd_plane* pd = addr(ref xd->plane[plane]); int eob = p->eobs[block]; if ((out_recon == null) && ((x->block_tx_domain) != 0) && (eob != 0)) { @@ -382,7 +382,7 @@ private static void block_rd_txfm(int plane, int block, int blk_row, int blk_col int coeff_ctx = combine_entropy_contexts(args->t_left[blk_row], args->t_above[blk_col]); buf_2d* recon = args->this_recon; BLOCK_SIZE tx_bsize = txsize_to_bsize[tx_size]; - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); int dst_stride = pd->dst.stride; uint8_t* dst = &pd->dst.buf[4 * (blk_row * dst_stride + blk_col)]; int enable_trellis_opt = args->cpi->sf.trellis_opt_tx_rd.method; @@ -404,7 +404,7 @@ private static void block_rd_txfm(int plane, int block, int blk_row, int blk_col dist_block(args->cpi, x, plane, plane_bsize, block, blk_row, blk_col, tx_size, &dist, &sse, /*out_recon=*/null, sse_calc_done); } else { - macroblock_plane* p = &x->plane[plane]; + macroblock_plane* p = addr(ref x->plane[plane]); int src_stride = p->src.stride; uint8_t* src = &p->src.buf[4 * (blk_row * src_stride + blk_col)]; uint tmp; @@ -435,7 +435,7 @@ private static void block_rd_txfm(int plane, int block, int blk_row, int blk_col if (skip_txfm_flag == SKIP_TXFM_NONE || ((recon != null) && skip_txfm_flag == SKIP_TXFM_AC_ONLY)) { - macroblock_plane* p = &x->plane[plane]; + macroblock_plane* p = addr(ref x->plane[plane]); int diff_stride = 4 * num_4x4_blocks_wide_lookup[plane_bsize]; int16_t* diff = &p->src_diff[4 * (blk_row * diff_stride + blk_col)]; int use_trellis_opt = do_trellis_opt(pd, diff, diff_stride, blk_row, blk_col, plane_bsize, @@ -466,7 +466,7 @@ private static void block_rd_txfm(int plane, int block, int blk_row, int blk_col } } - rd = ROUND_POWER_OF_TWO(((int64_t)( 0)) * (x->rdmult), VP9_PROB_COST_SHIFT) + (( dist) << ( x->rddiv)); + rd = ROUND_POWER_OF_TWO(((int64_t)( 0)), VP9_PROB_COST_SHIFT) + (( dist) << ( x->rddiv)); if (args->this_rd + rd > args->best_rd) { args->exit_early = 1; return; @@ -476,7 +476,7 @@ private static void block_rd_txfm(int plane, int block, int blk_row, int blk_col args->t_above[blk_col] = (byte)((x->plane[plane].eobs[block] > 0) ? 1 : 0); args->t_left[blk_row] = (byte)((x->plane[plane].eobs[block] > 0) ? 1 : 0); rd1 = ROUND_POWER_OF_TWO(((int64_t)( rate)) * (x->rdmult), VP9_PROB_COST_SHIFT) + (( dist) << ( x->rddiv)); - rd2 = ROUND_POWER_OF_TWO(((int64_t)( 0)) * (x->rdmult), VP9_PROB_COST_SHIFT) + (( sse) << ( x->rddiv)); + rd2 = ROUND_POWER_OF_TWO(((int64_t)( 0)), VP9_PROB_COST_SHIFT) + (( sse) << ( x->rddiv)); // TODO(jingning): temporarily enabled only for luma component rd = VPXMIN(rd1, rd2); @@ -503,7 +503,7 @@ private static void block_rd_txfm(int plane, int block, int blk_row, int blk_col private static void txfm_rd_in_plane(VP9_COMP* cpi, MACROBLOCK* x, int* rate, int64_t* distortion, int* skippable, int64_t* sse, int64_t ref_best_rd, int plane, BLOCK_SIZE bsize, TX_SIZE tx_size, int use_fast_coef_costing, buf_2d* recon) { MACROBLOCKD* xd = &x->e_mbd; - macroblockd_plane* pd = &xd->plane[plane]; + macroblockd_plane* pd = addr(ref xd->plane[plane]); rdcost_block_args args; Unsafe.SkipInit(out args); vp9_zero(ref args); args.cpi = cpi; @@ -586,10 +586,10 @@ private static void choose_tx_size_from_rd(VP9_COMP* cpi, MACROBLOCK* x, int* ra buf_2d this_recon; this_recon.buf = (byte*)&recon_buf[n]; this_recon.stride = recon->stride; - txfm_rd_in_plane(cpi, x, &r[n][0], &d[n], &s[n], &sse[n], best_rd, 0, bs, + txfm_rd_in_plane(cpi, x, addr(ref r[n][0]), &d[n], &s[n], &sse[n], best_rd, 0, bs, (byte)n, cpi->sf.use_fast_coef_costing, &this_recon); } else { - txfm_rd_in_plane(cpi, x, &r[n][0], &d[n], &s[n], &sse[n], best_rd, 0, bs, + txfm_rd_in_plane(cpi, x, addr(ref r[n][0]), &d[n], &s[n], &sse[n], best_rd, 0, bs, (byte)n, cpi->sf.use_fast_coef_costing, null); } r[n][1] = r[n][0]; @@ -677,8 +677,8 @@ private static int64_t rd_pick_intra4x4block(VP9_COMP* cpi, MACROBLOCK* x, int r PREDICTION_MODE mode; MACROBLOCKD* xd = &x->e_mbd; int64_t best_rd = rd_thresh; - macroblock_plane* p = &x->plane[0]; - macroblockd_plane* pd = &xd->plane[0]; + macroblock_plane* p = addr(ref x->plane[0]); + macroblockd_plane* pd = addr(ref xd->plane[0]); int src_stride = p->src.stride; int dst_stride = pd->dst.stride; uint8_t* src_init = &p->src.buf[row * 4 * src_stride + col * 4]; @@ -745,7 +745,7 @@ private static int64_t rd_pick_intra4x4block(VP9_COMP* cpi, MACROBLOCK* x, int r } else { int64_t unused; TX_TYPE tx_type = get_tx_type_4x4(PLANE_TYPE_Y, xd, block); - ScanOrder* so = &vp9_scan_orders[TX_4X4][tx_type]; + ScanOrder* so = addr(ref vp9_scan_orders[TX_4X4][tx_type]); int coeff_ctx = combine_entropy_contexts(tempa[idx], templ[idy]); vp9_fht4x4_simd(src_diff, coeff, 8, tx_type); vpx_quantize_b_simd(coeff, 4 * 4, p, qcoeff, dqcoeff, pd->dequant, eob, @@ -819,7 +819,7 @@ private static int64_t rd_pick_intra_sub_8x8_y_mode(VP9_COMP* cpi, MACROBLOCK* m PREDICTION_MODE A = vp9_above_block_mode(mic, above_mi, i); PREDICTION_MODE L = vp9_left_block_mode(mic, left_mi, i); - bmode_costs = (int*)&(cpi->y_mode_costs[A][L]); + bmode_costs = (int*)addr(ref cpi->y_mode_costs[A][L]); } this_rd = rd_pick_intra4x4block( @@ -867,7 +867,7 @@ private static int64_t rd_pick_intra_sby_mode(VP9_COMP* cpi, MACROBLOCK* x, int* MODE_INFO* left_mi = xd->left_mi; PREDICTION_MODE A = vp9_above_block_mode(mic, above_mi, 0); PREDICTION_MODE L = vp9_left_block_mode(mic, left_mi, 0); - bmode_costs = (int*)&(cpi->y_mode_costs[A][L]); + bmode_costs = (int*)addr(ref cpi->y_mode_costs[A][L]); memset(x->skip_txfm, SKIP_TXFM_NONE, (12 * sizeof(uint8_t))); /* Y Search for intra prediction mode */ @@ -912,7 +912,7 @@ private static int super_block_uvrd(VP9_COMP* cpi, MACROBLOCK* x, int* rate, int { MACROBLOCKD* xd = &x->e_mbd; MODE_INFO* mi = xd->mi[0]; - TX_SIZE uv_tx_size = get_uv_tx_size(mi, &xd->plane[1]); + TX_SIZE uv_tx_size = get_uv_tx_size(mi, addr(ref xd->plane[1])); int plane; int pnrate = 0; int pnskip = 1; int64_t pndist = 0; int64_t pnsse = 0; diff --git a/src/Codecs/SIPSorcery.VP9/encoder/vp9_speed_features.cs b/src/Codecs/SIPSorcery.VP9/encoder/vp9_speed_features.cs index dd78250a38..fc73c1c4ef 100644 --- a/src/Codecs/SIPSorcery.VP9/encoder/vp9_speed_features.cs +++ b/src/Codecs/SIPSorcery.VP9/encoder/vp9_speed_features.cs @@ -275,7 +275,7 @@ private static void set_rt_speed_feature_framesize_independent(VP9_COMP* cpi, SP YV12_BUFFER_CONFIG* yv12 = get_ref_frame_buffer(cpi, ref_frame); if (yv12 != null && ((cpi->ref_frame_flags & ref_frame_to_flag(ref_frame)) != 0)) { - scale_factors* scale_fac = &cm->frame_refs[ref_frame - 1].sf; + scale_factors* scale_fac = addr(ref cm->frame_refs[ref_frame - 1].sf); if ((vp9_is_scaled(scale_fac)) != 0) sf->reference_masking = 0; } } diff --git a/src/Codecs/SIPSorcery.VP9/encoder/vp9_svc_layercontext.cs b/src/Codecs/SIPSorcery.VP9/encoder/vp9_svc_layercontext.cs index 0678d6a5f0..ccb3483cc1 100644 --- a/src/Codecs/SIPSorcery.VP9/encoder/vp9_svc_layercontext.cs +++ b/src/Codecs/SIPSorcery.VP9/encoder/vp9_svc_layercontext.cs @@ -156,7 +156,7 @@ internal static void vp9_init_layer_context(VP9_COMP* cpi) for (sl = 0; sl < oxcf->ss_number_layers; ++sl) { for (tl = 0; tl < oxcf->ts_number_layers; ++tl) { int layer = ((sl) * ( oxcf->ts_number_layers) + ( tl)); - LAYER_CONTEXT* lc = &svc->layer_context[layer]; + LAYER_CONTEXT* lc = addr(ref svc->layer_context[layer]); RATE_CONTROL* lrc = &lc->rc; lc->current_video_frame_in_layer = 0; lc->layer_size = 0; @@ -262,7 +262,7 @@ internal static void vp9_update_layer_context_change_config(VP9_COMP* cpi, int t oxcf->layer_target_bitrate[layer]; for (tl = 0; tl < oxcf->ts_number_layers; ++tl) { - LAYER_CONTEXT* lc = &svc->layer_context[sl * oxcf->ts_number_layers + tl]; + LAYER_CONTEXT* lc = addr(ref svc->layer_context[sl * oxcf->ts_number_layers + tl]); RATE_CONTROL* lrc = &lc->rc; lc->spatial_layer_target_bandwidth = spatial_layer_target; @@ -296,7 +296,7 @@ internal static void vp9_update_layer_context_change_config(VP9_COMP* cpi, int t } for (layer = 0; layer < layer_end; ++layer) { - LAYER_CONTEXT* lc = &svc->layer_context[layer]; + LAYER_CONTEXT* lc = addr(ref svc->layer_context[layer]); RATE_CONTROL* lrc = &lc->rc; lc->target_bandwidth = oxcf->layer_target_bitrate[layer]; @@ -344,13 +344,13 @@ internal static void vp9_update_layer_context_change_config(VP9_COMP* cpi, int t private static LAYER_CONTEXT* get_layer_context(VP9_COMP* cpi) { if ((is_one_pass_svc(cpi)) != 0) - return &cpi->svc.layer_context[cpi->svc.spatial_layer_id * + return addr(ref cpi->svc.layer_context[cpi->svc.spatial_layer_id * cpi->svc.number_temporal_layers + - cpi->svc.temporal_layer_id]; + cpi->svc.temporal_layer_id]); else return (cpi->svc.number_temporal_layers > 1 && cpi->oxcf.rc_mode == VPX_CBR) - ? &cpi->svc.layer_context[cpi->svc.temporal_layer_id] - : &cpi->svc.layer_context[cpi->svc.spatial_layer_id]; + ? addr(ref cpi->svc.layer_context[cpi->svc.temporal_layer_id]) + : addr(ref cpi->svc.layer_context[cpi->svc.spatial_layer_id]); } internal static void vp9_update_temporal_layer_framerate(VP9_COMP* cpi) @@ -474,8 +474,8 @@ internal static void vp9_save_layer_context(VP9_COMP* cpi) internal static void vp9_inc_frame_in_layer(VP9_COMP* cpi) { - LAYER_CONTEXT* lc = &cpi->svc.layer_context[cpi->svc.spatial_layer_id * - cpi->svc.number_temporal_layers]; + LAYER_CONTEXT* lc = addr(ref cpi->svc.layer_context[cpi->svc.spatial_layer_id * + cpi->svc.number_temporal_layers]); ++lc->current_video_frame_in_layer; ++lc->frames_from_key_frame; if (cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1) @@ -841,7 +841,7 @@ internal static int vp9_one_pass_svc_start_layer(VP9_COMP* cpi) for (sl = svc->number_spatial_layers - 1; sl >= svc->first_spatial_layer_to_encode; sl--) { int layer = sl * svc->number_temporal_layers + svc->temporal_layer_id; - LAYER_CONTEXT* sl_lc = &svc->layer_context[layer]; + LAYER_CONTEXT* sl_lc = addr(ref svc->layer_context[layer]); cpi->rc = sl_lc->rc; cpi->oxcf.target_bandwidth = sl_lc->target_bandwidth; if ((vp9_test_drop(cpi)) != 0) { @@ -935,8 +935,8 @@ internal static int vp9_one_pass_svc_start_layer(VP9_COMP* cpi) } } - lc = &svc->layer_context[svc->spatial_layer_id * svc->number_temporal_layers + - svc->temporal_layer_id]; + lc = addr(ref svc->layer_context[svc->spatial_layer_id * svc->number_temporal_layers + + svc->temporal_layer_id]); // Setting the worst/best_quality via the encoder control: SET_SVC_PARAMETERS, // only for non-BYPASS mode for now. @@ -980,8 +980,8 @@ internal static int vp9_one_pass_svc_start_layer(VP9_COMP* cpi) if (svc->number_spatial_layers > 1) { int sl; for (sl = 0; sl < svc->number_spatial_layers - 1; ++sl) { - lc = &svc->layer_context[sl * svc->number_temporal_layers + - svc->temporal_layer_id]; + lc = addr(ref svc->layer_context[sl * svc->number_temporal_layers + + svc->temporal_layer_id]); if ((lc->scaling_factor_num != lc->scaling_factor_den >> 1) && !(lc->scaling_factor_num == lc->scaling_factor_den >> 2 && sl == 0 && svc->number_spatial_layers == 3)) { @@ -1058,7 +1058,7 @@ internal static void vp9_free_svc_cyclic_refresh(VP9_COMP* cpi) for (sl = 0; sl < oxcf->ss_number_layers; ++sl) { for (tl = 0; tl < oxcf->ts_number_layers; ++tl) { int layer = ((sl) * ( oxcf->ts_number_layers) + ( tl)); - LAYER_CONTEXT* lc = &svc->layer_context[layer]; + LAYER_CONTEXT* lc = addr(ref svc->layer_context[layer]); if ((lc->map) != null) vpx_free(lc->map); if ((lc->last_coded_q_map) != null) vpx_free(lc->last_coded_q_map); if ((lc->consec_zero_mv) != null) vpx_free(lc->consec_zero_mv); @@ -1074,7 +1074,7 @@ internal static void vp9_svc_reset_temporal_layers(VP9_COMP* cpi, int is_key) LAYER_CONTEXT* lc = null; for (sl = 0; sl < svc->number_spatial_layers; ++sl) { for (tl = 0; tl < svc->number_temporal_layers; ++tl) { - lc = &cpi->svc.layer_context[sl * svc->number_temporal_layers + tl]; + lc = addr(ref cpi->svc.layer_context[sl * svc->number_temporal_layers + tl]); lc->current_video_frame_in_layer = 0; if (is_key != 0) lc->frames_from_key_frame = 0; } @@ -1099,14 +1099,14 @@ internal static void vp9_svc_check_reset_layer_rc_flag(VP9_COMP* cpi) // Check for reset based on avg_frame_bandwidth for spatial layer sl. int spatial_layer_idx = (( sl) * ( svc->number_temporal_layers) + ( svc->number_temporal_layers - 1)); - LAYER_CONTEXT* lc = &svc->layer_context[spatial_layer_idx]; + LAYER_CONTEXT* lc = addr(ref svc->layer_context[spatial_layer_idx]); RATE_CONTROL* lrc = &lc->rc; if (lrc->avg_frame_bandwidth / 3 > (lrc->last_avg_frame_bandwidth >> 1) || lrc->avg_frame_bandwidth < (lrc->last_avg_frame_bandwidth >> 1)) { // Reset for all temporal layers with spatial layer sl. for (tl = 0; tl < svc->number_temporal_layers; ++tl) { int temporal_layer_idx = ((sl) * ( svc->number_temporal_layers) + ( tl)); - lrc = &svc->layer_context[temporal_layer_idx].rc; + lrc = addr(ref svc->layer_context[temporal_layer_idx].rc); lrc->rc_1_frame = 0; lrc->rc_2_frame = 0; lrc->bits_off_target = lrc->optimal_buffer_level; @@ -1136,7 +1136,7 @@ internal static void vp9_svc_constrain_inter_layer_pred(VP9_COMP* cpi) YV12_BUFFER_CONFIG* yv12 = get_ref_frame_buffer(cpi, ref_frame); if (yv12 != null && ((cpi->ref_frame_flags & ref_frame_to_flag(ref_frame)) != 0)) { - scale_factors* scale_fac = &cm->frame_refs[ref_frame - 1].sf; + scale_factors* scale_fac = addr(ref cm->frame_refs[ref_frame - 1].sf); if ((vp9_is_scaled(scale_fac)) != 0) { cpi->ref_frame_flags &= (~ref_frame_to_flag(ref_frame)); // Point golden/altref frame buffer index to last. @@ -1161,7 +1161,7 @@ internal static void vp9_svc_constrain_inter_layer_pred(VP9_COMP* cpi) // check both here. MV_REFERENCE_FRAME ref_frame; for (ref_frame = LAST_FRAME; ref_frame <= GOLDEN_FRAME; ref_frame++) { - scale_factors* scale_fac = &cm->frame_refs[ref_frame - 1].sf; + scale_factors* scale_fac = addr(ref cm->frame_refs[ref_frame - 1].sf); if ((vp9_is_scaled(scale_fac)) != 0) { // If this reference was updated on the previous spatial layer of the // current superframe, then we keep this reference (don't disable). @@ -1381,8 +1381,8 @@ internal static void vp9_svc_adjust_avg_frame_qindex(VP9_COMP* cpi) VPXMAX(rc->avg_frame_qindex[INTER_FRAME], (cm->base_qindex + rc->worst_quality) >> 1); for (tl = 0; tl < svc->number_temporal_layers; ++tl) { - int layer = ((0) * ( svc->number_temporal_layers) + ( tl)); - LAYER_CONTEXT* lc = &svc->layer_context[layer]; + int layer = ((0) + ( tl)); + LAYER_CONTEXT* lc = addr(ref svc->layer_context[layer]); RATE_CONTROL* lrc = &lc->rc; lrc->avg_frame_qindex[INTER_FRAME] = rc->avg_frame_qindex[INTER_FRAME]; } diff --git a/src/Codecs/SIPSorcery.VP9/encoder/vp9_tokenize.cs b/src/Codecs/SIPSorcery.VP9/encoder/vp9_tokenize.cs index fcaa2dab9b..e9857dca49 100644 --- a/src/Codecs/SIPSorcery.VP9/encoder/vp9_tokenize.cs +++ b/src/Codecs/SIPSorcery.VP9/encoder/vp9_tokenize.cs @@ -248,8 +248,8 @@ private static void set_entropy_context_b(int plane, int block, int row, int col ThreadData* td = args->td; MACROBLOCK* x = &td->mb; MACROBLOCKD* xd = &x->e_mbd; - macroblock_plane* p = &x->plane[plane]; - macroblockd_plane* pd = &xd->plane[plane]; + macroblock_plane* p = addr(ref x->plane[plane]); + macroblockd_plane* pd = addr(ref xd->plane[plane]); vp9_set_contexts(xd, pd, plane_bsize, tx_size, ((p->eobs[block] > 0) ? 1 : 0), col, row); } @@ -279,8 +279,8 @@ private static void tokenize_b(int plane, int block, int row, int col, BLOCK_SIZ MACROBLOCKD* xd = &x->e_mbd; TOKENEXTRA** tp = args->tp; uint8_t* token_cache = stackalloc uint8_t[32*32]; - macroblock_plane* p = &x->plane[plane]; - macroblockd_plane* pd = &xd->plane[plane]; + macroblock_plane* p = addr(ref x->plane[plane]); + macroblockd_plane* pd = addr(ref xd->plane[plane]); MODE_INFO* mi = xd->mi[0]; int pt; /* near block/prev token context index */ int c; @@ -291,9 +291,9 @@ private static void tokenize_b(int plane, int block, int row, int col, BLOCK_SIZ int16_t* scan; int16_t* nb; ScanOrder* so; int @ref = is_inter_block(mi); - A6>* counts = (A6>*)&(td->rd_counts.coef_counts[tx_size][type][@ref]); - A6>* coef_probs = (A6>*)&(cpi->common.fc->coef_probs[tx_size][type][@ref]); - A6* eob_branch = (A6*)&(td->counts->eob_branch[tx_size][type][@ref]); + A6>* counts = (A6>*)addr(ref td->rd_counts.coef_counts[tx_size][type][@ref]); + A6>* coef_probs = (A6>*)addr(ref cpi->common.fc->coef_probs[tx_size][type][@ref]); + A6* eob_branch = (A6*)addr(ref td->counts->eob_branch[tx_size][type][@ref]); uint8_t* band = get_band_translate(tx_size); int tx_eob = 16 << (tx_size << 1); int16_t token; @@ -311,8 +311,8 @@ private static void tokenize_b(int plane, int block, int row, int col, BLOCK_SIZ ++eob_branch[band[c]][pt]; while (v == 0) { - add_token_no_extra(&t, (byte*)&(coef_probs[band[c]][pt]), ZERO_TOKEN, - (uint*)&(counts[band[c]][pt])); + add_token_no_extra(&t, (byte*)addr(ref coef_probs[band[c]][pt]), ZERO_TOKEN, + (uint*)addr(ref counts[band[c]][pt])); token_cache[scan[c]] = 0; ++c; @@ -322,7 +322,7 @@ private static void tokenize_b(int plane, int block, int row, int col, BLOCK_SIZ vp9_get_token_extra(v, &token, &extra); - add_token(&t, (byte*)&(coef_probs[band[c]][pt]), token, extra, (uint*)&(counts[band[c]][pt])); + add_token(&t, (byte*)addr(ref coef_probs[band[c]][pt]), token, extra, (uint*)addr(ref counts[band[c]][pt])); token_cache[scan[c]] = vp9_pt_energy_class[token]; ++c; @@ -330,8 +330,8 @@ private static void tokenize_b(int plane, int block, int row, int col, BLOCK_SIZ } if (c < tx_eob) { ++eob_branch[band[c]][pt]; - add_token_no_extra(&t, (byte*)&(coef_probs[band[c]][pt]), EOB_TOKEN, - (uint*)&(counts[band[c]][pt])); + add_token_no_extra(&t, (byte*)addr(ref coef_probs[band[c]][pt]), EOB_TOKEN, + (uint*)addr(ref counts[band[c]][pt])); } *tp = t; diff --git a/src/Codecs/SIPSorcery.VP9/encoder/vp9_tpl_model.cs b/src/Codecs/SIPSorcery.VP9/encoder/vp9_tpl_model.cs index 59d660177a..d658ca1f8c 100644 --- a/src/Codecs/SIPSorcery.VP9/encoder/vp9_tpl_model.cs +++ b/src/Codecs/SIPSorcery.VP9/encoder/vp9_tpl_model.cs @@ -90,9 +90,9 @@ private static int init_gop_frames_rc(VP9_COMP* cpi, GF_PICTURE* gf_picture, GF_ for (i = 0; i < 3; ++i) ref_table[i] = -REFS_PER_FRAME; gf_picture[0].frame = - &cm->buffer_pool + addr(ref cm->buffer_pool ->frame_bufs[cm->ref_frame_map[gf_group->update_ref_idx[0]]] - .buf; + .buf); ref_table[gf_group->update_ref_idx[0]] = 0; for (i = 0; i < 3; ++i) gf_picture[0].ref_frame[i] = -REFS_PER_FRAME; @@ -101,7 +101,7 @@ private static int init_gop_frames_rc(VP9_COMP* cpi, GF_PICTURE* gf_picture, GF_ for (i = 0; i < REFS_PER_FRAME; i++) { if (cm->ref_frame_map[i] != -1) { gf_picture[-i].frame = - &cm->buffer_pool->frame_bufs[cm->ref_frame_map[i]].buf; + addr(ref cm->buffer_pool->frame_bufs[cm->ref_frame_map[i]].buf); ref_table[i] = -i; } else { ref_table[i] = -REFS_PER_FRAME; @@ -136,7 +136,7 @@ private static int init_gop_frames_rc(VP9_COMP* cpi, GF_PICTURE* gf_picture, GF_ for (i = 0; i < REFS_PER_FRAME; i++) { if (cm->ref_frame_map[i] != -1) { gf_picture[-i].frame = - &cm->buffer_pool->frame_bufs[cm->ref_frame_map[i]].buf; + addr(ref cm->buffer_pool->frame_bufs[cm->ref_frame_map[i]].buf); ref_table[i] = -i; } else { ref_table[i] = -REFS_PER_FRAME; @@ -379,7 +379,7 @@ private static void init_tpl_stats(VP9_COMP* cpi) { int frame_idx; for (frame_idx = 0; frame_idx < MAX_ARF_GOP_SIZE; ++frame_idx) { - TplDepFrame* tpl_frame = &cpi->tpl_stats[frame_idx]; + TplDepFrame* tpl_frame = addr(ref cpi->tpl_stats[frame_idx]); memset(tpl_frame->tpl_stats_ptr, 0, tpl_frame->height * tpl_frame->width * sizeof(TplDepStats)); @@ -454,7 +454,7 @@ private static uint32_t motion_compensated_prediction(VP9_COMP* cpi, ThreadData* // Ignore mv costing by sending NULL pointer instead of cost array bestsme = cpi->find_fractional_mv_step( x, mv, &best_ref_mv1, cpi->common.allow_high_precision_mv, x->errorperbit, - &cpi->fn_ptr[bsize], 0, mv_sf->subpel_search_level, + addr(ref cpi->fn_ptr[bsize]), 0, mv_sf->subpel_search_level, cond_cost_list(cpi, cost_list), null, null, &distortion, &sse, null, 0, 0, USE_2_TAPS); @@ -627,8 +627,8 @@ private static void tpl_model_update(TplDepFrame* tpl_frame, TplDepStats* tpl_st private static void get_quantize_error(MACROBLOCK* x, int plane, tran_low_t* coeff, tran_low_t* qcoeff, tran_low_t* dqcoeff, TX_SIZE tx_size, int64_t* recon_error, int64_t* sse, uint16_t* eob) { MACROBLOCKD* xd = &x->e_mbd; - macroblock_plane* p = &x->plane[plane]; - macroblockd_plane* pd = &xd->plane[plane]; + macroblock_plane* p = addr(ref x->plane[plane]); + macroblockd_plane* pd = addr(ref xd->plane[plane]); ScanOrder* scan_order = &vp9_default_scan_orders[tx_size]; int pix_num = 1 << num_pels_log2_lookup[txsize_to_bsize[tx_size]]; int shift = tx_size == TX_32X32 ? 0 : 2; @@ -668,7 +668,7 @@ private static void set_mv_limits(VP9_COMMON* cm, MACROBLOCK* x, int mi_row, int private static int rate_estimator(tran_low_t* qcoeff, int eob, TX_SIZE tx_size) { - ScanOrder* scan_order = &vp9_scan_orders[tx_size][DCT_DCT]; + ScanOrder* scan_order = addr(ref vp9_scan_orders[tx_size][DCT_DCT]); int rate_cost = 1; int idx; Debug.Assert((1 << num_pels_log2_lookup[txsize_to_bsize[tx_size]]) >= eob); @@ -785,7 +785,7 @@ private static void mode_estimation(VP9_COMP* cpi, MACROBLOCK* x, MACROBLOCKD* x private static void mc_flow_dispenser(VP9_COMP* cpi, GF_PICTURE* gf_picture, int frame_idx, BLOCK_SIZE bsize) { - TplDepFrame* tpl_frame = &cpi->tpl_stats[frame_idx]; + TplDepFrame* tpl_frame = addr(ref cpi->tpl_stats[frame_idx]); VpxTplFrameStats* tpl_frame_stats_before_propagation = &cpi->tpl_gop_stats.frame_stats_list[frame_idx]; YV12_BUFFER_CONFIG* this_frame = gf_picture[frame_idx].frame; YV12_BUFFER_CONFIG** ref_frame = stackalloc YV12_BUFFER_CONFIG*[MAX_INTER_REF_FRAMES]; memset(ref_frame, 0, 3 * sizeof(YV12_BUFFER_CONFIG*)); @@ -951,7 +951,7 @@ internal static void vp9_estimate_tpl_qp_gop(VP9_COMP* cpi) { Debug.Assert((&cm->error)->setjmp != 0); encode_frame_decision.sb_params_list = (sb_params *)vpx_malloc(frame_height_sb * frame_width_sb * sizeof(sb_params)); if (encode_frame_decision.sb_params_list == null) vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR, "Failed to allocate encode_frame_decision.sb_params_list"); } for (idx = gf_index; idx <= gop_length; ++idx) { - TplDepFrame* tpl_frame = &cpi->tpl_stats[idx]; + TplDepFrame* tpl_frame = addr(ref cpi->tpl_stats[idx]); int target_rate = cpi->twopass.gf_group.bit_allocation[idx]; cpi->twopass.gf_group.index = (byte)idx; vp9_rc_set_frame_target(cpi, target_rate); diff --git a/src/Codecs/SIPSorcery.VP9/netstandard/inline_arrays.cs b/src/Codecs/SIPSorcery.VP9/netstandard/inline_arrays.cs new file mode 100644 index 0000000000..2f2e7f7131 --- /dev/null +++ b/src/Codecs/SIPSorcery.VP9/netstandard/inline_arrays.cs @@ -0,0 +1,725 @@ +//----------------------------------------------------------------------------- +// Filename: inline_arrays.cs +// +// Description: The netstandard2.1 build's form of vpx_ports/inline_arrays.cs. +// The generic arrays A are N T's, as there, but not [InlineArray]s: +// inline arrays are a .NET 8 runtime feature, and a runtime without it (Unity's +// Mono, which loads this build) would lay such a struct out as one element. +// Here A is made of power-of-two blocks of T (B1 holds one T, B2 two +// B1s, and so on), so it holds exactly N T's, contiguous, and an indexer +// gives a ref to element i as the inline array's element access does. +// +// The pointer arrays P are as in vpx_ports/inline_arrays.cs, which need +// nothing from the runtime. +// +// Generated by refharness/tools/port.py arrays-netstandard, from the same +// lengths as port.py arrays. +// +// Author(s): +// Claude Opus 5.5 (Anthropic AI assistant, model: claude-opus-5-5), commissioned by Aaron Clauson +// +// History: +// 04 Dec 2026 Claude Created, for the netstandard2.1 build. +// +// License: +// BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file. +//----------------------------------------------------------------------------- + +using System.Diagnostics.CodeAnalysis; + +namespace SIPSorcery.VP9; + + +internal struct B1 where T : unmanaged { private T _0; } +internal struct B2 where T : unmanaged { private B1 _0, _1; } +internal struct B4 where T : unmanaged { private B2 _0, _1; } +internal struct B8 where T : unmanaged { private B4 _0, _1; } +internal struct B16 where T : unmanaged { private B8 _0, _1; } +internal struct B32 where T : unmanaged { private B16 _0, _1; } +internal struct B64 where T : unmanaged { private B32 _0, _1; } +internal struct B128 where T : unmanaged { private B64 _0, _1; } +internal struct B256 where T : unmanaged { private B128 _0, _1; } +internal struct B512 where T : unmanaged { private B256 _0, _1; } +internal struct B1024 where T : unmanaged { private B512 _0, _1; } +internal struct B2048 where T : unmanaged { private B1024 _0, _1; } +internal struct B4096 where T : unmanaged { private B2048 _0, _1; } +internal struct B8192 where T : unmanaged { private B4096 _0, _1; } +internal struct B16384 where T : unmanaged { private B8192 _0, _1; } + +internal struct A1 where T : unmanaged +{ + private B1 _0; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 1); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A2 where T : unmanaged +{ + private B2 _0; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 2); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A3 where T : unmanaged +{ + private B2 _0; private B1 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 3); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A4 where T : unmanaged +{ + private B4 _0; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 4); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A5 where T : unmanaged +{ + private B4 _0; private B1 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 5); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A6 where T : unmanaged +{ + private B4 _0; private B2 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 6); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A7 where T : unmanaged +{ + private B4 _0; private B2 _1; private B1 _2; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 7); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A8 where T : unmanaged +{ + private B8 _0; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 8); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A9 where T : unmanaged +{ + private B8 _0; private B1 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 9); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A10 where T : unmanaged +{ + private B8 _0; private B2 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 10); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A11 where T : unmanaged +{ + private B8 _0; private B2 _1; private B1 _2; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 11); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A12 where T : unmanaged +{ + private B8 _0; private B4 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 12); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A13 where T : unmanaged +{ + private B8 _0; private B4 _1; private B1 _2; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 13); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A14 where T : unmanaged +{ + private B8 _0; private B4 _1; private B2 _2; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 14); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A15 where T : unmanaged +{ + private B8 _0; private B4 _1; private B2 _2; private B1 _3; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 15); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A16 where T : unmanaged +{ + private B16 _0; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 16); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A17 where T : unmanaged +{ + private B16 _0; private B1 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 17); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A18 where T : unmanaged +{ + private B16 _0; private B2 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 18); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A19 where T : unmanaged +{ + private B16 _0; private B2 _1; private B1 _2; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 19); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A20 where T : unmanaged +{ + private B16 _0; private B4 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 20); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A21 where T : unmanaged +{ + private B16 _0; private B4 _1; private B1 _2; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 21); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A22 where T : unmanaged +{ + private B16 _0; private B4 _1; private B2 _2; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 22); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A23 where T : unmanaged +{ + private B16 _0; private B4 _1; private B2 _2; private B1 _3; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 23); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A24 where T : unmanaged +{ + private B16 _0; private B8 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 24); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A25 where T : unmanaged +{ + private B16 _0; private B8 _1; private B1 _2; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 25); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A26 where T : unmanaged +{ + private B16 _0; private B8 _1; private B2 _2; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 26); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A27 where T : unmanaged +{ + private B16 _0; private B8 _1; private B2 _2; private B1 _3; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 27); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A28 where T : unmanaged +{ + private B16 _0; private B8 _1; private B4 _2; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 28); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A29 where T : unmanaged +{ + private B16 _0; private B8 _1; private B4 _2; private B1 _3; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 29); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A30 where T : unmanaged +{ + private B16 _0; private B8 _1; private B4 _2; private B2 _3; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 30); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A31 where T : unmanaged +{ + private B16 _0; private B8 _1; private B4 _2; private B2 _3; private B1 _4; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 31); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A32 where T : unmanaged +{ + private B32 _0; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 32); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A33 where T : unmanaged +{ + private B32 _0; private B1 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 33); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A34 where T : unmanaged +{ + private B32 _0; private B2 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 34); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A35 where T : unmanaged +{ + private B32 _0; private B2 _1; private B1 _2; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 35); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A36 where T : unmanaged +{ + private B32 _0; private B4 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 36); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A37 where T : unmanaged +{ + private B32 _0; private B4 _1; private B1 _2; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 37); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A38 where T : unmanaged +{ + private B32 _0; private B4 _1; private B2 _2; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 38); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A39 where T : unmanaged +{ + private B32 _0; private B4 _1; private B2 _2; private B1 _3; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 39); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A40 where T : unmanaged +{ + private B32 _0; private B8 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 40); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A41 where T : unmanaged +{ + private B32 _0; private B8 _1; private B1 _2; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 41); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A42 where T : unmanaged +{ + private B32 _0; private B8 _1; private B2 _2; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 42); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A43 where T : unmanaged +{ + private B32 _0; private B8 _1; private B2 _2; private B1 _3; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 43); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A44 where T : unmanaged +{ + private B32 _0; private B8 _1; private B4 _2; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 44); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A45 where T : unmanaged +{ + private B32 _0; private B8 _1; private B4 _2; private B1 _3; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 45); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A46 where T : unmanaged +{ + private B32 _0; private B8 _1; private B4 _2; private B2 _3; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 46); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A47 where T : unmanaged +{ + private B32 _0; private B8 _1; private B4 _2; private B2 _3; private B1 _4; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 47); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A48 where T : unmanaged +{ + private B32 _0; private B16 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 48); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A49 where T : unmanaged +{ + private B32 _0; private B16 _1; private B1 _2; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 49); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A50 where T : unmanaged +{ + private B32 _0; private B16 _1; private B2 _2; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 50); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A51 where T : unmanaged +{ + private B32 _0; private B16 _1; private B2 _2; private B1 _3; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 51); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A52 where T : unmanaged +{ + private B32 _0; private B16 _1; private B4 _2; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 52); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A53 where T : unmanaged +{ + private B32 _0; private B16 _1; private B4 _2; private B1 _3; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 53); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A54 where T : unmanaged +{ + private B32 _0; private B16 _1; private B4 _2; private B2 _3; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 54); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A55 where T : unmanaged +{ + private B32 _0; private B16 _1; private B4 _2; private B2 _3; private B1 _4; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 55); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A56 where T : unmanaged +{ + private B32 _0; private B16 _1; private B8 _2; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 56); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A57 where T : unmanaged +{ + private B32 _0; private B16 _1; private B8 _2; private B1 _3; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 57); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A58 where T : unmanaged +{ + private B32 _0; private B16 _1; private B8 _2; private B2 _3; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 58); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A59 where T : unmanaged +{ + private B32 _0; private B16 _1; private B8 _2; private B2 _3; private B1 _4; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 59); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A60 where T : unmanaged +{ + private B32 _0; private B16 _1; private B8 _2; private B4 _3; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 60); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A61 where T : unmanaged +{ + private B32 _0; private B16 _1; private B8 _2; private B4 _3; private B1 _4; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 61); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A62 where T : unmanaged +{ + private B32 _0; private B16 _1; private B8 _2; private B4 _3; private B2 _4; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 62); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A63 where T : unmanaged +{ + private B32 _0; private B16 _1; private B8 _2; private B4 _3; private B2 _4; private B1 _5; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 63); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A64 where T : unmanaged +{ + private B64 _0; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 64); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A65 where T : unmanaged +{ + private B64 _0; private B1 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 65); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A66 where T : unmanaged +{ + private B64 _0; private B2 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 66); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A68 where T : unmanaged +{ + private B64 _0; private B4 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 68); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A72 where T : unmanaged +{ + private B64 _0; private B8 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 72); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A80 where T : unmanaged +{ + private B64 _0; private B16 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 80); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A81 where T : unmanaged +{ + private B64 _0; private B16 _1; private B1 _2; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 81); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A88 where T : unmanaged +{ + private B64 _0; private B16 _1; private B8 _2; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 88); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A96 where T : unmanaged +{ + private B64 _0; private B32 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 96); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A100 where T : unmanaged +{ + private B64 _0; private B32 _1; private B4 _2; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 100); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A120 where T : unmanaged +{ + private B64 _0; private B32 _1; private B16 _2; private B8 _3; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 120); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A128 where T : unmanaged +{ + private B128 _0; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 128); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A130 where T : unmanaged +{ + private B128 _0; private B2 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 130); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A135 where T : unmanaged +{ + private B128 _0; private B4 _1; private B2 _2; private B1 _3; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 135); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A144 where T : unmanaged +{ + private B128 _0; private B16 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 144); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A160 where T : unmanaged +{ + private B128 _0; private B32 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 160); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A192 where T : unmanaged +{ + private B128 _0; private B64 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 192); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A200 where T : unmanaged +{ + private B128 _0; private B64 _1; private B8 _2; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 200); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A252 where T : unmanaged +{ + private B128 _0; private B64 _1; private B32 _2; private B16 _3; private B8 _4; private B4 _5; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 252); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A255 where T : unmanaged +{ + private B128 _0; private B64 _1; private B32 _2; private B16 _3; private B8 _4; private B4 _5; private B2 _6; private B1 _7; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 255); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A256 where T : unmanaged +{ + private B256 _0; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 256); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A257 where T : unmanaged +{ + private B256 _0; private B1 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 257); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A288 where T : unmanaged +{ + private B256 _0; private B32 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 288); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A320 where T : unmanaged +{ + private B256 _0; private B64 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 320); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A384 where T : unmanaged +{ + private B256 _0; private B128 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 384); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A512 where T : unmanaged +{ + private B512 _0; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 512); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A576 where T : unmanaged +{ + private B512 _0; private B64 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 576); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A1024 where T : unmanaged +{ + private B1024 _0; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 1024); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A1056 where T : unmanaged +{ + private B1024 _0; private B32 _1; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 1056); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A2048 where T : unmanaged +{ + private B2048 _0; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 2048); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A4096 where T : unmanaged +{ + private B4096 _0; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 4096); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal struct A32767 where T : unmanaged +{ + private B16384 _0; private B8192 _1; private B4096 _2; private B2048 _3; private B1024 _4; private B512 _5; private B256 _6; private B128 _7; private B64 _8; private B32 _9; private B16 _10; private B8 _11; private B4 _12; private B2 _13; private B1 _14; + [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 32767); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } } +} + +internal unsafe struct P2 where T : unmanaged +{ + private T* e0, e1; + public ref T* this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 2); fixed (T** p = &e0) return ref p[i]; } } +} + +internal unsafe struct P3 where T : unmanaged +{ + private T* e0, e1, e2; + public ref T* this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 3); fixed (T** p = &e0) return ref p[i]; } } +} + +internal unsafe struct P4 where T : unmanaged +{ + private T* e0, e1, e2, e3; + public ref T* this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 4); fixed (T** p = &e0) return ref p[i]; } } +} + +internal unsafe struct P5 where T : unmanaged +{ + private T* e0, e1, e2, e3, e4; + public ref T* this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 5); fixed (T** p = &e0) return ref p[i]; } } +} + +internal unsafe struct P6 where T : unmanaged +{ + private T* e0, e1, e2, e3, e4, e5; + public ref T* this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 6); fixed (T** p = &e0) return ref p[i]; } } +} + +internal unsafe struct P7 where T : unmanaged +{ + private T* e0, e1, e2, e3, e4, e5, e6; + public ref T* this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 7); fixed (T** p = &e0) return ref p[i]; } } +} + +internal unsafe struct P8 where T : unmanaged +{ + private T* e0, e1, e2, e3, e4, e5, e6, e7; + public ref T* this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 8); fixed (T** p = &e0) return ref p[i]; } } +} + +internal unsafe struct P9 where T : unmanaged +{ + private T* e0, e1, e2, e3, e4, e5, e6, e7, e8; + public ref T* this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 9); fixed (T** p = &e0) return ref p[i]; } } +} + +internal unsafe struct P10 where T : unmanaged +{ + private T* e0, e1, e2, e3, e4, e5, e6, e7, e8, e9; + public ref T* this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 10); fixed (T** p = &e0) return ref p[i]; } } +} + +internal unsafe struct P11 where T : unmanaged +{ + private T* e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10; + public ref T* this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 11); fixed (T** p = &e0) return ref p[i]; } } +} + +internal unsafe struct P12 where T : unmanaged +{ + private T* e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11; + public ref T* this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 12); fixed (T** p = &e0) return ref p[i]; } } +} + +internal unsafe struct P13 where T : unmanaged +{ + private T* e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12; + public ref T* this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 13); fixed (T** p = &e0) return ref p[i]; } } +} + +internal unsafe struct P14 where T : unmanaged +{ + private T* e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13; + public ref T* this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 14); fixed (T** p = &e0) return ref p[i]; } } +} + +internal unsafe struct P15 where T : unmanaged +{ + private T* e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14; + public ref T* this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 15); fixed (T** p = &e0) return ref p[i]; } } +} + +internal unsafe struct P16 where T : unmanaged +{ + private T* e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15; + public ref T* this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 16); fixed (T** p = &e0) return ref p[i]; } } +} + +internal unsafe struct P25 where T : unmanaged +{ + private T* e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24; + public ref T* this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 25); fixed (T** p = &e0) return ref p[i]; } } +} + +internal unsafe struct P32 where T : unmanaged +{ + private T* e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31; + public ref T* this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 32); fixed (T** p = &e0) return ref p[i]; } } +} + +internal unsafe struct P64 where T : unmanaged +{ + private T* e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, e49, e50, e51, e52, e53, e54, e55, e56, e57, e58, e59, e60, e61, e62, e63; + public ref T* this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < 64); fixed (T** p = &e0) return ref p[i]; } } +} diff --git a/src/Codecs/SIPSorcery.VP9/netstandard/polyfills.cs b/src/Codecs/SIPSorcery.VP9/netstandard/polyfills.cs new file mode 100644 index 0000000000..efe474f991 --- /dev/null +++ b/src/Codecs/SIPSorcery.VP9/netstandard/polyfills.cs @@ -0,0 +1,122 @@ +//----------------------------------------------------------------------------- +// Filename: polyfills.cs +// +// Description: The newer .NET pieces the port uses that netstandard2.1 lacks, +// for the netstandard2.1 build (the one Unity's Mono loads). Only that build +// compiles this folder; the .NET 8 and later builds use the runtime's own. +// - SkipLocalsInitAttribute and UnscopedRefAttribute, which the compiler +// recognises by name. +// - NativeMemory, over Marshal.AllocHGlobal. +// - BitOperations' bit counts, in software. +// +// Author(s): +// Claude Opus 5.5 (Anthropic AI assistant, model: claude-opus-5-5), commissioned by Aaron Clauson +// +// History: +// 04 Dec 2026 Claude Created, for the netstandard2.1 build. +// +// License: +// BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file. +//----------------------------------------------------------------------------- + +namespace System.Runtime.CompilerServices +{ + [AttributeUsage(AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | + AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event, + Inherited = false)] + internal sealed class SkipLocalsInitAttribute : Attribute + { + } +} + +namespace System.Diagnostics.CodeAnalysis +{ + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property, + AllowMultiple = false, Inherited = false)] + internal sealed class UnscopedRefAttribute : Attribute + { + } +} + +namespace System.Runtime.InteropServices +{ + /// The members of .NET 6's NativeMemory the port uses. + internal static unsafe class NativeMemory + { + public static void* Alloc(nuint byteCount) => + (void*)Marshal.AllocHGlobal((nint)(byteCount == 0 ? 1 : byteCount)); + + public static void* AllocZeroed(nuint byteCount) + { + void* p = Alloc(byteCount); + Clear(p, byteCount); + return p; + } + + public static void Free(void* ptr) + { + if (ptr != null) + { + Marshal.FreeHGlobal((IntPtr)ptr); + } + } + + /// + /// Over-allocates by the alignment and keeps the block's own address just below the + /// aligned one, for AlignedFree. alignment must be a power of two. + /// + public static void* AlignedAlloc(nuint byteCount, nuint alignment) + { + nuint total = byteCount + alignment - 1 + (nuint)sizeof(void*); + byte* block = (byte*)Alloc(total); + nuint aligned = ((nuint)block + (nuint)sizeof(void*) + alignment - 1) & ~(alignment - 1); + ((void**)aligned)[-1] = block; + return (void*)aligned; + } + + public static void AlignedFree(void* ptr) + { + if (ptr != null) + { + Free(((void**)ptr)[-1]); + } + } + + public static void Clear(void* ptr, nuint byteCount) + { + byte* p = (byte*)ptr; + while (byteCount > uint.MaxValue) + { + Unsafe.InitBlockUnaligned(p, 0, uint.MaxValue); + p += uint.MaxValue; + byteCount -= uint.MaxValue; + } + Unsafe.InitBlockUnaligned(p, 0, (uint)byteCount); + } + } +} + +namespace System.Numerics +{ + /// The members of .NET Core 3's BitOperations the port uses, with their results for 0. + internal static class BitOperations + { + /// The index of the highest set bit; 0 for 0. + public static int Log2(uint value) + { + int r = 0; + if (value >= 1u << 16) { value >>= 16; r += 16; } + if (value >= 1u << 8) { value >>= 8; r += 8; } + if (value >= 1u << 4) { value >>= 4; r += 4; } + if (value >= 1u << 2) { value >>= 2; r += 2; } + if (value >= 1u << 1) { r += 1; } + return r; + } + + public static int LeadingZeroCount(uint value) => value == 0 ? 32 : 31 - Log2(value); + + public static int TrailingZeroCount(uint value) => value == 0 ? 32 : Log2(value & (uint)-(int)value); + + public static int TrailingZeroCount(int value) => TrailingZeroCount((uint)value); + } +} diff --git a/src/Codecs/SIPSorcery.VP9/netstandard/simd_c.cs b/src/Codecs/SIPSorcery.VP9/netstandard/simd_c.cs new file mode 100644 index 0000000000..230eed5d90 --- /dev/null +++ b/src/Codecs/SIPSorcery.VP9/netstandard/simd_c.cs @@ -0,0 +1,243 @@ +//----------------------------------------------------------------------------- +// Filename: simd_c.cs +// +// Description: The netstandard2.1 build's stand-ins for the SIMD kernels. +// netstandard2.1 has no System.Runtime.Intrinsics, so that build leaves simd/*.cs +// out. The ported code still calls each rtcd entry's NAME_simd (simd.py points +// the entries at them), so here every NAME_simd, in the class of the same name +// as its simd/*.cs file, calls NAME_c: what the SIMD kernels do when rtcd.vpx_simd +// is false. The streams are the same either way. +// +// Generated by refharness/tools/simd.py fallback from simd/*.cs: run it again +// after adding a SIMD kernel. +// +// Author(s): +// Claude Opus 5.5 (Anthropic AI assistant, model: claude-opus-5-5), commissioned by Aaron Clauson +// +// History: +// 04 Dec 2026 Claude Created, for the netstandard2.1 build. +// +// License: +// BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file. +//----------------------------------------------------------------------------- + +namespace SIPSorcery.VP9; + +internal static unsafe class avg_simd +{ + internal static uint vpx_avg_8x8_simd(uint8_t* s, int p) => vpx_avg_8x8_c(s, p); + internal static uint vpx_avg_4x4_simd(uint8_t* s, int p) => vpx_avg_4x4_c(s, p); + internal static void vpx_minmax_8x8_simd(uint8_t* s, int p, uint8_t* d, int dp, int* min, int* max) => vpx_minmax_8x8_c(s, p, d, dp, min, max); + internal static void vpx_hadamard_8x8_simd(int16_t* src_diff, ptrdiff_t src_stride, tran_low_t* coeff) => vpx_hadamard_8x8_c(src_diff, src_stride, coeff); + internal static void vpx_hadamard_16x16_simd(int16_t* src_diff, ptrdiff_t src_stride, tran_low_t* coeff) => vpx_hadamard_16x16_c(src_diff, src_stride, coeff); + internal static void vpx_hadamard_32x32_simd(int16_t* src_diff, ptrdiff_t src_stride, tran_low_t* coeff) => vpx_hadamard_32x32_c(src_diff, src_stride, coeff); + internal static int vpx_satd_simd(tran_low_t* coeff, int length) => vpx_satd_c(coeff, length); + internal static void vpx_int_pro_row_simd(int16_t* hbuf, uint8_t* @ref, int ref_stride, int height) => vpx_int_pro_row_c(hbuf, @ref, ref_stride, height); + internal static int16_t vpx_int_pro_col_simd(uint8_t* @ref, int width) => vpx_int_pro_col_c(@ref, width); + internal static int vpx_vector_var_simd(int16_t* @ref, int16_t* src, int bwl) => vpx_vector_var_c(@ref, src, bwl); +} + +internal static unsafe class intrapred_simd +{ + internal static void vpx_dc_predictor_4x4_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_dc_predictor_4x4_c(dst, stride, above, left); + internal static void vpx_dc_predictor_8x8_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_dc_predictor_8x8_c(dst, stride, above, left); + internal static void vpx_dc_predictor_16x16_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_dc_predictor_16x16_c(dst, stride, above, left); + internal static void vpx_dc_predictor_32x32_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_dc_predictor_32x32_c(dst, stride, above, left); + internal static void vpx_dc_top_predictor_4x4_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_dc_top_predictor_4x4_c(dst, stride, above, left); + internal static void vpx_dc_top_predictor_8x8_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_dc_top_predictor_8x8_c(dst, stride, above, left); + internal static void vpx_dc_top_predictor_16x16_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_dc_top_predictor_16x16_c(dst, stride, above, left); + internal static void vpx_dc_top_predictor_32x32_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_dc_top_predictor_32x32_c(dst, stride, above, left); + internal static void vpx_dc_left_predictor_4x4_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_dc_left_predictor_4x4_c(dst, stride, above, left); + internal static void vpx_dc_left_predictor_8x8_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_dc_left_predictor_8x8_c(dst, stride, above, left); + internal static void vpx_dc_left_predictor_16x16_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_dc_left_predictor_16x16_c(dst, stride, above, left); + internal static void vpx_dc_left_predictor_32x32_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_dc_left_predictor_32x32_c(dst, stride, above, left); + internal static void vpx_dc_128_predictor_4x4_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_dc_128_predictor_4x4_c(dst, stride, above, left); + internal static void vpx_dc_128_predictor_8x8_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_dc_128_predictor_8x8_c(dst, stride, above, left); + internal static void vpx_dc_128_predictor_16x16_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_dc_128_predictor_16x16_c(dst, stride, above, left); + internal static void vpx_dc_128_predictor_32x32_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_dc_128_predictor_32x32_c(dst, stride, above, left); + internal static void vpx_v_predictor_4x4_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_v_predictor_4x4_c(dst, stride, above, left); + internal static void vpx_v_predictor_8x8_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_v_predictor_8x8_c(dst, stride, above, left); + internal static void vpx_v_predictor_16x16_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_v_predictor_16x16_c(dst, stride, above, left); + internal static void vpx_v_predictor_32x32_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_v_predictor_32x32_c(dst, stride, above, left); + internal static void vpx_h_predictor_4x4_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_h_predictor_4x4_c(dst, stride, above, left); + internal static void vpx_h_predictor_8x8_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_h_predictor_8x8_c(dst, stride, above, left); + internal static void vpx_h_predictor_16x16_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_h_predictor_16x16_c(dst, stride, above, left); + internal static void vpx_h_predictor_32x32_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_h_predictor_32x32_c(dst, stride, above, left); + internal static void vpx_tm_predictor_4x4_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_tm_predictor_4x4_c(dst, stride, above, left); + internal static void vpx_tm_predictor_8x8_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_tm_predictor_8x8_c(dst, stride, above, left); + internal static void vpx_tm_predictor_16x16_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_tm_predictor_16x16_c(dst, stride, above, left); + internal static void vpx_tm_predictor_32x32_simd(uint8_t* dst, ptrdiff_t stride, uint8_t* above, uint8_t* left) => vpx_tm_predictor_32x32_c(dst, stride, above, left); +} + +internal static unsafe class loopfilter_simd +{ + internal static void vpx_lpf_horizontal_4_simd(uint8_t* s, int pitch, uint8_t* blimit, uint8_t* limit, uint8_t* thresh) => vpx_lpf_horizontal_4_c(s, pitch, blimit, limit, thresh); + internal static void vpx_lpf_horizontal_4_dual_simd(uint8_t* s, int pitch, uint8_t* blimit0, uint8_t* limit0, uint8_t* thresh0, uint8_t* blimit1, uint8_t* limit1, uint8_t* thresh1) => vpx_lpf_horizontal_4_dual_c(s, pitch, blimit0, limit0, thresh0, blimit1, limit1, thresh1); + internal static void vpx_lpf_horizontal_8_simd(uint8_t* s, int pitch, uint8_t* blimit, uint8_t* limit, uint8_t* thresh) => vpx_lpf_horizontal_8_c(s, pitch, blimit, limit, thresh); + internal static void vpx_lpf_horizontal_8_dual_simd(uint8_t* s, int pitch, uint8_t* blimit0, uint8_t* limit0, uint8_t* thresh0, uint8_t* blimit1, uint8_t* limit1, uint8_t* thresh1) => vpx_lpf_horizontal_8_dual_c(s, pitch, blimit0, limit0, thresh0, blimit1, limit1, thresh1); + internal static void vpx_lpf_horizontal_16_simd(uint8_t* s, int pitch, uint8_t* blimit, uint8_t* limit, uint8_t* thresh) => vpx_lpf_horizontal_16_c(s, pitch, blimit, limit, thresh); + internal static void vpx_lpf_horizontal_16_dual_simd(uint8_t* s, int pitch, uint8_t* blimit, uint8_t* limit, uint8_t* thresh) => vpx_lpf_horizontal_16_dual_c(s, pitch, blimit, limit, thresh); + internal static void vpx_lpf_vertical_4_simd(uint8_t* s, int pitch, uint8_t* blimit, uint8_t* limit, uint8_t* thresh) => vpx_lpf_vertical_4_c(s, pitch, blimit, limit, thresh); + internal static void vpx_lpf_vertical_4_dual_simd(uint8_t* s, int pitch, uint8_t* blimit0, uint8_t* limit0, uint8_t* thresh0, uint8_t* blimit1, uint8_t* limit1, uint8_t* thresh1) => vpx_lpf_vertical_4_dual_c(s, pitch, blimit0, limit0, thresh0, blimit1, limit1, thresh1); + internal static void vpx_lpf_vertical_8_simd(uint8_t* s, int pitch, uint8_t* blimit, uint8_t* limit, uint8_t* thresh) => vpx_lpf_vertical_8_c(s, pitch, blimit, limit, thresh); + internal static void vpx_lpf_vertical_8_dual_simd(uint8_t* s, int pitch, uint8_t* blimit0, uint8_t* limit0, uint8_t* thresh0, uint8_t* blimit1, uint8_t* limit1, uint8_t* thresh1) => vpx_lpf_vertical_8_dual_c(s, pitch, blimit0, limit0, thresh0, blimit1, limit1, thresh1); + internal static void vpx_lpf_vertical_16_simd(uint8_t* s, int pitch, uint8_t* blimit, uint8_t* limit, uint8_t* thresh) => vpx_lpf_vertical_16_c(s, pitch, blimit, limit, thresh); + internal static void vpx_lpf_vertical_16_dual_simd(uint8_t* s, int pitch, uint8_t* blimit, uint8_t* limit, uint8_t* thresh) => vpx_lpf_vertical_16_dual_c(s, pitch, blimit, limit, thresh); +} + +internal static unsafe class quantize_simd +{ + internal static void vp9_quantize_fp_simd(tran_low_t* coeff_ptr, intptr_t n_coeffs, macroblock_plane* mb_plane, tran_low_t* qcoeff_ptr, tran_low_t* dqcoeff_ptr, int16_t* dequant_ptr, uint16_t* eob_ptr, ScanOrder* scan_order) => vp9_quantize_fp_c(coeff_ptr, n_coeffs, mb_plane, qcoeff_ptr, dqcoeff_ptr, dequant_ptr, eob_ptr, scan_order); + internal static void vp9_quantize_fp_32x32_simd(tran_low_t* coeff_ptr, intptr_t n_coeffs, macroblock_plane* mb_plane, tran_low_t* qcoeff_ptr, tran_low_t* dqcoeff_ptr, int16_t* dequant_ptr, uint16_t* eob_ptr, ScanOrder* scan_order) => vp9_quantize_fp_32x32_c(coeff_ptr, n_coeffs, mb_plane, qcoeff_ptr, dqcoeff_ptr, dequant_ptr, eob_ptr, scan_order); + internal static void vpx_quantize_b_simd(tran_low_t* coeff_ptr, intptr_t n_coeffs, macroblock_plane* mb_plane, tran_low_t* qcoeff_ptr, tran_low_t* dqcoeff_ptr, int16_t* dequant_ptr, uint16_t* eob_ptr, ScanOrder* scan_order) => vpx_quantize_b_c(coeff_ptr, n_coeffs, mb_plane, qcoeff_ptr, dqcoeff_ptr, dequant_ptr, eob_ptr, scan_order); + internal static void vpx_quantize_b_32x32_simd(tran_low_t* coeff_ptr, macroblock_plane* mb_plane, tran_low_t* qcoeff_ptr, tran_low_t* dqcoeff_ptr, int16_t* dequant_ptr, uint16_t* eob_ptr, ScanOrder* scan_order) => vpx_quantize_b_32x32_c(coeff_ptr, mb_plane, qcoeff_ptr, dqcoeff_ptr, dequant_ptr, eob_ptr, scan_order); + internal static int64_t vp9_block_error_simd(tran_low_t* coeff, tran_low_t* dqcoeff, intptr_t block_size, int64_t* ssz) => vp9_block_error_c(coeff, dqcoeff, block_size, ssz); + internal static int64_t vp9_block_error_fp_simd(tran_low_t* coeff, tran_low_t* dqcoeff, int block_size) => vp9_block_error_fp_c(coeff, dqcoeff, block_size); + internal static void vpx_subtract_block_simd(int rows, int cols, int16_t* diff_ptr, ptrdiff_t diff_stride, uint8_t* src_ptr, ptrdiff_t src_stride, uint8_t* pred_ptr, ptrdiff_t pred_stride) => vpx_subtract_block_c(rows, cols, diff_ptr, diff_stride, src_ptr, src_stride, pred_ptr, pred_stride); +} + +internal static unsafe class txfm_simd +{ + internal static void vpx_fdct8x8_simd(int16_t* input, tran_low_t* output, int stride) => vpx_fdct8x8_c(input, output, stride); + internal static void vpx_fdct4x4_simd(int16_t* input, tran_low_t* output, int stride) => vpx_fdct4x4_c(input, output, stride); + internal static void vp9_fht4x4_simd(int16_t* input, tran_low_t* output, int stride, int tx_type) => vp9_fht4x4_c(input, output, stride, tx_type); + internal static void vp9_fht8x8_simd(int16_t* input, tran_low_t* output, int stride, int tx_type) => vp9_fht8x8_c(input, output, stride, tx_type); + internal static void vpx_idct8x8_64_add_simd(tran_low_t* input, uint8_t* dest, int stride) => vpx_idct8x8_64_add_c(input, dest, stride); + internal static void vpx_idct8x8_12_add_simd(tran_low_t* input, uint8_t* dest, int stride) => vpx_idct8x8_12_add_c(input, dest, stride); + internal static void vpx_idct8x8_1_add_simd(tran_low_t* input, uint8_t* dest, int stride) => vpx_idct8x8_1_add_c(input, dest, stride); + internal static void vpx_idct4x4_16_add_simd(tran_low_t* input, uint8_t* dest, int stride) => vpx_idct4x4_16_add_c(input, dest, stride); + internal static void vpx_idct4x4_1_add_simd(tran_low_t* input, uint8_t* dest, int stride) => vpx_idct4x4_1_add_c(input, dest, stride); +} + +internal static unsafe class vpx_convolve_simd +{ + internal static void vpx_convolve8_horiz_simd(uint8_t* src, ptrdiff_t src_stride, uint8_t* dst, ptrdiff_t dst_stride, InterpKernel* filter, int x0_q4, int x_step_q4, int y0_q4, int y_step_q4, int w, int h) => vpx_convolve8_horiz_c(src, src_stride, dst, dst_stride, filter, x0_q4, x_step_q4, y0_q4, y_step_q4, w, h); + internal static void vpx_convolve8_avg_horiz_simd(uint8_t* src, ptrdiff_t src_stride, uint8_t* dst, ptrdiff_t dst_stride, InterpKernel* filter, int x0_q4, int x_step_q4, int y0_q4, int y_step_q4, int w, int h) => vpx_convolve8_avg_horiz_c(src, src_stride, dst, dst_stride, filter, x0_q4, x_step_q4, y0_q4, y_step_q4, w, h); + internal static void vpx_convolve8_vert_simd(uint8_t* src, ptrdiff_t src_stride, uint8_t* dst, ptrdiff_t dst_stride, InterpKernel* filter, int x0_q4, int x_step_q4, int y0_q4, int y_step_q4, int w, int h) => vpx_convolve8_vert_c(src, src_stride, dst, dst_stride, filter, x0_q4, x_step_q4, y0_q4, y_step_q4, w, h); + internal static void vpx_convolve8_avg_vert_simd(uint8_t* src, ptrdiff_t src_stride, uint8_t* dst, ptrdiff_t dst_stride, InterpKernel* filter, int x0_q4, int x_step_q4, int y0_q4, int y_step_q4, int w, int h) => vpx_convolve8_avg_vert_c(src, src_stride, dst, dst_stride, filter, x0_q4, x_step_q4, y0_q4, y_step_q4, w, h); + internal static void vpx_convolve8_simd(uint8_t* src, ptrdiff_t src_stride, uint8_t* dst, ptrdiff_t dst_stride, InterpKernel* filter, int x0_q4, int x_step_q4, int y0_q4, int y_step_q4, int w, int h) => vpx_convolve8_c(src, src_stride, dst, dst_stride, filter, x0_q4, x_step_q4, y0_q4, y_step_q4, w, h); + internal static void vpx_convolve8_avg_simd(uint8_t* src, ptrdiff_t src_stride, uint8_t* dst, ptrdiff_t dst_stride, InterpKernel* filter, int x0_q4, int x_step_q4, int y0_q4, int y_step_q4, int w, int h) => vpx_convolve8_avg_c(src, src_stride, dst, dst_stride, filter, x0_q4, x_step_q4, y0_q4, y_step_q4, w, h); + internal static void vpx_convolve_copy_simd(uint8_t* src, ptrdiff_t src_stride, uint8_t* dst, ptrdiff_t dst_stride, InterpKernel* filter, int x0_q4, int x_step_q4, int y0_q4, int y_step_q4, int w, int h) => vpx_convolve_copy_c(src, src_stride, dst, dst_stride, filter, x0_q4, x_step_q4, y0_q4, y_step_q4, w, h); + internal static void vpx_convolve_avg_simd(uint8_t* src, ptrdiff_t src_stride, uint8_t* dst, ptrdiff_t dst_stride, InterpKernel* filter, int x0_q4, int x_step_q4, int y0_q4, int y_step_q4, int w, int h) => vpx_convolve_avg_c(src, src_stride, dst, dst_stride, filter, x0_q4, x_step_q4, y0_q4, y_step_q4, w, h); +} + +internal static unsafe class vpx_sad_simd +{ + internal static uint vpx_sad64x64_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad64x64_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static uint vpx_sad64x64_avg_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint8_t* second_pred) => vpx_sad64x64_avg_c(src_ptr, src_stride, ref_ptr, ref_stride, second_pred); + internal static uint vpx_sad_skip_64x64_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad_skip_64x64_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static void vpx_sad64x64x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad64x64x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static void vpx_sad_skip_64x64x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad_skip_64x64x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static uint vpx_sad64x32_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad64x32_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static uint vpx_sad64x32_avg_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint8_t* second_pred) => vpx_sad64x32_avg_c(src_ptr, src_stride, ref_ptr, ref_stride, second_pred); + internal static uint vpx_sad_skip_64x32_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad_skip_64x32_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static void vpx_sad64x32x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad64x32x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static void vpx_sad_skip_64x32x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad_skip_64x32x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static uint vpx_sad32x64_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad32x64_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static uint vpx_sad32x64_avg_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint8_t* second_pred) => vpx_sad32x64_avg_c(src_ptr, src_stride, ref_ptr, ref_stride, second_pred); + internal static uint vpx_sad_skip_32x64_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad_skip_32x64_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static void vpx_sad32x64x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad32x64x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static void vpx_sad_skip_32x64x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad_skip_32x64x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static uint vpx_sad32x32_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad32x32_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static uint vpx_sad32x32_avg_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint8_t* second_pred) => vpx_sad32x32_avg_c(src_ptr, src_stride, ref_ptr, ref_stride, second_pred); + internal static uint vpx_sad_skip_32x32_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad_skip_32x32_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static void vpx_sad32x32x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad32x32x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static void vpx_sad_skip_32x32x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad_skip_32x32x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static uint vpx_sad32x16_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad32x16_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static uint vpx_sad32x16_avg_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint8_t* second_pred) => vpx_sad32x16_avg_c(src_ptr, src_stride, ref_ptr, ref_stride, second_pred); + internal static uint vpx_sad_skip_32x16_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad_skip_32x16_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static void vpx_sad32x16x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad32x16x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static void vpx_sad_skip_32x16x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad_skip_32x16x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static uint vpx_sad16x32_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad16x32_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static uint vpx_sad16x32_avg_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint8_t* second_pred) => vpx_sad16x32_avg_c(src_ptr, src_stride, ref_ptr, ref_stride, second_pred); + internal static uint vpx_sad_skip_16x32_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad_skip_16x32_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static void vpx_sad16x32x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad16x32x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static void vpx_sad_skip_16x32x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad_skip_16x32x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static uint vpx_sad16x16_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad16x16_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static uint vpx_sad16x16_avg_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint8_t* second_pred) => vpx_sad16x16_avg_c(src_ptr, src_stride, ref_ptr, ref_stride, second_pred); + internal static uint vpx_sad_skip_16x16_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad_skip_16x16_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static void vpx_sad16x16x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad16x16x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static void vpx_sad_skip_16x16x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad_skip_16x16x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static uint vpx_sad16x8_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad16x8_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static uint vpx_sad16x8_avg_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint8_t* second_pred) => vpx_sad16x8_avg_c(src_ptr, src_stride, ref_ptr, ref_stride, second_pred); + internal static uint vpx_sad_skip_16x8_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad_skip_16x8_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static void vpx_sad16x8x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad16x8x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static void vpx_sad_skip_16x8x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad_skip_16x8x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static uint vpx_sad8x16_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad8x16_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static uint vpx_sad8x16_avg_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint8_t* second_pred) => vpx_sad8x16_avg_c(src_ptr, src_stride, ref_ptr, ref_stride, second_pred); + internal static uint vpx_sad_skip_8x16_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad_skip_8x16_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static void vpx_sad8x16x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad8x16x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static void vpx_sad_skip_8x16x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad_skip_8x16x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static uint vpx_sad8x8_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad8x8_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static uint vpx_sad8x8_avg_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint8_t* second_pred) => vpx_sad8x8_avg_c(src_ptr, src_stride, ref_ptr, ref_stride, second_pred); + internal static uint vpx_sad_skip_8x8_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad_skip_8x8_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static void vpx_sad8x8x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad8x8x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static void vpx_sad_skip_8x8x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad_skip_8x8x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static uint vpx_sad8x4_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad8x4_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static uint vpx_sad8x4_avg_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint8_t* second_pred) => vpx_sad8x4_avg_c(src_ptr, src_stride, ref_ptr, ref_stride, second_pred); + internal static uint vpx_sad_skip_8x4_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad_skip_8x4_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static void vpx_sad8x4x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad8x4x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static void vpx_sad_skip_8x4x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad_skip_8x4x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static uint vpx_sad4x8_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad4x8_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static uint vpx_sad4x8_avg_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint8_t* second_pred) => vpx_sad4x8_avg_c(src_ptr, src_stride, ref_ptr, ref_stride, second_pred); + internal static uint vpx_sad_skip_4x8_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad_skip_4x8_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static void vpx_sad4x8x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad4x8x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static void vpx_sad_skip_4x8x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad_skip_4x8x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static uint vpx_sad4x4_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad4x4_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static uint vpx_sad4x4_avg_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint8_t* second_pred) => vpx_sad4x4_avg_c(src_ptr, src_stride, ref_ptr, ref_stride, second_pred); + internal static uint vpx_sad_skip_4x4_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_sad_skip_4x4_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static void vpx_sad4x4x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad4x4x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); + internal static void vpx_sad_skip_4x4x4d_simd(uint8_t* src_ptr, int src_stride, uint8_t** ref_array, int ref_stride, uint32_t* sad_array) => vpx_sad_skip_4x4x4d_c(src_ptr, src_stride, ref_array, ref_stride, sad_array); +} + +internal static unsafe class vpx_variance_simd +{ + internal static uint32_t vpx_get4x4sse_cs_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride) => vpx_get4x4sse_cs_c(src_ptr, src_stride, ref_ptr, ref_stride); + internal static uint32_t vpx_get_mb_ss_simd(int16_t* src_ptr) => vpx_get_mb_ss_c(src_ptr); + internal static void vpx_comp_avg_pred_simd(uint8_t* comp_pred, uint8_t* pred, int width, int height, uint8_t* @ref, int ref_stride) => vpx_comp_avg_pred_c(comp_pred, pred, width, height, @ref, ref_stride); + internal static uint32_t vpx_variance64x64_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_variance64x64_c(src_ptr, src_stride, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_variance64x64_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_sub_pixel_variance64x64_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_avg_variance64x64_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse, uint8_t* second_pred) => vpx_sub_pixel_avg_variance64x64_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse, second_pred); + internal static uint32_t vpx_variance64x32_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_variance64x32_c(src_ptr, src_stride, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_variance64x32_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_sub_pixel_variance64x32_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_avg_variance64x32_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse, uint8_t* second_pred) => vpx_sub_pixel_avg_variance64x32_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse, second_pred); + internal static uint32_t vpx_variance32x64_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_variance32x64_c(src_ptr, src_stride, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_variance32x64_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_sub_pixel_variance32x64_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_avg_variance32x64_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse, uint8_t* second_pred) => vpx_sub_pixel_avg_variance32x64_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse, second_pred); + internal static uint32_t vpx_variance32x32_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_variance32x32_c(src_ptr, src_stride, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_variance32x32_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_sub_pixel_variance32x32_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_avg_variance32x32_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse, uint8_t* second_pred) => vpx_sub_pixel_avg_variance32x32_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse, second_pred); + internal static uint32_t vpx_variance32x16_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_variance32x16_c(src_ptr, src_stride, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_variance32x16_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_sub_pixel_variance32x16_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_avg_variance32x16_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse, uint8_t* second_pred) => vpx_sub_pixel_avg_variance32x16_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse, second_pred); + internal static uint32_t vpx_variance16x32_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_variance16x32_c(src_ptr, src_stride, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_variance16x32_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_sub_pixel_variance16x32_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_avg_variance16x32_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse, uint8_t* second_pred) => vpx_sub_pixel_avg_variance16x32_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse, second_pred); + internal static uint32_t vpx_variance16x16_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_variance16x16_c(src_ptr, src_stride, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_variance16x16_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_sub_pixel_variance16x16_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_avg_variance16x16_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse, uint8_t* second_pred) => vpx_sub_pixel_avg_variance16x16_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse, second_pred); + internal static uint32_t vpx_variance16x8_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_variance16x8_c(src_ptr, src_stride, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_variance16x8_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_sub_pixel_variance16x8_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_avg_variance16x8_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse, uint8_t* second_pred) => vpx_sub_pixel_avg_variance16x8_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse, second_pred); + internal static uint32_t vpx_variance8x16_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_variance8x16_c(src_ptr, src_stride, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_variance8x16_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_sub_pixel_variance8x16_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_avg_variance8x16_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse, uint8_t* second_pred) => vpx_sub_pixel_avg_variance8x16_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse, second_pred); + internal static uint32_t vpx_variance8x8_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_variance8x8_c(src_ptr, src_stride, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_variance8x8_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_sub_pixel_variance8x8_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_avg_variance8x8_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse, uint8_t* second_pred) => vpx_sub_pixel_avg_variance8x8_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse, second_pred); + internal static uint32_t vpx_variance8x4_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_variance8x4_c(src_ptr, src_stride, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_variance8x4_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_sub_pixel_variance8x4_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_avg_variance8x4_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse, uint8_t* second_pred) => vpx_sub_pixel_avg_variance8x4_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse, second_pred); + internal static uint32_t vpx_variance4x8_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_variance4x8_c(src_ptr, src_stride, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_variance4x8_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_sub_pixel_variance4x8_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_avg_variance4x8_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse, uint8_t* second_pred) => vpx_sub_pixel_avg_variance4x8_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse, second_pred); + internal static uint32_t vpx_variance4x4_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_variance4x4_c(src_ptr, src_stride, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_variance4x4_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_sub_pixel_variance4x4_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_sub_pixel_avg_variance4x4_simd(uint8_t* src_ptr, int src_stride, int x_offset, int y_offset, uint8_t* ref_ptr, int ref_stride, uint32_t* sse, uint8_t* second_pred) => vpx_sub_pixel_avg_variance4x4_c(src_ptr, src_stride, x_offset, y_offset, ref_ptr, ref_stride, sse, second_pred); + internal static uint32_t vpx_mse16x16_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_mse16x16_c(src_ptr, src_stride, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_mse16x8_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_mse16x8_c(src_ptr, src_stride, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_mse8x16_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_mse8x16_c(src_ptr, src_stride, ref_ptr, ref_stride, sse); + internal static uint32_t vpx_mse8x8_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint32_t* sse) => vpx_mse8x8_c(src_ptr, src_stride, ref_ptr, ref_stride, sse); + internal static void vpx_get16x16var_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint32_t* sse, int* sum) => vpx_get16x16var_c(src_ptr, src_stride, ref_ptr, ref_stride, sse, sum); + internal static void vpx_get8x8var_simd(uint8_t* src_ptr, int src_stride, uint8_t* ref_ptr, int ref_stride, uint32_t* sse, int* sum) => vpx_get8x8var_c(src_ptr, src_stride, ref_ptr, ref_stride, sse, sum); +} diff --git a/src/Codecs/SIPSorcery.VP9/vp9_cx_iface.cs b/src/Codecs/SIPSorcery.VP9/vp9_cx_iface.cs index c75baffd31..2954f0d84c 100644 --- a/src/Codecs/SIPSorcery.VP9/vp9_cx_iface.cs +++ b/src/Codecs/SIPSorcery.VP9/vp9_cx_iface.cs @@ -1597,7 +1597,7 @@ private static vpx_codec_err_t ctrl_set_svc_parameters(vp9_cx_alg_priv* ctx, va_ for (sl = 0; sl < cpi->svc.number_spatial_layers; ++sl) { for (tl = 0; tl < cpi->svc.number_temporal_layers; ++tl) { int layer = ((sl) * ( cpi->svc.number_temporal_layers) + ( tl)); - LAYER_CONTEXT* lc = &cpi->svc.layer_context[layer]; + LAYER_CONTEXT* lc = addr(ref cpi->svc.layer_context[layer]); lc->max_q = @params->max_quantizers[layer]; lc->min_q = @params->min_quantizers[layer]; // Checks on valid scale factors. diff --git a/src/Codecs/SIPSorcery.VP9/vpx_ports/crt.cs b/src/Codecs/SIPSorcery.VP9/vpx_ports/crt.cs index 8b3f89294b..d40bc3abb9 100644 --- a/src/Codecs/SIPSorcery.VP9/vpx_ports/crt.cs +++ b/src/Codecs/SIPSorcery.VP9/vpx_ports/crt.cs @@ -100,7 +100,11 @@ public static void vp9_zero(ref T s) where T : unmanaged [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double log(double x) => Math.Log(x); [MethodImpl(MethodImplOptions.AggressiveInlining)] +#if NETSTANDARD2_1 + public static double log2(double x) => Math.Log(x) / Math.Log(2.0); // no Math.Log2 there; unused by the port +#else public static double log2(double x) => Math.Log2(x); +#endif [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double log10(double x) => Math.Log10(x); /// MathF calls the CRT's float logf, as the C build does. @@ -135,6 +139,16 @@ public static void vp9_zero(ref T s) where T : unmanaged public static void* malloc(nuint size) => NativeMemory.Alloc(size); + /// + /// C's &x where x is an element of an inline array (or a member of one), as fixerr.py + /// writes it. On .NET 8 and later &s->a[i] is allowed as it is, but the netstandard2.1 + /// build's arrays (netstandard/inline_arrays.cs) are structs with an indexer, whose + /// result C# won't take the address of. The port's structs live in unmanaged memory or + /// on the stack, so the address is as stable as C's. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T* addr(ref T x) where T : unmanaged => (T*)Unsafe.AsPointer(ref x); + public static void free(void* p) => NativeMemory.Free(p); // : only the external rate control's optional log file uses a FILE*, diff --git a/src/Codecs/SIPSorcery.VP9/vpx_ports/rtcd.cs b/src/Codecs/SIPSorcery.VP9/vpx_ports/rtcd.cs index a0f8fbd980..ee05bef29c 100644 --- a/src/Codecs/SIPSorcery.VP9/vpx_ports/rtcd.cs +++ b/src/Codecs/SIPSorcery.VP9/vpx_ports/rtcd.cs @@ -54,8 +54,14 @@ internal static unsafe class rtcd /// the JIT folds every kernel's test of it away. Each SIMD kernel gives exactly what its C /// kernel gives, so the streams don't depend on it. /// +#if NETSTANDARD2_1 + // netstandard2.1 has no System.Runtime.Intrinsics: that build has no SIMD kernels + // (netstandard/simd_c.cs calls the C ones). + internal static readonly bool vpx_simd = false; +#else internal static readonly bool vpx_simd = System.Runtime.Intrinsics.Vector128.IsHardwareAccelerated && !(AppContext.TryGetSwitch(DISABLE_SIMD_SWITCH, out bool disabled) && disabled); +#endif internal static void vpx_dsp_rtcd() { } diff --git a/src/Codecs/SIPSorcery.VP9/vpx_ports/worker_threads.cs b/src/Codecs/SIPSorcery.VP9/vpx_ports/worker_threads.cs index 3691b46f1b..8c18fa0fd2 100644 --- a/src/Codecs/SIPSorcery.VP9/vpx_ports/worker_threads.cs +++ b/src/Codecs/SIPSorcery.VP9/vpx_ports/worker_threads.cs @@ -182,9 +182,49 @@ private void Run() private static readonly nint s_tileWorkerHook = (nint)(VPxWorkerHook)(&vp9_decodeframe.tile_worker_hook); private static readonly nint s_packHook = (nint)(VPxWorkerHook)(&pack_hook); +#if NETSTANDARD2_1 + // Mono, the runtime that loads the netstandard2.1 build (Unity's), gives &method a jump + // trampoline until the method is compiled and its code once it is, and each call site keeps + // the address it got when the site itself was compiled. So a worker's hook can come with + // either address: matching only the ones above, a hook taken after its method had run went + // unrecognised, ran on the launching thread, and the loop filter's rows waited for each + // other forever. The addresses above were taken when this class was first used, as the + // encoder or decoder started; these are the compiled code (GetFunctionPointer compiles it). + private static readonly (nint code, nint hook)[] s_hookCode = + { + (Code(typeof(vp9_ethread), nameof(vp9_ethread.enc_worker_hook)), s_encWorkerHook), + (Code(typeof(vp9_ethread), nameof(vp9_ethread.enc_row_mt_worker_hook)), s_encRowMtWorkerHook), + (Code(typeof(vp9_bitstream), nameof(vp9_bitstream.encode_tile_worker)), s_encodeTileWorker), + (Code(typeof(vp9_thread_common), nameof(vp9_thread_common.loop_filter_row_worker)), s_loopFilterRowWorker), + (Code(typeof(vp9_loopfilter), nameof(vp9_loopfilter.vp9_loop_filter_worker)), s_loopFilterWorker), + (Code(typeof(vp9_decodeframe), nameof(vp9_decodeframe.tile_worker_hook)), s_tileWorkerHook), + (Code(typeof(worker_threads), nameof(pack_hook)), s_packHook), + }; + + private static nint Code(Type type, string name) => + type.GetMethod(name, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | + System.Reflection.BindingFlags.NonPublic).MethodHandle.GetFunctionPointer(); + + /// The hook's address as the statics above have it. + private static nint Canonical(nint h) + { + foreach (var (code, hook) in s_hookCode) + { + if (h == code) + { + return hook; + } + } + return h; + } +#endif + private static bool Threaded(VPxWorker* worker) { nint h = (nint)worker->hook; +#if NETSTANDARD2_1 + h = Canonical(h); +#endif if (h == s_tileWorkerHook) { // With lpf_mt_opt the tile workers also share out the loop filter's diff --git a/test/SIPSorcery.VP9.UnitTest/StackFrameTests.cs b/test/SIPSorcery.VP9.UnitTest/StackFrameTests.cs new file mode 100644 index 0000000000..f65d11f003 --- /dev/null +++ b/test/SIPSorcery.VP9.UnitTest/StackFrameTests.cs @@ -0,0 +1,106 @@ +//----------------------------------------------------------------------------- +// Filename: StackFrameTests.cs +// +// Description: Checks the translated code's IL for reads through a pointer +// whose value is thrown away (C's (void)p->f, a constant 0 times p->f, a local +// nothing reads). Roslyn keeps such a read, for its null check, as a load of +// the whole struct then pop. CoreCLR's JIT turns that into a null check, but +// Mono (Unity) copies the struct onto the stack: VP9_COMP is over 900 KB, so +// one of these overflowed a 1 MB thread stack on the first inter frame. +// refharness/tools/patches.py discarded_reads() removes them on regeneration. +// +// Author(s): +// Claude Opus 5.5 (Anthropic AI assistant, model: claude-opus-5-5), commissioned by Aaron Clauson +// +// History: +// 04 Dec 2026 Claude Created. +// +// License: +// BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file. +//----------------------------------------------------------------------------- + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Reflection.Emit; +using System.Runtime.CompilerServices; +using Xunit; + +namespace SIPSorcery.VP9.UnitTest; + +public class StackFrameTests +{ + /// The biggest struct a discarded load may copy. The ones left are a few + /// bytes (an MV, a TileInfo), from unused locals libvpx declares. + private const int MAX_DISCARDED_LOAD = 1024; + + private static readonly Dictionary s_opCodes = typeof(OpCodes) + .GetFields(BindingFlags.Public | BindingFlags.Static) + .Select(f => (OpCode)f.GetValue(null)!) + .ToDictionary(o => o.Value); + + private static readonly MethodInfo s_sizeOf = typeof(Unsafe).GetMethod(nameof(Unsafe.SizeOf))!; + + [Fact] + public void NoLargeStructLoadIsDiscarded() + { + var found = new List(); + const BindingFlags all = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | + BindingFlags.Instance | BindingFlags.DeclaredOnly; + foreach (var type in typeof(VP9Codec).Assembly.GetTypes()) + { + foreach (MethodBase method in type.GetMethods(all).Cast().Concat(type.GetConstructors(all))) + { + var il = method.GetMethodBody()?.GetILAsByteArray(); + if (il == null) + { + continue; + } + foreach (var (offset, struct_) in DiscardedLoads(method, il)) + { + int size = (int)s_sizeOf.MakeGenericMethod(struct_).Invoke(null, null)!; + if (size > MAX_DISCARDED_LOAD) + { + found.Add($"{type.Name}.{method.Name} IL_{offset:x4}: {struct_.Name}, {size} bytes"); + } + } + } + } + Assert.True(found.Count == 0, "Whole-struct loads thrown away (see patches.py discarded_reads):\n" + + string.Join("\n", found)); + } + + /// Each ldobj of a struct that the next instruction pops. + private static IEnumerable<(int offset, Type struct_)> DiscardedLoads(MethodBase method, byte[] il) + { + int pos = 0; + (int offset, int token)? lastLdobj = null; + while (pos < il.Length) + { + int start = pos; + short value = il[pos] == 0xFE ? (short)(0xFE00 | il[pos + 1]) : il[pos]; + pos += il[pos] == 0xFE ? 2 : 1; + var op = s_opCodes[value]; + if (op == OpCodes.Pop && lastLdobj is { } ld) + { + var t = method.Module.ResolveType(ld.token, method.DeclaringType?.GetGenericArguments(), + method.IsGenericMethod ? method.GetGenericArguments() : null); + if (t.IsValueType && !t.ContainsGenericParameters) + { + yield return (ld.offset, t); + } + } + lastLdobj = op == OpCodes.Ldobj ? (start, BitConverter.ToInt32(il, pos)) : null; + pos += op.OperandType switch + { + OperandType.InlineNone => 0, + OperandType.ShortInlineBrTarget or OperandType.ShortInlineI or OperandType.ShortInlineVar => 1, + OperandType.InlineVar => 2, + OperandType.InlineI8 or OperandType.InlineR => 8, + OperandType.InlineSwitch => 4 + 4 * BitConverter.ToInt32(il, pos), + _ => 4, + }; + } + } +} diff --git a/thirdparty/libvpx-vp9-dotnet-port/README.md b/thirdparty/libvpx-vp9-dotnet-port/README.md index 6667df0293..88276826b3 100644 --- a/thirdparty/libvpx-vp9-dotnet-port/README.md +++ b/thirdparty/libvpx-vp9-dotnet-port/README.md @@ -86,19 +86,19 @@ whole port regenerates. Python 3. | `gen_config.py` | Writes `config/rt` and `config/full`. | | `fixes.py` | The port's deliberate changes to libvpx, made in the C: writes the fixed copies the reference build compiles (`refharness/fixes/`), and applies the same edits to the pruned tree before translation. | | `prune.py` | Resolves the configuration's `#if`s (its `KNOWN` table), leaving only the code the port translates. Conditions on unknown macros are kept. | -| `port.py` | Which libvpx files make which `.cs` file and class, in groups (`api`, `dspdec`, `scale`, `common`, `decoder`, `dspenc`, `encoder`, and `dec`, `enc` and `all` made of them). `port.py sources` lists every file to prune; `port.py arrays` writes `vpx_ports/inline_arrays.cs`. | +| `port.py` | Which libvpx files make which `.cs` file and class, in groups (`api`, `dspdec`, `scale`, `common`, `decoder`, `dspenc`, `encoder`, and `dec`, `enc` and `all` made of them). `port.py sources` lists every file to prune; `port.py arrays` writes `vpx_ports/inline_arrays.cs`, and `port.py arrays-netstandard` the netstandard2.1 build's `netstandard/inline_arrays.cs` (the same arrays as nested structs, without `[InlineArray]`). | | `c2cs.py` | The translator. `scan` builds a registry of the pruned C's types, structs, macros, constants and functions; translation turns each C file into C# using it (types, inline arrays for C arrays, function pointers, macro expansion, static tables, ...). | -| `patches.py` | The fixes that are particular to one place in libvpx, applied before (`_pre`) and after (`_post`) the generic passes. | +| `patches.py` | The fixes that are particular to one place in libvpx, applied before (`_pre`) and after (`_post`) the generic passes. `discarded_reads` (after) drops reads through a pointer whose value is thrown away (`(void)p->f`, `0 * p->f`): Roslyn compiles each to a load of the whole struct, which Mono copies onto the stack (937 KB for `VP9_COMP`). `StackFrameTests` checks the IL for any that come back. | | `cmacros.py` | Rewrites `CHECK_MEM_ERROR` and `setjmp`/`longjmp` error handling into C# (`try`/`catch` of `VpxInternalError`). | -| `simd.py` | Points the pruned tree's rtcd headers at the SIMD kernels: each `NAME_simd` in `src/Codecs/SIPSorcery.VP9/simd/*.cs` becomes the `#define` for rtcd entry `NAME`, as upstream's `rtcd.pl` would for a CPU with the instructions. Run it before the scan. | -| `fixerr.py` | Builds the project and fixes the compile errors that come from C's implicit conversions (integer promotion, `int` ↔ `bool`, pointer arithmetic) by inserting the casts C does implicitly, repeating until the build is clean. An unassigned local (CS0165) gets `= default`, or `Unsafe.SkipInit` for a struct, which `default` would zero on every call. | +| `simd.py` | Points the pruned tree's rtcd headers at the SIMD kernels: each `NAME_simd` in `src/Codecs/SIPSorcery.VP9/simd/*.cs` becomes the `#define` for rtcd entry `NAME`, as upstream's `rtcd.pl` would for a CPU with the instructions. Run it before the scan. `simd.py fallback` writes the netstandard2.1 build's `netstandard/simd_c.cs`, each `NAME_simd` calling `NAME_c`. | +| `fixerr.py` | Builds the project and fixes the compile errors that come from C's implicit conversions (integer promotion, `int` ↔ `bool`, pointer arithmetic) by inserting the casts C does implicitly, repeating until the build is clean. An unassigned local (CS0165) gets `= default`, or `Unsafe.SkipInit` for a struct, which `default` would zero on every call. Then it builds netstandard2.1, where an inline array's element is an indexer's `ref` rather than a variable: `&a[i]` (CS0212) becomes `addr(ref a[i])`, and a fixed buffer in one (CS1666) is reached through `addr(ref a[i])->buf`. | | `regen.py` | All of the above for one group. | | `mktrace.py` | Writes the instrumented decoder sources for `vp9trace`. | Regenerating the port (Git Bash, paths relative to this folder): ``` -python refharness/tools/prune.py C:/dev/libvpx $(python refharness/tools/port.py sources) +python refharness/tools/prune.py C:/dev/libvpx $(python refharness/tools/port.py sources | tr -d '\r') cp refharness/config/rt/vpx_config.h refharness/config/rt/*_rtcd.h python refharness/tools/fixes.py python refharness/tools/simd.py ../../src/Codecs/SIPSorcery.VP9 @@ -110,8 +110,8 @@ python refharness/tools/regen.py ../../src/Codecs/SIPSorcery `TypeAliases.cs` (`dec` was used to bring the decoder up before the encoder existed; with the encoder in the tree, regenerate `all`). The hand-written files, `VP9Codec.cs`, `VP9NetVideoEndPoint.cs`, `GlobalUsings.cs`, `vpx_ports/*` (the C runtime, -`vpx_ports/mem.h` in C# and the worker threads), `simd/*` and `vpx_mem`, are -left alone, as are +`vpx_ports/mem.h` in C# and the worker threads), `simd/*`, `vpx_mem` and +`netstandard/polyfills.cs` (the APIs netstandard2.1 lacks), are left alone, as are `vp9_dx_iface.cs` and `vpx/vpx_codec.cs` (`patches.HAND_OWNED`). The result builds without errors and passes the tests; a change that breaks that is a tool bug to fix in the tools, not in the C#. diff --git a/thirdparty/libvpx-vp9-dotnet-port/refharness/tools/fixerr.py b/thirdparty/libvpx-vp9-dotnet-port/refharness/tools/fixerr.py index 409869a49b..444ab6e634 100644 --- a/thirdparty/libvpx-vp9-dotnet-port/refharness/tools/fixerr.py +++ b/thirdparty/libvpx-vp9-dotnet-port/refharness/tools/fixerr.py @@ -18,8 +18,14 @@ CS0031/CS0221 constant range -> unchecked((T)(expr)) CS0030 (T)bool -> (T)((expr) ? 1 : 0) +and, from the netstandard2.1 build, whose inline arrays are structs with an indexer: + + CS0212 &a[i] (an inline array element, or a member of one) -> addr(ref a[i]) + CS1666 a[i].buf (a fixed size buffer in an element) -> addr(ref a[i])->buf + Usage: fixerr.py [max_iterations] [file filter substring] -Builds net8.0 only with end locations, applies the fixes, repeats. +Builds net8.0 with end locations, applies the fixes, repeats; then the same for +netstandard2.1's CS0212 and CS1666, if the project targets it. """ import collections import os @@ -34,8 +40,8 @@ UNSIGNED = {'byte', 'ushort', 'uint', 'ulong', 'nuint'} -def build(csproj): - p = subprocess.run(['dotnet', 'build', csproj, '-f', 'net8.0', '-p:ErrorEndLocation=true', +def build(csproj, tfm='net8.0'): + p = subprocess.run(['dotnet', 'build', csproj, '-f', tfm, '-p:ErrorEndLocation=true', '-nologo', '-v:q', '-clp:NoSummary;ErrorsOnly'], capture_output=True, text=True, encoding='utf-8', errors='replace') errs = [] @@ -259,8 +265,45 @@ def join(a, b): return None +def strip_parens(e): + e = e.strip() + while balanced_parens(e): + e = e[1:-1].strip() + return e + + +def address_of(text): + """CS0212, from the netstandard2.1 build: &E where E is an element of an inline array, or a + member of one. There the arrays are structs with an indexer (netstandard/inline_arrays.cs), + whose result C# won't take the address of. crt.addr(ref E) is the same pointer on every build.""" + e = text.strip() + if not e.startswith('&') or e.startswith('&&'): + return None + return 'addr(ref %s)' % strip_parens(e[1:]) + + +def fixed_buffer_member(text): + """CS1666, from the netstandard2.1 build: E.buf, buf a fixed size buffer in an inline array + element E, which C# won't read through the indexer's result: addr(ref E)->buf.""" + e = text.strip() + d = 0 + for i in range(len(e) - 1, -1, -1): + ch = e[i] + if ch in ')]': + d += 1 + elif ch in '([': + d -= 1 + elif ch == '.' and d == 0: + return 'addr(ref %s)->%s' % (strip_parens(e[:i]), e[i + 1:]) + return None + + def fix_one(e, text): code, msg = e['code'], e['msg'] + if code == 'CS0212': + return address_of(text) + if code == 'CS1666': + return fixed_buffer_member(text) m = re.match(r"Cannot implicitly convert type '(.+?)' to '(.+?)'", msg) if code in ('CS0266', 'CS0029') and m: x, y = short_type(m.group(1)), short_type(m.group(2)) @@ -480,16 +523,47 @@ def cleanup(path): open(f, 'w', encoding='utf-8', newline='\n').write(s2) +# The netstandard2.1 build (the one Unity's Mono loads) has no inline arrays, so it reports +# these at the places the net8.0 build accepts; fixing them leaves both building. +NETSTANDARD_CODES = ('CS0212', 'CS1666') + + +def targets(csproj): + m = re.search(r'([^<]*)<', open(csproj, encoding='utf-8').read()) + return m.group(1).split(';') if m else [] + + def main(): csproj = sys.argv[1] max_iter = int(sys.argv[2]) if len(sys.argv) > 2 else 30 filt = sys.argv[3] if len(sys.argv) > 3 else None + fix_loop(csproj, 'net8.0', max_iter, filt) + if 'netstandard2.1' in targets(csproj): + fix_loop(csproj, 'netstandard2.1', max_iter, filt, NETSTANDARD_CODES) + cleanup(os.path.dirname(os.path.abspath(csproj))) + remaining = 0 + for tfm in ['net8.0'] + (['netstandard2.1'] if 'netstandard2.1' in targets(csproj) else []): + errs, out = build(csproj, tfm) + if filt: + errs = [e for e in errs if filt in e['file']] + for e in errs[:400]: + print('%s(%d,%d): %s %s' % (e['file'], e['l1'], e['c1'], e['code'], e['msg'])) + print('remaining (%s): %d' % (tfm, len(errs))) + remaining += len(errs) + print('remaining: %d' % remaining) + + +def fix_loop(csproj, tfm, max_iter, filt, codes=None): + """Builds tfm and applies fixes until it builds or nothing more can be fixed. codes, if + given, limits the fixes to those error codes.""" for it in range(max_iter): - errs, out = build(csproj) + errs, out = build(csproj, tfm) if filt: errs = [e for e in errs if filt in e['file']] + if codes: + errs = [e for e in errs if e['code'] in codes] counts = collections.Counter(e['code'] for e in errs) - print('iter %d: %d errors %s' % (it, len(errs), dict(counts.most_common(12))), flush=True) + print('%s iter %d: %d errors %s' % (tfm, it, len(errs), dict(counts.most_common(12))), flush=True) if not errs: break byfile = collections.defaultdict(list) @@ -536,13 +610,6 @@ def main(): print(' applied %d fixes' % applied, flush=True) if applied == 0: break - cleanup(os.path.dirname(os.path.abspath(csproj))) - errs, out = build(csproj) - if filt: - errs = [e for e in errs if filt in e['file']] - for e in errs[:400]: - print('%s(%d,%d): %s %s' % (e['file'], e['l1'], e['c1'], e['code'], e['msg'])) - print('remaining: %d' % len(errs)) if __name__ == '__main__': diff --git a/thirdparty/libvpx-vp9-dotnet-port/refharness/tools/patches.py b/thirdparty/libvpx-vp9-dotnet-port/refharness/tools/patches.py index d16df1ee8c..6dcb24cd22 100644 --- a/thirdparty/libvpx-vp9-dotnet-port/refharness/tools/patches.py +++ b/thirdparty/libvpx-vp9-dotnet-port/refharness/tools/patches.py @@ -634,6 +634,29 @@ def warnings(): sub(f, ' if (sad_fn_ptr.sdf != fn_ptr->sdf) {\n', ' if (skip_row_sad) {\n') +def discarded_reads(): + """Reads through a pointer whose value is thrown away: C's (void)p->f, a constant 0 times + p->f (LAYER_IDS_TO_IDX(0, ...), RDCOST(..., 0, ...)) and a local nothing reads. Roslyn + keeps such a read for its null check, as a load of the whole struct then pop. CoreCLR's + JIT makes that a null check, but Mono (Unity) copies the struct onto the stack: VP9_COMP + is 937 KB, so one in calc_active_worst_quality_one_pass_cbr overflowed a 1 MB thread stack + on the first inter frame. The reads do nothing in C, so they go. The unit tests check the + IL for any that come back (StackFrameTests).""" + removed = 0 + for f in all_cs(): + if f.startswith('netstandard'): + continue + s = read(f) + s2, n1 = re.subn(r'^[ \t]*_ = (?:\w+->[\w.>-]+|\*\w+);[ \t]*\n', '', s, flags=re.M) + s2, n2 = re.subn(r'(\(0\)|\(\(int64_t\)\( 0\)\)) \* \(\s*\w+->[\w.]+\)', r'\1', s2) + if s2 != s: + write(f, s2) + removed += n1 + n2 + if removed != 13: + raise SystemExit('discarded_reads: expected 13 reads, removed %d' % removed) + sub('common/vp9_thread_common.cs', ' int num_tile_cols = 1 << cm->log2_tile_cols;\n', '') + + def dec_post(): addr_fixed() @@ -641,6 +664,7 @@ def dec_post(): def all_post(): addr_fixed() warnings() + discarded_reads() def dbg_hooks(): diff --git a/thirdparty/libvpx-vp9-dotnet-port/refharness/tools/port.py b/thirdparty/libvpx-vp9-dotnet-port/refharness/tools/port.py index 145f7fc8b0..d28a77c992 100644 --- a/thirdparty/libvpx-vp9-dotnet-port/refharness/tools/port.py +++ b/thirdparty/libvpx-vp9-dotnet-port/refharness/tools/port.py @@ -4,6 +4,8 @@ port.py gen [--force] port.py usings (print the global using static lines) port.py arrays (write the generic inline array types) + port.py arrays-netstandard + (the same for the netstandard2.1 build, without [InlineArray]) port.py sources (print the libvpx files prune.py prunes) Each entry: (output path under src/Codecs/SIPSorcery.VP9, class name, inputs). A @@ -254,11 +256,7 @@ def all_classes(): P_SIZES = list(range(2, 17)) + [25, 32, 64] -def arrays(out): - lines = [ARRAY_HEADER] - for n in A_SIZES: - lines.append('[InlineArray(%d)] internal struct A%d where T : unmanaged { private T _e; }' % (n, n)) - lines.append('') +def pointer_arrays(lines): for n in P_SIZES: fields = ', '.join('e%d' % i for i in range(n)) lines.append('internal unsafe struct P%d where T : unmanaged' % n) @@ -267,6 +265,79 @@ def arrays(out): lines.append(' public ref T* this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert((uint)i < %d); fixed (T** p = &e0) return ref p[i]; } }' % n) lines.append('}') lines.append('') + + +def arrays(out): + lines = [ARRAY_HEADER] + for n in A_SIZES: + lines.append('[InlineArray(%d)] internal struct A%d where T : unmanaged { private T _e; }' % (n, n)) + lines.append('') + pointer_arrays(lines) + open(out, 'w', encoding='utf-8', newline='\n').write('\n'.join(lines)) + + +NS_ARRAY_HEADER = '''//----------------------------------------------------------------------------- +// Filename: inline_arrays.cs +// +// Description: The netstandard2.1 build's form of vpx_ports/inline_arrays.cs. +// The generic arrays A are N T's, as there, but not [InlineArray]s: +// inline arrays are a .NET 8 runtime feature, and a runtime without it (Unity's +// Mono, which loads this build) would lay such a struct out as one element. +// Here A is made of power-of-two blocks of T (B1 holds one T, B2 two +// B1s, and so on), so it holds exactly N T's, contiguous, and an indexer +// gives a ref to element i as the inline array's element access does. +// +// The pointer arrays P are as in vpx_ports/inline_arrays.cs, which need +// nothing from the runtime. +// +// Generated by refharness/tools/port.py arrays-netstandard, from the same +// lengths as port.py arrays. +// +// Author(s): +// Claude Opus 5.5 (Anthropic AI assistant, model: claude-opus-5-5), commissioned by Aaron Clauson +// +// History: +// 04 Dec 2026 Claude Created, for the netstandard2.1 build. +// +// License: +// BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file. +//----------------------------------------------------------------------------- + +using System.Diagnostics.CodeAnalysis; + +namespace SIPSorcery.VP9; + +''' + + +def arrays_netstandard(out): + """netstandard/inline_arrays.cs: A without the runtime's inline arrays.""" + lines = [NS_ARRAY_HEADER] + top = 1 + while top * 2 <= max(A_SIZES): + top *= 2 + lines.append('internal struct B1 where T : unmanaged { private T _0; }') + b = 2 + while b <= top: + lines.append('internal struct B%d where T : unmanaged { private B%d _0, _1; }' % (b, b // 2)) + b *= 2 + lines.append('') + for n in A_SIZES: + blocks = [] + b = top + while b >= 1: + if n & b: + blocks.append('B%d _%d;' % (b, len(blocks))) + b //= 2 + lines.append('internal struct A%d where T : unmanaged' % n) + lines.append('{') + lines.append(' private %s' % ' private '.join(blocks)) + lines.append(' [UnscopedRef] public readonly ref T this[int i] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get ' + '{ Debug.Assert((uint)i < %d); return ref Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), i); } }' + % (n, n)) + lines.append('}') + lines.append('') + pointer_arrays(lines) open(out, 'w', encoding='utf-8', newline='\n').write('\n'.join(lines)) @@ -278,6 +349,8 @@ def arrays(out): print('global using static SIPSorcery.VP9.%s;' % c) elif sys.argv[1] == 'arrays': arrays(sys.argv[2]) + elif sys.argv[1] == 'arrays-netstandard': + arrays_netstandard(sys.argv[2]) elif sys.argv[1] == 'sources': for f in sources(): print(f) diff --git a/thirdparty/libvpx-vp9-dotnet-port/refharness/tools/regen.py b/thirdparty/libvpx-vp9-dotnet-port/refharness/tools/regen.py index 7748683d58..7b53c9fd9d 100644 --- a/thirdparty/libvpx-vp9-dotnet-port/refharness/tools/regen.py +++ b/thirdparty/libvpx-vp9-dotnet-port/refharness/tools/regen.py @@ -2,6 +2,7 @@ """regen.py - regenerates the translated C# of one port.py group end to end: port.py gen (all files of the group except patches.HAND_OWNED) + port.py arrays-netstandard, simd.py fallback (netstandard/, the netstandard2.1 build's) patches.py _pre, cmacros.py, fixerr.py, patches.py _post [--trace: trace/cs/dbg.cs and TraceTests.cs copied in, then patches.py dbg_hooks] @@ -43,6 +44,12 @@ def repo_root(start): for f in patches.HAND_OWNED: shutil.copy(os.path.join(keep, f.replace('/', '_')), os.path.join(root, f)) shutil.rmtree(keep) +# The netstandard2.1 build's stand-ins: the inline arrays without [InlineArray], and each SIMD +# kernel's name calling its C kernel. +subprocess.run([sys.executable, os.path.join(TOOLS, 'port.py'), 'arrays-netstandard', + os.path.join(root, 'netstandard', 'inline_arrays.cs')], check=True) +subprocess.run([sys.executable, os.path.join(TOOLS, 'simd.py'), 'fallback', root, + os.path.join(root, 'netstandard', 'simd_c.cs')], check=True, stdout=subprocess.DEVNULL) if group == 'all': # the C typedef names (with the encoder in, none are left out) subprocess.run([sys.executable, '-I', os.path.join(TOOLS, 'c2cs.py'), 'aliases', reg, diff --git a/thirdparty/libvpx-vp9-dotnet-port/refharness/tools/simd.py b/thirdparty/libvpx-vp9-dotnet-port/refharness/tools/simd.py index 85578049cc..ec270bdc84 100644 --- a/thirdparty/libvpx-vp9-dotnet-port/refharness/tools/simd.py +++ b/thirdparty/libvpx-vp9-dotnet-port/refharness/tools/simd.py @@ -2,6 +2,8 @@ """simd.py - points the port's rtcd entries at their SIMD kernels. Usage: simd.py + simd.py fallback /netstandard/simd_c.cs + (the netstandard2.1 build's NAME_simd stand-ins, which call NAME_c) Every `internal static NAME_simd(` in /simd/*.cs is the SIMD form of the rtcd entry NAME. In the pruned tree's copies of the rtcd @@ -61,5 +63,59 @@ def repl(m): print('simd.py: %d rtcd entries point at SIMD kernels' % len(done)) +FALLBACK_HEADER = '''//----------------------------------------------------------------------------- +// Filename: simd_c.cs +// +// Description: The netstandard2.1 build's stand-ins for the SIMD kernels. +// netstandard2.1 has no System.Runtime.Intrinsics, so that build leaves simd/*.cs +// out. The ported code still calls each rtcd entry's NAME_simd (simd.py points +// the entries at them), so here every NAME_simd, in the class of the same name +// as its simd/*.cs file, calls NAME_c: what the SIMD kernels do when rtcd.vpx_simd +// is false. The streams are the same either way. +// +// Generated by refharness/tools/simd.py fallback from simd/*.cs: run it again +// after adding a SIMD kernel. +// +// Author(s): +// Claude Opus 5.5 (Anthropic AI assistant, model: claude-opus-5-5), commissioned by Aaron Clauson +// +// History: +// 04 Dec 2026 Claude Created, for the netstandard2.1 build. +// +// License: +// BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file. +//----------------------------------------------------------------------------- + +namespace SIPSorcery.VP9; +''' + + +def fallback(root, out): + """Write netstandard/simd_c.cs: each NAME_simd in simd/*.cs, calling NAME_c.""" + sig = re.compile(r'internal static ([\w*]+) (\w+)_simd\(([^)]*)\)') + lines = [FALLBACK_HEADER] + count = 0 + for f in sorted(glob.glob(os.path.join(root, 'simd', '*.cs'))): + src = open(f, encoding='utf-8').read() + cls = re.search(r'internal static unsafe class (\w+)', src).group(1) + kernels = sig.findall(src) + if not kernels: + continue + lines.append('internal static unsafe class %s' % cls) + lines.append('{') + for ret, name, params in kernels: + args = ', '.join(p.split()[-1] for p in params.split(',') if p.strip()) + body = '%s_c(%s)' % (name, args) + lines.append(' internal static %s %s_simd(%s) => %s;' % (ret, name, params, body)) + count += 1 + lines.append('}') + lines.append('') + open(out, 'w', encoding='utf-8', newline='\n').write('\n'.join(lines)) + print('simd.py: %d SIMD kernels call their C kernels in %s' % (count, out)) + + if __name__ == '__main__': - main() + if len(sys.argv) > 1 and sys.argv[1] == 'fallback': + fallback(sys.argv[2], sys.argv[3]) + else: + main()