recorder.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. /*jslint node: true */
  2. "use strict";
  3. var fs = require('fs'),
  4. path = require('path'),
  5. url = require('url'),
  6. util = require('util');
  7. var mime = require('mime-types'),
  8. streamprocess = require('streamprocess'),
  9. oncemore = require('oncemore'),
  10. m3u8parse = require('m3u8parse'),
  11. mkdirp = require('mkdirp'),
  12. writeFileAtomic = require('write-file-atomic'),
  13. debug = require('debug')('hls:recorder');
  14. var SegmentDecrypt = require('./segment-decrypt');
  15. // add custom extensions
  16. mime.extensions['audio/aac'] = ['aac'];
  17. mime.extensions['audio/ac3'] = ['ac3'];
  18. function HlsStreamRecorder(reader, dst, options) {
  19. options = options || {};
  20. this.reader = reader;
  21. this.dst = dst; // target directory
  22. this.nextSegmentSeq = -1;
  23. this.seq = 0;
  24. this.index = null;
  25. this.startOffset = parseFloat(options.startOffset);
  26. this.subreader = options.subreader;
  27. this.collect = !!options.collect; // collect into a single file (v4 feature)
  28. this.decrypt = options.decrypt;
  29. this.recorders = [];
  30. }
  31. HlsStreamRecorder.prototype.start = function() {
  32. // TODO: make async?
  33. if (!fs.existsSync(this.dst))
  34. mkdirp.sync(this.dst);
  35. streamprocess(this.reader, this.process.bind(this));
  36. this.updateIndex(this.reader.index);
  37. this.reader.on('index', this.updateIndex.bind(this));
  38. };
  39. HlsStreamRecorder.prototype.updateIndex = function(update) {
  40. var self = this;
  41. if (!update) return;
  42. if (!this.index) {
  43. this.index = new m3u8parse.M3U8Playlist(update);
  44. if (!this.index.variant) {
  45. if (this.collect)
  46. this.index.version = Math.max(4, this.index.version); // v4 is required for byterange support
  47. this.index.version = Math.max(2, this.index.version); // v2 is required to support the remapped IV attribute
  48. if (this.index.version !== update.version)
  49. debug('changed index version to:', this.index.version);
  50. this.index.segments = [];
  51. this.index.first_seq_no = this.seq;
  52. this.index.type = 'EVENT';
  53. this.index.ended = false;
  54. this.index.discontinuity_sequence = 0; // not allowed in event playlists
  55. if (!isNaN(this.startOffset)) {
  56. var offset = this.startOffset;
  57. if (!update.ended) {
  58. if (offset < 0) offset = Math.min(offset, -3 * this.index.target_duration);
  59. }
  60. this.index.start.decimalInteger('time-offset', offset);
  61. }
  62. } else {
  63. debug('programs', this.index.programs);
  64. if (this.subreader) {
  65. var programNo = Object.keys(this.index.programs)[0];
  66. var programs = this.index.programs[programNo];
  67. // remove backup sources
  68. var used = {};
  69. programs = programs.filter(function(program) {
  70. var bw = parseInt(program.info.bandwidth, 10);
  71. var res = !(bw in used);
  72. used[bw] = true;
  73. return res;
  74. });
  75. this.index.programs[programNo] = programs;
  76. programs.forEach(function(program, index) {
  77. var programUrl = url.resolve(self.reader.baseUrl, program.uri);
  78. debug('url', programUrl);
  79. // check for duplicate source urls
  80. var rec = this.recorderForUrl(programUrl);
  81. if (!rec || !rec.localUrl) {
  82. var dir = self.variantName(program.info, index);
  83. rec = new HlsStreamRecorder(self.subreader(programUrl), path.join(self.dst, dir), { startOffset: self.startOffset, collect: self.collect, decrypt: this.decrypt });
  84. rec.localUrl = url.format({pathname: path.join(dir, 'index.m3u8')});
  85. rec.remoteUrl = programUrl;
  86. this.recorders.push(rec);
  87. }
  88. program.uri = rec.localUrl;
  89. }, this);
  90. var allGroups = [];
  91. for (var group in this.index.groups)
  92. [].push.apply(allGroups, this.index.groups[group]);
  93. allGroups.forEach(function(groupItem, index) {
  94. var srcUri = groupItem.quotedString('uri');
  95. if (srcUri) {
  96. var itemUrl = url.resolve(self.reader.baseUrl, srcUri);
  97. debug('url', itemUrl);
  98. var rec = this.recorderForUrl(itemUrl);
  99. if (!rec || !rec.localUrl) {
  100. var dir = self.groupSrcName(groupItem, index);
  101. rec = new HlsStreamRecorder(self.subreader(itemUrl), path.join(self.dst, dir), { startOffset: self.startOffset, collect: self.collect, decrypt: this.decrypt });
  102. rec.localUrl = url.format({pathname: path.join(dir, 'index.m3u8')});
  103. rec.remoteUrl = itemUrl;
  104. this.recorders.push(rec);
  105. }
  106. groupItem.quotedString('uri', rec.localUrl);
  107. }
  108. }, this);
  109. // start all recordings
  110. this.recorders.forEach(function(recording) {
  111. recording.start();
  112. });
  113. this.index.iframes = {};
  114. } else {
  115. this.index.programs = {};
  116. this.index.groups = {};
  117. this.index.iframes = {};
  118. }
  119. }
  120. // hook end listener
  121. this.reader.on('end', function() {
  122. self.index.ended = true;
  123. self.flushIndex(function(/*err*/) {
  124. debug('done');
  125. });
  126. });
  127. if (this.decrypt) {
  128. this.decrypt.base = this.reader.baseUrl;
  129. }
  130. }
  131. // validate update
  132. if (this.index.target_duration > update.target_duration)
  133. throw new Error('Invalid index');
  134. };
  135. HlsStreamRecorder.prototype.process = function(segmentInfo, done) {
  136. var self = this;
  137. var segment = new m3u8parse.M3U8Segment(segmentInfo.details, true);
  138. var meta = segmentInfo.file;
  139. // mark discontinuities
  140. if (this.nextSegmentSeq !== -1 &&
  141. this.nextSegmentSeq !== segmentInfo.seq)
  142. segment.discontinuity = true;
  143. this.nextSegmentSeq = segmentInfo.seq + 1;
  144. // create our own uri
  145. segment.uri = util.format('%s.%s', this.segmentName(this.seq), mime.extension(meta.mime));
  146. // handle byterange
  147. var first = self.index.segments.length === 0;
  148. var newFile = first || self.index.segments[self.index.segments.length - 1].uri !== segment.uri;
  149. if (this.collect) {
  150. segment.byterange = {
  151. length: 0,
  152. offset: newFile ? 0 : null
  153. }
  154. } else {
  155. delete segment.byterange;
  156. }
  157. // save the stream segment
  158. SegmentDecrypt.decrypt(segmentInfo.stream, segmentInfo.details.key, this.decrypt, function (err, stream, decrypted) {
  159. if (err) {
  160. console.error('decrypt failed', err.stack);
  161. stream = segmentInfo.stream;
  162. } else if (decrypted) {
  163. segment.key = null;
  164. }
  165. stream = oncemore(stream);
  166. stream.pipe(fs.createWriteStream(path.join(self.dst, segment.uri), { flags: newFile ? 'w' : 'a' }));
  167. var bytesWritten = 0;
  168. if (self.collect) {
  169. stream.on('data', function(chunk) {
  170. bytesWritten += chunk.length;
  171. });
  172. }
  173. stream.once('end', 'error', function(err) {
  174. // only to report errors
  175. if (err) debug('stream error', err.stack || err);
  176. if (segment.byterange)
  177. segment.byterange.length = bytesWritten;
  178. // update index
  179. self.index.segments.push(segment);
  180. self.flushIndex(done);
  181. });
  182. self.seq++;
  183. });
  184. };
  185. HlsStreamRecorder.prototype.variantName = function(info, index) {
  186. return util.format('v%d', index);
  187. };
  188. HlsStreamRecorder.prototype.groupSrcName = function(info, index) {
  189. var lang = (info.quotedString('language') || '').replace(/\W/g, '').toLowerCase();
  190. var id = (info.quotedString('group-id') || 'unk').replace(/\W/g, '').toLowerCase();
  191. return util.format('grp/%s/%s%d', id, lang ? lang + '-' : '', index);
  192. };
  193. HlsStreamRecorder.prototype.segmentName = function(seqNo) {
  194. function name(n) {
  195. var next = ~~(n / 26);
  196. var chr = String.fromCharCode(97 + n % 26); // 'a' + n
  197. if (next) return name(next - 1) + chr;
  198. return chr;
  199. }
  200. return this.collect ? 'stream' : name(seqNo);
  201. };
  202. HlsStreamRecorder.prototype.flushIndex = function(cb) {
  203. var appendString, indexString = this.index.toString().trim();
  204. if (this.lastIndexString && indexString.lastIndexOf(this.lastIndexString, 0) === 0) {
  205. var lastLength = this.lastIndexString.length;
  206. appendString = indexString.substr(lastLength);
  207. }
  208. this.lastIndexString = indexString;
  209. if (appendString) {
  210. fs.appendFile(path.join(this.dst, 'index.m3u8'), appendString, cb);
  211. } else {
  212. writeFileAtomic(path.join(this.dst, 'index.m3u8'), indexString, cb);
  213. }
  214. };
  215. HlsStreamRecorder.prototype.recorderForUrl = function(remoteUrl) {
  216. var idx, len = this.recorders.length;
  217. for (idx = 0; idx < len; idx++) {
  218. var rec = this.recorders[idx];
  219. if (rec.remoteUrl === remoteUrl)
  220. return rec;
  221. }
  222. return null;
  223. };
  224. var hlsrecorder = module.exports = function hlsrecorder(reader, dst, options) {
  225. return new HlsStreamRecorder(reader, dst, options);
  226. };
  227. hlsrecorder.HlsStreamRecorder = HlsStreamRecorder;