ffmpeg transcoding video
Not sure if running this in a google cloud function would time out if it takes too long? Probably better to consider using google cloud compute or google engine?
in a Google Cloud Function that is triggered by the upload Google Cloud Storage bucket.
Interesting how it uses stream to save the output of ffmpeg back into the bucket
1
const storage = require('@google-cloud/storage')();
2
const ffmpegPath = require('@ffmpeg-installer/ffmpeg').path;
3
const ffmpeg = require('fluent-ffmpeg');
4
​
5
const transcodedBucket = storage.bucket('transcode');
6
const uploadBucket = storage.bucket('upload');
7
ffmpeg.setFfmpegPath(ffmpegPath);
8
​
9
exports.transcodeVideo = function transcodeVideo(event, callback) {
10
const file = event.data;
11
​
12
// Ensure that you only proceed if the file is newly created, and exists.
13
if (file.metageneration !== '1' || file.resourceState !== 'exists') {
14
callback();
15
return;
16
}
17
​
18
// Open write stream to new bucket, modify the filename as needed.
19
const remoteWriteStream = transcodedBucket.file(file.name.replace('.webm', '.mp4'))
20
.createWriteStream({
21
metadata: {
22
metadata: file.metadata, // You may not need this, my uploads have associated metadata
23
contentType: 'video/mp4', // This could be whatever else you are transcoding to
24
},
25
});
26
​
27
// Open read stream to our uploaded file
28
const remoteReadStream = uploadBucket.file(file.name).createReadStream();
29
​
30
// Transcode
31
ffmpeg()
32
.input(remoteReadStream)
33
.outputOptions('-c:v copy') // Change these options to whatever suits your needs
34
.outputOptions('-c:a aac')
35
.outputOptions('-b:a 160k')
36
.outputOptions('-f mp4')
37
.outputOptions('-preset fast')
38
.outputOptions('-movflags frag_keyframe+empty_moov')
39
// https://github.com/fluent-ffmpeg/node-fluent-ffmpeg/issues/346#issuecomment-67299526
40
.on('start', (cmdLine) => {
41
console.log('Started ffmpeg with command:', cmdLine);
42
})
43
.on('end', () => {
44
console.log('Successfully re-encoded video.');
45
callback();
46
})
47
.on('error', (err, stdout, stderr) => {
48
console.error('An error occured during encoding', err.message);
49
console.error('stdout:', stdout);
50
console.error('stderr:', stderr);
51
callback(err);
52
})
53
.pipe(remoteWriteStream, { end: true }); // end: true, emit end event when readable stream ends
54
};
Copied!
Last modified 1yr ago
Copy link