aboutsummaryrefslogtreecommitdiffstats
path: root/youtube/static/js/watch.hls.js
blob: cedfbf3034eb2023eb486e8ddd5537f802137010 (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
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,
            startLevel: -1,
        });

        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:
                        hls.startLoad();
                        break;
                    case Hls.ErrorTypes.MEDIA_ERROR:
                        hls.recoverMediaError();
                        break;
                    default:
                        hls.destroy();
                        break;
                }
            }
        });

    } 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');
    if (qualitySelect) {
        qualitySelect.addEventListener('change', function () {
            const level = parseInt(this.value);

            if (hls) {
                hls.currentLevel = level;
                console.log('Quality:', level === -1 ? 'Auto' : hls.levels[level]?.height + 'p');
            }
        });
    }
}

// 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 trackId = this.value;

            if (hls && hls.audioTracks) {
                const index = hls.audioTracks.findIndex(t =>
                    t.lang === trackId || t.name === trackId
                );

                if (index !== -1) {
                    hls.audioTrack = index;
                    console.log('Audio track changed to:', index);
                }
            }
        });
    }

    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>';
                data.audioTracks.forEach(track => {
                    const option = document.createElement('option');
                    option.value = track.lang || track.name;
                    option.textContent = track.name || track.lang || `Track ${track.id}`;
                    audioTrackSelect.appendChild(option);
                });
                audioTrackSelect.disabled = false;
            }
        });
    }
});

// ============
// 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);
        }
    }
})();