【发布时间】:2022-01-01 18:04:31
【问题描述】:
我从事流媒体项目已经有一段时间了。 一切都很好,但是当对大型 MP4 文件进行流式传输时,我得到了 206 错误的部分内容。我确实理解为什么我研究了很多,它似乎是 NodeJS 压缩或其他东西中的错误。 我将整个项目上传到 git-hub。
https://github.com/oyosied/cat-flix-frontend
https://github.com/oyosied/cat-flix-backend
当流在 controllers/videoStream.js getVideoStream 中开始时,我确实从调试大文件中看到了这一点。是不是 Range 标头中的开始等于结束。这很奇怪,我不知道为什么。 如果有人熟悉此问题以及如何解决此问题,我将非常高兴,我尝试更改 ReactPlayers PlyR、VideoJS 等,但没有成功。
exports.getVideoStream = (req, res, next) => {
const DBConn = getDataBaseConnection("getVideoStream");
DBConn().conn.client.connect(function (error, client) {
if (error) {
res.status(500).json(error);
return;
}
// Check for range headers to find our start time
const range = req.headers.range;
if (!range) {
res.status(400).send("Requires Range header");
}
const db = client.db("CatFlix");
// GridFS Collection
db.collection("VideoFiles.files").findOne(
{ _id: mongoose.Types.ObjectId(req.params.id) },
(err, video) => {
if (!video) {
res.status(404).send("Video is not found");
return;
}
console.log(video);
// Create response headers
const videoSize = video.length;
const start = Number(range.replace(/\D/g, ""));
const end = videoSize - 1;
let contentLength = end - start + 1;
const headers = {
"Content-Range": `bytes ${start}-${end}/${videoSize}`,
"Accept-Ranges": "bytes",
"Content-Length": contentLength,
"Content-Type": "video/mp4",
};
// HTTP Status 206 for Partial Content
res.writeHead(206, headers);
// Get the bucket and download stream from GridFS
const bucket = new mongodb.GridFSBucket(db, {
bucketName: "VideoFiles",
});
const downloadStream = bucket.openDownloadStream(video._id, {
start: start,
end: end,
});
// Finally pipe video to response
console.log(
streamCounter,
" start ",
start,
" end ",
end,
"content-length",
contentLength,
"video size",
videoSize
);
streamCounter++;
downloadStream.pipe(res);
}
);
});
};
最有可能出现的问题是流式传输函数和传递的范围标头以最大值而不是 0 开头。示例视频长度为 2:17 秒 起始值为 0,结束值为 164923。此 mp4 约为 6mb。 当我尝试流式传输约 45mb 的视频时,从一开始就开始值为 4178967 结束值为 4178967。
【问题讨论】:
-
查看给定的请求,似乎对于第二个请求上的某些文件,浏览器要求 99% 的块。在某些视频中,它要求一半。不确定是什么导致了这种行为。现在使用 ReactPlayer
-
问题仍未解决。可能与文件大小有关。内容长度以千字节为单位,而不是字节
标签: node.js reactjs mongodb gridfs gridfs-stream