File size: 12,566 Bytes
ec17af3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
import { useCallback, useEffect, useRef, useState } from "react";
import { isSafariBrowser } from "@/lib/browser";

type RecorderState = {
  stream: MediaStream | null;
  recording: boolean;
  paused: boolean;
  error: string | null;
  mimeType: string | null;
  audioOnly: boolean;
};

type Options = {
  videoDeviceId?: string;
  audioDeviceId?: string;
  preferAudioOnly?: boolean;
  onChunk: (chunk: Blob) => void;
};

export const useMediaRecorder = ({ videoDeviceId, audioDeviceId, preferAudioOnly = false, onChunk }: Options) => {
  const recorderRef = useRef<MediaRecorder | null>(null);
  const streamRef = useRef<MediaStream | null>(null);
  const startStreamPromiseRef = useRef<Promise<MediaStream> | null>(null);
  const chunkBufferRef = useRef<Blob[]>([]);
  const stopResolveRef = useRef<((chunks: Blob[]) => void) | null>(null);
  const stopTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const stopFinalizeTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const [state, setState] = useState<RecorderState>({
    stream: null,
    recording: false,
    paused: false,
    error: null,
    mimeType: null,
    audioOnly: preferAudioOnly,
  });

  const resetStream = useCallback(() => {
    streamRef.current?.getTracks().forEach((track) => track.stop());
    streamRef.current = null;
    startStreamPromiseRef.current = null;
    setState((prev) => ({ ...prev, stream: null }));
  }, []);

  const startStream = useCallback(async () => {
    if (streamRef.current) {
      return streamRef.current;
    }

    if (startStreamPromiseRef.current) {
      return startStreamPromiseRef.current;
    }

    startStreamPromiseRef.current = (async () => {
      try {
        if (!navigator.mediaDevices?.getUserMedia) {
          throw new Error("Media devices API not available in this browser context.");
        }

        if (preferAudioOnly) {
          const audioStream = await navigator.mediaDevices.getUserMedia({
            video: false,
            audio: audioDeviceId ? { deviceId: { exact: audioDeviceId } } : true,
          });
          streamRef.current = audioStream;
          setState((prev) => ({ ...prev, stream: audioStream, error: null, audioOnly: true }));
          return audioStream;
        }

        const constraints = {
          video: videoDeviceId
            ? { deviceId: { exact: videoDeviceId } }
            : { facingMode: "user", width: { ideal: 1280 }, height: { ideal: 720 } },
          audio: audioDeviceId ? { deviceId: { exact: audioDeviceId } } : true,
        };

        try {
          let stream = await navigator.mediaDevices.getUserMedia(constraints);
          if (!stream.getVideoTracks().length && constraints.video) {
            stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
          }
          streamRef.current = stream;
          setState((prev) => ({ ...prev, stream, error: null, audioOnly: false }));
          return stream;
        } catch (error) {
          try {
            const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
            streamRef.current = stream;
            setState((prev) => ({
              ...prev,
              stream,
              error: "Fell back to default camera & microphone.",
              audioOnly: false,
            }));
            return stream;
          } catch (fallbackError) {
            try {
              const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
              streamRef.current = stream;
              setState((prev) => ({
                ...prev,
                stream,
                error: "Microphone blocked. Previewing camera video only.",
                audioOnly: false,
              }));
              return stream;
            } catch (_videoOnlyError) {
              try {
                const audioOnlyStream = await navigator.mediaDevices.getUserMedia({ video: false, audio: true });
                streamRef.current = audioOnlyStream;
                setState((prev) => ({
                  ...prev,
                  stream: audioOnlyStream,
                  error: "Camera unavailable — switched automatically to Audio Presenter Mode.",
                  audioOnly: true,
                }));
                return audioOnlyStream;
              } catch (_audioError) {
                const baseError = error instanceof Error ? error : fallbackError;
                const message =
                  baseError instanceof Error
                    ? `${baseError.name}: ${baseError.message}`
                    : "Camera or microphone permission denied";
                setState((prev) => ({ ...prev, error: message }));
                throw baseError;
              }
            }
          }
        }
      } catch (error) {
        const message =
          error instanceof Error
            ? `${error.name}: ${error.message}`
            : "Camera or microphone permission denied";
        setState((prev) => ({ ...prev, error: message }));
        throw error;
      } finally {
        startStreamPromiseRef.current = null;
      }
    })();

    return startStreamPromiseRef.current;
  }, [audioDeviceId, preferAudioOnly, videoDeviceId]);

  const startRecording = useCallback(async () => {
    if (typeof MediaRecorder === "undefined") {
      const message = "MediaRecorder not supported in this browser.";
      setState((prev) => ({ ...prev, error: message }));
      throw new Error(message);
    }
    const isSafari = isSafariBrowser();
    if (streamRef.current && !streamRef.current.active) {
      resetStream();
    }
    const stream = streamRef.current ?? (await startStream());
    const hasVideo = stream.getVideoTracks().length > 0;
    const preferredTypes = !hasVideo
      ? isSafari
        ? ["audio/mp4", "audio/webm;codecs=opus", "audio/webm"]
        : ["audio/webm;codecs=opus", "audio/webm", "audio/mp4"]
      : isSafari
        ? ["video/mp4;codecs=avc1,mp4a.40.2", "video/mp4;codecs=h264,aac", "video/mp4"]
        : [
            "video/webm;codecs=vp9,opus",
            "video/webm;codecs=vp8,opus",
            "video/webm",
            "video/mp4;codecs=h264,aac",
            "video/mp4",
          ];
    const supportedType = preferredTypes.find((type) => MediaRecorder.isTypeSupported(type));
    const recorder = supportedType ? new MediaRecorder(stream, { mimeType: supportedType }) : new MediaRecorder(stream);
    const shouldUseMp4 = Boolean(isSafari || supportedType?.includes("mp4"));
    const fallbackMimeType = !hasVideo
      ? shouldUseMp4
        ? "audio/mp4"
        : "audio/webm"
      : shouldUseMp4
        ? "video/mp4"
        : "video/webm";
    const initialMimeType = recorder.mimeType || supportedType || fallbackMimeType;
    chunkBufferRef.current = [];
    recorderRef.current = recorder;
    recorder.ondataavailable = (event) => {
      if (event.data.size > 0) {
        chunkBufferRef.current.push(event.data);
        onChunk(event.data);
      }
      if (event.data.type) {
        setState((prev) => (prev.mimeType === event.data.type ? prev : { ...prev, mimeType: event.data.type }));
      }
      if (recorder.state === "inactive" && stopResolveRef.current) {
        if (stopFinalizeTimeoutRef.current) {
          clearTimeout(stopFinalizeTimeoutRef.current);
        }
        stopFinalizeTimeoutRef.current = setTimeout(() => {
          stopFinalizeTimeoutRef.current = null;
          stopResolveRef.current?.([...chunkBufferRef.current]);
          stopResolveRef.current = null;
        }, 400);
      }
    };
    recorder.onpause = () => {
      setState((prev) => ({ ...prev, paused: true }));
    };
    recorder.onresume = () => {
      setState((prev) => ({ ...prev, paused: false }));
    };
    recorder.onerror = (event) => {
      const nextError =
        event.error?.message || "Recording failed before any media chunk was produced.";
      setState((prev) => ({ ...prev, error: nextError, recording: false, paused: false }));
    };
    recorder.onstop = () => {
      if (stopTimeoutRef.current) {
        clearTimeout(stopTimeoutRef.current);
        stopTimeoutRef.current = null;
      }
      if (stopResolveRef.current) {
        if (stopFinalizeTimeoutRef.current) {
          clearTimeout(stopFinalizeTimeoutRef.current);
        }
        stopFinalizeTimeoutRef.current = setTimeout(() => {
          stopFinalizeTimeoutRef.current = null;
          stopResolveRef.current?.([...chunkBufferRef.current]);
          stopResolveRef.current = null;
        }, 400);
      }
      setState((prev) => ({ ...prev, recording: false, paused: false }));
    };
    try {
      recorder.start(shouldUseMp4 ? 1000 : 2000);
    } catch (_error) {
      recorder.start();
    }
    setState((prev) => ({
      ...prev,
      recording: true,
      paused: false,
      audioOnly: !hasVideo,
      mimeType: initialMimeType || prev.mimeType,
    }));
  }, [onChunk, resetStream, startStream]);

  const pauseRecording = useCallback(() => {
    const recorder = recorderRef.current;
    if (!recorder) return false;
    if (typeof recorder.pause !== "function") {
      setState((prev) => ({ ...prev, error: "Pause not supported in this browser." }));
      return false;
    }
    if (recorder.state !== "recording") {
      return false;
    }
    try {
      recorder.pause();
      return true;
    } catch (error) {
      const message =
        error instanceof Error ? `${error.name}: ${error.message}` : "Pause failed.";
      setState((prev) => ({ ...prev, error: message }));
      return false;
    }
  }, []);

  const resumeRecording = useCallback(() => {
    const recorder = recorderRef.current;
    if (!recorder) return false;
    if (typeof recorder.resume !== "function") {
      setState((prev) => ({ ...prev, error: "Resume not supported in this browser." }));
      return false;
    }
    if (recorder.state !== "paused") {
      return false;
    }
    try {
      recorder.resume();
      return true;
    } catch (error) {
      const message =
        error instanceof Error ? `${error.name}: ${error.message}` : "Resume failed.";
      setState((prev) => ({ ...prev, error: message }));
      return false;
    }
  }, []);

  const stopRecording = useCallback(() => {
    const recorder = recorderRef.current;
    if (!recorder || recorder.state === "inactive") {
      return Promise.resolve([...chunkBufferRef.current]);
    }

    if (stopTimeoutRef.current) {
      clearTimeout(stopTimeoutRef.current);
      stopTimeoutRef.current = null;
    }
    if (stopFinalizeTimeoutRef.current) {
      clearTimeout(stopFinalizeTimeoutRef.current);
      stopFinalizeTimeoutRef.current = null;
    }

    return new Promise<Blob[]>((resolve) => {
      stopResolveRef.current = resolve;
      stopTimeoutRef.current = setTimeout(() => {
        stopTimeoutRef.current = null;
        if (stopFinalizeTimeoutRef.current) {
          clearTimeout(stopFinalizeTimeoutRef.current);
          stopFinalizeTimeoutRef.current = null;
        }
        stopResolveRef.current?.([...chunkBufferRef.current]);
        stopResolveRef.current = null;
      }, isSafariBrowser() ? 5000 : 2500);

      try {
        if (!isSafariBrowser() && typeof recorder.requestData === "function" && recorder.state === "recording") {
          recorder.requestData();
        }
        recorder.stop();
      } catch (error) {
        if (stopTimeoutRef.current) {
          clearTimeout(stopTimeoutRef.current);
          stopTimeoutRef.current = null;
        }
        stopResolveRef.current?.([...chunkBufferRef.current]);
        stopResolveRef.current = null;
        throw error;
      }
      setState((prev) => ({ ...prev, recording: false, paused: false }));
    });
  }, []);

  const stopTracks = useCallback(() => {
    if (stopTimeoutRef.current) {
      clearTimeout(stopTimeoutRef.current);
      stopTimeoutRef.current = null;
    }
    if (stopFinalizeTimeoutRef.current) {
      clearTimeout(stopFinalizeTimeoutRef.current);
      stopFinalizeTimeoutRef.current = null;
    }
    stopResolveRef.current = null;
    recorderRef.current = null;
    resetStream();
  }, [resetStream]);

  const stopStream = useCallback(() => {
    stopTracks();
    setState((prev) => ({ ...prev, stream: null }));
  }, [stopTracks]);

  useEffect(() => () => stopTracks(), [stopTracks]);

  return {
    ...state,
    startStream,
    startRecording,
    pauseRecording,
    resumeRecording,
    stopRecording,
    stopStream,
  };
};