"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useHlsStream = void 0;
var tslib_1 = require("tslib");
var react_1 = require("react");
var utils_1 = require("./utils");
var isHlsUrl = function (url) {
    try {
        return new URL(url).pathname.toLowerCase().endsWith('.m3u8');
    }
    catch (_a) {
        return false;
    }
};
var useHlsStream = function (_a) {
    var src = _a.src, audioRef = _a.audioRef, live = _a.live;
    var hlsRef = (0, react_1.useRef)(null);
    var isHls = isHlsUrl(src);
    var initializeHls = function (audio, src) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
        var Hls_1, setupHls, hls, error_1;
        return tslib_1.__generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, Promise.resolve().then(function () { return tslib_1.__importStar(require('hls.js')); })];
                case 1:
                    Hls_1 = (_a.sent()).default;
                    if (!Hls_1.isSupported()) {
                        console.error('HLS.js not supported');
                        return [2 /*return*/];
                    }
                    setupHls = function (el, audioSrc) {
                        var hls = new Hls_1({
                            enableWorker: true,
                            liveSyncDurationCount: 3,
                            liveMaxLatencyDurationCount: 6,
                            liveDurationInfinity: true,
                            maxLiveSyncPlaybackRate: 1,
                            maxBufferLength: 30,
                            maxBufferSize: 5 * 1000 * 1000,
                            maxBufferHole: 0.5,
                            highBufferWatchdogPeriod: 3,
                            nudgeOffset: 0.1,
                            nudgeMaxRetry: 3,
                            lowLatencyMode: false,
                            manifestLoadPolicy: {
                                default: {
                                    maxTimeToFirstByteMs: 10000,
                                    maxLoadTimeMs: 20000,
                                    timeoutRetry: {
                                        maxNumRetry: 2,
                                        retryDelayMs: 0,
                                        maxRetryDelayMs: 0,
                                    },
                                    errorRetry: {
                                        maxNumRetry: 3,
                                        retryDelayMs: 1000,
                                        maxRetryDelayMs: 8000,
                                    },
                                },
                            },
                            playlistLoadPolicy: {
                                default: {
                                    maxTimeToFirstByteMs: 8000,
                                    maxLoadTimeMs: 20000,
                                    timeoutRetry: {
                                        maxNumRetry: 2,
                                        retryDelayMs: 0,
                                        maxRetryDelayMs: 0,
                                    },
                                    errorRetry: {
                                        maxNumRetry: 4,
                                        retryDelayMs: 500,
                                        maxRetryDelayMs: 4000,
                                    },
                                },
                            },
                            fragLoadPolicy: {
                                default: {
                                    maxTimeToFirstByteMs: 8000,
                                    maxLoadTimeMs: 60000,
                                    timeoutRetry: {
                                        maxNumRetry: 4,
                                        retryDelayMs: 0,
                                        maxRetryDelayMs: 0,
                                    },
                                    errorRetry: {
                                        maxNumRetry: 6,
                                        retryDelayMs: 500,
                                        maxRetryDelayMs: 4000,
                                    },
                                },
                            },
                        });
                        hls.attachMedia(el);
                        hls.loadSource(audioSrc);
                        hls.on(Hls_1.Events.ERROR, function (_e, data) {
                            if (!data.fatal)
                                return;
                            switch (data.type) {
                                case Hls_1.ErrorTypes.NETWORK_ERROR:
                                    return hls.startLoad();
                                case Hls_1.ErrorTypes.MEDIA_ERROR:
                                    return hls.recoverMediaError();
                                default:
                                    console.error('Fatal HLS error', data);
                                    hls.destroy();
                                    hlsRef.current = null;
                            }
                        });
                        return { hls: hls };
                    };
                    hls = setupHls(audio, src).hls;
                    hlsRef.current = hls;
                    return [2 /*return*/, hls];
                case 2:
                    error_1 = _a.sent();
                    console.error('Failed to load HLS.js', error_1);
                    return [3 /*break*/, 3];
                case 3: return [2 /*return*/];
            }
        });
    }); };
    (0, react_1.useEffect)(function () {
        if (!live || !src || !isHls || !(audioRef === null || audioRef === void 0 ? void 0 : audioRef.current))
            return;
        var audio = audioRef.current;
        var shouldUseNativeHls = (0, utils_1.isSafari)() && audio.canPlayType('application/vnd.apple.mpegurl') !== '';
        if (shouldUseNativeHls) {
            audio.src = src;
            return function () {
                audio.src = '';
                audio.load();
            };
        }
        var hlsInitialization = initializeHls(audio, src);
        return function () {
            hlsInitialization.then(function (hls) {
                hls === null || hls === void 0 ? void 0 : hls.stopLoad();
                hls === null || hls === void 0 ? void 0 : hls.detachMedia();
                hls === null || hls === void 0 ? void 0 : hls.destroy();
                hlsRef.current = null;
            });
        };
    }, [src, isHls, audioRef, live]);
    return { isHlsStream: isHls && !!live, hlsInstance: hlsRef };
};
exports.useHlsStream = useHlsStream;
//# sourceMappingURL=use-hls-stream.js.map