recorder.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. 'use strict';
  2. const Path = require('path');
  3. const Url = require('url');
  4. const Mime = require('mime-types');
  5. const StreamEach = require('stream-each');
  6. const M3U8Parse = require('m3u8parse');
  7. const debug = require('debug')('hls:recorder');
  8. const HlsUploader = require('./hls-uploader');
  9. const SegmentDecrypt = require('./segment-decrypt');
  10. // add custom extensions
  11. Mime.extensions['audio/aac'] = ['aac'];
  12. Mime.extensions['audio/ac3'] = ['ac3'];
  13. function HlsStreamRecorder(reader, dst, options) {
  14. options = options || {};
  15. this.reader = reader;
  16. this.dst = dst; // target directory / s3 url
  17. this.nextSegmentSeq = -1;
  18. this.seq = 0;
  19. this.index = null;
  20. this.startOffset = parseFloat(options.startOffset);
  21. this.subreader = options.subreader;
  22. this.collect = !!options.collect; // collect into a single file (v4 feature)
  23. this.decrypt = options.decrypt;
  24. this.recorders = [];
  25. this.mapSeq = 0;
  26. this.nextMap = null;
  27. this.uploader = null;
  28. this.segmentHead = 0;
  29. }
  30. HlsStreamRecorder.prototype.start = function() {
  31. this.uploader = new HlsUploader(this.dst, { collect: this.collect });
  32. StreamEach(this.reader, this.process.bind(this));
  33. this.updateIndex(this.reader.index);
  34. this.reader.on('index', this.updateIndex.bind(this));
  35. };
  36. HlsStreamRecorder.prototype.updateIndex = function(update) {
  37. if (!update) {
  38. return;
  39. }
  40. if (!this.index) {
  41. this.index = new M3U8Parse.M3U8Playlist(update);
  42. if (!this.index.master) {
  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. let 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. }
  61. else {
  62. debug('variants', this.index.variants);
  63. if (this.subreader) {
  64. // remove backup sources
  65. let used = {};
  66. this.index.variants = this.index.variants.filter((variant) => {
  67. let bw = parseInt(variant.info.bandwidth, 10);
  68. let res = !(bw in used);
  69. used[bw] = true;
  70. return res;
  71. });
  72. this.index.variants.forEach((variant, index) => {
  73. let variantUrl = Url.resolve(this.reader.baseUrl, variant.uri);
  74. debug('url', variantUrl);
  75. // check for duplicate source urls
  76. let rec = this.recorderForUrl(variantUrl);
  77. if (!rec || !rec.localUrl) {
  78. let dir = this.variantName(variant.info, index);
  79. rec = new HlsStreamRecorder(this.subreader(variantUrl), Path.join(this.dst, dir), { startOffset: this.startOffset, collect: this.collect, decrypt: this.decrypt });
  80. rec.localUrl = Url.format({pathname: Path.join(dir, 'index.m3u8')});
  81. rec.remoteUrl = variantUrl;
  82. this.recorders.push(rec);
  83. }
  84. variant.uri = rec.localUrl;
  85. });
  86. let allGroups = [];
  87. for (let group in this.index.groups)
  88. Array.prototype.push.apply(allGroups, this.index.groups[group]);
  89. allGroups.forEach((groupItem, index) => {
  90. let srcUri = groupItem.quotedString('uri');
  91. if (srcUri) {
  92. let itemUrl = Url.resolve(this.reader.baseUrl, srcUri);
  93. debug('url', itemUrl);
  94. let rec = this.recorderForUrl(itemUrl);
  95. if (!rec || !rec.localUrl) {
  96. let dir = this.groupSrcName(groupItem, index);
  97. rec = new HlsStreamRecorder(this.subreader(itemUrl), Path.join(this.dst, dir), { startOffset: this.startOffset, collect: this.collect, decrypt: this.decrypt });
  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. });
  105. // start all recordings
  106. this.recorders.forEach((recording) => {
  107. recording.start();
  108. });
  109. this.index.iframes = [];
  110. }
  111. else {
  112. this.index.variants = [];
  113. this.index.groups = {};
  114. this.index.iframes = [];
  115. }
  116. }
  117. // hook end listener
  118. this.reader.on('end', () => {
  119. this.index.ended = true;
  120. this.flushIndex((/*err*/) => {
  121. debug('done');
  122. });
  123. });
  124. if (this.decrypt) {
  125. this.decrypt.base = this.reader.baseUrl;
  126. }
  127. }
  128. // validate update
  129. if (this.index.target_duration > update.target_duration) {
  130. throw new Error('Invalid index');
  131. }
  132. };
  133. HlsStreamRecorder.prototype.process = function (segmentInfo, next) {
  134. if (segmentInfo.type === 'segment') {
  135. return this.processSegment(segmentInfo, next);
  136. }
  137. if (segmentInfo.type === 'init') {
  138. return this.processInfo(segmentInfo, next);
  139. }
  140. debug('unknown segment type: ' + segmentInfo.type);
  141. return next();
  142. };
  143. HlsStreamRecorder.prototype.processInfo = function (segmentInfo, callback) {
  144. const meta = segmentInfo.file;
  145. const uri = `${this.segmentName(this.mapSeq, true)}.${Mime.extension(meta.mime)}`;
  146. this.writeStream(segmentInfo.stream, uri, meta, (err, bytesWritten) => {
  147. // only to report errors
  148. if (err) debug('stream error', err.stack || err);
  149. const map = new M3U8Parse.AttrList();
  150. map.quotedString('uri', uri);
  151. // handle byterange
  152. if (this.collect) {
  153. map.quotedString('byterange', `${bytesWritten}@${this.uploader.segmentBytes - bytesWritten}`);
  154. }
  155. this.nextMap = map;
  156. return callback();
  157. });
  158. this.mapSeq++;
  159. };
  160. HlsStreamRecorder.prototype.processSegment = function (segmentInfo, callback) {
  161. let segment = new M3U8Parse.M3U8Segment(segmentInfo.segment.details, true);
  162. let meta = segmentInfo.file;
  163. // mark discontinuities
  164. if (this.nextSegmentSeq !== -1 &&
  165. this.nextSegmentSeq !== segmentInfo.segment.seq) {
  166. segment.discontinuity = true;
  167. }
  168. this.nextSegmentSeq = segmentInfo.segment.seq + 1;
  169. // create our own uri
  170. segment.uri = `${this.segmentName(this.seq)}.${Mime.extension(meta.mime)}`;
  171. // add map info
  172. if (this.nextMap) {
  173. segment.map = this.nextMap;
  174. this.nextMap = null;
  175. }
  176. delete segment.byterange;
  177. // save the stream segment
  178. SegmentDecrypt.decrypt(segmentInfo.stream, segmentInfo.segment.details.keys, this.decrypt, (err, stream, decrypted) => {
  179. if (err) {
  180. console.error('decrypt failed', err.stack);
  181. stream = segmentInfo.stream;
  182. }
  183. else if (decrypted) {
  184. segment.keys = null;
  185. meta = { mime: meta.mime, modified: meta.modified }; // size is no longer valid
  186. }
  187. this.writeStream(stream, segment.uri, meta, (err, bytesWritten) => {
  188. // only to report errors
  189. if (err) debug('stream error', err.stack || err);
  190. // handle byterange
  191. if (this.collect) {
  192. const isContigious = this.segmentHead > 0 && ((this.segmentHead + bytesWritten) === this.uploader.segmentBytes);
  193. segment.byterange = {
  194. length: bytesWritten,
  195. offset: isContigious ? null : this.uploader.segmentBytes - bytesWritten
  196. }
  197. this.segmentHead = this.uploader.segmentBytes;
  198. }
  199. // update index
  200. this.index.segments.push(segment);
  201. this.flushIndex(callback);
  202. });
  203. this.seq++;
  204. });
  205. };
  206. HlsStreamRecorder.prototype.writeStream = function (stream, name, meta, callback) {
  207. this.uploader.pushSegment(stream, name, meta).then((written) => callback(null, written), callback);
  208. };
  209. HlsStreamRecorder.prototype.variantName = function(info, index) {
  210. return `v${index}`;
  211. };
  212. HlsStreamRecorder.prototype.groupSrcName = function(info, index) {
  213. let lang = (info.quotedString('language') || '').replace(/\W/g, '').toLowerCase();
  214. let id = (info.quotedString('group-id') || 'unk').replace(/\W/g, '').toLowerCase();
  215. return `grp/${id}/${lang ? lang + '-' : ''}${index}`;
  216. };
  217. HlsStreamRecorder.prototype.segmentName = function(seqNo, isInit) {
  218. const name = (n) => {
  219. let next = ~~(n / 26);
  220. let chr = String.fromCharCode(97 + n % 26); // 'a' + n
  221. if (next) return name(next - 1) + chr;
  222. return chr;
  223. };
  224. return this.collect ? 'stream' : (isInit ? 'init-' : '') + name(seqNo);
  225. };
  226. HlsStreamRecorder.prototype.flushIndex = function(cb) {
  227. this.uploader.flushIndex(this.index).then(() => cb(), cb);
  228. };
  229. HlsStreamRecorder.prototype.recorderForUrl = function(remoteUrl) {
  230. let idx, len = this.recorders.length;
  231. for (idx = 0; idx < len; idx++) {
  232. let rec = this.recorders[idx];
  233. if (rec.remoteUrl === remoteUrl) {
  234. return rec;
  235. }
  236. }
  237. return null;
  238. };
  239. const hlsrecorder = module.exports = function hlsrecorder(reader, dst, options) {
  240. return new HlsStreamRecorder(reader, dst, options);
  241. };
  242. hlsrecorder.HlsStreamRecorder = HlsStreamRecorder;