recorder.js 7.0 KB

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