Search code examples
expressgoogle-cloud-storagepipe

expressJS pipe video from GCS


I am sure this question has been asked a million times, but I am having issues with the following script. It works fine in Safari browsers but not Firefox or Chrome.

app.get('/stream', async (req, res) => {
  const bucket = storage.bucket("REMOVED");
  const file = bucket.file("syndication/2023/09/1696116750736video_Kelly_finished.mp4");

  const stat = await file.getMetadata();
  const fileSize = stat[0].size;
  res.set({
    "Content-Length": fileSize.toString(),
    "Accept-Ranges": "bytes",
    Connection: "Keep-Alive",
    "Keep-Alive": "timeout=2, max=100",
    "Content-Type": "video/mp4",
    "X-Accel-Buffering": "no"
  });
  
  // Pipe the video stream to the response
  const stream = file.createReadStream();

  stream.pipe(res)
});

I am wondering if anyone knows how to pipe a video file.

It works fine when it's a mp3.

When I code it like this

app.get('/stream', async (req, res) => {
  const fileStream = storage.bucket("REMOVED").file("syndication/2023/09/1696116750736video_Kelly_finished.mp4");
  const [metadata] = await fileStream.getMetadata();
  const fileSize = metadata.size;
 
  // Set appropriate headers to allow the audio to play in the browser and track streaming duration
  res.set('Content-Type', 'video/mp4');
  res.set('Content-Length', fileSize.toString()); // Convert fileSize to a string
  res.set('Accept-Ranges', 'bytes');
  //res.set('Cache-Control', 'public, max-age=3600'); // Cache the file for 1 hour (adjust as needed)

  fileStream.createReadStream().pipe(res);
});

it works in microsoft edge (chrome) but not Firefox


Solution

  • The issue is the codec used it should not use any h.264 or h.265

    I am not sure why some mp4 work but I know when I encoded the videos with

    ffmpeg -i $INPUT_VIDEO -c:v libx264 -profile:v main -preset medium -b:v 1M -c:a aac -pix_fmt yuv420p $OUTPUT_VIDEO
    
    

    It worked.