简体   繁体   中英

How to convert the stream from h265 to h264

I'm trying to create a media server using nodejs, and i have no problem streaming any formats but Since web browsers cant play H265 codec videos i need to convert them to H264 while createReadStream creates a chunk so that i dont have to convert them completely before hand, just that chunk which is sent by the server to the browser.

const path = 'assets/yourfavmov.mkv';
const stat = fs.statSync(path);
const fileSize = stat.size;
const range = req.headers.range;
if (range) {  
const rangeArray = range.replace(/bytes=/, "").split("-"); 
console.log(rangeArray) 
const start = parseInt(rangeArray[0], 10); 
const end = rangeArray[1] ? parseInt(rangeArray[1], 10) : fileSize-1; 
const chunksize = (end-start) + 1; 
const fileChunk = fs.createReadStream(path, {start, end});
const head = {
    'Content-Range': `bytes ${start}-${end}/${fileSize}`,  
    'Accept-Ranges': 'bytes', 
    'Content-Length': chunksize, 
    'Content-Type': 'video/x-matroska' 
};
res.writeHead(206, head); 
fileChunk.pipe(res); 
} else {
   res.end("wont let you stream");
}

I tried to convert the stream using ffmpeg-stream, like so

const converter = new Converter();
const input = converter.createInputStream({
      f: "matroska,webm",
      vcodec : "hevc"
})
const fileChunk = fs.createReadStream(path, {start, end}); 
fileChunk.pipe(input);
converter
  .createOutputStream({ f: "matroska,webm", vcodec: "h264" })
  .pipe(res);

But i have no idea what i did is correct or wrong, so no luck so is there an way to do it right?

Thanks in advance.

"is there an way to do it right":

Not out of the box, no. What you are trying to do is called "Just in time" transcoding, and it is extremely complex. You must take into account container timestamps, audio priming samples, video sequence headers, and a few other things. ffmpeg does not do this for you. For all intents and purposes, what you want to do is not possible with open source tools today.

What you should do is do the encoding BEFORE the video is requested. (just in time encoding means you re-encode EVERY time someone watches the movie, which is really inefficient)

Netflix is not encoding your videos when you request them - Netflix has a library of videos encoded and ready to go when the request is made.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM