aboutsummaryrefslogtreecommitdiffstats
path: root/youtube/static/js/watch.hls.js
blob: 38e80a978c77a1fa445bceba85aef3e6efb283dd (plain)
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
362
363
364
365
366
367
368
369
370
371
372
373
const video = document.getElementById('js-video-player');

window.hls = null;
let hls = null;

// ===========
// HLS NATIVE
// ===========
function initHLSNative(manifestUrl) {
    if (!manifestUrl) {
        console.error('No HLS manifest URL provided');
        return;
    }

    console.log('Initializing native HLS player with manifest:', manifestUrl);

    if (hls) {
        window.hls = null;
        hls.destroy();
        hls = null;
    }

    if (Hls.isSupported()) {
        hls = new Hls({
            enableWorker: true,
            lowLatencyMode: false,
            maxBufferLength: 30,
            maxMaxBufferLength: 60,
            maxBufferHole: 0.5,
            startLevel: -1,
            // Prevent stalls on quality switch: nudge playback past small gaps
            nudgeMaxRetry: 5,
            // Allow more time for segments coming through our proxy
            fragLoadingTimeOut: 30000,
            fragLoadingMaxRetry: 5,
            fragLoadingRetryDelay: 1000,
            levelLoadingTimeOut: 15000,
            levelLoadingMaxRetry: 4,
            levelLoadingRetryDelay: 1000,
        });

        window.hls = hls;

        hls.loadSource(manifestUrl);
        hls.attachMedia(video);

        hls.on(Hls.Events.MANIFEST_PARSED, function(event, data) {
            console.log('Native manifest parsed');
            console.log('Levels:', data.levels.length);

            const qualitySelect = document.getElementById('quality-select');

            if (qualitySelect && data.levels?.length) {
                qualitySelect.innerHTML = '<option value="-1">Auto</option>';

                const sorted = [...data.levels].sort((a, b) => b.height - a.height);
                const seen = new Set();

                sorted.forEach(level => {
                    if (!seen.has(level.height)) {
                        seen.add(level.height);

                        const i = data.levels.indexOf(level);
                        const opt = document.createElement('option');

                        opt.value = i;
                        opt.textContent = level.height + 'p';

                        qualitySelect.appendChild(opt);
                    }
                });

                // Set initial quality from settings
                if (typeof window.data !== 'undefined' && window.data.settings) {
                    const defaultRes = window.data.settings.default_resolution;
                    if (defaultRes !== 'auto' && defaultRes) {
                        const target = parseInt(defaultRes);
                        let bestLevel = -1;
                        let bestHeight = 0;
                        for (let i = 0; i < hls.levels.length; i++) {
                            const h = hls.levels[i].height;
                            if (h <= target && h > bestHeight) {
                                bestHeight = h;
                                bestLevel = i;
                            }
                        }
                        if (bestLevel !== -1) {
                            hls.currentLevel = bestLevel;
                            qualitySelect.value = bestLevel;
                            console.log('Starting at resolution:', bestHeight + 'p');
                        }
                    }
                }
            }
        });

        hls.on(Hls.Events.ERROR, function(_, data) {
            if (data.fatal) {
                console.error('HLS fatal error:', data.type, data.details);
                switch(data.type) {
                    case Hls.ErrorTypes.NETWORK_ERROR:
                        console.warn('HLS network error, attempting recovery...');
                        hls.startLoad();
                        break;
                    case Hls.ErrorTypes.MEDIA_ERROR:
                        console.warn('HLS media error, attempting recovery...');
                        hls.recoverMediaError();
                        break;
                    default:
                        hls.destroy();
                        break;
                }
            } else {
                // Non-fatal errors can still cause stalls, especially
                // bufferStalledError after a quality switch through our proxy
                console.warn('HLS non-fatal error:', data.type, data.details);
                if (data.details === 'bufferStalledError') {
                    // Buffer ran dry — HLS.js is waiting for data.
                    // Nudge it to retry loading the current fragment.
                    hls.startLoad();
                }
            }
        });

    } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
        video.src = manifestUrl;
    } else {
        console.error('HLS not supported');
    }
}

// ======
// INIT
// ======
function initPlayer() {
    console.log('Init native player');

    if (typeof hls_manifest_url === 'undefined' || !hls_manifest_url) {
        console.error('No manifest URL');
        return;
    }

    initHLSNative(hls_manifest_url);

    const qualitySelect = document.getElementById('quality-select');
    // Set initial Auto option while manifest loads
    if (qualitySelect) {
        qualitySelect.innerHTML = '<option value="-1" selected>Auto</option>';
    }
    if (qualitySelect) {
        qualitySelect.addEventListener('change', function () {
            const level = parseInt(this.value);

            if (hls) {
                const currentTime = video.currentTime;
                const wasPaused = video.paused;

                // Use nextLevel for smoother transition: it waits for the
                // current segment to finish before switching, avoiding an
                // abrupt buffer flush that starves the player.
                if (level === -1) {
                    // Back to auto — re-enable ABR
                    hls.currentLevel = -1;
                    console.log('Quality: Auto (ABR)');
                } else {
                    hls.nextLevel = level;
                    console.log('Quality: switching to',
                                hls.levels[level]?.height + 'p');
                }

                // If the video was already stalled, kick the loader
                // so it starts fetching the new level immediately.
                if (video.readyState < 3) {
                    hls.startLoad(currentTime);
                }
            }
        });
    }
}

// DOM READY
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initPlayer);
} else {
    initPlayer();
}

