File size: 9,162 Bytes
9d57416
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import {SEEK_DRIFT_S,nudgedRate,mustWait} from './media-sync.ts';
import type {MediaRoute} from './contract.ts';
import type {ReviewClock} from './clock.ts';
import {mediaTime, presentedFrame, recordPresentation} from './media-clock.ts';
import {errorText} from './text.ts';

type Route = {source: MediaRoute; node: HTMLElement; video: HTMLVideoElement; canvas: HTMLCanvasElement;
  callback: number | null; last: {world: number; endWorld: number; display: number} | null; waiting: boolean; correction: boolean; recording: boolean};

export class NativePlayback {
  private panel: HTMLElement;
  private clock: ReviewClock;
  private fail: (message: string) => void;
  private owner = {};
  private routes: Route[];
  private master: Route | null = null;
  private active = true;
  private blocked = false;
  private removers: (() => void)[] = [];
  private gap: number | null = null;
  world: number;
  speed: number;

  constructor(panel: HTMLElement, sources: MediaRoute[], clock: ReviewClock,
    fail: (message: string) => void) {
    this.panel=panel; this.clock=clock; this.fail=fail;
    this.world=clock.snapshot().time; this.speed=clock.snapshot().speed;
    this.routes=sources.map(source => {
      const node=Array.from(panel.querySelectorAll<HTMLElement>('[data-media-observer]')).find(n=>n.dataset.mediaObserver===source.observer_id)!;
      const span=source.window_world_span;
      return {source,node,video:node.querySelector('video')!,canvas:node.querySelector('canvas')!,callback:null,last:null,waiting:false,correction:false,recording:this.world>=span[0]&&this.world<span[1]};
    });
    clock.drive(this.owner);
    panel.dataset.mediaMode='native';
    for (const route of this.routes) {
      const listen=(name: string, fn: () => void) => {route.video.addEventListener(name,fn);this.removers.push(()=>route.video.removeEventListener(name,fn));};
      listen('waiting',()=>{if(this.inWindow(route,this.world)){route.waiting=true;this.block();}});
      listen('canplay',()=>{route.waiting=false;this.resume();});
      listen('seeked',()=>{route.correction=false;route.waiting=false;this.resume();});
      listen('ended',()=>this.ended(route));
      this.watch(route);
    }
    this.choose(); this.resume();
  }
  private inWindow(route: Route, world: number) {
    const span=route.source.window_world_span;
    return world>=span[0] && world<span[1];
  }
  private show(route: Route, recording: boolean) {
    // Native playback is composited directly by the video element. Canvas is
    // reserved for strict paused pictures, avoiding two 720p copies per tick.
    route.canvas.hidden=true;
    route.video.style.visibility=recording?'visible':'hidden';
    const status=route.node.querySelector<HTMLElement>('[role="status"]');
    if(status){status.hidden=recording;status.textContent='未在录';}
    if(!recording){
      route.video.pause();route.canvas.getContext('2d')!.clearRect(0,0,route.canvas.width,route.canvas.height);
      route.node.dataset.mediaStatus='not_recording';route.node.dataset.frameIndex='';route.node.dataset.presentedLocalS='';
    }
  }
  private choose() {
    for(const route of this.routes) {
      const recording=this.inWindow(route,this.world);
      if(recording && !route.recording) {
        route.recording=true;route.correction=true;route.last=null;
        route.canvas.hidden=true;route.video.currentTime=mediaTime(route.source,this.world,'world_s');
        this.block();
      }else if(!recording){route.recording=false;route.last=null;this.show(route,false);}
    }
    if(!this.master || !this.inWindow(this.master,this.world))this.master=this.routes.find(r=>this.inWindow(r,this.world))||null;
    const masterId=this.master?.source.observer_id || '';
    if(this.panel.dataset.mediaMaster!==masterId)this.panel.dataset.mediaMaster=masterId;
    if(!this.master)this.bridgeGap();
  }
  private bridgeGap() {
    if(this.gap!==null || !this.active)return;
    let previous=performance.now();
    const tick=(now: number)=>{
      this.gap=null;if(!this.active || this.master)return;
      this.world=Math.min(this.clock.end,this.world+(now-previous)/1000*this.speed);previous=now;
      this.panel.dataset.mediaWorldS=String(this.world);this.clock.present(this.owner,this.world);
      if(this.world===this.clock.end){this.clock.setPlaying(false);return;}
      this.master=this.routes.find(r=>this.inWindow(r,this.world))||null;
      if(this.master){
        for(const route of this.routes)if(this.inWindow(route,this.world)){
          route.recording=true;route.canvas.hidden=true;route.correction=true;route.video.currentTime=mediaTime(route.source,this.world,'world_s');
        }
        this.block();this.resume();
      }else this.gap=requestAnimationFrame(tick);
    };
    this.gap=requestAnimationFrame(tick);
  }
  private block() {
    if(!this.active)return;
    this.blocked=true;this.panel.dataset.mediaWaiting='true';this.panel.dataset.mediaReady='false';
    for(const route of this.routes)route.video.pause();
  }
  private resume() {
    if(!this.active || !this.master)return;
    const recording=this.routes.filter(r=>this.inWindow(r,this.world));
    if(recording.some(r=>r.waiting || r.correction || mustWait(r.video)))return;
    const restarting=this.blocked || recording.some(r=>r.video.paused);
    // A paused frame remains displayed; do not extrapolate its old display
    // timestamp across a buffering wait when the first new callback arrives.
    if(restarting)for(const route of recording)route.last=null;
    this.blocked=false;this.panel.dataset.mediaWaiting='false';this.panel.dataset.mediaReady='true';
    for(const route of recording){
      if(restarting)route.video.playbackRate=this.speed;
      if(route.video.paused)void route.video.play().catch(error=>{if(this.active && error.name!=='AbortError')this.fail(errorText(error));});
    }
  }
  private ended(route: Route) {
    if(!this.active || route!==this.master)return;
    this.world=route.source.window_world_span[1];
    this.choose();this.panel.dataset.mediaWorldS=String(this.world);this.clock.present(this.owner,this.world);
    if(this.world>=this.clock.end)this.clock.setPlaying(false);else this.resume();
  }
  private watch(route: Route) {
    route.callback=route.video.requestVideoFrameCallback((_now,info)=>{
      if(!this.active)return;
      try {
        const frame=presentedFrame(route.source,info.mediaTime), world=mediaTime(route.source,info.mediaTime,'local_s');
        recordPresentation(route.video,route.source.url,info.mediaTime);
        const index=route.source.frames.indexOf(frame);
        route.last={world,endWorld:route.source.frames[index+1]?.world_s ?? route.source.window_world_span[1],display:info.expectedDisplayTime};
        if(this.inWindow(route,this.world)) {
          this.show(route,true);route.node.dataset.mediaStatus='recording';
          route.node.dataset.frameIndex=String(frame.frame_index);route.node.dataset.worldS=String(world);
          route.node.dataset.presentedLocalS=String(info.mediaTime);
        }
        if(route===this.master && !this.blocked) {
          this.world=world;this.choose();this.panel.dataset.mediaWorldS=String(world);
          this.clock.present(this.owner,world);this.correct(info.expectedDisplayTime);
        }
      }catch(error){this.fail(errorText(error));}
      this.watch(route);
    });
  }
  private correct(display: number) {
    if(!this.master?.last || this.blocked)return;
    const masterWorld=this.master.last.world;
    for(const route of this.routes) {
      if(route===this.master || !route.last || !this.inWindow(route,this.world) || route.video.seeking)continue;
      // Compare presented timestamps on one world axis at one display instant.
      const peerWorld=route.last.world+(display-route.last.display)/1000*route.video.playbackRate;
      const drift=masterWorld-peerWorld;
      if(Math.abs(drift)>SEEK_DRIFT_S) {
        route.correction=true;
        route.video.currentTime=mediaTime(route.source,masterWorld,'world_s');
      }else {
        // A presented PTS identifies a public frame row, not the playback
        // phase within its span. Chasing that quantization makes the rate
        // oscillate even when both displayed frame spans overlap.
        const peerEnd=route.last.endWorld+(display-route.last.display)/1000*route.video.playbackRate;
        const masterEnd=this.master.last.endWorld;
        const rateError=masterWorld>peerEnd ? masterWorld-peerEnd : peerWorld>masterEnd ? masterEnd-peerWorld : 0;
        route.video.playbackRate=nudgedRate(rateError,this.speed);
      }
    }
  }
  setSpeed(speed: number) {this.speed=speed;for(const route of this.routes)route.video.playbackRate=speed;}
  stop() {
    if(!this.active)return;
    this.active=false;if(this.gap!==null)cancelAnimationFrame(this.gap);
    for(const remove of this.removers)remove();
    for(const route of this.routes){route.video.pause();route.video.playbackRate=1;if(route.callback!==null)route.video.cancelVideoFrameCallback(route.callback);}
    this.clock.undrive(this.owner);this.panel.dataset.mediaMode='precise';this.panel.dataset.mediaWaiting='false';
  }
}