recorder.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. debug = require('debug')('hls:recorder');
  13. // add custom types for ext mapping
  14. mime.define({
  15. 'audio/aac': ['aac'],
  16. 'audio/ac3': ['ac3'],
  17. });
  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.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.index.version < 2) {
  44. // version 2 is required to support the remapped IV attribute
  45. this.index.version = 2;
  46. debug('changed index version to:', this.index.version);
  47. }
  48. this.index.segments = [];
  49. this.index.first_seq_no = self.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 (offset < 0) offset = Math.min(offset, -3 * this.target_duration);
  56. this.index.start.decimalInteger('offset', offset);
  57. }
  58. } else {
  59. debug('programs', this.index.programs);
  60. if (this.subreader) {
  61. var programNo = Object.keys(this.index.programs)[0];
  62. var programs = this.index.programs[programNo];
  63. // remove backup sources
  64. var used = {};
  65. programs = programs.filter(function(program) {
  66. var bw = parseInt(program.info.bandwidth, 10);
  67. var res = !(bw in used);
  68. used[bw] = true;
  69. return res;
  70. });
  71. this.index.programs[programNo] = programs;
  72. programs.forEach(function(program, index) {
  73. var programUrl = url.resolve(self.reader.baseUrl, program.uri);
  74. debug('url', programUrl);
  75. // check for duplicate source urls
  76. var rec = this.recorderForUrl(programUrl);
  77. if (!rec || !rec.localUrl) {
  78. var dir = self.variantName(program.info, index);
  79. rec = new HlsStreamRecorder(self.subreader(programUrl), path.join(self.dst, dir), { startOffset: self.startOffset });
  80. rec.localUrl = url.format({pathname: path.join(dir, 'index.m3u8')});
  81. rec.remoteUrl = programUrl;
  82. this.recorders.push(rec);
  83. }
  84. program.uri = rec.localUrl;
  85. }, this);
  86. var allGroups = [];
  87. for (var group in this.index.groups)
  88. [].push.apply(allGroups, this.index.groups[group]);
  89. allGroups.forEach(function(groupItem, index) {
  90. var srcUri = groupItem.quotedString('uri');
  91. if (srcUri) {
  92. var itemUrl = url.resolve(self.reader.baseUrl, srcUri);
  93. debug('url', itemUrl);
  94. var rec = this.recorderForUrl(itemUrl);
  95. if (!rec || !rec.localUrl) {
  96. var dir = self.groupSrcName(groupItem, index);
  97. rec = new HlsStreamRecorder(self.subreader(itemUrl), path.join(self.dst, dir), { startOffset: self.startOffset });
  98. rec.localUrl = url.format({pathname: path.join(dir, 'index.m3u8')});
  99. rec.remoteUrl = itemUrl;
  100. this.recorders.push(rec);
  101. }
  102. groupItem.quotedString('uri', rec.localUrl);
  103. }
  104. }, this);
  105. // start all recordings
  106. this.recorders.forEach(function(recording) {
  107. recording.start();
  108. });
  109. this.index.iframes = {};
  110. } else {
  111. this.index.programs = {};
  112. this.index.groups = {};
  113. this.index.iframes = {};
  114. }
  115. }
  116. // hook end listener
  117. this.reader.on('end', function() {
  118. self.index.ended = true;
  119. self.flushIndex(function(/*err*/) {
  120. debug('done');
  121. });
  122. });
  123. }
  124. // validate update
  125. if (this.index.target_duration > update.target_duration)
  126. throw new Error('Invalid index');
  127. };
  128. HlsStreamRecorder.prototype.process = function(obj, next) {
  129. var self = this;
  130. var segment = new m3u8parse.M3U8Segment(obj.segment);
  131. var meta = obj.meta;
  132. // mark discontinuities
  133. if (this.nextSegmentSeq !== -1 &&
  134. this.nextSegmentSeq !== obj.seq)
  135. segment.discontinuity = true;
  136. this.nextSegmentSeq = obj.seq + 1;
  137. // create our own uri
  138. segment.uri = util.format('%s.%s', this.segmentName(this.seq), mime.extension(meta.mime));
  139. // save the stream segment
  140. var stream = oncemore(obj.stream);
  141. stream.pipe(fs.createWriteStream(path.join(this.dst, segment.uri)));
  142. stream.once('end', 'error', function(err) {
  143. // only to report errors
  144. if (err) debug('stream error', err.stack || err);
  145. // update index
  146. self.index.segments.push(segment);
  147. self.flushIndex(next);
  148. });
  149. this.seq++;
  150. };
  151. HlsStreamRecorder.prototype.variantName = function(info, index) {
  152. return util.format('v%d', index);
  153. };
  154. HlsStreamRecorder.prototype.groupSrcName = function(info, index) {
  155. var lang = (info.quotedString('language') || '').replace(/\W/g, '').toLowerCase();
  156. var id = (info.quotedString('group-id') || 'unk').replace(/\W/g, '').toLowerCase();
  157. return util.format('grp/%s/%s%d', id, lang ? lang + '-' : '', index);
  158. };
  159. HlsStreamRecorder.prototype.segmentName = function(seqNo) {
  160. function name(n) {
  161. var next = ~~(n / 26);
  162. var chr = String.fromCharCode(97 + n % 26); // 'a' + n
  163. if (next) return name(next - 1) + chr;
  164. return chr;
  165. }
  166. return name(seqNo);
  167. };
  168. HlsStreamRecorder.prototype.flushIndex = function(cb) {
  169. var appendString, indexString = this.index.toString().trim();
  170. if (this.lastIndexString && indexString.lastIndexOf(this.lastIndexString, 0) === 0) {
  171. var lastLength = this.lastIndexString.length;
  172. appendString = indexString.substr(lastLength);
  173. }
  174. this.lastIndexString = indexString;
  175. if (appendString) {
  176. fs.appendFile(path.join(this.dst, 'index.m3u8'), appendString, cb);
  177. } else {
  178. fs.writeFile(path.join(this.dst, 'index.m3u8'), indexString, cb);
  179. }
  180. };
  181. HlsStreamRecorder.prototype.recorderForUrl = function(remoteUrl) {
  182. var idx, len = this.recorders.length;
  183. for (idx = 0; idx < len; idx++) {
  184. var rec = this.recorders[idx];
  185. if (rec.remoteUrl === remoteUrl)
  186. return rec;
  187. }
  188. return null;
  189. };
  190. var hlsrecorder = module.exports = function hlsrecorder(reader, dst, options) {
  191. return new HlsStreamRecorder(reader, dst, options);
  192. };
  193. hlsrecorder.HlsStreamRecorder = HlsStreamRecorder;