Skip to content

Instantly share code, notes, and snippets.

@Qquanwei
Last active November 26, 2018 01:21
Show Gist options
  • Save Qquanwei/68ff490b8a183af472f0e432a39dc696 to your computer and use it in GitHub Desktop.
Save Qquanwei/68ff490b8a183af472f0e432a39dc696 to your computer and use it in GitHub Desktop.
video stream server
"use strict"
let koa = require('koa');
let Router = require('koa-router');
let fs = require('fs');
let assert = require('http-assert');
let sscanf = require('scanf').sscanf;
let app = new koa();
let router = new Router();
let hash_streams = {} ;
//partial size
const SEED_SIZE = 5*1024*1024;
router.get('/file',function*(ctx,next){
assert(this.query.filename,400,'Can\'t find the file');
const self = this;
const filename = this.query.filename;
const range = sscanf(this.request.header.range,'bytes=%d-%d\r\n','begin','end');
yield new Promise(function(resolve,done){
fs.stat(filename,function(err,stat){
assert(!err,404,'Nothing!');
range.begin = range.begin || 0;
range.end =Math.min( range.end || (range.begin + SEED_SIZE ),stat.size-1);
assert(range.begin < range.end,403,`${range.begin} ${range.end}`);
let stream = null;
//if(!(filename in hash_streams))
stream = fs.createReadStream(filename,{start: range.begin,end: range.end,autoClose: true });
self.set('Cache-Control','no-cache');
self.set('Content-Range',`bytes ${range.begin}-${range.end}/${stat.size}`);
self.set('Content-Length',range.end-range.begin+1);
self.set('Date',Date());
self.set('ETag',Date.now().toString());
self.set('Expires',new Date(Date.now()+24*60*60*1000));
self.set('Content-type','text/plain');
self.body = stream;
self.status = 206;
resolve('done');
});
});
});
app.use(function*(next){
try{
yield next;
}catch(e){
this.status = 403;
this.body = e.message;
}
});
app.use(router.routes());
const start = function(cb){
return app.listen(1333,'127.0.0.1',cb);
}
module.exports = {
start
}
@Qquanwei
Copy link
Author

Qquanwei commented Sep 4, 2016

require video source

<body>
   <video source="http://127.0.0.1:1337/file?filename=/tmp/music.mp4" type="video/mp4">
</body>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment