File size: 7,645 Bytes
752f539
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
export type OptimizedNativeVideo = {
  blob: Blob;
  durationSeconds: number;
  ext: 'webm';
};

const OUTPUT_WIDTH = 540;
const OUTPUT_HEIGHT = 960;
const OUTPUT_FPS = 24;
const OUTPUT_VIDEO_BITRATE = 1_100_000;
const OUTPUT_AUDIO_BITRATE = 32_000;
const MAX_OPTIMIZED_SECONDS = 5;

const recorderMimePriority = [
  'video/webm;codecs=vp8,opus',
  'video/webm;codecs=vp9,opus',
  'video/webm',
];

function pickRecorderMime() {
  if (typeof MediaRecorder === 'undefined') return undefined;
  for (const mime of recorderMimePriority) {
    if (MediaRecorder.isTypeSupported(mime)) return mime;
  }
  return undefined;
}

function drawContainedVideo(
  ctx: CanvasRenderingContext2D,
  video: HTMLVideoElement,
  width: number,
  height: number,
) {
  const sourceWidth = video.videoWidth || width;
  const sourceHeight = video.videoHeight || height;
  const scale = Math.min(width / sourceWidth, height / sourceHeight);
  const drawWidth = sourceWidth * scale;
  const drawHeight = sourceHeight * scale;
  const dx = (width - drawWidth) / 2;
  const dy = (height - drawHeight) / 2;

  ctx.fillStyle = '#0e0d0b';
  ctx.fillRect(0, 0, width, height);
  ctx.drawImage(video, dx, dy, drawWidth, drawHeight);
}

