fix(video): recover encoder capacity, pace RTP and isolate preview sessions
This commit is contained in:
@@ -5,7 +5,7 @@ const result=await build({entryPoints:[new URL('../../../packages/sensor-ui/src/
|
||||
b.onResolve({filter:/^(react|\.\/contracts|\.\/observationStart)$/},a=>({path:a.path,namespace:'fixture'}));
|
||||
b.onLoad({filter:/.*/,namespace:'fixture'},a=>({contents:a.path==='react'?
|
||||
'export const useEffect=f=>globalThis.previewUI.effects.push(f),useRef=v=>({current:v}),useState=v=>[v,next=>globalThis.previewUI.writes.push(next)];':a.path==='./contracts'?
|
||||
'export const perform=(...args)=>globalThis.previewUI.perform(...args);':'export const currentPreviewDevice=async d=>d;'}));
|
||||
'export const perform=(...args)=>globalThis.previewUI.perform(...args);':'export const currentPreviewDevice=async d=>d;export const observationSession=d=>d.snapshot.context.session_id;'}));
|
||||
}}]});
|
||||
const {useSensorPreview}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
test('stuck signaling expires, retires late answers and removes every retry/listener on unmount',async()=>{
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
|
||||
const result=await build({entryPoints:[new URL('../../../plugins/insta360-x4/frontend/src/useX4Preview.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm',plugins:[{name:'fixture',setup(b){
|
||||
b.onResolve({filter:/^react$/},()=>({path:'react',namespace:'fixture'}));
|
||||
b.onResolve({filter:/^\.\/observationStart$/},a=>a.importer.endsWith('/frontend/src/useX4Preview.ts')?{path:'start',namespace:'fixture'}:undefined);
|
||||
b.onResolve({filter:/^\.\/contracts$/},()=>({path:'contracts',namespace:'fixture'}));
|
||||
b.onLoad({filter:/.*/,namespace:'fixture'},a=>({contents:a.path==='react'?
|
||||
'export const useState=v=>globalThis.sessionUI.state(v),useRef=v=>globalThis.sessionUI.ref(v),useEffect=(f,d)=>globalThis.sessionUI.effect(f,d),useCallback=f=>globalThis.sessionUI.callback(f);':a.path==='start'?
|
||||
'export const startX4Observation=(...args)=>globalThis.sessionUI.start(...args);':
|
||||
'export const perform=(...args)=>globalThis.sessionUI.perform(...args);'}));
|
||||
}}]});
|
||||
const {useX4Preview}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
|
||||
async function fixture(run){
|
||||
const keys=['sessionUI','window','document','performance','RTCPeerConnection','MediaStream','setTimeout','clearTimeout','setInterval','clearInterval'],old=new Map(keys.map(k=>[k,globalThis[k]]));
|
||||
const values=[],effects=[],tasks=[],timers=new Map(),intervals=new Map(),events=new Map(),peers=[];
|
||||
let cursor=0,dirty=true,now=100,id=0,closed=false,frame;
|
||||
const video={paused:false,muted:true,srcObject:null,dataset:{},videoWidth:1280,videoHeight:640,
|
||||
play:()=>Promise.resolve(),requestVideoFrameCallback(f){frame=f;return ++id;},cancelVideoFrameCallback(){frame=null;}};
|
||||
const device=session=>({id:'camera',online:true,prepared:true,camera_status:{connected:true,preview:1,recording:0},snapshot:{acquisition:'streaming',context:{session_id:session,execution:{node_id:'node'}}}});
|
||||
const h={device:device('old'),enabled:true,view:null,starts:[],offers:[],
|
||||
state(v){const i=cursor++;if(!(i in values))values[i]=v;return[values[i],next=>{const value=typeof next==='function'?next(values[i]):next;if(!Object.is(value,values[i])){values[i]=value;dirty=true;}}];},
|
||||
ref(v){const i=cursor++;return values[i]??={current:i===0?video:v};},callback(f){return values[cursor++]??=f;},
|
||||
effect(f,d){const i=cursor++,previous=effects[i];if(!previous||d.some((v,j)=>v!==previous.d[j])){tasks.push(()=>{previous?.cleanup?.();effects[i]={d,cleanup:f()};});}},
|
||||
start(d){h.starts.push(d.snapshot.context.session_id);return Promise.resolve('active');},
|
||||
perform(_transport,d,action){if(action==='offer'){h.offers.push(d.snapshot.context.session_id);return Promise.resolve({peer_id:'peer-'+h.offers.length,sdp:'answer',type:'answer'});}return Promise.resolve({});},
|
||||
async settle(){dirty=true;for(let n=0;n<60;n++){await Promise.resolve();if(dirty&&!closed){dirty=false;cursor=0;h.view=useX4Preview(h.device,transport,h.enabled,true);tasks.splice(0).forEach(f=>f());}}},
|
||||
async live(){const pc=peers.at(-1);pc.connectionState='connected';pc.onconnectionstatechange();pc.ontrack({receiver:{},track:{}});frame();await h.settle();assert.equal(h.view.preview.live,true);},
|
||||
async replace(session,streaming=false){h.device=device(session);if(!streaming){h.device.snapshot.acquisition='idle';h.device.camera_status.preview=0;}await h.settle();},
|
||||
close(){closed=true;effects.forEach(e=>e?.cleanup?.());},peers,
|
||||
};
|
||||
const transport={inventory:async()=>({fresh:true,items:[h.device]})};
|
||||
class Peer{constructor(){peers.push(this);this.iceGatheringState='complete';this.remoteDescription=null;this.connectionState='new';}createDataChannel(){return this.channel={readyState:'open',send(){}};}addTransceiver(){}async createOffer(){return{sdp:'fixture'};}async setLocalDescription(v){this.localDescription=v;}async setRemoteDescription(v){this.remoteDescription=v;}getStats(){return Promise.resolve(new Map());}close(){this.connectionState='closed';}}
|
||||
const eventAPI={addEventListener:(key,f)=>{const set=events.get(key)??new Set();set.add(f);events.set(key,set);},removeEventListener:(key,f)=>events.get(key)?.delete(f)};
|
||||
Object.assign(globalThis,{sessionUI:h,window:{...eventAPI},document:{...eventAPI,visibilityState:'visible'},performance:{now:()=>now},RTCPeerConnection:Peer,MediaStream:class{},
|
||||
setTimeout:(f,delay)=>{timers.set(++id,{f,at:now+delay});return id;},clearTimeout:id=>timers.delete(id),setInterval:f=>{intervals.set(++id,f);return id;},clearInterval:id=>intervals.delete(id)});
|
||||
try{await run(h);}finally{h.close();await h.settle();for(const[k,v]of old){if(v===undefined)delete globalThis[k];else globalThis[k]=v;}}
|
||||
}
|
||||
|
||||
test('fast USB re-enumeration cannot carry live state into an idle replacement session',()=>fixture(async h=>{
|
||||
await h.settle();await h.live();assert.deepEqual(h.starts,['old']);
|
||||
await h.replace('new');assert.equal(h.view.preview.live,false);
|
||||
assert.deepEqual(h.starts,['old','new'],'the new camera must start without leaving observation');
|
||||
}));
|
||||
test('an already-streaming replacement still verifies the new session and negotiates a new peer',()=>fixture(async h=>{
|
||||
await h.settle();await h.live();await h.replace('new',true);
|
||||
assert.deepEqual(h.starts,['old','new']);assert.deepEqual(h.offers,['old','new']);
|
||||
await h.live();assert.equal(h.view.preview.live,true);
|
||||
}));
|
||||
test('ordinary live inventory refresh does not restart capture or its peer',()=>fixture(async h=>{
|
||||
await h.settle();await h.live();h.device={...h.device};await h.settle();
|
||||
assert.deepEqual(h.starts,['old']);assert.deepEqual(h.offers,['old']);
|
||||
}));
|
||||
@@ -0,0 +1,80 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// After a real blackout, repeated isolated 130 ms echoes on a 50 ms
|
||||
// baseline used to restart the capacity recovery timer forever. Exercise
|
||||
// the shared estimator AND feedback gate; testing either alone misses it.
|
||||
func TestVideoBudgetRecoversAfterBlackoutWithIsolatedEchoJitter(t *testing.T) {
|
||||
for _, control := range []bool{false, true} {
|
||||
b, now := testBudget(t)
|
||||
b.Configure(LinkPolicy{"missioncore.link-budget/v1", 6000, 512})
|
||||
b.SetControl(control)
|
||||
b.EnableDatagramFeedback()
|
||||
b.ObserveDatagramFeedback(50*time.Millisecond, 0, 0)
|
||||
// A long interruption must close admission and lower the estimate.
|
||||
b.SetControl(true)
|
||||
b.ObserveCommandFrame(50*time.Millisecond, 20*time.Millisecond)
|
||||
for i := 0; i < 100; i++ {
|
||||
*now = now.Add(100 * time.Millisecond)
|
||||
b.SetControl(true)
|
||||
b.ObserveCommandSilence()
|
||||
if b.optional(*now) != 0 && i >= 2 {
|
||||
t.Fatal("blackout admitted payload")
|
||||
}
|
||||
}
|
||||
if b.effective != 640 {
|
||||
t.Fatal("blackout failed to reduce budget", b.effective)
|
||||
}
|
||||
for i := 0; i < 600; i++ {
|
||||
*now = now.Add(100 * time.Millisecond)
|
||||
b.SetControl(control)
|
||||
b.ObserveCommandFrame(50*time.Millisecond, 30*time.Millisecond)
|
||||
b.allocateRole(testClockID, "video", true, 5000000, true)
|
||||
rtt := 50 * time.Millisecond
|
||||
if i%5 == 0 {
|
||||
rtt = 130 * time.Millisecond
|
||||
}
|
||||
b.ObserveDatagramFeedback(rtt, 0, b.DatagramFeedbackMark())
|
||||
// Current useful camera packets only, under existing admission.
|
||||
for packet := 0; packet < 45; packet++ {
|
||||
*now = now.Add(2 * time.Millisecond)
|
||||
b.Try("video", 1100)
|
||||
}
|
||||
}
|
||||
allocation, _ := b.allocateRole(testClockID, "video", true, 5000000, true)
|
||||
t.Logf("control=%v recovered capacity=%.0f allocation=%v", control, b.effective, allocation["allocation_bps"])
|
||||
if b.effective < 4500 || b.effective > 6000 || allocation["allocation_bps"].(int) < 3000000 {
|
||||
t.Fatal("isolated echo jitter stranded the recovered video budget", b.Snapshot())
|
||||
}
|
||||
// Return-path failure still blocks payload after recovery, immediately.
|
||||
*now = now.Add(400 * time.Millisecond)
|
||||
if b.optional(*now) != 0 {
|
||||
t.Fatal("recovered budget bypassed feedback silence")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSustainedModerateEchoDelayStillPreventsCapacityRecovery(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
b.SetControl(false)
|
||||
b.EnableDatagramFeedback()
|
||||
b.ObserveDatagramFeedback(50*time.Millisecond, 0, 0)
|
||||
b.effective = 640
|
||||
for i := 0; i < 150; i++ {
|
||||
*now = now.Add(100 * time.Millisecond)
|
||||
b.SetControl(false)
|
||||
b.allocateRole(testClockID, "video", true, 5000000, true)
|
||||
b.ObserveDatagramFeedback(130*time.Millisecond, 0, b.DatagramFeedbackMark())
|
||||
b.Try("video", 1100)
|
||||
}
|
||||
if b.effective != 640 || !b.healthy.IsZero() {
|
||||
t.Fatal("continuing delay increased the budget", b.Snapshot())
|
||||
}
|
||||
if b.runtime.feedback.window > feedbackMinWindow {
|
||||
t.Fatal("continuing delay failed to constrain outstanding bytes")
|
||||
}
|
||||
}
|
||||
@@ -89,18 +89,30 @@ func (b *LinkBudget) feedbackLimited(now time.Time) bool {
|
||||
if !h.enabled {
|
||||
return false
|
||||
}
|
||||
// Previously earned capacity is usable only within the existing recovery
|
||||
// lifetime. Check even after echoes resume: an almost five-second outage
|
||||
// must not carry old capacity past the healthy-feedback settling period.
|
||||
if h.limited && !h.recoverUntil.IsZero() && !now.Before(h.recoverUntil) {
|
||||
h.window = min(h.window, uint64(linkClassBurst))
|
||||
h.recoverWindow = 0
|
||||
}
|
||||
if now.Sub(h.seen) > max(250*time.Millisecond, b.baseline+150*time.Millisecond) {
|
||||
if !h.limited {
|
||||
h.recoverWindow = h.window
|
||||
h.recoverUntil = h.seen.Add(5 * time.Second)
|
||||
}
|
||||
h.recordPressure(now, "feedback_silence", now.Sub(h.seen), h.rtt, max(250*time.Millisecond, b.baseline+150*time.Millisecond))
|
||||
// A silent return path invalidates the previously grown send window.
|
||||
// Latch pressure before updating seen: one fresh ACK after a blackout
|
||||
// must not release old optional credit as a burst. Caller holds b.mu.
|
||||
// Pause admission immediately, but distinguish a brief feedback gap
|
||||
// from a new path. Forgetting capacity on every pause creates a circular
|
||||
// recovery dependency with a receiver-limited camera. Keep only the
|
||||
// recently earned window; prolonged silence expires it. Tokens never
|
||||
// survive, and the unchanged healthy-feedback gate must still reopen.
|
||||
h.limited = true
|
||||
h.healthy = time.Time{}
|
||||
h.window = min(h.window, uint64(linkClassBurst))
|
||||
if !now.Before(h.recoverUntil) {
|
||||
h.window = min(h.window, uint64(linkClassBurst))
|
||||
h.recoverWindow = 0
|
||||
}
|
||||
h.adjusted = now
|
||||
b.healthy = time.Time{}
|
||||
b.tokens = 0
|
||||
@@ -154,11 +166,14 @@ func (b *LinkBudget) ObserveDatagramFeedback(elapsed time.Duration, coreMS float
|
||||
h.limited = true
|
||||
h.healthy = time.Time{}
|
||||
}
|
||||
b.healthy = time.Time{}
|
||||
// Delay-based admission must not mistake isolated RTT jitter for a
|
||||
// growing queue. Require a sustained trend before reducing its window;
|
||||
// severe delay and silence still suspend optional traffic immediately.
|
||||
if h.limited || now.Sub(h.delayed) >= 200*time.Millisecond {
|
||||
// The same sustained-pressure evidence must invalidate capacity
|
||||
// recovery. Resetting it for every isolated delayed echo strands
|
||||
// a recovered path at its blackout floor indefinitely.
|
||||
b.healthy = time.Time{}
|
||||
if h.adjusted.IsZero() || now.Sub(h.adjusted) >= 200*time.Millisecond {
|
||||
h.window = max(feedbackMinWindow, h.window/2)
|
||||
h.adjusted = now
|
||||
|
||||
@@ -142,8 +142,8 @@ func TestDatagramFeedbackSilenceLatchesBeforeFreshEcho(t *testing.T) {
|
||||
b.Snapshot()
|
||||
}
|
||||
b.ObserveDatagramFeedback(100*time.Millisecond, 0, 0)
|
||||
if !b.runtime.feedback.limited || b.runtime.feedback.window > linkClassBurst {
|
||||
t.Fatal("fresh echo restored the old send window", b.runtime.feedback)
|
||||
if !b.runtime.feedback.limited || b.optional(*now) != 0 {
|
||||
t.Fatal("fresh echo restored old admission", b.runtime.feedback)
|
||||
}
|
||||
if b.tokens != 0 || b.classes["video"].tokens != 0 {
|
||||
t.Fatal("old burst credit survived silence")
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A receiver-limited camera cannot earn a collapsed admission window back by
|
||||
// sending more bytes: the receiver is also waiting for its rate to recover.
|
||||
// Brief silence must pause packets without forgetting recently earned capacity.
|
||||
func TestFeedbackPauseDoesNotStrandReceiverLimitedCamera(t *testing.T) {
|
||||
for _, gap := range []time.Duration{254 * time.Millisecond, 285 * time.Millisecond, 434 * time.Millisecond, time.Second} {
|
||||
t.Run(gap.String(), func(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
b.effective = 35000
|
||||
b.SetControl(false)
|
||||
b.EnableDatagramFeedback()
|
||||
b.ObserveDatagramFeedback(15*time.Millisecond, 0, 0)
|
||||
b.runtime.feedback.window = 64000 // Previously acknowledged path.
|
||||
for cycle := 0; cycle < 6; cycle++ {
|
||||
*now = now.Add(gap)
|
||||
if b.optional(*now) != 0 {
|
||||
t.Fatal("silent feedback admitted media")
|
||||
}
|
||||
b.ObserveDatagramFeedback(300*time.Millisecond, 0, b.DatagramFeedbackMark())
|
||||
if ok, _ := b.Try("video", 1000); ok {
|
||||
t.Fatal("delayed first echo resumed media")
|
||||
}
|
||||
for tick := 0; tick < 4; tick++ {
|
||||
*now = now.Add(100 * time.Millisecond)
|
||||
b.SetControl(false)
|
||||
b.ObserveDatagramFeedback(15*time.Millisecond, 0, b.DatagramFeedbackMark())
|
||||
if tick < 2 && b.optional(*now) != 0 {
|
||||
t.Fatal("recovery bypassed continuous healthy feedback")
|
||||
}
|
||||
}
|
||||
if b.optional(*now) < 5000 {
|
||||
t.Fatal("brief pause stranded useful video despite healthy feedback", b.optional(*now))
|
||||
}
|
||||
if b.tokens != 0 || b.classes["video"].tokens != 0 {
|
||||
t.Fatal("remembered capacity restored old burst tokens")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedbackPauseCapacityExpiresBeforeRecovery(t *testing.T) {
|
||||
for _, gap := range []time.Duration{4900 * time.Millisecond, 5100 * time.Millisecond, 10 * time.Second} {
|
||||
t.Run(gap.String(), func(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
b.SetControl(false)
|
||||
b.EnableDatagramFeedback()
|
||||
b.ObserveDatagramFeedback(15*time.Millisecond, 0, 0)
|
||||
b.runtime.feedback.window = 64000
|
||||
*now = now.Add(gap)
|
||||
b.ObserveDatagramFeedback(15*time.Millisecond, 0, 0)
|
||||
for tick := 0; tick < 3; tick++ {
|
||||
*now = now.Add(100 * time.Millisecond)
|
||||
b.ObserveDatagramFeedback(15*time.Millisecond, 0, 0)
|
||||
}
|
||||
if b.runtime.feedback.window > linkClassBurst {
|
||||
t.Fatal("expired capacity survived a long outage", b.runtime.feedback.window)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -204,7 +204,7 @@ func roverReceiveDatagrams(ctx context.Context, conn *net.UDPConn, tx, rx *rover
|
||||
return errors.New("invalid datagram intent")
|
||||
}
|
||||
state.receivedFrame(frame.Reply, item.at)
|
||||
state.recordDev("datagram_received", map[string]any{"channel": channel, "packet_sequence": item.counter, "bytes": len(item.raw) + 44})
|
||||
state.recordDev("datagram_received", map[string]any{"channel": channel, "packet_sequence": item.counter, "bytes": len(item.raw) + 44, "socket_read_mono_ms": float64(item.at.Sub(state.origin).Microseconds()) / 1000, "receiver_queue_ms": float64(time.Since(item.at).Microseconds()) / 1000, "receive_gap_ms": float64(item.at.Sub(lastFrame).Microseconds()) / 1000})
|
||||
if !frame.Reply.Watch {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"schema": "missioncore.node.bundled-model/v1",
|
||||
"model_id": "insta360.x4",
|
||||
"version": "0.1.3-30",
|
||||
"revision": "6b548a3432798e8f8a06e208",
|
||||
"bytes": 58235788,
|
||||
"sha256": "a3312eab74d193498b8524674f4a60c77b0c04fcc4f45caa09bb4b44fbae4403"
|
||||
"version": "0.1.3-32",
|
||||
"revision": "32cb6bc3da452632d3e1301b",
|
||||
"bytes": 58236496,
|
||||
"sha256": "0af8654f8a766729a1869416256430fcb63ef3255d439f1d2e43bcd1e21e131d"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
"""Revision a qualified Node package and its separately qualified camera SDK.
|
||||
|
||||
No compiler or installer runs. Admit the exact qualified camera SDK and,
|
||||
optionally, a separately tested Node executable. Preserve every OS/network
|
||||
helper and the motor-controller payload from the qualified predecessor.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
from node_package_delta import parts
|
||||
|
||||
REPO = Path(__file__).resolve().parents[3]
|
||||
sys.path.insert(0, str(REPO / 'scripts/packaging'))
|
||||
from debian import package # noqa: E402
|
||||
from qualified_payloads import QualifiedPayloads # noqa: E402
|
||||
|
||||
SDK_FILES = ('codec_recovery.py', 'media_budget.py', 'diagnostic_options.py',
|
||||
'link_budget.py', 'rtp_send_clock.py')
|
||||
SDK = 'usr/lib/mission-core-node/sdk/missioncore_plugin_sdk/'
|
||||
MODEL = 'usr/share/mission-core-node/profiles/insta360-x4/'
|
||||
PROOF = 'usr/share/doc/mission-core-node/media-sdk-revision.json'
|
||||
|
||||
|
||||
def sha(raw):
|
||||
return hashlib.sha256(raw).hexdigest()
|
||||
|
||||
|
||||
def build(base, base_sha, model_dir, version, output, binary=None):
|
||||
if output.exists() or not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+-[1-9][0-9]*', version):
|
||||
raise ValueError('New immutable version/output required')
|
||||
evidence = json.loads((base.parent / 'qualification.json').read_text())
|
||||
if evidence['state'] != 'complete':
|
||||
raise ValueError('Qualified predecessor required')
|
||||
with QualifiedPayloads(base.parent, REPO / 'apps/node-agent/build', REPO).locked() as store:
|
||||
raw = store.read(base.name)
|
||||
if sha(raw) != base_sha or evidence['artifacts'][base.name]['sha256'] != base_sha:
|
||||
raise ValueError('Predecessor identity mismatch')
|
||||
archives = parts(raw)
|
||||
old = dict((n, d) for n, d, _ in archives['data.tar.gz'])
|
||||
model = json.loads((model_dir / 'package-result.json').read_text())
|
||||
check = json.loads((model_dir / 'build-report.json').read_text())
|
||||
if check['state'] != 'complete':
|
||||
raise ValueError('Camera package qualification required')
|
||||
model_name = 'mission-core-insta360-x4_' + model['version'] + '_amd64.deb'
|
||||
model_bytes = (model_dir / model_name).read_bytes()
|
||||
if sha(model_bytes) != model['sha256'] or len(model_bytes) != model['bytes']:
|
||||
raise ValueError('Camera package identity mismatch')
|
||||
prior = json.loads(old[MODEL + 'profile.json'])
|
||||
old_model = MODEL + 'mission-core-insta360-x4_' + prior['version'] + '_amd64.deb'
|
||||
if sha(old[old_model]) != prior['sha256']:
|
||||
raise ValueError('Previous camera identity mismatch')
|
||||
sdk_root = REPO / 'packages/plugin-sdk/python/missioncore_plugin_sdk'
|
||||
sources = {name: (sdk_root / name).read_bytes() for name in SDK_FILES}
|
||||
# The shipped model predates passive DEV options. Admit the existing,
|
||||
# backward-compatible parser from this checkout in both SDK copies: old
|
||||
# capture choices keep their values, passive choices cannot enable uploads.
|
||||
options = {}
|
||||
exec(compile(sources['diagnostic_options.py'], 'diagnostic_options.py', 'exec'), options)
|
||||
legacy = {"live": True, "core_trace": True, "motor_samples": True,
|
||||
"network": True, "live_kbps": 32, "core_kbps": 32}
|
||||
normalized = options['diagnostic_options'](legacy)
|
||||
if any(normalized[k] != v for k, v in legacy.items()):
|
||||
raise ValueError('Legacy diagnostic behavior changed')
|
||||
passive = options['diagnostic_options'](options['PASSIVE_OPTIONS'])
|
||||
if not passive['passive'] or passive['live'] or passive['core_trace']:
|
||||
raise ValueError('Passive DEV unexpectedly transmits')
|
||||
# Both installed SDK copies must carry exactly the reviewed source. The
|
||||
# camera's native libraries, wheels and other SDK modules remain identical.
|
||||
previous_camera = dict((n, d) for n, d, _ in parts(old[old_model])['data.tar.gz'])
|
||||
camera = dict((n, d) for n, d, _ in parts(model_bytes)['data.tar.gz'])
|
||||
payload = 'usr/share/mission-core-node/insta360/payload.zip'
|
||||
with (zipfile.ZipFile(io.BytesIO(previous_camera[payload])) as before,
|
||||
zipfile.ZipFile(io.BytesIO(camera[payload])) as after):
|
||||
old_names, new_names = set(before.namelist()), set(after.namelist())
|
||||
permitted = {'python/missioncore_plugin_sdk/' + n for n in sources}
|
||||
if old_names - new_names or (new_names - old_names) - permitted:
|
||||
raise ValueError('Camera payload inventory changed')
|
||||
changed = {n for n in old_names & new_names if before.read(n) != after.read(n)}
|
||||
changed |= new_names - old_names
|
||||
expected = {'python/missioncore_plugin_sdk/' + n for n, d in sources.items()
|
||||
if 'python/missioncore_plugin_sdk/' + n not in old_names
|
||||
or before.read('python/missioncore_plugin_sdk/' + n) != d}
|
||||
if changed != expected:
|
||||
raise ValueError('Unreviewed camera runtime delta: ' + repr(changed))
|
||||
for name, data in sources.items():
|
||||
if after.read('python/missioncore_plugin_sdk/' + name) != data:
|
||||
raise ValueError('Camera and Node SDK differ')
|
||||
profile = {**prior, **{k: model[k] for k in ('version', 'revision', 'bytes', 'sha256')}}
|
||||
changes = {SDK + n: d for n, d in sources.items()}
|
||||
changes[MODEL + 'profile.json'] = (json.dumps(profile, indent=2) + '\n').encode()
|
||||
proof = dict(schema='missioncore.node.media-sdk-revision/v1', version=version,
|
||||
predecessor_sha256=base_sha, compiled_node_unchanged=binary is None,
|
||||
os_network_and_motor_payloads_unchanged=True,
|
||||
sdk={n: sha(d) for n, d in sources.items()}, model=profile,
|
||||
prepared_host_only=True, camera_qualification=check)
|
||||
if binary is not None:
|
||||
from repack_runtime import verify_embedded_ui
|
||||
executable = binary.read_bytes()
|
||||
if executable[:6] != b'\x7fELF\x02\x01' or executable[18:20] != b'\x3e\x00':
|
||||
raise ValueError('Expected Linux amd64 executable')
|
||||
verify_embedded_ui(executable)
|
||||
changes['usr/lib/mission-core-node/node-agent'] = executable
|
||||
proof['binary_sha256'] = sha(executable)
|
||||
proof['node_sources'] = {str(p.relative_to(REPO)): sha(p.read_bytes())
|
||||
for p in sorted((REPO / 'apps/node-agent/internal').rglob('*.go'))}
|
||||
changes[PROOF] = (json.dumps(proof, indent=2) + '\n').encode()
|
||||
controls = []
|
||||
for name, data, mode in archives['control.tar.gz']:
|
||||
if name == 'control':
|
||||
data, count = re.subn(rb'(?m)^Version: [^\n]+$', b'Version: ' + version.encode(), data)
|
||||
assert count == 1
|
||||
controls.append((name, data, mode))
|
||||
files = [(n, changes.get(n, d), m) for n, d, m in archives['data.tar.gz'] if n != old_model]
|
||||
files += [(n, d, 0o644) for n, d in changes.items() if n not in old]
|
||||
files.append((MODEL + model_name, model_bytes, 0o644))
|
||||
result = package(controls, files)
|
||||
actual = parts(result)
|
||||
if actual['control.tar.gz'] != controls or actual['data.tar.gz'] != sorted(files):
|
||||
raise ValueError('Packaged bytes differ from the admitted manifest')
|
||||
output.mkdir(mode=0o700)
|
||||
name = 'mission-core-node_' + version + '_amd64.deb'
|
||||
(output / name).write_bytes(result)
|
||||
artifacts = {name: {'bytes': len(result), 'sha256': sha(result)}}
|
||||
for dep, meta in evidence['artifacts'].items():
|
||||
if dep.startswith('mission-core-node_'):
|
||||
continue
|
||||
with QualifiedPayloads(base.parent, REPO / 'apps/node-agent/build', REPO).locked() as store:
|
||||
data = store.read(dep)
|
||||
if sha(data) != meta['sha256']:
|
||||
raise ValueError('Predecessor dependency changed')
|
||||
(output / dep).write_bytes(data)
|
||||
artifacts[dep] = meta
|
||||
report = dict(schema=evidence['schema'], state='pending' if binary else 'complete',
|
||||
artifacts=artifacts,
|
||||
clean_image_qualified=False, packaging_revision=proof,
|
||||
predecessor_qualification=evidence)
|
||||
(output / 'qualification.json').write_text(json.dumps(report, indent=2) + '\n')
|
||||
return dict(directory=str(output), artifacts=artifacts)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--base', required=True, type=Path)
|
||||
parser.add_argument('--base-sha256', required=True)
|
||||
parser.add_argument('--model', required=True, type=Path)
|
||||
parser.add_argument('--version', required=True)
|
||||
parser.add_argument('--output', required=True, type=Path)
|
||||
parser.add_argument('--binary', type=Path)
|
||||
args = parser.parse_args()
|
||||
print(json.dumps(build(args.base, args.base_sha256, args.model, args.version,
|
||||
args.output, args.binary)))
|
||||
@@ -1,6 +1,6 @@
|
||||
# Shared Node link budget
|
||||
|
||||
Release status, 2026-10-26: Node75 / VESC 0.20.9 / X4-23 are installed on Rover006.
|
||||
Historical release status, 2026-10-26: Node75 / VESC 0.20.9 / X4-23 are installed on Rover006.
|
||||
Node75 corrects selected-video credit starvation under repeated moderate command
|
||||
age. Full Ubuntu/race/package checks and scoped passive observation passed;
|
||||
driving/WAN impairment acceptance remains open. Earlier Node72 DEV start/stop,
|
||||
@@ -13,6 +13,28 @@ same Node/Core stack. Node 0.8.49-58, X4 0.1.3-19, RealSense 0.6.7 and K1
|
||||
0.1.16 add producer sizing through that same regulator; qualification and
|
||||
installation evidence is recorded in the installation ledger.
|
||||
|
||||
## RTP pacing correction, Node163 / X4-36, 2026-11-16
|
||||
|
||||
The pinned aiortc 1.14 adapter admits plaintext RTP before SRTP encryption.
|
||||
After the permit wait it refreshes the negotiated absolute-send-time extension,
|
||||
then lets aiortc authenticate/encrypt/send. An existing timestamp created before
|
||||
our wait falsely describes that wait as network timing; it is not corrected in
|
||||
encrypted bytes. Primary and RTX senders use their negotiated extension map.
|
||||
|
||||
Task-local admission credit is consumed exactly once at the existing ICE send
|
||||
boundary. Unadmitted RTP is rejected. Accounting charges the SRTP overhead upper
|
||||
bound and records actual wire bytes separately. The same Node regulator remains
|
||||
the sole owner; no second bandwidth policy, route, VPN rule or SIM knowledge is
|
||||
introduced. Existing 500 ms frame deadlines and bounded RTX history remain;
|
||||
retransmission cannot renew an expired frame. RTCP and SCTP retain their bounded
|
||||
protocol allowance/queue. REMB, bitrate floor and safety thresholds are unchanged.
|
||||
|
||||
Runtime evidence includes `pacing_boundary=before_srtp/v1`, send-clock update
|
||||
count and maximum correction. Tests include delayed admission, authenticated
|
||||
SRTP decryption, RTP/RTX timestamps, deadline expiry and bypass rejection.
|
||||
Passing these does not itself prove this defect caused every observed quality
|
||||
collapse; actual receiver quality and feedback must be observed together.
|
||||
|
||||
## Ownership and routing
|
||||
|
||||
One Go Node regulator owns the board's optional application egress. Critical
|
||||
@@ -103,8 +125,10 @@ and deferrals/active producer counts. Stale observations do not masquerade as cu
|
||||
|
||||
## Sender behavior and bounds
|
||||
|
||||
The shared Python SDK adapter is pinned to aiortc 1.14.0. It gates encrypted
|
||||
application datagrams and retransmissions at the existing ICE send boundary.
|
||||
The shared Python SDK adapter is pinned to aiortc 1.14.0. Since Node163/X4-36,
|
||||
it admits RTP and retransmissions before SRTP, restamps send time after waiting,
|
||||
and consumes admission credit at the existing ICE boundary. SCTP retains its
|
||||
existing bounded datagram queue.
|
||||
Small handshake/RTCP feedback is exempt to avoid deadlock. RTP awaits permits
|
||||
inside its existing sender; SCTP uses one bounded FIFO per transport (64
|
||||
packets/64 KiB, max queued age 0.5 s). A missing budget service, overflow or
|
||||
@@ -513,3 +537,30 @@ tests and a two-minute passive hardware/browser check. Command-pressure behavior
|
||||
on a physical drive remains unqualified. Detailed scope and telemetry tails:
|
||||
`39_NETWORK_RUNTIME_AB.md`, private `outputs/network-contention-20261026/` and
|
||||
`outputs/network-release-75-20261026/`.
|
||||
|
||||
### Feedback pause recovery · Node164 · 2026-11-16
|
||||
|
||||
An isolated return-feedback gap still suspends all optional traffic at the
|
||||
existing threshold and clears both aggregate and class tokens. It now retains
|
||||
the recently acknowledged window within the existing five-second recovery
|
||||
lifetime. Continuous healthy feedback for 200 ms is still required to resume;
|
||||
one delayed ACK or a queued burst cannot reopen admission. Capacity expires
|
||||
even if the first returning ACK precedes the deadline but recovery completes
|
||||
after it. Sustained RTT pressure still shrinks the window, and the aggregate
|
||||
adaptive budget and command guards remain authoritative.
|
||||
|
||||
This removes a circular dependency: resetting the window to 4096 bytes on each
|
||||
brief pause left a receiver-limited camera unable to send enough to regain
|
||||
credit. Recorded-gap regressions (254, 285, 434 and 1000 ms), long-outage expiry
|
||||
and the complete Node race suite pass. No fake receiver estimate, minimum
|
||||
bitrate increase, payload probing or safety-threshold change is introduced.
|
||||
Prepared-host package and stationary acceptance evidence is retained separately
|
||||
under `outputs/video-recovery-164`; this contract is not field acceptance.
|
||||
|
||||
|
||||
Node164 stationary acceptance remains incomplete: paired send/receive sequences
|
||||
showed a 1229.924 ms arrival gap against a 50.823 ms departure gap (Node receiver
|
||||
queue 0.126 ms). Before an independent Core restart, video had an 8.297 s pause.
|
||||
Retaining short-gap credit fixes the reproduced circular recovery defect; it
|
||||
is not evidence that the entire path is stable. No admission deadline, command
|
||||
lease or safety-stop threshold was relaxed. See the Node installation ledger.
|
||||
|
||||
@@ -5,6 +5,31 @@ SSID, proximity to an access point, or a local-address shortcut are not acceptan
|
||||
criteria. No motion, arming, calibration, controller configuration, or firmware
|
||||
commands belong to this qualification.
|
||||
|
||||
## Telemetry clock correction, Node162, 2026-11-16
|
||||
|
||||
The previous extrapolated observation lower-bound model is superseded. Each
|
||||
new local snapshot freezes a causal Core timestamp received before its capture,
|
||||
from a bounded 64-anchor history in the same Core epoch (maximum age two seconds).
|
||||
Node never advances that timestamp using its own clock. No suitable anchor means
|
||||
an invalid old timestamp, not an arrival-time fallback. Replaying a snapshot
|
||||
cannot refresh its measurement age. This is deliberately conservative by return
|
||||
path latency and anchor cadence; it does not estimate one-way latency as RTT/2.
|
||||
|
||||
Authenticated typed `sample_clock` rejection recalibrates only the observation
|
||||
clock. Compact metadata rejection resets only its encoder. Neither rejection
|
||||
renews an observation, authority, command lease or safety deadline. Unknown,
|
||||
transport, authentication and Core-epoch failures retain the negotiated reconnect.
|
||||
Repeated application rejection has bounded backoff; a late failed sequence
|
||||
cannot invalidate a newer successful publication.
|
||||
|
||||
The full Go race suite passed, including 30,000 clock/delay/reordering cases,
|
||||
expiry, replay and epoch boundaries; Core clock and metadata regressions passed.
|
||||
An isolated 144-second passive Node162 test recorded 1,426 successful exchanges,
|
||||
zero `sample_clock` rejects, zero reconnects and a maximum success gap of 289 ms.
|
||||
This is stationary evidence, not a driving or arbitrary WAN acceptance claim.
|
||||
Control thresholds, stop barriers, command upper clock and network policy did
|
||||
not change. Joint video acceptance belongs to the Node163 installation ledger.
|
||||
|
||||
## Earlier incident evidence, 2026-10-26 08:48 MSK
|
||||
|
||||
The reported drive failures are not yet a closed field incident. In the bounded
|
||||
|
||||
@@ -1,27 +1,88 @@
|
||||
"""Debounce expensive codec upgrades; never enlarge the caller's bitrate ceiling."""
|
||||
"""Coalesce codec upgrades without delaying reductions or exceeding either cap."""
|
||||
|
||||
from collections import deque
|
||||
from math import sqrt
|
||||
|
||||
|
||||
class SpatialQuality:
|
||||
"""Bound live H264 pixel count by its applied rate, without reducing cadence.
|
||||
|
||||
A 0.04 bits/pixel/frame starting envelope avoids feeding HD motion into a
|
||||
tens-of-kbit encoder. It is a sizing policy, not a guaranteed image-quality
|
||||
score. Keep native aspect ratio and the producer's upper size bound. The
|
||||
codec owns this state; Track/Node allocation and recording stay independent.
|
||||
"""
|
||||
|
||||
BITS_PER_PIXEL_FRAME = 0.04
|
||||
WIDTHS = (160, 320, 480, 640, 960, 1280)
|
||||
|
||||
def __init__(self, clock):
|
||||
self.clock = clock
|
||||
self.width = None
|
||||
self.aspect = None
|
||||
self.pending = None
|
||||
|
||||
def select(self, width, height, fps, bitrate):
|
||||
aspect = width / height
|
||||
limit = sqrt(max(1, bitrate) * aspect / (max(1, fps) * self.BITS_PER_PIXEL_FRAME))
|
||||
choices = sorted({min(width, w) for w in self.WIDTHS} | {width})
|
||||
desired = max((w for w in choices if w <= limit), default=choices[0])
|
||||
now = self.clock()
|
||||
if self.width is None or self.aspect != aspect:
|
||||
self.width, self.aspect, self.pending = desired, aspect, None
|
||||
# Never upscale a smaller source/Node profile, even during debounce.
|
||||
self.width = min(self.width, width)
|
||||
if desired <= self.width:
|
||||
# Rate cuts apply on this frame. Holding HD for another second at
|
||||
# 32k only manufactures gray frames; reduce size at the same reset.
|
||||
self.width = desired
|
||||
self.pending = None
|
||||
else:
|
||||
if self.pending is None:
|
||||
self.pending = now
|
||||
# A moving recovery ramp does not restart continuous improvement.
|
||||
if now - self.pending >= 2:
|
||||
self.width, self.pending = desired, None
|
||||
out_width = max(2, int(self.width) // 2 * 2)
|
||||
out_height = max(2, int(out_width / aspect) // 2 * 2)
|
||||
return out_width, out_height
|
||||
|
||||
|
||||
class CodecRecovery:
|
||||
# libx264 requires a new context for our pinned VBV configuration. A moving
|
||||
# REMB ramp is one recovery, not a new stream every 10% of bitrate. Wait for
|
||||
# an unchanged 2 s target, with a 6 s bound so continuous growth cannot pin quality.
|
||||
SETTLE_SECONDS = 2.0
|
||||
MAX_WAIT_SECONDS = 6.0
|
||||
|
||||
def __init__(self, clock):
|
||||
self.clock = clock
|
||||
self.pending = None
|
||||
self.samples = deque(maxlen=128)
|
||||
|
||||
def select(self, requested, applied):
|
||||
# aiortc recreates libx264 above a 10% change. Every reduction and initial
|
||||
# creation retain the original path; brief gains need not restart a GOP.
|
||||
if applied is None or requested * 10 <= applied * 11:
|
||||
self.pending = None
|
||||
self.samples.clear()
|
||||
return requested
|
||||
now = self.clock()
|
||||
if self.pending is None:
|
||||
self.pending = (now, requested)
|
||||
started, floor = self.pending
|
||||
floor = min(floor, requested)
|
||||
self.pending = (started, floor)
|
||||
if now - started >= 2:
|
||||
# This sustained floor completes one upgrade. A later, higher
|
||||
# request must earn its own window instead of inheriting this floor
|
||||
# forever after the encoder applies it.
|
||||
self.pending = (now, now, requested)
|
||||
started, settled, anchor = self.pending
|
||||
# Every target change restarts settling. The encoder already has a 10%
|
||||
# recreation threshold; reusing that threshold here treats a slow REMB
|
||||
# ramp as stable and keeps recreating the codec every few seconds.
|
||||
# The overall deadline still guarantees progress during continuous growth.
|
||||
if requested != anchor:
|
||||
settled, anchor = now, requested
|
||||
self.pending = (started, settled, anchor)
|
||||
self.samples.append((now, requested))
|
||||
while len(self.samples) > 1 and self.samples[1][0] <= now - self.SETTLE_SECONDS:
|
||||
self.samples.popleft()
|
||||
if (now - settled >= self.SETTLE_SECONDS
|
||||
or now - started >= self.MAX_WAIT_SECONDS):
|
||||
floor = min(rate for _, rate in self.samples)
|
||||
self.pending = None
|
||||
return floor
|
||||
self.samples.clear()
|
||||
return min(requested, floor)
|
||||
return applied
|
||||
|
||||
@@ -9,7 +9,9 @@ import importlib.metadata
|
||||
import json
|
||||
import socket
|
||||
import time
|
||||
from contextvars import ContextVar
|
||||
|
||||
from .rtp_send_clock import restamp
|
||||
from .runtime_metrics import LatencyStats
|
||||
|
||||
SOCKET = "/run/mission-core-node/budget.sock"
|
||||
@@ -54,11 +56,14 @@ class BudgetClient:
|
||||
self.requests += 1
|
||||
try:
|
||||
if self.writer is None:
|
||||
self.reader, self.writer = await asyncio.open_unix_connection(SOCKET, limit=4096)
|
||||
self.reader, self.writer = await asyncio.open_unix_connection(
|
||||
SOCKET, limit=4096)
|
||||
request = {"class": self.traffic_class, "bytes": size}
|
||||
if self.producer_id: request["producer_id"] = self.producer_id
|
||||
if self.producer_id:
|
||||
request["producer_id"] = self.producer_id
|
||||
body = json.dumps(request).encode()
|
||||
self.writer.write(b"POST /permit HTTP/1.1\r\nHost: local\r\nContent-Type: application/json\r\nContent-Length: "
|
||||
self.writer.write(b"POST /permit HTTP/1.1\r\nHost: local\r\n"
|
||||
b"Content-Type: application/json\r\nContent-Length: "
|
||||
+ str(len(body)).encode() + b"\r\n\r\n" + body)
|
||||
await self.writer.drain()
|
||||
header = await self.reader.readuntil(b"\r\n\r\n")
|
||||
@@ -137,8 +142,10 @@ def budget_peer(pc, traffic_class, *, client=None, clock=time.monotonic, produce
|
||||
if importlib.metadata.version("aiortc") != "1.14.0":
|
||||
raise RuntimeError("Qualify the media budget adapter for this aiortc version")
|
||||
client = client or BudgetClient(traffic_class, producer_id)
|
||||
transports = {t.sender.transport.transport for t in pc.getTransceivers()}
|
||||
dtls_transports = {t.sender.transport for t in pc.getTransceivers()}
|
||||
transports = {dtls.transport for dtls in dtls_transports}
|
||||
if pc.sctp is not None:
|
||||
dtls_transports.add(pc.sctp.transport)
|
||||
transports.add(pc.sctp.transport.transport)
|
||||
if not transports:
|
||||
raise ValueError("Peer has no admitted transport")
|
||||
@@ -152,9 +159,12 @@ def budget_peer(pc, traffic_class, *, client=None, clock=time.monotonic, produce
|
||||
frame_sources[retry.to_bytes(4, "big")] = primary.to_bytes(4, "big")
|
||||
workers, counters = [], []
|
||||
metrics = {"sent_bytes": 0, "expired_frames": 0, "expired_datagrams": 0,
|
||||
"queue_dropped": 0, "stale_rtp_packets": 0, "protocol_bytes": 0, "protocol_dropped": 0,
|
||||
"queue_dropped": 0, "stale_rtp_packets": 0, "protocol_bytes": 0,
|
||||
"protocol_dropped": 0,
|
||||
"max_permit_wait_ms": 0.0, "close_reason": None, "keyframe_requests": 0,
|
||||
"retransmitted_packets": 0, "retained_frame_deadlines": 0}
|
||||
"retransmitted_packets": 0, "retained_frame_deadlines": 0,
|
||||
"pacing_boundary": "before_srtp/v1", "send_clock_updates": 0,
|
||||
"max_send_clock_correction_ms": 0.0}
|
||||
pc._missioncore_admission_metrics = getattr(client, "snapshot", lambda: {})
|
||||
pc._missioncore_egress_metrics = metrics
|
||||
pc._missioncore_pending_media = lambda: sum(value[0] for value in counters)
|
||||
@@ -183,6 +193,9 @@ def budget_peer(pc, traffic_class, *, client=None, clock=time.monotonic, produce
|
||||
raise ValueError("Peer already has an egress budget")
|
||||
transport._missioncore_budget = True
|
||||
original, frames, history = transport._send, {}, {}
|
||||
# A permit belongs to one task and one encryption call. The ICE layer
|
||||
# consumes it exactly once; unrelated/SCTP writes cannot inherit credit.
|
||||
admitted = ContextVar("missioncore_rtp_credit", default=None)
|
||||
queue, pending = asyncio.Queue(maxsize=64), [0]
|
||||
protocol = [8192.0, clock()]
|
||||
counters.append(pending)
|
||||
@@ -216,7 +229,17 @@ def budget_peer(pc, traffic_class, *, client=None, clock=time.monotonic, produce
|
||||
|
||||
workers.append(asyncio.create_task(drain()))
|
||||
|
||||
async def send(data, queue=queue, pending=pending, frames=frames, history=history, protocol=protocol, deliver=deliver):
|
||||
async def send(data, queue=queue, pending=pending, frames=frames, history=history,
|
||||
protocol=protocol, deliver=deliver, admitted=admitted, rtp_deliver=None):
|
||||
credit = admitted.get()
|
||||
if credit is not None:
|
||||
admitted.set(None)
|
||||
if len(data) > credit:
|
||||
retire("invalid_srtp_size")
|
||||
raise BudgetProtocolError("SRTP exceeds its admission")
|
||||
await deliver(data, clock() + MEDIA_LIFETIME)
|
||||
metrics["sent_bytes"] += len(data)
|
||||
return
|
||||
if _essential(data):
|
||||
# A bounded protocol allowance bypasses disposable SCTP backlog.
|
||||
# ICE connectivity checks use their existing transport path.
|
||||
@@ -239,6 +262,15 @@ def budget_peer(pc, traffic_class, *, client=None, clock=time.monotonic, produce
|
||||
retire("oversized_datagram")
|
||||
raise BudgetProtocolError("Media datagram exceeds budget contract")
|
||||
if len(data) >= 12 and 128 <= data[0] <= 191:
|
||||
if rtp_deliver is None:
|
||||
retire("unadmitted_rtp")
|
||||
raise BudgetProtocolError("RTP must be admitted before encryption")
|
||||
# Pinned SRTP profiles append at most 16 authentication bytes.
|
||||
# Charge that upper bound; count actual wire bytes at ICE.
|
||||
wire_limit = len(data) + 16
|
||||
if wire_limit > MAX_PACKET:
|
||||
retire("oversized_datagram")
|
||||
raise BudgetProtocolError("RTP exceeds budget contract")
|
||||
ssrc, stamp = data[8:12], int.from_bytes(data[4:8], "big")
|
||||
retry = ssrc in frame_sources
|
||||
ssrc = frame_sources.get(ssrc, ssrc)
|
||||
@@ -247,8 +279,10 @@ def budget_peer(pc, traffic_class, *, client=None, clock=time.monotonic, produce
|
||||
# NACK commonly arrives after the next primary frame. Keep
|
||||
# only deadline metadata (never payload) for known frames;
|
||||
# RTX cannot create or renew a lease, or roll back latest.
|
||||
known = current if current is not None and current[0] == stamp else history.get((ssrc, stamp))
|
||||
if known is None or (known is not current and (known[2] or clock() >= known[1])):
|
||||
known = (current if current is not None and current[0] == stamp
|
||||
else history.get((ssrc, stamp)))
|
||||
if (known is None
|
||||
or (known is not current and (known[2] or clock() >= known[1]))):
|
||||
metrics["stale_rtp_packets"] += 1
|
||||
return
|
||||
current = known
|
||||
@@ -273,9 +307,8 @@ def budget_peer(pc, traffic_class, *, client=None, clock=time.monotonic, produce
|
||||
try:
|
||||
if started >= current[1]:
|
||||
raise BudgetDeferred("Frame expired")
|
||||
await client.acquire(len(data), deadline=current[1])
|
||||
await deliver(data, current[1])
|
||||
metrics["sent_bytes"] += len(data)
|
||||
await client.acquire(wire_limit, deadline=current[1])
|
||||
await rtp_deliver(data, current[1], wire_limit)
|
||||
if retry:
|
||||
metrics["retransmitted_packets"] += 1
|
||||
except BudgetDeferred:
|
||||
@@ -286,7 +319,8 @@ def budget_peer(pc, traffic_class, *, client=None, clock=time.monotonic, produce
|
||||
retire("admission_or_transport_error")
|
||||
raise ConnectionError("Media egress unavailable") from None
|
||||
finally:
|
||||
metrics["max_permit_wait_ms"] = max(metrics["max_permit_wait_ms"], (clock() - started) * 1000)
|
||||
metrics["max_permit_wait_ms"] = max(
|
||||
metrics["max_permit_wait_ms"], (clock() - started) * 1000)
|
||||
return
|
||||
# SCTP sees ordinary bounded datagram loss and can retransmit within
|
||||
# its own protocol. Overflow cannot tear down an otherwise live peer.
|
||||
@@ -297,6 +331,40 @@ def budget_peer(pc, traffic_class, *, client=None, clock=time.monotonic, produce
|
||||
queue.put_nowait((data, clock() + MEDIA_LIFETIME))
|
||||
|
||||
transport._send = send
|
||||
for dtls in dtls_transports:
|
||||
if dtls.transport is not transport:
|
||||
continue
|
||||
original_rtp = dtls._send_rtp
|
||||
senders = [t.sender for t in pc.getTransceivers() if t.sender.transport is dtls]
|
||||
|
||||
async def encrypt(data, expires, wire_limit, original_rtp=original_rtp,
|
||||
senders=senders, admitted=admitted):
|
||||
remaining = expires - clock()
|
||||
if remaining <= 0:
|
||||
raise BudgetDeferred("Frame expired before encryption")
|
||||
data, correction = restamp(data, senders)
|
||||
if correction is not None:
|
||||
metrics["send_clock_updates"] += 1
|
||||
metrics["max_send_clock_correction_ms"] = max(
|
||||
metrics["max_send_clock_correction_ms"], correction)
|
||||
token = admitted.set(wire_limit)
|
||||
try:
|
||||
# The send stamp describes actual egress, after our wait.
|
||||
# Encryption/authentication and ICE remain aiortc-owned.
|
||||
await asyncio.wait_for(original_rtp(data), remaining)
|
||||
except TimeoutError:
|
||||
raise BudgetDeferred("Media send expired") from None
|
||||
finally:
|
||||
admitted.reset(token)
|
||||
|
||||
async def send_rtp(data, original_rtp=original_rtp, send=send, encrypt=encrypt):
|
||||
from aiortc.rtp import is_rtcp
|
||||
if is_rtcp(data):
|
||||
await original_rtp(data)
|
||||
else:
|
||||
await send(data, rtp_deliver=encrypt)
|
||||
|
||||
dtls._send_rtp = send_rtp
|
||||
|
||||
@pc.on("connectionstatechange")
|
||||
async def changed():
|
||||
|
||||
@@ -13,7 +13,7 @@ import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from .codec_recovery import CodecRecovery
|
||||
from .codec_recovery import CodecRecovery, SpatialQuality
|
||||
from .h264_packetizer import RTP_PAYLOAD_BYTES, packetize_h264
|
||||
from .link_budget import BudgetProtocolError, _Connection
|
||||
from .runtime_metrics import LATENCY_BOUNDS_MS, LatencyStats
|
||||
@@ -30,8 +30,11 @@ class MediaBudget:
|
||||
self.allocation = 0
|
||||
self.profile = self.candidate = (0, 0)
|
||||
self.candidate_at = 0
|
||||
self.profile_mode = None
|
||||
self.degrading_at = None
|
||||
self.encoder_bps = self.receiver_bps = self.encode_ms = 0
|
||||
self.encoder_fps = None
|
||||
self.encoder_size = None
|
||||
self.encoder_rate_control = None
|
||||
self.egress = lambda: {}
|
||||
self.admission = lambda: {}
|
||||
@@ -100,29 +103,52 @@ class MediaBudget:
|
||||
return int(self.target) if not self.closed and self.clock() < self.valid_until else 0
|
||||
|
||||
def video(self):
|
||||
# Source-limited bitrate / REMB cannot determine spatial quality. A quiet
|
||||
# scene must retain detail. Observation trades FPS before resolution.
|
||||
# Node owns the source cadence and maximum size. Receiver congestion
|
||||
# may further constrain encoder size, but must not pin Track at 1–2 FPS
|
||||
# merely because a quiet scene produces little traffic.
|
||||
driving = ((1_800_000, 1280, 15), (900_000, 960, 12), (450_000, 640, 10),
|
||||
(180_000, 480, 6), (70_000, 320, 4), (16_000, 160, 2))
|
||||
observing = ((1_800_000, 1280, 15), (900_000, 1280, 8), (450_000, 960, 6),
|
||||
(180_000, 640, 4), (70_000, 480, 2), (16_000, 320, 1))
|
||||
ladder = observing if self.mode == "observing" else driving
|
||||
desired = next(((w, fps) for threshold, w, fps in ladder if self.bps >= threshold), (0, 0))
|
||||
rate = self.bps
|
||||
desired = next(((w, fps) for threshold, w, fps in ladder if rate >= threshold), (0, 0))
|
||||
now = self.clock()
|
||||
if self.bps <= 0:
|
||||
if desired == (0, 0):
|
||||
# Pausing payload must not turn the next grant into a fresh start
|
||||
# that bypasses the existing spatial-upgrade debounce.
|
||||
self.candidate, self.candidate_at = self.profile, now
|
||||
self.degrading_at = None
|
||||
return (0, 0)
|
||||
if (self.profile == (0, 0) or desired[0] < self.profile[0]
|
||||
or (desired[0] == self.profile[0] and desired[1] <= self.profile[1])):
|
||||
if self.profile == (0, 0) or self.profile_mode != self.mode:
|
||||
self.profile = desired
|
||||
self.candidate = desired
|
||||
self.candidate_at = now
|
||||
elif desired != self.candidate:
|
||||
self.candidate, self.candidate_at = desired, now
|
||||
elif now - self.candidate_at >= 2:
|
||||
self.profile = desired
|
||||
self.degrading_at = None
|
||||
self.profile_mode = self.mode
|
||||
elif desired < self.profile:
|
||||
# The bitrate and per-packet gate shrink immediately. Resolution
|
||||
# and cadence need a sustained lower allocation (two normal 0.5 s
|
||||
# refresh periods), not the first tiny grant after a short pause.
|
||||
self.candidate, self.candidate_at = self.profile, now
|
||||
if self.degrading_at is None:
|
||||
self.degrading_at = now
|
||||
if now - self.degrading_at >= 1:
|
||||
self.profile = self.candidate = desired
|
||||
self.degrading_at = None
|
||||
elif desired > self.profile:
|
||||
self.degrading_at = None
|
||||
if self.candidate <= self.profile:
|
||||
self.candidate_at = now
|
||||
# Higher grants during recovery are still continuous improvement.
|
||||
# Restarting for each rung held a recorded 0.5 s recovery ramp at
|
||||
# 2 FPS for five seconds. A relapse or pause resets this interval.
|
||||
self.candidate = desired
|
||||
if now - self.candidate_at >= 2:
|
||||
self.profile = desired
|
||||
else:
|
||||
self.candidate, self.candidate_at = self.profile, now
|
||||
self.degrading_at = None
|
||||
return self.profile
|
||||
|
||||
def cloud(self, maximum=5000, bytes_per_point=32):
|
||||
@@ -142,6 +168,7 @@ class MediaBudget:
|
||||
"max_width": width, "max_fps": fps, "mode": self.mode, "reason": self.reason,
|
||||
"encoder_bps": self.encoder_bps, "receiver_bps": self.receiver_bps,
|
||||
"encoder_fps": self.encoder_fps, "encoder_rate_control": self.encoder_rate_control,
|
||||
"encoder_size": self.encoder_size,
|
||||
"encode_ms": self.encode_ms, "egress": dict(self.egress()),
|
||||
"encoder_frames": self.encoder_frames, "encoder_reinitializations": self.encoder_reinitializations,
|
||||
"encoder_paused_frames": self.encoder_paused_frames,
|
||||
@@ -219,6 +246,7 @@ def cap_video_sender(sender, budget):
|
||||
raise RuntimeError("Qualify adaptive media for this aiortc version")
|
||||
from aiortc.codecs import h264, vpx
|
||||
from aiortc.mediastreams import VIDEO_TIME_BASE, convert_timebase
|
||||
|
||||
from .preview_h264 import encode_preview_frame
|
||||
|
||||
class Capped:
|
||||
@@ -245,7 +273,16 @@ def cap_video_sender(sender, budget):
|
||||
budget.encoder_frames += 1
|
||||
if before is not None and before is not getattr(self, "codec", None):
|
||||
budget.encoder_reinitializations += 1
|
||||
budget.last_encoder_reset = {"reason": "encoder_recreated", "frame": budget.encoder_frames,
|
||||
budget.last_encoder_reset = {"reason": "+".join(
|
||||
reason for reason, changed in (
|
||||
("size", (before.width, before.height)
|
||||
!= (self.codec.width, self.codec.height)),
|
||||
("cadence", before.framerate != self.codec.framerate),
|
||||
("bitrate", before.bit_rate != self.codec.bit_rate),
|
||||
) if changed) or "encoder_recreated", "frame": budget.encoder_frames,
|
||||
"before_bps": before.bit_rate, "after_bps": self.codec.bit_rate,
|
||||
"before_fps": float(before.framerate) if before.framerate else None,
|
||||
"after_fps": float(self.codec.framerate) if self.codec.framerate else None,
|
||||
"mono_ms": round(budget.clock() * 1000, 3),
|
||||
"before_size": [getattr(before, "width", None), getattr(before, "height", None)],
|
||||
"after_size": [getattr(self.codec, "width", None), getattr(self.codec, "height", None)]}
|
||||
@@ -256,6 +293,7 @@ def cap_video_sender(sender, budget):
|
||||
budget.encode_timing.observe(elapsed)
|
||||
budget.encode_ms = round(elapsed * 1000, 3)
|
||||
budget.encoder_bps = getattr(self.codec, "bit_rate", self.target_bitrate)
|
||||
budget.encoder_size = [getattr(self.codec, "width", None), getattr(self.codec, "height", None)]
|
||||
rate = getattr(getattr(self, "codec", None), "framerate", None)
|
||||
budget.encoder_fps = float(rate) if rate is not None else None
|
||||
return result
|
||||
@@ -271,24 +309,36 @@ def cap_video_sender(sender, budget):
|
||||
@target_bitrate.setter
|
||||
def target_bitrate(self, value):
|
||||
budget.receiver_bps = int(value)
|
||||
self.network_target = max(self.receiver_min, min(int(value), self.receiver_max))
|
||||
# This adapter already qualifies low-rate encoding. The stock
|
||||
# H264 floor (500 kbit/s) would otherwise overrule receiver REMB
|
||||
# during congestion, even when Node's own allocation is high.
|
||||
self.network_target = max(16000, min(int(value), self.receiver_max))
|
||||
|
||||
class H264(Capped, h264.H264Encoder):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.recovery = CodecRecovery(budget.clock)
|
||||
self.spatial_quality = SpatialQuality(budget.clock)
|
||||
self.encoding_target = None
|
||||
budget.encoder_rate_control = "paced-h264-vbv/v2"
|
||||
budget.encoder_rate_control = "coalesced-h264-vbv/v5"
|
||||
|
||||
def _encode_frame(self, frame, force_keyframe):
|
||||
# profile retains the last cadence while a zero grant pauses Track.
|
||||
# Read its tuple only: spatial adaptation belongs to Track's event
|
||||
# loop, not this encoder executor thread.
|
||||
# Read its tuple only: Node profile adaptation belongs to Track's
|
||||
# event loop. Additional codec sizing is local to this encoder.
|
||||
requested = Capped.target_bitrate.fget(self)
|
||||
applied = self.codec.bit_rate if self.codec is not None else None
|
||||
self.encoding_target = self.recovery.select(requested, applied)
|
||||
try:
|
||||
yield from encode_preview_frame(self, frame, force_keyframe, budget.profile[1] or 15)
|
||||
fps = budget.profile[1] or 15
|
||||
# Use the actual coalesced encoder rate, not only Node's grant.
|
||||
# A receiver REMB of 32k with a 5M Node grant previously left HD
|
||||
# at 15 FPS: valid decoded frames, but almost entirely gray.
|
||||
width, height = self.spatial_quality.select(
|
||||
frame.width, frame.height, fps, self.target_bitrate)
|
||||
if (frame.width, frame.height) != (width, height):
|
||||
frame = frame.reformat(width=width, height=height, format="yuv420p")
|
||||
yield from encode_preview_frame(self, frame, force_keyframe, fps)
|
||||
finally:
|
||||
self.encoding_target = None
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Send-time extension at the qualified aiortc 1.14 plaintext boundary."""
|
||||
|
||||
from aiortc import clock
|
||||
from aiortc.rtp import RtpPacket
|
||||
|
||||
|
||||
def restamp(data, senders):
|
||||
ssrc = int.from_bytes(data[8:12], "big")
|
||||
for sender in senders:
|
||||
if ssrc not in (getattr(sender, "_ssrc", None), getattr(sender, "_rtx_ssrc", None)):
|
||||
continue
|
||||
mapping = sender._RTCRtpSender__rtp_header_extensions_map
|
||||
packet = RtpPacket.parse(data, mapping)
|
||||
previous = packet.extensions.abs_send_time
|
||||
if previous is None:
|
||||
return data, None
|
||||
current = (clock.current_ntp_time() >> 14) & 0xFFFFFF
|
||||
packet.extensions.abs_send_time = current
|
||||
# 24-bit, 6.18 seconds: wrap at 64 s. Diagnostic only, never a lease.
|
||||
correction_ms = ((current - previous) & 0xFFFFFF) * 1000 / 2**18
|
||||
return packet.serialize(mapping), correction_ms
|
||||
# Sender registration precedes any aiortc RTP send. An unknown sender is
|
||||
# an adapter/qualification error; do not silently send a false timestamp.
|
||||
raise ValueError("RTP sender was not registered")
|
||||
@@ -2,7 +2,7 @@ import {useEffect,useRef,useState,type RefObject} from 'react';
|
||||
import {perform,type Sensor,type SensorTransport} from './contracts';
|
||||
import {PreviewLiveness} from './previewLiveness';
|
||||
import {previewPlayback} from './previewPlayback';
|
||||
import {currentPreviewDevice} from './observationStart';
|
||||
import {currentPreviewDevice,observationSession} from './observationStart';
|
||||
import {PreviewMetrics} from './previewMetrics';
|
||||
import {configurePreviewPlayout} from './previewPlayout';
|
||||
import {previewEvidence} from './previewEvidence';
|
||||
@@ -11,14 +11,21 @@ import {previewReconnect,previewRetryDelay} from './previewReconnect';
|
||||
export interface SensorPreviewTelemetry {points?:number[];motion?:Record<string,{x:number;y:number;z:number}>;frame_age_ms?:number;fresh?:boolean;media_budget?:{target_bps?:number}}
|
||||
/** One viewing peer; capture ownership belongs to the device session. */
|
||||
export function useSensorPreview(device:Sensor,layer:string,transport:SensorTransport,video:RefObject<HTMLVideoElement|null>,enabled=true,generation=0){
|
||||
const scope=JSON.stringify([observationSession(device),layer]);
|
||||
const [state,setState]=useState('Подключение просмотра');
|
||||
const [telemetry,setTelemetry]=useState<SensorPreviewTelemetry>({});
|
||||
const [error,setError]=useState(''),[live,setLive]=useState(false),[hasFrame,setHasFrame]=useState(false);
|
||||
const [error,setError]=useState(''),[liveScope,setLiveScope]=useState(''),[frameScope,setFrameScope]=useState('');
|
||||
// USB can re-enumerate between inventory samples without an offline render.
|
||||
// Old media state must not suppress activation of the replacement session.
|
||||
const live=liveScope===scope,hasFrame=frameScope===scope;
|
||||
const setLive=(value:boolean)=>setLiveScope(value?scope:'');
|
||||
const setHasFrame=(value:boolean)=>setFrameScope(value?scope:'');
|
||||
const presented=useRef<number|null>(null),[frameAgeMS,setFrameAgeMS]=useState<number|null>(null);
|
||||
const [sourceStalled,setSourceStalled]=useState(false),[retryGeneration,setRetryGeneration]=useState(0);const retries=useRef(0);
|
||||
useEffect(()=>{setHasFrame(false);presented.current=null;setFrameAgeMS(null);},[device.id,device.snapshot.context.session_id,layer]);
|
||||
const [stalledScope,setStalledScope]=useState(''),[retryGeneration,setRetryGeneration]=useState(0);const retries=useRef(0);
|
||||
const sourceStalled=stalledScope===scope,setSourceStalled=(value:boolean)=>setStalledScope(value?scope:'');
|
||||
useEffect(()=>{setHasFrame(false);presented.current=null;setFrameAgeMS(null);},[scope]);
|
||||
useEffect(()=>{const timer=setInterval(()=>setFrameAgeMS(presented.current===null?null:Math.max(0,performance.now()-presented.current)),1000);return()=>clearInterval(timer);},[]);
|
||||
useEffect(()=>{retries.current=0;},[device.id,device.snapshot.context.session_id,layer,enabled,generation]);
|
||||
useEffect(()=>{retries.current=0;},[scope,enabled,generation]);
|
||||
useEffect(()=>{
|
||||
setTelemetry({});setError('');setLive(false);setSourceStalled(false);
|
||||
if(!enabled||!device.online){setState('Нет связи с источником');return;}
|
||||
@@ -96,6 +103,6 @@ export function useSensorPreview(device:Sensor,layer:string,transport:SensorTran
|
||||
}catch(reason){fail(reason instanceof Error?reason.message:'Не удалось открыть просмотр.');}}
|
||||
void connect();
|
||||
return()=>{cancelled=true;playback.dispose();document.removeEventListener('visibilitychange',visibility);window.removeEventListener('pagehide',pagehide);window.removeEventListener('pageshow',pageshow);window.removeEventListener('online',online);reconnect.dispose();clearTimeout(iceTimer);clearInterval(timer);if(frameHandle!==undefined)element?.cancelVideoFrameCallback(frameHandle);pc.ontrack=null;pc.onconnectionstatechange=null;data.onmessage=null;pc.close();if(element){element.srcObject=null;delete element.dataset.previewTiming;delete element.dataset.previewRuntime;}closePeer();};
|
||||
},[device.id,device.online,device.transport_generation,device.snapshot.context.session_id,device.snapshot.acquisition,device.playback_id,layer,transport,video,enabled,generation,retryGeneration]);
|
||||
return {state,telemetry,error,live,hasFrame,sourceStalled,frameAgeMS};
|
||||
},[scope,device.online,device.transport_generation,device.snapshot.acquisition,device.playback_id,transport,video,enabled,generation,retryGeneration]);
|
||||
return {state,telemetry,error,live,hasFrame,sourceStalled,frameAgeMS:hasFrame?frameAgeMS:null};
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ sys.path.insert(0, str(REPOSITORY / "scripts/packaging"))
|
||||
from debian import package # noqa: E402
|
||||
from fetch_sdk import verify # noqa: E402
|
||||
|
||||
VERSION = "0.1.3-30"
|
||||
VERSION = "0.1.3-37"
|
||||
WHEELS = {
|
||||
"aiohappyeyeballs",
|
||||
"aiohttp",
|
||||
|
||||
@@ -89,6 +89,18 @@ try:
|
||||
)
|
||||
suite = unittest.defaultTestLoader.discover(str(ROOT / "tests"), pattern="check_*.py")
|
||||
suite.addTests(unittest.defaultTestLoader.discover(str(ROOT / "tests"), pattern="test_ble*.py"))
|
||||
# Exercise the exact packaged SDK/libx264 wheels, not the Mac's native codec.
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"codec_regressions", ROOT.parents[1] / "tests/test_media_reconfiguration.py")
|
||||
codec_tests = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(codec_tests)
|
||||
suite.addTests(unittest.FunctionTestCase(test) for name, test in vars(codec_tests).items()
|
||||
if name.startswith("test_") and callable(test))
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"profile_regressions", ROOT.parents[1] / "tests/test_media_profile_recovery.py")
|
||||
profile_tests = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(profile_tests)
|
||||
suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(profile_tests))
|
||||
if not unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful():
|
||||
raise RuntimeError("Package qualification tests failed")
|
||||
finally:
|
||||
|
||||
@@ -157,7 +157,14 @@ class Broker:
|
||||
def item(self, value, node):
|
||||
status = value["status"]
|
||||
preview = status.get("preview")
|
||||
frames = None
|
||||
if value["online"]:
|
||||
if preview == 0:
|
||||
frames = "idle"
|
||||
elif preview == 1 and self.media is not None:
|
||||
frames = self.media.frame_state((value["id"], value["session_id"]))
|
||||
return {
|
||||
**({"local_frame_state": frames} if frames else {}),
|
||||
"id": value["id"],
|
||||
"name": "Insta360 X4",
|
||||
"model": "Insta360 X4",
|
||||
|
||||
@@ -90,6 +90,16 @@ class Source:
|
||||
with self.lock:
|
||||
return self.sequence, self.frame, self.observed
|
||||
|
||||
def frame_state(self):
|
||||
# Read only the decoder slot already used by the preview. No SDK call.
|
||||
with self.lock:
|
||||
now = time.monotonic()
|
||||
if self.sequence and now - self.observed < 2:
|
||||
return "online"
|
||||
if now - self.started >= 2:
|
||||
return "lost"
|
||||
return None
|
||||
|
||||
def health(self):
|
||||
"""Bounded in-memory counters; no encoded media or monitoring history."""
|
||||
with self.lock:
|
||||
@@ -435,6 +445,12 @@ class Engine:
|
||||
self.thread = threading.Thread(target=self.loop.run_forever, daemon=True)
|
||||
self.thread.start()
|
||||
|
||||
def frame_state(self, key):
|
||||
# Sources are installed/removed atomically on the engine thread. Hold a
|
||||
# reference during the read; a fresh session always has a different key.
|
||||
source = self.peers.sources.get(key)
|
||||
return source.frame_state() if source is not None else None
|
||||
|
||||
def capture(self, key, path, start):
|
||||
work = self.peers.prime(key, path) if start else self.peers.release(key)
|
||||
future = asyncio.run_coroutine_threadsafe(work, self.loop)
|
||||
|
||||
@@ -28,6 +28,26 @@ def packet(number, data=b"synthetic", generation=1):
|
||||
|
||||
|
||||
class FrameTests(unittest.TestCase):
|
||||
def test_operator_frame_state_reads_only_existing_decoder(self):
|
||||
source = media.Source("/unused", "session")
|
||||
clock = [100.]
|
||||
source.started = clock[0]
|
||||
engine = object.__new__(media.Engine)
|
||||
engine.peers = media.Peers()
|
||||
key = ("x4", "session")
|
||||
with patch.object(media.time, "monotonic", lambda: clock[0]):
|
||||
self.assertIsNone(engine.frame_state(key))
|
||||
self.assertFalse(engine.peers.sources)
|
||||
engine.peers.sources[key] = source
|
||||
self.assertIsNone(engine.frame_state(key))
|
||||
source.sequence, source.observed = 1, clock[0]
|
||||
self.assertEqual(engine.frame_state(key), "online")
|
||||
clock[0] += 3
|
||||
self.assertEqual(engine.frame_state(key), "lost")
|
||||
source.sequence, source.observed = 2, clock[0]
|
||||
self.assertEqual(engine.frame_state(key), "online")
|
||||
self.assertFalse(source.thread.is_alive())
|
||||
|
||||
def test_encoder_recovers_above_an_already_applied_sustained_floor(self):
|
||||
from aiortc.rtcrtpparameters import RTCRtpCodecParameters
|
||||
from missioncore_plugin_sdk.media_budget import MediaBudget, cap_video_sender
|
||||
@@ -51,8 +71,8 @@ class FrameTests(unittest.TestCase):
|
||||
codec = RTCRtpCodecParameters(mimeType="video/H264", clockRate=90000, payloadType=96)
|
||||
try:
|
||||
for at, requested, expected in [(10, 100000, 100000), (10.1, 225000, 100000),
|
||||
(11, 365544, 100000), (12.2, 365544, 225000),
|
||||
(12.3, 365544, 225000), (14.4, 365544, 365000),
|
||||
(11, 365544, 100000), (12.2, 365544, 100000),
|
||||
(13.1, 365544, 365000), (14.4, 365544, 365000),
|
||||
(14.5, 160000, 160000)]:
|
||||
now[0] = at
|
||||
budget.target, budget.valid_until = requested, at + 3
|
||||
@@ -100,10 +120,10 @@ class FrameTests(unittest.TestCase):
|
||||
encoder = sender._RTCRtpSender__encoder
|
||||
self.assertEqual(encoder.codec.bit_rate, 52000)
|
||||
encoder.target_bitrate = 32000
|
||||
self.assertEqual(encoder.target_bitrate, 52000)
|
||||
self.assertEqual(encoder.target_bitrate, 32000)
|
||||
budget.target = 2600000
|
||||
self.assertEqual(budget.video(), (1280, 15))
|
||||
self.assertGreaterEqual(encoder.target_bitrate, 250000)
|
||||
self.assertEqual(encoder.target_bitrate, 32000)
|
||||
encoder.target_bitrate = 600000
|
||||
self.assertEqual(encoder.target_bitrate, 600000)
|
||||
self.assertEqual(budget.video(), (1280, 15))
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Qualify the packaged aiortc/SRTP wheels without a camera or network socket."""
|
||||
|
||||
import asyncio
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import pylibsrtp
|
||||
from aiortc.rtp import HeaderExtensionsMap, RtpPacket
|
||||
from aiortc.rtcrtpparameters import RTCRtpHeaderExtensionParameters, RTCRtpSendParameters
|
||||
|
||||
from missioncore_plugin_sdk.link_budget import budget_peer
|
||||
|
||||
|
||||
class RtpPacingTests(unittest.TestCase):
|
||||
def test_plaintext_wait_then_authenticated_timestamp(self):
|
||||
async def run():
|
||||
now, sent, handlers, charged = [100.0], [], {}, []
|
||||
ice = type("Ice", (), {})()
|
||||
|
||||
async def transmit(data):
|
||||
sent.append(data)
|
||||
|
||||
ice._send = transmit
|
||||
|
||||
class Dtls:
|
||||
transport = ice
|
||||
|
||||
dtls = Dtls()
|
||||
key = bytes(range(30))
|
||||
tx = pylibsrtp.Session(pylibsrtp.Policy(
|
||||
key=key, ssrc_type=pylibsrtp.Policy.SSRC_ANY_OUTBOUND))
|
||||
rx = pylibsrtp.Session(pylibsrtp.Policy(
|
||||
key=key, ssrc_type=pylibsrtp.Policy.SSRC_ANY_INBOUND))
|
||||
|
||||
async def encrypt(data):
|
||||
await ice._send(tx.protect(data))
|
||||
|
||||
dtls._send_rtp = encrypt
|
||||
mapping = HeaderExtensionsMap()
|
||||
mapping.configure(RTCRtpSendParameters(headerExtensions=[
|
||||
RTCRtpHeaderExtensionParameters(
|
||||
3, "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"),
|
||||
]))
|
||||
sender = SimpleNamespace(transport=dtls, _ssrc=10, _rtx_ssrc=11,
|
||||
_RTCRtpSender__rtp_header_extensions_map=mapping)
|
||||
|
||||
class Peer:
|
||||
sctp = None
|
||||
connectionState = "new"
|
||||
|
||||
def getTransceivers(self):
|
||||
return [SimpleNamespace(sender=sender)]
|
||||
|
||||
def on(self, name):
|
||||
return lambda handler: handlers.update({name: handler})
|
||||
|
||||
async def close(self):
|
||||
self.connectionState = "closed"
|
||||
await handlers["connectionstatechange"]()
|
||||
|
||||
class Client:
|
||||
async def acquire(self, size, *, deadline=None):
|
||||
charged.append(size)
|
||||
now[0] += .05
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
peer = Peer()
|
||||
budget_peer(peer, "video", client=Client(), clock=lambda: now[0])
|
||||
packet = RtpPacket(payload_type=96, sequence_number=123, timestamp=3000,
|
||||
ssrc=10, payload=b"synthetic fragment")
|
||||
packet.extensions.abs_send_time = (int(100 * 2**32) >> 14) & 0xFFFFFF
|
||||
raw = packet.serialize(mapping)
|
||||
try:
|
||||
with patch("missioncore_plugin_sdk.rtp_send_clock.clock.current_ntp_time",
|
||||
side_effect=lambda: int(now[0] * 2**32)):
|
||||
await dtls._send_rtp(raw)
|
||||
self.assertEqual(len(sent), 1)
|
||||
received = RtpPacket.parse(rx.unprotect(sent[0]), mapping)
|
||||
self.assertEqual(received.payload, packet.payload)
|
||||
self.assertEqual(received.sequence_number, 123)
|
||||
self.assertEqual(received.timestamp, 3000)
|
||||
self.assertEqual(received.extensions.abs_send_time,
|
||||
(int(100.05 * 2**32) >> 14) & 0xFFFFFF)
|
||||
self.assertEqual(charged, [len(raw) + 16])
|
||||
finally:
|
||||
await peer.close()
|
||||
|
||||
asyncio.run(run())
|
||||
@@ -98,7 +98,8 @@ class RoverDatagramServer:
|
||||
self.channels[channel] = {
|
||||
"value": dict(value), "certificate": certificate,
|
||||
"send": DatagramCipher(channel, send), "receive": DatagramCipher(channel, receive),
|
||||
"peer": None, "probe": 0, "probe_clock": None, "last_probe": now,
|
||||
"peer": None, "probe": 0, "sent_probe": 0, "probe_clock": None,
|
||||
"last_probe": now, "probe_gap_ms": None,
|
||||
"next": now, "last_sent": -1e9, "last_command": None, "expires": now + 86400,
|
||||
}
|
||||
return 200, {"channel": channel.hex(), "send_key": receive.hex(),
|
||||
@@ -114,6 +115,7 @@ class RoverDatagramServer:
|
||||
|
||||
def run(self):
|
||||
while not self.stop.is_set():
|
||||
waiting = time.monotonic()
|
||||
try:
|
||||
packet, peer = self.socket.recvfrom(MAX_PACKET + 1)
|
||||
except (TimeoutError, BlockingIOError):
|
||||
@@ -122,6 +124,7 @@ class RoverDatagramServer:
|
||||
break
|
||||
now = time.monotonic()
|
||||
with self.lock:
|
||||
locked = time.monotonic()
|
||||
if packet is not None and len(packet) <= MAX_PACKET:
|
||||
c = self.channels.get(packet[4:20])
|
||||
if c is not None:
|
||||
@@ -131,19 +134,25 @@ class RoverDatagramServer:
|
||||
# never at a later periodic send for that same probe.
|
||||
c.update(peer=peer, probe=opened[0],
|
||||
probe_clock=self.registry.rover_control._clock(),
|
||||
probe_gap_ms=(now - c["last_probe"]) * 1000,
|
||||
last_probe=now)
|
||||
for key, c in list(self.channels.items()):
|
||||
checking = time.monotonic()
|
||||
if (now >= c["expires"] or now - c["last_probe"] >= 2
|
||||
or not self.registry.rover_channel.same_generation(c["value"])):
|
||||
self.channels.pop(key, None)
|
||||
continue
|
||||
checked = time.monotonic()
|
||||
if c["peer"] is None or now - c["last_sent"] < MIN_SEND_INTERVAL:
|
||||
continue
|
||||
# Fresh input and withdrawal must not wait for a keepalive
|
||||
# tick. This hint does not authorize a send: the original
|
||||
# Fresh probes, input and withdrawal must not wait for a
|
||||
# keepalive tick. Echo only the latest authenticated probe;
|
||||
# duplicate/replayed probes never bypass the normal cadence.
|
||||
# This hint does not authorize a send: the original
|
||||
# certificate/binding/endpoint is checked again below.
|
||||
if now < c["next"] and not self.registry.rover_control.intent_changed(
|
||||
c["value"]["node_id"], c["value"]["relay_id"], c["last_command"]):
|
||||
if (c["probe"] == c["sent_probe"] and now < c["next"]
|
||||
and not self.registry.rover_control.intent_changed(
|
||||
c["value"]["node_id"], c["value"]["relay_id"], c["last_command"])):
|
||||
continue
|
||||
periodic_lag_ms = max(0., (now - c["next"]) * 1000)
|
||||
dispatched = time.monotonic()
|
||||
@@ -160,7 +169,8 @@ class RoverDatagramServer:
|
||||
sealed = time.monotonic()
|
||||
self.socket.sendto(packet, c["peer"])
|
||||
sent = time.monotonic()
|
||||
c.update(last_sent=sent, next=sent + KEEPALIVE_INTERVAL,
|
||||
c.update(last_sent=sent, sent_probe=c["probe"],
|
||||
next=sent + KEEPALIVE_INTERVAL,
|
||||
last_command=reply.get("command"))
|
||||
trace = self.registry.rover_control.stream_trace(c["value"]["node_id"])
|
||||
if trace is not None:
|
||||
@@ -174,7 +184,13 @@ class RoverDatagramServer:
|
||||
registry_ms=(received - dispatched) * 1000,
|
||||
encrypt_ms=(sealed - received) * 1000,
|
||||
socket_ms=(sent - sealed) * 1000,
|
||||
periodic_lag_ms=periodic_lag_ms)
|
||||
periodic_lag_ms=periodic_lag_ms,
|
||||
probe_sequence=c["probe"],
|
||||
probe_receive_gap_ms=c["probe_gap_ms"],
|
||||
probe_to_send_ms=(sent - c["last_probe"]) * 1000,
|
||||
receive_wait_ms=(now - waiting) * 1000,
|
||||
channel_lock_ms=(locked - now) * 1000,
|
||||
generation_check_ms=(checked - checking) * 1000)
|
||||
if not reply.get("watch"):
|
||||
self.channels.pop(key, None)
|
||||
except (OSError, ValueError, TypeError, KeyError):
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Deterministic echo scheduling: no network, authority or safety shortcuts."""
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.fleet import rover_datagram as mod
|
||||
|
||||
|
||||
def run_schedule(monkeypatch, schedule, *, denied_at=None):
|
||||
clock, frames, traces, calls = [100.0], [], [], []
|
||||
monkeypatch.setattr(mod.time, 'monotonic', lambda: clock[0])
|
||||
channel, key = b'a' * 16, b'b' * 32
|
||||
tx, rx = mod.DatagramCipher(channel, key), mod.DatagramCipher(channel, key)
|
||||
probes = {i: tx.seal({}) for i in range(1, 5)}
|
||||
events = iter(schedule)
|
||||
|
||||
def receive(*_args, **_kwargs):
|
||||
calls.append(clock[0])
|
||||
if denied_at is not None and clock[0] >= 100 + denied_at:
|
||||
return 410, {}
|
||||
return 200, {'watch': True, 'command': None}
|
||||
|
||||
class Socket:
|
||||
def recvfrom(self, _size):
|
||||
try:
|
||||
at, probe = next(events)
|
||||
except StopIteration:
|
||||
raise OSError from None
|
||||
clock[0] = 100 + at
|
||||
if probe is None:
|
||||
raise TimeoutError
|
||||
return probes[probe], ('127.0.0.1', 1234)
|
||||
|
||||
def sendto(self, packet, _peer):
|
||||
frames.append((clock[0] - 100, rx.open(packet)[1]))
|
||||
|
||||
def getsockname(self):
|
||||
return ('127.0.0.1', 1234)
|
||||
|
||||
server = mod.RoverDatagramServer.__new__(mod.RoverDatagramServer)
|
||||
server.address, server.socket = '127.0.0.1', Socket()
|
||||
server.lock, server.stop, server.channels = threading.Lock(), threading.Event(), {}
|
||||
server.registry = SimpleNamespace(
|
||||
receive=receive,
|
||||
rover_channel=SimpleNamespace(same_generation=lambda _: True),
|
||||
rover_control=SimpleNamespace(
|
||||
_clock=lambda: {'monotonic_ms': clock[0] * 1000},
|
||||
intent_changed=lambda *_: False,
|
||||
stream_trace=lambda _: SimpleNamespace(add=lambda event, **data: traces.append(data))))
|
||||
_, grant = server.open(b'fixture-cert', {'node_id': 'fixture', 'relay_id': 'c' * 32})
|
||||
state = server.channels.pop(bytes.fromhex(grant['channel']))
|
||||
state.update(send=mod.DatagramCipher(channel, key), receive=mod.DatagramCipher(channel, key))
|
||||
server.channels[channel] = state
|
||||
server.run()
|
||||
return frames, traces, calls, server.channels
|
||||
|
||||
|
||||
def test_fresh_probe_echo_does_not_wait_for_periodic_command_tick(monkeypatch):
|
||||
frames, traces, calls, _ = run_schedule(monkeypatch, [(0, 1), (.02, 2), (.075, None)])
|
||||
assert [time for time, _ in frames] == pytest.approx([0, .02, .075])
|
||||
assert [frame['probe'] for _, frame in frames] == [1, 2, 2]
|
||||
assert len(calls) == len(frames) # Every echo fully rechecks authority.
|
||||
assert traces[1]['probe_to_send_ms'] == 0
|
||||
assert traces[1]['probe_receive_gap_ms'] == pytest.approx(20)
|
||||
for row in traces:
|
||||
assert row['probe_sequence'] in (1, 2)
|
||||
for name in ('receive_wait_ms', 'channel_lock_ms', 'generation_check_ms'):
|
||||
assert row[name] >= 0
|
||||
|
||||
|
||||
def test_probe_burst_keeps_only_latest_and_respects_send_limit(monkeypatch):
|
||||
frames, traces, _, _ = run_schedule(monkeypatch, [
|
||||
(0, 1), (.003, 2), (.006, 3), (.011, None), (.015, 3), (.03, 2), (.065, None)])
|
||||
assert [time for time, _ in frames] == pytest.approx([0, .011, .065])
|
||||
assert [frame['probe'] for _, frame in frames] == [1, 3, 3]
|
||||
assert traces[1]['probe_to_send_ms'] == pytest.approx(5)
|
||||
assert frames[1][1]['probe_clock'] == frames[2][1]['probe_clock']
|
||||
assert all(b[0] - a[0] >= mod.MIN_SEND_INTERVAL
|
||||
for a, b in zip(frames, frames[1:], strict=False))
|
||||
|
||||
|
||||
def test_fresh_probe_cannot_bypass_revocation(monkeypatch):
|
||||
frames, _, calls, channels = run_schedule(monkeypatch, [(0, 1), (.02, 2)], denied_at=.015)
|
||||
assert len(calls) == 2
|
||||
assert len(frames) == 1
|
||||
assert channels == {}
|
||||
+46
-32
@@ -16,10 +16,24 @@ class Peer:
|
||||
self.sent.append(data)
|
||||
self.ice = type("Ice", (), {})()
|
||||
self.ice._send = send
|
||||
self.dtls = type("Dtls", (), {})()
|
||||
self.dtls.transport = self.ice
|
||||
async def encrypt(data):
|
||||
await self.ice._send(data)
|
||||
self.dtls._send_rtp = encrypt
|
||||
from aiortc.rtp import HeaderExtensionsMap
|
||||
self.sender = SimpleNamespace(transport=self.dtls, _ssrc=int.from_bytes(b"ssrc", "big"),
|
||||
_rtx_ssrc=int.from_bytes(b"rtxs", "big"),
|
||||
_RTCRtpSender__rtp_header_extensions_map=HeaderExtensionsMap())
|
||||
|
||||
async def send(self, data):
|
||||
if len(data) >= 12 and 128 <= data[0] <= 191:
|
||||
await self.dtls._send_rtp(data)
|
||||
else:
|
||||
await self.ice._send(data)
|
||||
|
||||
def getTransceivers(self):
|
||||
transport = SimpleNamespace(transport=self.ice)
|
||||
return [SimpleNamespace(sender=SimpleNamespace(transport=transport))]
|
||||
return [SimpleNamespace(sender=self.sender)]
|
||||
|
||||
def on(self, event):
|
||||
return lambda handler: self.handlers.update({event: handler})
|
||||
@@ -48,13 +62,13 @@ def test_existing_transport_accounts_rtp_sctp_and_retransmits():
|
||||
async def run():
|
||||
pc, client = Peer(), Client()
|
||||
budget_peer(pc, "video", client=client)
|
||||
rtp = b"\x80\x60" + b"x" * 100
|
||||
rtp = b"\x80\x60" + b"x" * 6 + b"ssrc" + b"x" * 90
|
||||
sctp = b"\x17" + b"x" * 100
|
||||
rtcp = b"\x80\xc8" + b"x" * 20
|
||||
for packet in (rtp, rtp, sctp, rtcp):
|
||||
await pc.ice._send(packet)
|
||||
await pc.send(packet)
|
||||
await asyncio.sleep(.02)
|
||||
assert client.sizes == [102, 102, 101]
|
||||
assert client.sizes == [118, 118, 101]
|
||||
assert pc.sent[:2] == [rtp, rtp]
|
||||
assert sctp in pc.sent and rtcp in pc.sent and len(pc.sent) == 4
|
||||
await pc.close()
|
||||
@@ -67,7 +81,7 @@ def test_budget_failure_closes_media_without_sending_or_self_deadlock():
|
||||
pc, client = Peer(), Client()
|
||||
client.fail = True
|
||||
budget_peer(pc, "cloud", client=client)
|
||||
await pc.ice._send(b"\x17data")
|
||||
await pc.send(b"\x17data")
|
||||
await asyncio.sleep(.02)
|
||||
assert pc.connectionState == "closed" and not pc.sent
|
||||
asyncio.run(run())
|
||||
@@ -93,11 +107,11 @@ def test_frame_age_bounds_all_fragments_and_keeps_next_frame_live():
|
||||
budget_peer(pc, "video", client=client, clock=lambda: now[0])
|
||||
first = b"\x80\x60\x00\x01" + (1).to_bytes(4, "big") + b"ssrc" + b"x" * 100
|
||||
second = first[:4] + (2).to_bytes(4, "big") + first[8:]
|
||||
await pc.ice._send(first)
|
||||
await pc.send(first)
|
||||
now[0] += .6
|
||||
await pc.ice._send(first)
|
||||
await pc.ice._send(first)
|
||||
await pc.ice._send(second)
|
||||
await pc.send(first)
|
||||
await pc.send(first)
|
||||
await pc.send(second)
|
||||
assert pc.sent == [first, second]
|
||||
assert pc._missioncore_egress_metrics["expired_frames"] == 1
|
||||
assert pc.connectionState != "closed"
|
||||
@@ -127,15 +141,15 @@ def test_policy_pause_drops_stale_media_without_retiring_peer(monkeypatch, cycle
|
||||
rtp = b'\x80\x60\x00\x01' + (1 + cycle * 3000).to_bytes(4,'big') + b'ssrc' + b'x'*100
|
||||
fresh = rtp[:4] + (2 + cycle * 3000).to_bytes(4,'big') + rtp[8:]
|
||||
try:
|
||||
await pc.ice._send(rtp)
|
||||
await pc.ice._send(b'\x17stale-sensor')
|
||||
await pc.send(rtp)
|
||||
await pc.send(b'\x17stale-sensor')
|
||||
await asyncio.sleep(.58)
|
||||
assert pc.connectionState != 'closed' and not pc.sent
|
||||
assert keyframes and pc._missioncore_pending_media() == 0
|
||||
client.paused = False
|
||||
await pc.ice._send(rtp) # No replay of expired fragments.
|
||||
await pc.ice._send(fresh)
|
||||
await pc.ice._send(b'\x17fresh-sensor')
|
||||
await pc.send(rtp) # No replay of expired fragments.
|
||||
await pc.send(fresh)
|
||||
await pc.send(b'\x17fresh-sensor')
|
||||
await asyncio.sleep(.03)
|
||||
assert pc.sent == [fresh, b'\x17fresh-sensor']
|
||||
assert pc._missioncore_egress_metrics['expired_frames'] == 1
|
||||
@@ -155,9 +169,9 @@ def test_expired_fifo_never_waits_again_and_protocol_bypasses_backlog():
|
||||
raise BudgetDeferred()
|
||||
pc=Peer();budget_peer(pc,'cloud',client=Paused(),clock=lambda:now[0])
|
||||
try:
|
||||
for _ in range(3):await pc.ice._send(b'\x17queued')
|
||||
for _ in range(3):await pc.send(b'\x17queued')
|
||||
await blocked.wait()
|
||||
await pc.ice._send(b'\x16handshake')
|
||||
await pc.send(b'\x16handshake')
|
||||
assert pc.sent==[b'\x16handshake']
|
||||
release.set();await asyncio.sleep(.01)
|
||||
assert calls==[(0.0,.5)]
|
||||
@@ -180,7 +194,7 @@ def test_frame_fragments_share_one_deadline():
|
||||
pc=Peer();budget_peer(pc,'video',client=Late(),clock=lambda:now[0])
|
||||
frame=b'\x80\x60\x00\x01'+(1).to_bytes(4,'big')+b'ssrc'+b'x'*100
|
||||
try:
|
||||
await pc.ice._send(frame);await pc.ice._send(frame)
|
||||
await pc.send(frame);await pc.send(frame)
|
||||
assert deadlines==[.5,.5] and now[0]==.5
|
||||
assert pc.sent==[frame] and pc.connectionState!='closed'
|
||||
finally:await pc.close()
|
||||
@@ -251,14 +265,14 @@ def test_rtx_cannot_renew_original_deadline_or_replay_before_new_frame():
|
||||
return b"\x80\x60\x00\x01" + stamp.to_bytes(4,"big") + (11 if retry else 10).to_bytes(4,"big") + b"x"*100
|
||||
try:
|
||||
first, retry = packet(0xfffffff0), packet(0xfffffff0, True)
|
||||
await pc.ice._send(first)
|
||||
await pc.send(first)
|
||||
now[0] += .2
|
||||
await pc.ice._send(retry) # Same deadline, legitimate early retry.
|
||||
await pc.send(retry) # Same deadline, legitimate early retry.
|
||||
now[0] += .31
|
||||
await pc.ice._send(retry)
|
||||
await pc.send(retry)
|
||||
fresh = packet(16) # Timestamp wrap is a new frame.
|
||||
await pc.ice._send(fresh)
|
||||
await pc.ice._send(retry)
|
||||
await pc.send(fresh)
|
||||
await pc.send(retry)
|
||||
assert pc.sent == [first, retry, fresh]
|
||||
assert len(client.sizes) == 3
|
||||
assert pc._missioncore_egress_metrics["expired_frames"] == 1
|
||||
@@ -284,17 +298,17 @@ def test_rtx_of_previous_frame_retains_original_unexpired_deadline():
|
||||
|
||||
try:
|
||||
first, second, retry = packet(1000), packet(7000), packet(1000, True)
|
||||
await pc.ice._send(first)
|
||||
await pc.send(first)
|
||||
now[0] += .067
|
||||
await pc.ice._send(second)
|
||||
await pc.send(second)
|
||||
now[0] += .1
|
||||
await pc.ice._send(retry)
|
||||
await pc.send(retry)
|
||||
assert pc.sent == [first, second, retry]
|
||||
# Neither a retry nor a newer frame can extend the original lease.
|
||||
now[0] = 100.501
|
||||
await pc.ice._send(retry)
|
||||
await pc.ice._send(first) # Old primary payload remains forbidden.
|
||||
await pc.ice._send(packet(9000, True)) # Unknown RTX has no lease.
|
||||
await pc.send(retry)
|
||||
await pc.send(first) # Old primary payload remains forbidden.
|
||||
await pc.send(packet(9000, True)) # Unknown RTX has no lease.
|
||||
assert pc.sent == [first, second, retry]
|
||||
assert len(client.sizes) == 3
|
||||
assert pc.connectionState != "closed"
|
||||
@@ -318,11 +332,11 @@ def test_rtx_deadline_history_is_bounded_without_retaining_payload():
|
||||
|
||||
try:
|
||||
for stamp in range(300):
|
||||
await pc.ice._send(packet(stamp))
|
||||
await pc.send(packet(stamp))
|
||||
assert pc._missioncore_egress_metrics["retained_frame_deadlines"] == 256
|
||||
await pc.ice._send(packet(0, True)) # Evicted metadata cannot grant a lease.
|
||||
await pc.send(packet(0, True)) # Evicted metadata cannot grant a lease.
|
||||
assert len(pc.sent) == 300
|
||||
await pc.ice._send(packet(250, True))
|
||||
await pc.send(packet(250, True))
|
||||
assert pc.sent[-1] == packet(250, True) and len(pc.sent) == 301
|
||||
assert pc._missioncore_egress_metrics["retransmitted_packets"] == 1
|
||||
finally:
|
||||
|
||||
@@ -25,14 +25,17 @@ def test_profile_rate_recovery_has_no_second_hold_and_profile_debounces():
|
||||
b.update(allocation(4_000_000))
|
||||
assert b.video() == (1280, 15)
|
||||
b.update(allocation(100_000))
|
||||
assert b.video() == (160, 2) and b.bps == 65000
|
||||
assert b.video() == (1280, 15) and b.bps == 65000
|
||||
now[0] = 101
|
||||
b.update(allocation(100_000))
|
||||
assert b.video() == (160, 2)
|
||||
now[0] = 102
|
||||
b.update(allocation(4_000_000))
|
||||
assert b.bps == 2_600_000 and b.video() == (160, 2)
|
||||
now[0] = 103
|
||||
now[0] = 104
|
||||
b.update(allocation(4_000_000))
|
||||
assert b.video() == (1280, 15)
|
||||
now[0] = 107
|
||||
now[0] = 108
|
||||
assert b.video() == (0, 0) and b.cloud()[0] == 0
|
||||
with pytest.raises(ConnectionError):
|
||||
b.update(allocation(True))
|
||||
@@ -78,28 +81,28 @@ def test_real_encoder_honors_node_below_vendor_floor_and_receiver_remb(codec):
|
||||
assert max(map(len,result.payloads)) <= 1100
|
||||
assert encoder.codec.framerate == b.video()[1]
|
||||
assert b.snapshot()["encoder_fps"] == b.video()[1]
|
||||
assert b.snapshot()["encoder_rate_control"] == "paced-h264-vbv/v2"
|
||||
assert b.snapshot()["encoder_rate_control"] == "coalesced-h264-vbv/v5"
|
||||
assert b.encoder_frames == 1 and b.encoded_frame_bytes > 0
|
||||
assert b.snapshot()["encode_timing"]["count"] == 1
|
||||
assert sum(b.snapshot()["encode_timing"]["bins"]) == 1
|
||||
assert encoder.codec.bit_rate == 52000
|
||||
encoder.target_bitrate = 32000
|
||||
assert encoder.target_bitrate == 52000
|
||||
assert encoder.target_bitrate == 32000
|
||||
b.update(allocation(30_000))
|
||||
assert encoder.target_bitrate == 19500
|
||||
# Quiet imagery is not proof of a smaller allocation. Retain the
|
||||
# stock receiver floor, but allow Node's cap below it.
|
||||
# Spatial quality follows allocation, but receiver congestion is
|
||||
# also a ceiling on the encoder, including below the stock floor.
|
||||
b.target = 2_600_000
|
||||
b.profile = (1280, 15)
|
||||
assert b.video() == (1280, 15)
|
||||
assert encoder.target_bitrate >= 250000
|
||||
assert encoder.target_bitrate == 32000
|
||||
encoder.target_bitrate = 600000
|
||||
assert encoder.target_bitrate == 600000 and b.video() == (1280, 15)
|
||||
# Node75 observation: a recovered Node allocation is only a ceiling;
|
||||
# receiver feedback can still keep the real encoder near its floor.
|
||||
b.target = 3_250_000
|
||||
encoder.target_bitrate = 307644
|
||||
assert encoder.target_bitrate == (500000 if codec == "H264" else 307644)
|
||||
assert encoder.target_bitrate == 307644
|
||||
assert b.bps == 3_250_000 and b.video() == (1280, 15)
|
||||
encoder.target_bitrate = 3_000_000
|
||||
assert encoder.target_bitrate == (3_000_000 if codec == "H264" else 1_500_000)
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Replay the observed grant ramp without hardware or altered packet admission."""
|
||||
|
||||
import unittest
|
||||
|
||||
from missioncore_plugin_sdk.media_budget import MediaBudget
|
||||
|
||||
|
||||
class PreviewRecoveryTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
now = [100.]
|
||||
budget = MediaBudget("video", clock=lambda: now[0])
|
||||
|
||||
def grant(at, rate, mode="observing"):
|
||||
now[0] = 100 + at
|
||||
budget.update({"schema": "missioncore.media-budget/v1", "allocation_bps": rate,
|
||||
"ttl_ms": 3000, "mode": mode})
|
||||
return budget.video()
|
||||
|
||||
self.preview = budget, now, grant
|
||||
|
||||
def tearDown(self):
|
||||
self.preview[0].connection.close()
|
||||
|
||||
def test_brief_pause_and_single_low_grant_do_not_resize_video(self):
|
||||
budget, _, grant = self.preview
|
||||
assert grant(0, 5_000_000) == (1280, 15)
|
||||
assert grant(1, 0) == (0, 0)
|
||||
assert budget.bps == 0
|
||||
assert grant(1.3, 184320) == (1280, 15)
|
||||
assert budget.bps == 119808 # The smaller bitrate applies immediately.
|
||||
assert grant(1.8, 5_000_000) == (1280, 15)
|
||||
assert budget.profile == (1280, 15)
|
||||
|
||||
|
||||
def test_recorded_recovery_ramp_does_not_pin_stream_at_two_fps(self):
|
||||
budget, _, grant = self.preview
|
||||
grant(0, 5_000_000)
|
||||
assert grant(1, 0) == (0, 0)
|
||||
# Node159 stationary recording: grant recovered every 0.5 s, but video
|
||||
# remained 480x240 / 2 FPS for five seconds as its upgrade timer restarted.
|
||||
rates = [184320, 672160, 1206080, 1720160, 1903120,
|
||||
2494480, 3077520, 3634400, 4271520, 4841440]
|
||||
profiles = []
|
||||
for tick, rate in enumerate(rates):
|
||||
profiles.append(grant(1.5 + tick * .5, rate))
|
||||
assert budget.bps == int(rate * .65)
|
||||
assert min(fps for _, fps in profiles) >= 6
|
||||
assert profiles[7] == (1280, 15)
|
||||
|
||||
|
||||
def test_sustained_low_capacity_still_reduces_profile(self):
|
||||
budget, _, grant = self.preview
|
||||
grant(0, 5_000_000)
|
||||
grant(1, 100_000)
|
||||
assert grant(1.5, 100_000) == (1280, 15)
|
||||
assert grant(2, 100_000) == (320, 1)
|
||||
assert budget.bps == 65000
|
||||
assert grant(2.1, 0) == (0, 0)
|
||||
assert grant(20, 100_000) == (320, 1)
|
||||
|
||||
|
||||
def test_quality_recovery_needs_continuous_improvement_not_equal_numbers(self):
|
||||
_, _, grant = self.preview
|
||||
assert grant(0, 800000) == (960, 6)
|
||||
assert grant(1, 1500000) == (960, 6)
|
||||
assert grant(2, 5000000) == (960, 6)
|
||||
assert grant(3, 5000000) == (1280, 15)
|
||||
|
||||
|
||||
def test_pause_and_relapse_do_not_count_as_healthy_upgrade_time(self):
|
||||
_, _, grant = self.preview
|
||||
assert grant(0, 800000) == (960, 6)
|
||||
grant(1, 5000000)
|
||||
assert grant(2, 0) == (0, 0)
|
||||
assert grant(10, 5000000) == (960, 6)
|
||||
assert grant(11, 800000) == (960, 6)
|
||||
assert grant(12, 5000000) == (960, 6)
|
||||
assert grant(14, 5000000) == (1280, 15)
|
||||
|
||||
|
||||
def test_expired_grant_pauses_and_mode_change_uses_current_policy(self):
|
||||
budget, now, grant = self.preview
|
||||
assert grant(0, 800000) == (960, 6)
|
||||
now[0] = 104
|
||||
assert budget.bps == 0 and budget.video() == (0, 0)
|
||||
assert grant(5, 800000, "control_reserved") == (640, 10)
|
||||
@@ -100,7 +100,79 @@ def test_zero_quota_pauses_without_erasing_profile_upgrade_debounce():
|
||||
budget.connection.close()
|
||||
|
||||
|
||||
def test_codec_recovery_uses_sustained_floor_and_never_delays_reduction():
|
||||
def test_h264_honors_receiver_below_stock_floor_and_still_decodes():
|
||||
async def run():
|
||||
pc = RTCPeerConnection()
|
||||
budget = MediaBudget("video")
|
||||
budget.update({"schema": "missioncore.media-budget/v1", "allocation_bps": 5_000_000,
|
||||
"ttl_ms": 3000})
|
||||
class Track(VideoStreamTrack):
|
||||
async def recv(self):
|
||||
return frame(0)
|
||||
sender = pc.addTrack(Track())
|
||||
cap_video_sender(sender, budget)
|
||||
codec = RTCRtpCodecParameters(mimeType="video/H264", clockRate=90000, payloadType=96)
|
||||
decoder = H264Decoder()
|
||||
try:
|
||||
await sender._next_encoded_frame(codec)
|
||||
encoder = sender._RTCRtpSender__encoder
|
||||
# Receiver estimates observed in the drive; Node has spare capacity.
|
||||
# The receiver's lower ceiling must win over aiortc's stock 500k floor.
|
||||
for index, requested in enumerate((242982, 69850, 32000), 1):
|
||||
encoder.target_bitrate = requested
|
||||
payloads, stamp = encoder.encode(frame(index), force_keyframe=True)
|
||||
pictures = decoder.decode(JitterFrame(
|
||||
b"".join(h264_depayload(p) for p in payloads), stamp))
|
||||
assert len(pictures) == 1 and pictures[0].key_frame
|
||||
assert encoder.codec.bit_rate <= requested
|
||||
assert encoder.target_bitrate == requested
|
||||
assert budget.receiver_bps == requested
|
||||
finally:
|
||||
await pc.close()
|
||||
budget.connection.close()
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_brief_spatial_hold_still_encodes_below_current_bitrate_cap():
|
||||
async def run():
|
||||
pc = RTCPeerConnection()
|
||||
now = [0.]
|
||||
budget = MediaBudget("video", clock=lambda: now[0])
|
||||
class Track(VideoStreamTrack):
|
||||
async def recv(self):
|
||||
return frame(0)
|
||||
sender = pc.addTrack(Track())
|
||||
cap_video_sender(sender, budget)
|
||||
codec = RTCRtpCodecParameters(mimeType="video/H264", clockRate=90000, payloadType=96)
|
||||
decoder = H264Decoder()
|
||||
try:
|
||||
for index, (at, rate) in enumerate(((0, 5000000), (.1, 0), (.4, 184320),
|
||||
(.9, 5000000), (3, 5000000))):
|
||||
now[0] = at
|
||||
budget.update({"schema": "missioncore.media-budget/v1", "allocation_bps": rate,
|
||||
"ttl_ms": 3000, "mode": "observing"})
|
||||
profile = budget.video()
|
||||
if index == 0:
|
||||
await sender._next_encoded_frame(codec)
|
||||
encoder = sender._RTCRtpSender__encoder
|
||||
payloads, stamp = encoder.encode(frame(index + 1), force_keyframe=True)
|
||||
if rate == 0:
|
||||
assert profile == (0, 0) and payloads == []
|
||||
continue
|
||||
assert profile == (1280, 15)
|
||||
assert encoder.codec.bit_rate <= min(budget.bps, encoder.target_bitrate)
|
||||
assert encoder.codec.framerate == 15
|
||||
pictures = decoder.decode(JitterFrame(
|
||||
b"".join(h264_depayload(p) for p in payloads), stamp))
|
||||
assert len(pictures) == 1 and pictures[0].key_frame
|
||||
assert budget.encoder_reinitializations == 2 # Rate down/up only.
|
||||
finally:
|
||||
await pc.close()
|
||||
budget.connection.close()
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_codec_recovery_coalesces_a_ramp_but_never_delays_reduction():
|
||||
from missioncore_plugin_sdk.codec_recovery import CodecRecovery
|
||||
now = [10.]
|
||||
recovery = CodecRecovery(lambda: now[0])
|
||||
@@ -109,32 +181,240 @@ def test_codec_recovery_uses_sustained_floor_and_never_delays_reduction():
|
||||
now[0] += 1
|
||||
assert recovery.select(500000, 250000) == 250000
|
||||
now[0] += 1.1
|
||||
assert recovery.select(800000, 250000) == 500000
|
||||
assert recovery.select(200000, 500000) == 200000
|
||||
# A reduction discards previous recovery time; receiver and Node cap both
|
||||
# enter through requested, and can never be raised by this helper.
|
||||
assert recovery.select(800000, 250000) == 250000
|
||||
now[0] += 2.1
|
||||
assert recovery.select(800000, 250000) == 800000
|
||||
assert recovery.select(200000, 800000) == 200000
|
||||
assert recovery.select(1000000, 200000) == 200000
|
||||
now[0] += 1
|
||||
assert recovery.select(300000, 200000) == 200000
|
||||
|
||||
|
||||
def test_codec_recovery_allows_successive_sustained_upgrades():
|
||||
def test_codec_recovery_continuous_growth_is_bounded_and_reaches_final_target():
|
||||
from missioncore_plugin_sdk.codec_recovery import CodecRecovery
|
||||
now = [10.0]
|
||||
now = [0.]
|
||||
recovery = CodecRecovery(lambda: now[0])
|
||||
applied = 100000
|
||||
assert recovery.select(225000, applied) == applied
|
||||
now[0] += 1
|
||||
assert recovery.select(365544, applied) == applied
|
||||
now[0] += 1.1
|
||||
applied = recovery.select(365544, applied)
|
||||
assert applied == 225000 # Lowest sustained target in the first window.
|
||||
assert recovery.select(365544, applied) == applied
|
||||
now[0] += 2.1
|
||||
applied = recovery.select(365544, applied)
|
||||
assert applied == 365544 # A completed lower step must not pin later recovery.
|
||||
assert recovery.select(1000000, applied) == applied
|
||||
now[0] += 2.1
|
||||
assert recovery.select(1000000, applied) == 1000000
|
||||
# Receiver/Node reductions still apply immediately, including after recovery.
|
||||
assert recovery.select(160000, 1000000) == 160000
|
||||
applied, upgrades = 500000, []
|
||||
# Synthetic REMB ramp: >10% gains continue more often than the quiet window.
|
||||
# Preserve the next-frame ceiling and reduce recreation frequency, without
|
||||
# suppressing all upgrades until the ramp stops.
|
||||
for tick in range(180):
|
||||
now[0] = tick / 4
|
||||
requested = min(3000000, int(500000 * 1.12 ** (tick // 2)))
|
||||
target = recovery.select(requested, applied)
|
||||
assert 0 < target <= requested
|
||||
if target > applied * 1.1:
|
||||
upgrades.append(now[0])
|
||||
applied = target
|
||||
assert 1 <= len(upgrades) <= 4
|
||||
assert upgrades[0] <= 7
|
||||
assert applied >= 3000000 / 1.1
|
||||
assert recovery.select(160000, applied) == 160000
|
||||
assert not recovery.samples and recovery.pending is None
|
||||
|
||||
|
||||
def test_codec_recovery_rolling_floor_rejects_recent_unproven_spike():
|
||||
from missioncore_plugin_sdk.codec_recovery import CodecRecovery
|
||||
now = [0.]
|
||||
recovery = CodecRecovery(lambda: now[0])
|
||||
for value in range(12):
|
||||
now[0] = value * .5
|
||||
assert recovery.select(600000 + value * 100000, 500000) == 500000
|
||||
now[0] = 6
|
||||
assert recovery.select(3000000, 500000) == 1400000
|
||||
# A later sustained upgrade is independent; no inherited old floor pins it.
|
||||
assert recovery.select(3000000, 1400000) == 1400000
|
||||
now[0] = 8.1
|
||||
assert recovery.select(3000000, 1400000) == 3000000
|
||||
|
||||
|
||||
def test_h264_ramping_remb_keeps_decoding_and_reports_actual_reset_cause():
|
||||
async def run():
|
||||
now = [0.]
|
||||
budget = MediaBudget("video", clock=lambda: now[0])
|
||||
pc = RTCPeerConnection()
|
||||
class Track(VideoStreamTrack):
|
||||
async def recv(self):
|
||||
return frame(0)
|
||||
sender = pc.addTrack(Track())
|
||||
cap_video_sender(sender, budget)
|
||||
codec = RTCRtpCodecParameters(mimeType="video/H264", clockRate=90000, payloadType=96)
|
||||
decoder = H264Decoder()
|
||||
try:
|
||||
budget.update({"schema": "missioncore.media-budget/v1", "allocation_bps": 5000000,
|
||||
"ttl_ms": 3000})
|
||||
await sender._next_encoded_frame(codec)
|
||||
encoder = sender._RTCRtpSender__encoder
|
||||
for index in range(40):
|
||||
now[0] = index * .5
|
||||
budget.valid_until = now[0] + 3
|
||||
encoder.target_bitrate = min(3000000, int(500000 * 1.12 ** index))
|
||||
value = frame(index + 1)
|
||||
value.pts = (index + 1) * 45000
|
||||
payloads, timestamp = encoder.encode(value, force_keyframe=index == 3)
|
||||
pictures = decoder.decode(JitterFrame(
|
||||
b"".join(h264_depayload(p) for p in payloads), timestamp))
|
||||
assert len(pictures) == 1
|
||||
if index == 3:
|
||||
assert pictures[0].key_frame
|
||||
assert encoder.codec.bit_rate <= encoder.target_bitrate
|
||||
assert 1 <= budget.encoder_reinitializations <= 4
|
||||
assert encoder.codec.bit_rate >= 3000000 / 1.1 - 1000
|
||||
reset = budget.last_encoder_reset
|
||||
assert reset["reason"] == "bitrate"
|
||||
assert reset["before_size"] == reset["after_size"] == [64, 32]
|
||||
assert reset["before_fps"] == reset["after_fps"]
|
||||
assert reset["after_bps"] > reset["before_bps"]
|
||||
finally:
|
||||
await pc.close()
|
||||
budget.connection.close()
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_codec_recovery_slow_remb_growth_is_not_mistaken_for_a_stable_target():
|
||||
from missioncore_plugin_sdk.codec_recovery import CodecRecovery
|
||||
now = [0.]
|
||||
recovery = CodecRecovery(lambda: now[0])
|
||||
applied, upgrades = 500000, []
|
||||
# Observed REMB rises by less than the encoder's 10% deadband in two seconds.
|
||||
# It is still a ramp: only a genuinely unchanged target may settle early.
|
||||
for tick in range(280):
|
||||
now[0] = tick / 4
|
||||
requested = min(3000000, int(500000 * 1.035 ** now[0]))
|
||||
target = recovery.select(requested, applied)
|
||||
assert 0 < target <= requested
|
||||
if target > applied * 1.1:
|
||||
upgrades.append(now[0])
|
||||
applied = target
|
||||
assert 1 <= len(upgrades) <= 9
|
||||
assert upgrades[0] <= 10
|
||||
assert applied >= 3000000 / 1.1
|
||||
|
||||
|
||||
def test_spatial_quality_bounds_pixels_preserves_aspect_and_debounces_recovery():
|
||||
from missioncore_plugin_sdk.codec_recovery import SpatialQuality
|
||||
now = [0.]
|
||||
sizing = SpatialQuality(lambda: now[0])
|
||||
assert sizing.select(1280, 640, 15, 700000) == (1280, 640)
|
||||
assert sizing.select(1280, 640, 15, 32000) == (320, 160)
|
||||
now[0] = 1.01
|
||||
assert sizing.select(1280, 640, 15, 32000) == (320, 160)
|
||||
# A rising rate is continuous recovery; do not reset for every rung.
|
||||
assert sizing.select(1280, 640, 15, 70000) == (320, 160)
|
||||
now[0] = 2.1
|
||||
assert sizing.select(1280, 640, 15, 250000) == (320, 160)
|
||||
now[0] = 3.1
|
||||
assert sizing.select(1280, 640, 15, 700000) == (1280, 640)
|
||||
assert sizing.select(640, 480, 15, 32000) == (160, 120)
|
||||
assert sizing.select(64, 32, 15, 32000) == (64, 32)
|
||||
# No spatial-state coupling between separate viewers / cameras.
|
||||
other = SpatialQuality(lambda: now[0])
|
||||
assert other.select(1280, 640, 15, 32000) == (320, 160)
|
||||
|
||||
|
||||
def test_spatial_quality_transient_cap_recovers_but_relapse_resets_upgrade():
|
||||
from missioncore_plugin_sdk.codec_recovery import SpatialQuality
|
||||
now = [0.]
|
||||
sizing = SpatialQuality(lambda: now[0])
|
||||
assert sizing.select(1280, 640, 15, 700000) == (1280, 640)
|
||||
now[0] = .1
|
||||
assert sizing.select(1280, 640, 15, 32000) == (320, 160)
|
||||
now[0] = .9
|
||||
assert sizing.select(1280, 640, 15, 700000) == (320, 160)
|
||||
now[0] = 2
|
||||
assert sizing.select(1280, 640, 15, 32000) == (320, 160)
|
||||
now[0] = 3.1
|
||||
assert sizing.select(1280, 640, 15, 32000) == (320, 160)
|
||||
assert sizing.select(1280, 640, 15, 700000) == (320, 160)
|
||||
now[0] = 4.5
|
||||
assert sizing.select(1280, 640, 15, 32000) == (320, 160)
|
||||
now[0] = 5.2
|
||||
assert sizing.select(1280, 640, 15, 700000) == (320, 160)
|
||||
now[0] = 7.3
|
||||
assert sizing.select(1280, 640, 15, 700000) == (1280, 640)
|
||||
|
||||
|
||||
def test_h264_low_receiver_rate_retains_moving_picture_not_just_decodable_frames():
|
||||
import math
|
||||
|
||||
async def run():
|
||||
now = [0.]
|
||||
budget = MediaBudget("video", clock=lambda: now[0])
|
||||
budget.update({"schema": "missioncore.media-budget/v1", "allocation_bps": 5000000,
|
||||
"ttl_ms": 3000})
|
||||
budget.video()
|
||||
# Deterministic moving luma/chroma edges without adding a runtime
|
||||
# NumPy dependency to the portable camera package.
|
||||
rows = [
|
||||
[bytes(32 + (x % 256) // 2 + ((x // 64 + y // 64) % 2) * 64
|
||||
for x in range(1280)) for y in range(640)],
|
||||
[bytes(96 + (x // 32 % 2) * 64 for x in range(640)) for _ in range(320)],
|
||||
[bytes([96 + (y // 32 % 2) * 64]) * 640 for y in range(320)],
|
||||
]
|
||||
def moving(index):
|
||||
value = av.VideoFrame(1280, 640, "yuv420p")
|
||||
for plane, source in zip(value.planes, rows, strict=True):
|
||||
divisor = 1 if plane.width == 1280 else 2
|
||||
shift_x, shift_y = index * 7 // divisor, index * 3 // divisor
|
||||
data = []
|
||||
for y in range(plane.height):
|
||||
row = source[(y - shift_y) % plane.height]
|
||||
shift = shift_x % len(row)
|
||||
data.append(row[-shift:] + row[:-shift] if shift else row)
|
||||
data.append(bytes(plane.line_size - plane.width))
|
||||
plane.update(b"".join(data))
|
||||
value.pts, value.time_base = index * 6000, Fraction(1, 90000)
|
||||
return value
|
||||
def coarse(value):
|
||||
value = value.reformat(width=80, height=40, format="yuv420p")
|
||||
return b"".join(bytes(plane)[y * plane.line_size:y * plane.line_size + plane.width]
|
||||
for plane in value.planes for y in range(plane.height))
|
||||
pc = RTCPeerConnection()
|
||||
class Track(VideoStreamTrack):
|
||||
async def recv(self):
|
||||
return moving(0)
|
||||
sender = pc.addTrack(Track())
|
||||
cap_video_sender(sender, budget)
|
||||
codec = RTCRtpCodecParameters(mimeType="video/H264", clockRate=90000, payloadType=96)
|
||||
decoder, scores = H264Decoder(), []
|
||||
try:
|
||||
first = await sender._next_encoded_frame(codec)
|
||||
decoder.decode(JitterFrame(b"".join(h264_depayload(p) for p in first.payloads), first.timestamp))
|
||||
encoder = sender._RTCRtpSender__encoder
|
||||
encoder.target_bitrate = 32000
|
||||
for index in range(1, 46):
|
||||
now[0] = index / 15
|
||||
budget.valid_until = now[0] + 3
|
||||
source = moving(index)
|
||||
payloads, timestamp = encoder.encode(source)
|
||||
pictures = decoder.decode(JitterFrame(b"".join(h264_depayload(p) for p in payloads), timestamp))
|
||||
assert len(pictures) == 1
|
||||
assert encoder.codec.framerate == 15 and encoder.codec.bit_rate <= 32000
|
||||
if index >= 30:
|
||||
picture = pictures[0]
|
||||
assert (picture.width, picture.height) == (320, 160)
|
||||
# At this narrow rate fine texture is expendable, large shapes
|
||||
# and colors are not. Compare both at the same coarse scale.
|
||||
ref, got = coarse(source), coarse(picture)
|
||||
mse = sum((a - b) ** 2 for a, b in zip(ref, got, strict=True)) / len(ref)
|
||||
scores.append(10 * math.log10(255 ** 2 / max(1, mse)))
|
||||
assert sum(scores) / len(scores) > 20, scores
|
||||
assert budget.encoder_size == [320, 160]
|
||||
assert budget.snapshot()["max_fps"] == 15
|
||||
# Only the existing producer lease may pause cadence/payload.
|
||||
budget.valid_until = now[0]
|
||||
assert encoder.encode(moving(46))[0] == []
|
||||
# A sustained recovered REMB restores size without reconnecting.
|
||||
budget.valid_until = now[0] + 20
|
||||
encoder.target_bitrate = 700000
|
||||
for index, at in enumerate((3.1, 5.2, 7.3), 47):
|
||||
now[0] = at
|
||||
payloads, timestamp = encoder.encode(moving(index))
|
||||
pictures = decoder.decode(JitterFrame(b"".join(h264_depayload(p) for p in payloads), timestamp))
|
||||
assert len(pictures) == 1 and encoder.codec.framerate == 15
|
||||
assert budget.encoder_size == [1280, 640]
|
||||
assert pictures[0].key_frame
|
||||
finally:
|
||||
await pc.close()
|
||||
budget.connection.close()
|
||||
asyncio.run(run())
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Exercise plaintext pacing followed by real SRTP authentication/decryption."""
|
||||
|
||||
import asyncio
|
||||
|
||||
import pylibsrtp
|
||||
import pytest
|
||||
from aiortc.rtcrtpparameters import RTCRtpHeaderExtensionParameters, RTCRtpSendParameters
|
||||
from aiortc.rtp import RtpPacket
|
||||
from missioncore_plugin_sdk.link_budget import BudgetProtocolError, budget_peer
|
||||
from test_link_budget import Client, Peer
|
||||
|
||||
|
||||
def test_actual_srtp_timestamp_is_after_admission_and_payload_is_unchanged(monkeypatch):
|
||||
from missioncore_plugin_sdk import rtp_send_clock
|
||||
|
||||
async def run():
|
||||
now = [100.0]
|
||||
monkeypatch.setattr(rtp_send_clock.clock, "current_ntp_time", lambda: int(now[0] * 2**32))
|
||||
pc = Peer()
|
||||
sender = pc.sender
|
||||
mapping = sender._RTCRtpSender__rtp_header_extensions_map
|
||||
mapping.configure(RTCRtpSendParameters(headerExtensions=[
|
||||
RTCRtpHeaderExtensionParameters(3, "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"),
|
||||
RTCRtpHeaderExtensionParameters(1, "urn:ietf:params:rtp-hdrext:sdes:mid"),
|
||||
]))
|
||||
key = bytes(range(30))
|
||||
tx = pylibsrtp.Session(pylibsrtp.Policy(
|
||||
key=key, ssrc_type=pylibsrtp.Policy.SSRC_ANY_OUTBOUND))
|
||||
rx = pylibsrtp.Session(pylibsrtp.Policy(
|
||||
key=key, ssrc_type=pylibsrtp.Policy.SSRC_ANY_INBOUND))
|
||||
encrypted_at = []
|
||||
|
||||
async def encrypt(data):
|
||||
encrypted_at.append(now[0])
|
||||
await pc.ice._send(tx.protect(data))
|
||||
|
||||
pc.dtls._send_rtp = encrypt
|
||||
|
||||
class Delayed(Client):
|
||||
async def acquire(self, size, *, deadline=None):
|
||||
self.sizes.append(size)
|
||||
now[0] += .05
|
||||
|
||||
client = Delayed()
|
||||
budget_peer(pc, "video", client=client, clock=lambda: now[0])
|
||||
packet = RtpPacket(payload_type=96, marker=1, sequence_number=123, timestamp=45000,
|
||||
ssrc=sender._ssrc, payload=b"synthetic H264 fragment")
|
||||
packet.extensions.mid = "0"
|
||||
packet.extensions.abs_send_time = (int(now[0] * 2**32) >> 14) & 0xFFFFFF
|
||||
raw = packet.serialize(mapping)
|
||||
try:
|
||||
await pc.dtls._send_rtp(raw)
|
||||
assert len(pc.sent) == 1 and encrypted_at == [100.05]
|
||||
received = RtpPacket.parse(rx.unprotect(pc.sent[0]), mapping)
|
||||
assert received.payload == packet.payload
|
||||
assert (received.sequence_number, received.timestamp) == (123, 45000)
|
||||
assert (received.ssrc, received.marker) == (sender._ssrc, 1)
|
||||
assert received.extensions.mid == "0"
|
||||
assert received.extensions.abs_send_time == (int(100.05 * 2**32) >> 14) & 0xFFFFFF
|
||||
assert client.sizes == [len(raw) + 16]
|
||||
metrics = pc._missioncore_egress_metrics
|
||||
assert metrics["sent_bytes"] == len(pc.sent[0])
|
||||
assert metrics["send_clock_updates"] == 1
|
||||
assert 49.9 < metrics["max_send_clock_correction_ms"] < 50.1
|
||||
finally:
|
||||
await pc.close()
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_direct_srtp_cannot_bypass_admission():
|
||||
async def run():
|
||||
pc, client = Peer(), Client()
|
||||
budget_peer(pc, "video", client=client)
|
||||
try:
|
||||
with pytest.raises(BudgetProtocolError):
|
||||
await pc.ice._send(b"\x80\x60" + b"x" * 20)
|
||||
assert not pc.sent and not client.sizes
|
||||
finally:
|
||||
await pc.close()
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_expiry_during_admission_prevents_encryption():
|
||||
async def run():
|
||||
now = [10.0]
|
||||
pc = Peer()
|
||||
|
||||
class Late(Client):
|
||||
async def acquire(self, size, *, deadline=None):
|
||||
now[0] += .6
|
||||
|
||||
budget_peer(pc, "video", client=Late(), clock=lambda: now[0])
|
||||
try:
|
||||
await pc.send(b"\x80\x60\x00\x01" + (1).to_bytes(4, "big") + b"ssrc" + b"x" * 100)
|
||||
assert not pc.sent
|
||||
assert pc._missioncore_egress_metrics["expired_frames"] == 1
|
||||
finally:
|
||||
await pc.close()
|
||||
asyncio.run(run())
|
||||
Reference in New Issue
Block a user