recorder.js 8.0 KB

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