function createSilentAudioTrack() {
  const AudioContextCtor =
    window.AudioContext ??
    (window as typeof window & { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;
  if (!AudioContextCtor) return null;

  const audioContext = new AudioContextCtor();
  const oscillator = audioContext.createOscillator();
  const gain = audioContext.createGain();
  const destination = audioContext.createMediaStreamDestination();

  gain.gain.value = 0;
  oscillator.connect(gain);
  gain.connect(destination);
  oscillator.start();

  const track = destination.stream.getAudioTracks()[0];
  if (!track) {
    oscillator.stop();
    void audioContext.close();
    return null;
  }

  return {
    track,
    close: () => {
      try {
        oscillator.stop();
      } catch {
        /* ignore */
      }
      track.stop();
      void audioContext.close();
    },
  };
}

async function probeDuration(blob: Blob, fallbackSeconds: number) {
  return await new Promise<number>((resolve) => {
    const url = URL.createObjectURL(blob);
    const video = document.createElement('video');
    let settled = false;

    const finish = (duration: number) => {
      if (settled) return;
      settled = true;
      URL.revokeObjectURL(url);
      resolve(duration);
    };

    const timer = window.setTimeout(() => finish(fallbackSeconds), 3000);
    video.preload = 'metadata';
    video.muted = true;
    video.onloadedmetadata = () => {
      window.clearTimeout(timer);
      finish(Number.isFinite(video.duration) ? Math.max(0, video.duration) : fallbackSeconds);
    };
    video.onerror = () => {
      window.clearTimeout(timer);
      finish(fallbackSeconds);
    };
    video.src = url;
  });
}

export async function optimizeNativeVideoClip(
  blob: Blob,
  maxSeconds: number,
  onProgress?: (progress: number) => void,
): Promise<OptimizedNativeVideo> {
  if (
    typeof MediaRecorder === 'undefined' ||
    typeof HTMLCanvasElement === 'undefined' ||
    typeof HTMLCanvasElement.prototype.captureStream !== 'function'
  ) {
    throw new Error('This phone cannot prepare the native video for stitching.');
  }

  const silentAudio = createSilentAudioTrack();
  if (!silentAudio) {
    throw new Error('This phone could not prepare audio for the native video.');
  }

  const url = URL.createObjectURL(blob);
  const video = document.createElement('video');
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d', { alpha: false });

  if (!ctx) {
    silentAudio.close();
    URL.revokeObjectURL(url);
    throw new Error('Could not prepare this shot for stitching.');
  }

  canvas.width = OUTPUT_WIDTH;
  canvas.height = OUTPUT_HEIGHT;

  const waitForMetadata = new Promise<void>((resolve, reject) => {
    const timer = window.setTimeout(() => reject(new Error('Video took too long to load.')), 5000);
    video.onloadedmetadata = () => {
      window.clearTimeout(timer);
      resolve();
    };
    video.onerror = () => {
      window.clearTimeout(timer);
      reject(new Error('That shot could not be read. Please record it again.'));
    };
  });

  video.preload = 'auto';
  video.muted = true;
  video.playsInline = true;
  video.src = url;
  await waitForMetadata;

  const sourceDuration = Number.isFinite(video.duration) ? video.duration : maxSeconds;
  const durationLimit = Math.max(
    1,
    Math.min(sourceDuration, maxSeconds, MAX_OPTIMIZED_SECONDS),
  );
  const stream = canvas.captureStream(OUTPUT_FPS);
  stream.addTrack(silentAudio.track);

  const mimeType = pickRecorderMime();
  const recorder = mimeType
    ? new MediaRecorder(stream, {
        mimeType,
        videoBitsPerSecond: OUTPUT_VIDEO_BITRATE,
        audioBitsPerSecond: OUTPUT_AUDIO_BITRATE,
      })
    : new MediaRecorder(stream, {
        videoBitsPerSecond: OUTPUT_VIDEO_BITRATE,
        audioBitsPerSecond: OUTPUT_AUDIO_BITRATE,
      });
  const chunks: Blob[] = [];

  return await new Promise<OptimizedNativeVideo>((resolve, reject) => {
    let raf = 0;
    let timeout = 0;
    let forceFinishTimeout = 0;
    let settled = false;

    const cleanup = () => {
      if (raf) window.cancelAnimationFrame(raf);
      if (timeout) window.clearTimeout(timeout);
      if (forceFinishTimeout) window.clearTimeout(forceFinishTimeout);
      video.pause();
      stream.getTracks().forEach((track) => track.stop());
      silentAudio.close();
      URL.revokeObjectURL(url);
    };

    const finish = () => {
      if (settled) return;
      settled = true;
      cleanup();
      const output = new Blob(chunks, { type: mimeType ?? 'video/webm' });
      if (output.size <= 0) {
        reject(new Error('That shot did not save cleanly. Please record it again.'));
        return;
      }
      onProgress?.(1);
      resolve({
        blob: output,
        durationSeconds: Math.max(1, Math.round(Math.min(video.currentTime, durationLimit))),
        ext: 'webm',
      });
    };

    const stopRecorder = () => {
      if (recorder.state === 'inactive') {
        finish();
        return;
      }

      try {
        recorder.requestData();
      } catch {
        /* ignore */
      }

      try {
        recorder.stop();
      } catch {
        finish();
        return;
      }

      forceFinishTimeout = window.setTimeout(finish, 1800);
    };

    const draw = () => {
      drawContainedVideo(ctx, video, OUTPUT_WIDTH, OUTPUT_HEIGHT);
      onProgress?.(Math.min(0.98, video.currentTime / durationLimit));

      if (video.ended || video.currentTime >= durationLimit) {
        stopRecorder();
        return;
      }

      raf = window.requestAnimationFrame(draw);
    };

    recorder.ondataavailable = (event) => {
      if (event.data.size > 0) chunks.push(event.data);
    };
    recorder.onerror = () => {
      if (settled) return;
      settled = true;
      cleanup();
      reject(new Error('Could not optimize this shot. Please record a shorter clip.'));
    };
    recorder.onstop = finish;

    timeout = window.setTimeout(stopRecorder, (durationLimit + 3) * 1000);
    recorder.start(500);
    void video.play().then(draw).catch(() => {
      if (settled) return;
      settled = true;
      cleanup();
      reject(new Error('Could not play this shot for stitching.'));
    });
  });
}

export async function estimateNativeVideoDuration(blob: Blob, fallbackSeconds: number) {
  return Math.max(1, Math.round(await probeDuration(blob, fallbackSeconds)));
}