fluent-ffmpeg / node-fluent-ffmpeg

A fluent API to FFMPEG (http://www.ffmpeg.org)
MIT License
7.96k stars 881 forks source link

Can someone help me use fetch to transcode and return a response object that is a stream? #1293

Open ralyodio opened 3 months ago

ralyodio commented 3 months ago
async start(url, user = null, pass = null) {
            console.log('Transcoding:', url);
            const headers = {};

            try {
                if (user && pass) {
                    const encodedCredentials = Buffer.from(`${user}:${pass}`).toString('base64');
                    headers['Authorization'] = `Basic ${encodedCredentials}`;
                }

                // Fetch the video from the URL
                const response = await fetch(url, { headers, redirect: 'follow' });

                if (!response.ok) {
                    throw new Error(`Failed to fetch video: ${response.statusText}`);
                }

                // Create a readable stream from the response
                const videoStream = response.body;
                // const videoStream = response.body;

                // const reader = response.body.getReader();
                // const videoStream = new ReadableStream(response.body);

                // Ensure videoStream is a valid readable stream
                if (!videoStream) {
                    throw new Error('Failed to get video stream from response');
                }

                // Create a pass-through stream to handle ffmpeg output
                const outputStream = new PassThrough();

                // outputStream.writable = true;

                // Pipe the video stream through ffmpeg to transcode it to mp4
                ffmpeg(videoStream)
                    .format('mp4')
                    .output(outputStream)
                    .videoCodec('libx264')
                    .audioCodec('aac')
                    .on('start', (commandLine) => {
                        console.log('Spawned Ffmpeg with command: ' + commandLine);
                    })
                    .on('error', (err) => {
                        console.error('Error:', err.message);
                        console.error(err);
                        outputStream.destroy(err); // destroy the stream in case of error
                    })
                    .on('progress', (progress) => {
                        console.log(JSON.stringify(progress, null, 2));
                        console.log('Processing: ' + progress.percent + '% done');
                    })
                    .on('end', () => {
                        console.log('Transcoding finished');
                    })
                    // .pipe(outputStream)
                    .run();

                return outputStream;
            } catch (err) {
                throw err;
            }
        }

I get a conversion error ffmpeg 234

ralyodio commented 3 months ago

I do not want to have to download the entire file first.