Streaming chunks of video using javascript

Using JavaScript I am trying to receive chunks of video and display them in a html video tag. but in the code I have, after displaying 3 or 4 chunks, it gets stuck and doesn’t move to the next chunk.
can you help me with this?


// Fetch an encrypted video chunk from the server
async function fetchChunk(chunkIndex) {
    const url = `http://localhost/video/encrypted_chunks/chunk_${chunkIndex}.enc`;
    try {
        const response = await fetch(url);
        if (response.ok) {
            return await response.arrayBuffer();
        } else {
            console.error(`Failed to fetch chunk ${chunkIndex}: Status ${response.status}`);
            return null;
        }
    } catch (error) {
        console.error(`Error fetching chunk ${chunkIndex}:`, error);
        return null;
    }
}

function appendBuffer(sourceBuffer, decryptedData) {
    return new Promise((resolve, reject) => {
        function onUpdateEnd() {
            sourceBuffer.removeEventListener('updateend', onUpdateEnd);
            resolve();
        }

        if (sourceBuffer.updating) {
            sourceBuffer.addEventListener('updateend', onUpdateEnd, { once: true });
        } else {
            sourceBuffer.appendBuffer(new Uint8Array(decryptedData));
            resolve();
        }
    });
}

// Finalize the MediaSource stream
function finalizeStream(mediaSource) {
    if (mediaSource.readyState === 'open') {
        mediaSource.endOfStream();
    }
}

// Main function to handle video streaming
async function streamVideo() {
    const mediaSource = new MediaSource();
    const video = document.getElementById('videoPlayer');
    video.src = URL.createObjectURL(mediaSource);

    mediaSource.addEventListener('sourceopen', async () => {
        const sourceBuffer = mediaSource.addSourceBuffer('video/webm; codecs="vp8, vorbis"');
        let chunkIndex = 1;

        const filename = 'sample-2.webm'; // Replace with the actual filename
        const { key, iv } = await calculateKeyIv(filename);

        // Function to handle fetching, decrypting, and appending chunks
        async function handleChunks() {
            try {
                while (true) {
                    if (sourceBuffer.updating) {
                        await new Promise(resolve => sourceBuffer.addEventListener('updateend', resolve, { once: true }));
                    }

                    const encryptedData = await fetchChunk(chunkIndex);
                    if (!encryptedData) break; // No more data

                    const decryptedData = await decryptChunk(encryptedData, key, iv);
                    await appendBuffer(sourceBuffer, decryptedData);

                    chunkIndex++;
                }

                // Wait for buffer to be done updating before finalizing
                if (!sourceBuffer.updating) {
                    finalizeStream(mediaSource);
                    createWatermark();
                }
            } catch (error) {
                console.error('Error processing chunks:', error);
            }
        }

        // Start processing chunks
        handleChunks();
    });
}

// Call the streamVideo function to start streaming
streamVideo();

I think the problem is probably with the buffer but I’m new to JavaScript and I haven’t been able to debug it!