recorder.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. 'use strict';
  2. const Fs = require('fs');
  3. const Path = require('path');
  4. const Url = require('url');
  5. const Mime = require('mime-types');
  6. const StreamEach = require('stream-each');
  7. const Oncemore = require('oncemore');
  8. const M3U8Parse = require('m3u8parse');
  9. const Mkdirp = require('mkdirp');
  10. const writeFileAtomic = require('write-file-atomic');
  11. const debug = require('debug')('hls:recorder');
  12. const SegmentDecrypt = require('./segment-decrypt');
  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.collect = !!options.collect; // collect into a single file (v4 feature)
  26. this.decrypt = options.decrypt;
  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. }
  34. StreamEach(this.reader, this.process.bind(this));
  35. this.updateIndex(this.reader.index);
  36. this.reader.on('index', this.updateIndex.bind(this));
  37. };
  38. HlsStreamRecorder.prototype.updateIndex = function(update) {
  39. if (!update) {
  40. return;
  41. }
  42. if (!this.index) {
  43. this.index = new M3U8Parse.M3U8Playlist(update);
  44. if (!this.index.master) {
  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. let 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. }
  63. else {
  64. debug('variants', this.index.variants);
  65. if (this.subreader) {
  66. // remove backup sources
  67. let used = {};
  68. this.index.variants = this.index.variants.filter((variant) => {
  69. let bw = parseInt(variant.info.bandwidth, 10);
  70. let res = !(bw in used);
  71. used[bw] = true;
  72. return res;
  73. });
  74. this.index.variants.forEach((variant, index) => {
  75. let variantUrl = Url.resolve(this.reader.baseUrl, variant.uri);
  76. debug('url', variantUrl);
  77. // check for duplicate source urls
  78. let rec = this.recorderForUrl(variantUrl);
  79. if (!rec || !rec.localUrl) {
  80. let dir = this.variantName(variant.info, index);
  81. rec = new HlsStreamRecorder(this.subreader(variantUrl), Path.join(this.dst, dir), { startOffset: this.startOffset, collect: this.collect, decrypt: this.decrypt });
  82. rec.localUrl = Url.format({pathname: Path.join(dir, 'index.m3u8')});
  83. rec.remoteUrl = variantUrl;
  84. this.recorders.push(rec);
  85. }
  86. variant.uri = rec.localUrl;
  87. });
  88. let allGroups = [];
  89. for (let group in this.index.groups)
  90. Array.prototype.push.apply(allGroups, this.index.groups[group]);
  91. allGroups.forEach((groupItem, index) => {
  92. let srcUri = groupItem.quotedString('uri');
  93. if (srcUri) {
  94. let itemUrl = Url.resolve(this.reader.baseUrl, srcUri);
  95. debug('url', itemUrl);
  96. let rec = this.recorderForUrl(itemUrl);
  97. if (!rec || !rec.localUrl) {
  98. let dir = this.groupSrcName(groupItem, index);
  99. rec = new HlsStreamRecorder(this.subreader(itemUrl), Path.join(this.dst, dir), { startOffset: this.startOffset, collect: this.collect, decrypt: this.decrypt });
  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. });
  107. // start all recordings
  108. this.recorders.forEach((recording) => {
  109. recording.start();
  110. });
  111. this.index.iframes = [];
  112. }
  113. else {
  114. this.index.variants = [];
  115. this.index.groups = {};
  116. this.index.iframes = [];
  117. }
  118. }
  119. // hook end listener
  120. this.reader.on('end', () => {
  121. this.index.ended = true;
  122. this.flushIndex((/*err*/) => {
  123. debug('done');
  124. });
  125. });
  126. if (this.decrypt) {
  127. this.decrypt.base = this.reader.baseUrl;
  128. }
  129. }
  130. // validate update
  131. if (this.index.target_duration > update.target_duration) {
  132. throw new Error('Invalid index');
  133. }
  134. };
  135. HlsStreamRecorder.prototype.process = function(segmentInfo, done) {
  136. let segment = new M3U8Parse.M3U8Segment(segmentInfo.details, true);
  137. let meta = segmentInfo.file;
  138. // mark discontinuities
  139. if (this.nextSegmentSeq !== -1 &&
  140. this.nextSegmentSeq !== segmentInfo.seq) {
  141. segment.discontinuity = true;
  142. }
  143. this.nextSegmentSeq = segmentInfo.seq + 1;
  144. // create our own uri
  145. segment.uri = `${this.segmentName(this.seq)}.${Mime.extension(meta.mime)}`;
  146. // handle byterange
  147. let first = this.index.segments.length === 0;
  148. let newFile = first || this.index.segments[this.index.segments.length - 1].uri !== segment.uri;
  149. if (this.collect) {
  150. segment.byterange = {
  151. length: 0,
  152. offset: newFile ? 0 : null
  153. }
  154. }
  155. else {
  156. delete segment.byterange;
  157. }
  158. // save the stream segment
  159. SegmentDecrypt.decrypt(segmentInfo.stream, segmentInfo.details.keys, this.decrypt, (err, stream, decrypted) => {
  160. if (err) {
  161. console.error('decrypt failed', err.stack);
  162. stream = segmentInfo.stream;
  163. }
  164. else if (decrypted) {
  165. segment.keys = null;
  166. }
  167. stream = Oncemore(stream);
  168. stream.pipe(Fs.createWriteStream(Path.join(this.dst, segment.uri), { flags: newFile ? 'w' : 'a' }));
  169. let bytesWritten = 0;
  170. if (this.collect) {
  171. stream.on('data', (chunk) => {
  172. bytesWritten += chunk.length;
  173. });
  174. }
  175. stream.once('end', 'error', (err) => {
  176. // only to report errors
  177. if (err) debug('stream error', err.stack || err);
  178. if (segment.byterange) {
  179. segment.byterange.length = bytesWritten;
  180. }
  181. // update index
  182. this.index.segments.push(segment);
  183. this.flushIndex(done);
  184. });
  185. this.seq++;
  186. });
  187. };
  188. HlsStreamRecorder.prototype.variantName = function(info, index) {
  189. return `v${index}`;
  190. };
  191. HlsStreamRecorder.prototype.groupSrcName = function(info, index) {
  192. let lang = (info.quotedString('language') || '').replace(/\W/g, '').toLowerCase();
  193. let id = (info.quotedString('group-id') || 'unk').replace(/\W/g, '').toLowerCase();
  194. return `grp/${id}/${lang ? lang + '-' : ''}${index}`;
  195. };
  196. HlsStreamRecorder.prototype.segmentName = function(seqNo) {
  197. const name = (n) => {
  198. let next = ~~(n / 26);
  199. let chr = String.fromCharCode(97 + n % 26); // 'a' + n
  200. if (next) return name(next - 1) + chr;
  201. return chr;
  202. };
  203. return this.collect ? 'stream' : name(seqNo);
  204. };
  205. HlsStreamRecorder.prototype.flushIndex = function(cb) {
  206. let appendString, indexString = this.index.toString().trim();
  207. if (this.lastIndexString && indexString.lastIndexOf(this.lastIndexString, 0) === 0) {
  208. let lastLength = this.lastIndexString.length;
  209. appendString = indexString.substr(lastLength);
  210. }
  211. this.lastIndexString = indexString;
  212. if (appendString) {
  213. Fs.appendFile(Path.join(this.dst, 'index.m3u8'), appendString, cb);
  214. }
  215. else {
  216. writeFileAtomic(Path.join(this.dst, 'index.m3u8'), indexString, cb);
  217. }
  218. };
  219. HlsStreamRecorder.prototype.recorderForUrl = function(remoteUrl) {
  220. let idx, len = this.recorders.length;
  221. for (idx = 0; idx < len; idx++) {
  222. let rec = this.recorders[idx];
  223. if (rec.remoteUrl === remoteUrl) {
  224. return rec;
  225. }
  226. }
  227. return null;
  228. };
  229. const hlsrecorder = module.exports = function hlsrecorder(reader, dst, options) {
  230. return new HlsStreamRecorder(reader, dst, options);
  231. };
  232. hlsrecorder.HlsStreamRecorder = HlsStreamRecorder;