UNPKG

media-recorder-hooks

Version:

React hooks para gerenciar dispositivos de mídia, permissões e streams para aplicações de videoconferência

386 lines (376 loc) 19.4 kB
import { create } from 'zustand'; import { useState, useCallback, useEffect, useMemo } from 'react'; var usePreferencesStore = create(function (set) { return ({ audio: undefined, video: undefined, audioOutput: undefined, muted: false, videoOff: false, set: function (deviceId, type) { var _a; return set((_a = {}, _a[type] = deviceId, _a)); }, toggleMute: function () { return set(function (state) { return ({ muted: !state.muted }); }); }, toggleVideoOff: function () { return set(function (state) { return ({ videoOff: !state.videoOff }); }); }, }); }); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise */ function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var useUserMedia = function (_a) { var _b = _a === void 0 ? {} : _a, _c = _b.preferEnvironmentCamera, preferEnvironmentCamera = _c === void 0 ? false : _c; var preferences = usePreferencesStore(); var _d = useState(), stream = _d[0], setStream = _d[1]; var _e = useState(), activeStream = _e[0], setActiveStream = _e[1]; var _f = useState([]), devices = _f[0], setDevices = _f[1]; var _g = useState(false), ready = _g[0], setReady = _g[1]; var _h = useState(false), accessGranted = _h[0], setAccessGranted = _h[1]; var checkPermission = useCallback(function () { return __awaiter(void 0, void 0, void 0, function () { var _stream, error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, navigator.mediaDevices.getUserMedia({ video: true, audio: true, })]; case 1: _stream = _a.sent(); setAccessGranted(true); stopStreaming(_stream); return [2 /*return*/, { video: true, audio: true }]; case 2: error_1 = _a.sent(); console.error("Error checking permission:", error_1); setAccessGranted(false); return [2 /*return*/, { video: false, audio: false }]; case 3: return [2 /*return*/]; } }); }); }, [setAccessGranted]); var stopStreaming = useCallback(function (_stream) { if (_stream) { _stream.getTracks().forEach(function (track) { return track.stop(); }); } }, []); var requestPermission = useCallback(function () { return __awaiter(void 0, void 0, void 0, function () { var _stream; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, navigator.mediaDevices.getUserMedia({ video: true, audio: true, })]; case 1: _stream = _a.sent(); stopStreaming(_stream); checkPermission(); return [2 /*return*/]; } }); }); }, [stopStreaming, checkPermission]); var updateUserMedia = useCallback(function (constraints) { return __awaiter(void 0, void 0, void 0, function () { var _stream; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, navigator.mediaDevices.getUserMedia({ video: constraints.video && typeof constraints.video === 'string' ? { deviceId: { exact: constraints.video } } : !!constraints.video, audio: constraints.audio && typeof constraints.audio === 'string' ? { deviceId: { exact: constraints.audio } } : !!constraints.audio, })]; case 1: _stream = _a.sent(); _stream.getVideoTracks().forEach(function (track) { track.enabled = !preferences.videoOff; }); _stream.getAudioTracks().forEach(function (track) { track.enabled = !preferences.muted; }); setActiveStream(_stream); setReady(true); return [2 /*return*/, _stream]; } }); }); }, [preferences.muted, preferences.videoOff]); var getDevices = useCallback(function () { return __awaiter(void 0, void 0, void 0, function () { var devices; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, navigator.mediaDevices.enumerateDevices()]; case 1: devices = _a.sent(); setDevices(devices || []); return [2 /*return*/, devices]; } }); }); }, [setDevices]); var toggleMute = useCallback(function () { activeStream === null || activeStream === void 0 ? void 0 : activeStream.getAudioTracks().forEach(function (track) { track.enabled = preferences.muted; }); preferences.toggleMute(); }, [preferences, activeStream]); var toggleVideo = useCallback(function () { activeStream === null || activeStream === void 0 ? void 0 : activeStream.getVideoTracks().forEach(function (track) { track.enabled = preferences.videoOff; }); preferences.toggleVideoOff(); }, [preferences, activeStream]); var switchAudioOutput = useCallback(function (deviceId) { preferences.set(deviceId, "audioOutput"); }, [preferences]); var switchInput = useCallback(function (deviceId, type) { return __awaiter(void 0, void 0, void 0, function () { var newStream, oldVideoTrack, oldAudioTrack, newVideoTrack, newAudioTrack; return __generator(this, function (_a) { switch (_a.label) { case 0: oldVideoTrack = activeStream === null || activeStream === void 0 ? void 0 : activeStream.getVideoTracks()[0]; oldAudioTrack = activeStream === null || activeStream === void 0 ? void 0 : activeStream.getAudioTracks()[0]; if (!oldVideoTrack || !oldAudioTrack) { return [2 /*return*/, undefined]; } if (!(type === "audio")) return [3 /*break*/, 2]; return [4 /*yield*/, navigator.mediaDevices.getUserMedia({ audio: { deviceId: { exact: deviceId } }, video: { deviceId: { exact: preferences.video } }, })]; case 1: newStream = _a.sent(); preferences.set(deviceId, "audio"); return [3 /*break*/, 4]; case 2: return [4 /*yield*/, navigator.mediaDevices.getUserMedia({ audio: { deviceId: { exact: preferences.audio } }, video: { deviceId: { exact: deviceId } }, })]; case 3: newStream = _a.sent(); preferences.set(deviceId, "video"); _a.label = 4; case 4: if (!newStream) return [2 /*return*/, undefined]; newVideoTrack = newStream.getVideoTracks()[0]; newAudioTrack = newStream.getAudioTracks()[0]; newVideoTrack.enabled = !preferences.videoOff; newAudioTrack.enabled = !preferences.muted; stopStreaming(activeStream); setActiveStream(newStream); return [2 /*return*/, { oldVideoTrack: oldVideoTrack, newVideoTrack: newVideoTrack, oldAudioTrack: oldAudioTrack, newAudioTrack: newAudioTrack, newStream: newStream, }]; } }); }); }, [activeStream, preferences, stopStreaming]); var stopAllStreaming = useCallback(function () { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) { stream === null || stream === void 0 ? void 0 : stream.getTracks().forEach(function (track) { return track.stop(); }); return [2 /*return*/]; }); }); }, [stream]); useEffect(function () { if (accessGranted) { getDevices(); } }, [getDevices, accessGranted]); var audioDevices = useMemo(function () { return devices.filter(function (device) { return device.kind === "audioinput" && !!device.deviceId; }); }, [devices]); var outputDevices = useMemo(function () { return devices.filter(function (device) { return device.kind === "audiooutput" && !!device.deviceId; }); }, [devices]); var videoDevices = useMemo(function () { return devices.filter(function (device) { return device.kind === "videoinput" && !!device.deviceId; }); }, [devices]); useEffect(function () { var init = function () { return __awaiter(void 0, void 0, void 0, function () { var permission; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, checkPermission()]; case 1: permission = _a.sent(); if (!permission.audio || !permission.video) { requestPermission(); } return [2 /*return*/]; } }); }); }; init(); }, [checkPermission, getDevices, requestPermission]); useEffect(function () { var init = function () { return __awaiter(void 0, void 0, void 0, function () { var _devices, audio, video, audioOutput, environmentCamera, backCamera, defaultAudio, defaultVideo, defaultOutput, _stream; var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, getDevices()]; case 1: _devices = _b.sent(); audio = preferences.audio || undefined; video = preferences.video || undefined; audioOutput = preferences.audioOutput || undefined; if (!_devices || !_devices.length) { console.log("No devices found"); return [2 /*return*/]; } // Se preferir a câmera "environment", procure por ela if (preferEnvironmentCamera) { environmentCamera = _devices.find(function (device) { return device.kind === "videoinput" && device.label.toLowerCase().includes("environment"); }); if (environmentCamera) { video = environmentCamera.deviceId; console.log("Using environment camera:", environmentCamera.label); } else { console.log("Environment camera not found"); } } // Fallback para procurar a câmera traseira se "environment" não foi encontrado if (!video) { backCamera = _devices.find(function (device) { return device.kind === "videoinput" && device.label.toLowerCase().includes("back"); }) || _devices.find(function (device) { return device.kind === "videoinput" && device.label.toLowerCase().includes("environment"); }); video = backCamera ? backCamera.deviceId : (_a = _devices.find(function (device) { return device.kind === "videoinput"; })) === null || _a === void 0 ? void 0 : _a.deviceId; if (backCamera) { console.log("Using back camera:", backCamera.label); } else { console.log("Using default camera:", video); } } if (!audio) { defaultAudio = _devices.find(function (device) { return device.kind === "audioinput"; }); audio = defaultAudio === null || defaultAudio === void 0 ? void 0 : defaultAudio.deviceId; if (!defaultAudio) console.warn("No audio input found."); } if (!video) { defaultVideo = _devices.find(function (device) { return device.kind === "videoinput"; }); video = defaultVideo === null || defaultVideo === void 0 ? void 0 : defaultVideo.deviceId; if (!defaultVideo) console.warn("No video input found."); } if (!audioOutput) { defaultOutput = _devices.find(function (device) { return device.kind === "audiooutput"; }); audioOutput = defaultOutput === null || defaultOutput === void 0 ? void 0 : defaultOutput.deviceId; if (!defaultOutput) console.warn("No audio output found."); } if (video) { preferences.set(video, "video"); } if (audio) { preferences.set(audio, "audio"); } if (audioOutput) { preferences.set(audioOutput, "audioOutput"); } return [4 /*yield*/, updateUserMedia({ audio: audio || true, video: video || true, })]; case 2: _stream = _b.sent(); setStream(_stream); setActiveStream(_stream); return [2 /*return*/]; } }); }); }; if (accessGranted && !stream) { init(); } }, [ updateUserMedia, accessGranted, stream, getDevices, preferEnvironmentCamera, ]); return { stream: stream, activeStream: activeStream, audioDevices: audioDevices, videoDevices: videoDevices, outputDevices: outputDevices, selectedAudioDevice: preferences.audio, selectedVideoDevice: preferences.video, selectedOutputDevice: preferences.audioOutput, ready: ready, accessGranted: accessGranted, switchInput: switchInput, stopStreaming: stopStreaming, stopAllStreaming: stopAllStreaming, toggleMute: toggleMute, toggleVideo: toggleVideo, switchAudioOutput: switchAudioOutput, muted: preferences.muted, videoOff: preferences.videoOff, checkPermission: checkPermission, }; }; export { usePreferencesStore, useUserMedia }; //# sourceMappingURL=index.esm.js.map