// =============
// AUDIO TRACKS
// =============
document.addEventListener('DOMContentLoaded', function() {
    const audioTrackSelect = document.getElementById('audio-track-select');

    if (audioTrackSelect) {
        audioTrackSelect.addEventListener('change', function() {
            const trackIdx = parseInt(this.value);

            if (!isNaN(trackIdx) && hls && hls.audioTracks && trackIdx >= 0 && trackIdx < hls.audioTracks.length) {
                hls.audioTrack = trackIdx;
                console.log('Audio track changed to:', hls.audioTracks[trackIdx].name || trackIdx);
            }
        });
    }

    if (hls) {
        hls.on(Hls.Events.AUDIO_TRACKS_UPDATED, (_, data) => {
            console.log('Audio tracks:', data.audioTracks);

            // Populate audio track select if needed
            if (audioTrackSelect && data.audioTracks.length > 0) {
                audioTrackSelect.innerHTML = '<option value="">Select audio track</option>';
                let originalIdx = -1;
                data.audioTracks.forEach((track, idx) => {
                    // Find "original" track
                    if (originalIdx === -1 && (track.name || '').toLowerCase().includes('original')) {
                        originalIdx = idx;
                    }
                    const option = document.createElement('option');
                    option.value = String(idx);
                    option.textContent = track.name || track.lang || `Track ${idx}`;
                    audioTrackSelect.appendChild(option);
                });
                audioTrackSelect.disabled = false;

                // Auto-select "original" audio track
                if (originalIdx !== -1) {
                    hls.audioTrack = originalIdx;
                    audioTrackSelect.value = String(originalIdx);
                    console.log('Auto-selected original audio track:', data.audioTracks[originalIdx].name);
                }
            }
        });
    }
});

// ============
// START TIME
// ============
if (typeof data !== 'undefined' && data.time_start != 0 && video) {
    video.addEventListener('loadedmetadata', function() {
        video.currentTime = data.time_start;
    });
}

// ==============
// SPEED CONTROL
// ==============
let speedInput = document.getElementById('speed-control');

if (speedInput) {
    speedInput.addEventListener('keyup', (event) => {
        if (event.key === 'Enter') {
            let speed = parseFloat(speedInput.value);
            if(!isNaN(speed)){
                video.playbackRate = speed;
            }
        }
    });
}

// =========
// Autoplay
// =========
(function() {
    if (typeof data === 'undefined' || (data.settings.related_videos_mode === 0 && data.playlist === null)) {
        return;
    }

    let playability_error = !!data.playability_error;
    let isPlaylist = false;
    if (data.playlist !== null && data.playlist['current_index'] !== null)
        isPlaylist = true;

    // read cookies on whether to autoplay
    // https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
    let cookieValue;
    let playlist_id;
    if (isPlaylist) {
        // from https://stackoverflow.com/a/6969486
        function escapeRegExp(string) {
            // $& means the whole matched string
            return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        }
        playlist_id = data.playlist['id'];
        playlist_id = escapeRegExp(playlist_id);

        cookieValue = document.cookie.replace(new RegExp(
            '(?:(?:^|.*;\\s*)autoplay_'
            + playlist_id + '\\s*\\=\\s*([^;]*).*$)|^.*$'
        ), '$1');
    } else {
        cookieValue = document.cookie.replace(new RegExp(
            '(?:(?:^|.*;\\s*)autoplay\\s*\\=\\s*([^;]*).*$)|^.*$'
        ),'$1');
    }

    let autoplayEnabled = 0;
    if(cookieValue.length === 0){
        autoplayEnabled = 0;
    } else {
        autoplayEnabled = Number(cookieValue);
    }

    // check the checkbox if autoplay is on
    let checkbox = document.querySelector('.autoplay-toggle');
    if(autoplayEnabled){
        checkbox.checked = true;
    }

    // listen for checkbox to turn autoplay on and off
    let cookie = 'autoplay'
    if (isPlaylist)
        cookie += '_' + playlist_id;

    checkbox.addEventListener( 'change', function() {
        if(this.checked) {
            autoplayEnabled = 1;
            document.cookie = cookie + '=1; SameSite=Strict';
        } else {
            autoplayEnabled = 0;
            document.cookie = cookie + '=0; SameSite=Strict';
        }
    });

    if(!playability_error){
        // play the video if autoplay is on
        if(autoplayEnabled){
            video.play().catch(function(e) {
                // Autoplay blocked by browser - ignore silently
                console.log('Autoplay blocked:', e.message);
            });
        }
    }

    // determine next video url
    let nextVideoUrl;
    if (isPlaylist) {
        let currentIndex = data.playlist['current_index'];
        if (data.playlist['current_index']+1 == data.playlist['items'].length)
            nextVideoUrl = null;
        else
            nextVideoUrl = data.playlist['items'][data.playlist['current_index']+1]['url'];

        // scroll playlist to proper position
        // item height + gap == 100
        let pl = document.querySelector('.playlist-videos');
        pl.scrollTop = 100*currentIndex;
    } else {
        if (data.related.length === 0)
            nextVideoUrl = null;
        else
            nextVideoUrl = data.related[0]['url'];
    }
    let nextVideoDelay = 1000;

    // go to next video when video ends
    // https://stackoverflow.com/a/2880950
    if (nextVideoUrl) {
        if(playability_error){
            videoEnded();
        } else {
            video.addEventListener('ended', videoEnded, false);
        }
        function nextVideo(){
            if(autoplayEnabled){
                window.location.href = nextVideoUrl;
            }
        }
        function videoEnded(e) {
            window.setTimeout(nextVideo, nextVideoDelay);
        }
    }
})();