code
stringlengths
2
1.05M
"use strict"; angular.module('myApp', ['ionic','ngCordova','myApp.controllers']) .run(function($ionicPlatform, $cordovaStatusbar) { // どうもうまく動作しない // $ionicPlatform.ready(function() { // }); // document.addEventListener("deviceready", function() { // $cordovaStatusbar.overlaysWebView(true); // }, false); ionic.Platform.ready(function(){ $cordovaStatusbar.overlaysWebView(true); }); }) ;
var express = require('express'); var request = require('request'); var cheerio = require('cheerio'); var cache = require('memory-cache'); var config = require('../config'); var routes = function (s) { var productRouter = express.Router(); var prds = [] ; var item = {} ; var scrape = function(html){ var $ = cheerio.load(html); prds = [] ; $('.product-container').each(function (i, el) { try { item = {}; item['site'] = s.site; item['href'] = $(this).find('.product-image-container').children('a').attr('href').split(/[?#]/)[0]; item['image_tn'] = $(this).find('.product-image-container').find('img').attr('src'); item['product'] = $(this).find('.product-image-container').children('a').attr('title'); item['price'] = Number($(this).find('.product-price').html().trim().split(/ /)[0].trim()); item['stock'] = $(this).find(' .out-of-stock').html() === null ? 1 : 0 ; prds.push(item); } catch (e) { console.log(i + item['product'] + e); } }); }; productRouter.route('/Products') .get(function(req, res) { var options = { url: s.burl + '/en/search?controller=search&orderby=position&orderway=desc&search_query='+req.query.q+'&submit_search=', headers: { 'User-Agent': 'Request' } }; var html = cache.get( s.site + '-' + req.query.q ); if(html){ scrape(html) ; //console.log(html); res.set(config.res_headers).status(200).json(prds); } else { request(options, function (error, response, html) { console.log('request callback ' + s.site); if (error) { res.set(config.res_headers).send(500); } else { cache.put(s.site + '-' + req.query.q, html, config.cache_expiry) ; scrape(html) ; res.set(config.res_headers).status(200).json(prds); } }); } }); return productRouter; }; module.exports = routes;
import React, { Component } from 'react'; import FitImage from 'react-native-fit-image'; import { StyleSheet, View, ListView, } from 'react-native'; import { MoviePoster, } from '../'; export default class MovieGrid extends React.Component { constructor(props) { super(props); const rows = createRows(props.movies); this.state = { dataSource: ds.cloneWithRows(rows), }; this.handleOnEndReached = this.handleOnEndReached.bind(this); } componentWillReceiveProps(nextProps) { if(this.props.movies === nextProps.movies) return; const rows = createRows(nextProps.movies); this.setState({ dataSource: ds.cloneWithRows(rows), }); } handleOnEndReached() { if(!!this.props.onEndReached) { this.props.onEndReached() } } render() { return ( <ListView enableEmptySections={true} dataSource={this.state.dataSource} renderRow={(array) => { return ( <View style={styles.row}> { array.map((movie) => { return ( <MoviePoster movie={movie} key={movie.id}/> ) }) } { array.length == 1 && <View style={{flex: 0.5}}></View> } </View> ) }} style={styles.container} onEndReached={this.handleOnEndReached} /> ); } }; MovieGrid.propTypes = { movies: React.PropTypes.array.isRequired, onEndReached: React.PropTypes.func, }; const styles = StyleSheet.create({ container: { flex: 1, }, row: { flexDirection: 'row', flex: 1, paddingRight: 3, }, }); const createRows = function(movies) { if(!movies) { return []; } let i,j; let rows = []; let chunk = 2; for (i = 0, j = movies.length; i<j; i+=chunk) { let temparray = movies.slice(i,i+chunk); rows.push(temparray); } return rows; } const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
// Default Settings jqueryPopup = Object(); jqueryPopup.defaultSettings = { centerBrowser:0, // center window over browser window? {1 (YES) or 0 (NO)}. overrides top and left centerScreen:0, // center window over entire screen? {1 (YES) or 0 (NO)}. overrides top and left height:500, // sets the height in pixels of the window. left:0, // left position when the window appears. location:0, // determines whether the address bar is displayed {1 (YES) or 0 (NO)}. menubar:0, // determines whether the menu bar is displayed {1 (YES) or 0 (NO)}. resizable:0, // whether the window can be resized {1 (YES) or 0 (NO)}. Can also be overloaded using resizable. scrollbars:0, // determines whether scrollbars appear on the window {1 (YES) or 0 (NO)}. status:0, // whether a status line appears at the bottom of the window {1 (YES) or 0 (NO)}. width:500, // sets the width in pixels of the window. windowName:null, // name of window set from the name attribute of the element that invokes the click windowURL:null, // url used for the popup top:0, // top position when the window appears. toolbar:0, // determines whether a toolbar (includes the forward and back buttons) is displayed {1 (YES) or 0 (NO)}. data:null, event:'click' }; function popupWindow(object, instanceSettings, beforeCallback, afterCallback) { beforeCallback = typeof beforeCallback !== 'undefined' ? beforeCallback : null; afterCallback = typeof afterCallback !== 'undefined' ? afterCallback : null; if (typeof object == 'string') { object = jQuery(object); } if (!(object instanceof jQuery)) { return false; } var settings = jQuery.extend({}, jqueryPopup.defaultSettings, instanceSettings || {}); object.handler = jQuery(object).bind(settings.event, function() { if (beforeCallback) { beforeCallback(); } var windowFeatures = 'height=' + settings.height + ',width=' + settings.width + ',toolbar=' + settings.toolbar + ',scrollbars=' + settings.scrollbars + ',status=' + settings.status + ',resizable=' + settings.resizable + ',location=' + settings.location + ',menuBar=' + settings.menubar; settings.windowName = settings.windowName || jQuery(this).attr('name'); var href = jQuery(this).attr('href'); if (!settings.windowURL && !(href == '#') && !(href == '')) { settings.windowURL = jQuery(this).attr('href'); } var centeredY,centeredX; var win = null; if (settings.centerBrowser) { if (jQuery.browser.msie) {//hacked together for IE browsers centeredY = (window.screenTop - 120) + ((((document.documentElement.clientHeight + 120)/2) - (settings.height/2))); centeredX = window.screenLeft + ((((document.body.offsetWidth + 20)/2) - (settings.width/2))); } else { centeredY = window.screenY + (((window.outerHeight/2) - (settings.height/2))); centeredX = window.screenX + (((window.outerWidth/2) - (settings.width/2))); } win = window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY); } else if (settings.centerScreen) { centeredY = (screen.height - settings.height)/2; centeredX = (screen.width - settings.width)/2; win = window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY); } else { win = window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + settings.left +',top=' + settings.top); } if (win != null) { win.focus(); if (settings.data) { win.document.write(settings.data); } } if (afterCallback) { afterCallback(); } }); return settings; } function popdownWindow(object, event) { if (typeof event == 'undefined') { event = 'click'; } object = jQuery(object); if (!(object instanceof jQuery)) { return false; } object.unbind(event, object.handler); }
var fs = require('fs') , path = require('path') , jsonParser = require('./jsonparser') , crypto = require('crypto'); /** Function: storeScreenShot * Stores base64 encoded PNG data to the file at the given path. * * Parameters: * (String) data - PNG data, encoded in base64 * (String) file - Target file path */ function storeScreenShot(data, file) { var stream = fs.createWriteStream(file); stream.write(new Buffer(data, 'base64')); stream.end(); } function addHTMLReport(jsonData, baseName, options){ var basePath = path.dirname(baseName), htmlFile = path.join(basePath, options.docName), stream; stream = fs.createWriteStream(htmlFile); stream.write(jsonParser.processJson(jsonData, options)); stream.end(); console.log(reportBaseUrl + "/" + htmlFile); } function addMetaData(metaData, baseName, descriptions, options){ var json, stream, basePath = path.dirname(baseName), file = path.join(basePath,'combined.json'); try { metaData.description = descriptions.join('|'); json = metaData; var currentData; try{ currentData = JSON.parse(fs.readFileSync(file, { encoding: 'utf8' })); if(currentData.length && currentData.length>0){ currentData.push(json); } json = currentData; }catch(e){ json = [json]; } stream = fs.createWriteStream(file); stream.write(JSON.stringify(json)); stream.end(); addHTMLReport(json, baseName, options); } catch(e) { console.error('Could not save meta data'); } } /** Function: storeMetaData * Converts the metaData object to a JSON string and stores it to the file at * the given path. * * Parameters: * (Object) metaData - Object to save as JSON * (String) file - Target file path */ function storeMetaData(metaData, file) { var json , stream; try { json = JSON.stringify(metaData); stream = fs.createWriteStream(file); stream.write(json); stream.end(); } catch(e) { console.error('Could not save meta data for ' + file); } } /** Function: gatherDescriptions * Traverses the parent suites of a test spec recursivly and gathers all * descriptions. Finally returns them as an array. * * Example: * If your test file has the following structure, this function returns an * array like ['My Tests', 'Module 1', 'Case A'] when executed for `Case A`: * * describe('My Tests', function() { * describe('Module 1', function() { * it('Case A', function() { /* ... * / }); * }); * }); * * Parameters: * (Object) suite - Test suite * (Array) soFar - Already gathered descriptions. On first call, pass an * array containing the specs description itself. * * Returns: * (Array) containing the descriptions of all parental suites and the suite * itself. */ function gatherDescriptions(suite, soFar) { soFar.push(suite.description); if(suite.parentSuite) { return gatherDescriptions(suite.parentSuite, soFar); } else { return soFar; } } /** Function: generateGuid * Generates a GUID using node.js' crypto module. * * Returns: * (String) containing a guid */ function generateGuid() { var buf = new Uint16Array(8); buf = crypto.randomBytes(8); var S4 = function(num) { var ret = num.toString(16); while(ret.length < 4){ ret = "0"+ret; } return ret; }; return ( S4(buf[0])+S4(buf[1])+"-"+S4(buf[2])+"-"+S4(buf[3])+"-"+ S4(buf[4])+"-"+S4(buf[5])+S4(buf[6])+S4(buf[7]) ); } function removeDirectory(dirPath){ try { var files = fs.readdirSync(dirPath); } catch(e) { return; } if (files.length > 0) for (var i = 0; i < files.length; i++) { var filePath = dirPath + '/' + files[i]; if (fs.statSync(filePath).isFile()) fs.unlinkSync(filePath); else removeDirectory(filePath); } fs.rmdirSync(dirPath); }; module.exports = { storeScreenShot: storeScreenShot , storeMetaData: storeMetaData , gatherDescriptions: gatherDescriptions , generateGuid: generateGuid , addMetaData: addMetaData , removeDirectory: removeDirectory };
export default class Mailer {}
/** * DocuSign REST API * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * * NOTE: This class is auto generated. Do not edit the class manually and submit a new issue instead. * */ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['ApiClient'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. module.exports = factory(require('../ApiClient')); } else { // Browser globals (root is window) if (!root.Docusign) { root.Docusign = {}; } root.Docusign.SignatureProperties = factory(root.Docusign.ApiClient); } }(this, function(ApiClient) { 'use strict'; /** * The SignatureProperties model module. * @module model/SignatureProperties */ /** * Constructs a new <code>SignatureProperties</code>. * @alias module:model/SignatureProperties * @class */ var exports = function() { var _this = this; }; /** * Constructs a <code>SignatureProperties</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/SignatureProperties} obj Optional instance to populate. * @return {module:model/SignatureProperties} The populated <code>SignatureProperties</code> instance. */ exports.constructFromObject = function(data, obj) { if (data) { obj = obj || new exports(); if (data.hasOwnProperty('filter')) { obj['filter'] = ApiClient.convertToType(data['filter'], 'String'); } if (data.hasOwnProperty('subFilter')) { obj['subFilter'] = ApiClient.convertToType(data['subFilter'], 'String'); } } return obj; } /** * * @member {String} filter */ exports.prototype['filter'] = undefined; /** * * @member {String} subFilter */ exports.prototype['subFilter'] = undefined; return exports; }));
'use strict'; /** * Handles matching page URL with defined connectors and injecting scripts into content document */ define([ 'connectors', 'config', 'objects/injectResult', 'customPatterns' ], function (connectors, config, injectResult, customPatterns) { /** * Creates regex from single match pattern * * @author lacivert * @param {String} input * @returns RegExp */ function createPattern(input) { if (typeof input !== 'string') { return null; } var match_pattern = '^', regEscape = function (s) { return s.replace(/[[^$.|?*+(){}\\]/g, '\\$&'); }, result = /^(\*|https?|file|ftp|chrome-extension):\/\//.exec(input); // Parse scheme if (!result) { return null; } input = input.substr(result[0].length); match_pattern += result[1] === '*' ? 'https?://' : result[1] + '://'; // Parse host if scheme is not `file` if (result[1] !== 'file') { if (!(result = /^(?:\*|(\*\.)?([^\/*]+))/.exec(input))) { return null; } input = input.substr(result[0].length); if (result[0] === '*') { // host is '*' match_pattern += '[^/]+'; } else { if (result[1]) { // Subdomain wildcard exists match_pattern += '(?:[^/]+\\.)?'; } // Append host (escape special regex characters) match_pattern += regEscape(result[2]);// + '/'; } } // Add remainder (path) match_pattern += input.split('*').map(regEscape).join('.*'); match_pattern += '$'; return new RegExp(match_pattern); } /** * Pings the loaded page and checks if there is already loaded connector. If not injects it. * * @param tabId * @param connector * @param cb */ function pingAndInject(tabId, connector, cb) { // Ping the content page to see if the script is already in place. // In the future, connectors will have unified interface, so they will all support // the 'ping' request. Right now only YouTube supports this, because it // is the only site that uses ajax navigation via History API (which is quite hard to catch). // Other connectors will work as usual. // // Sadly there is no way to silently check if the script has been already injected // so we will see an error in the background console on load of every supported page chrome.tabs.sendMessage(tabId, {type: 'ping'}, function (response) { // if the message was sent to a non existing script or the script // does not implement the 'ping' message, we get response==undefined; if (!response) { console.log('-- loaded for the first time, injecting the scripts'); // inject all scripts and jQuery, use slice to avoid mutating var scripts = connector.js.slice(0); // for v2 connectors prepend BaseConnector, newer jQuery (!) and append starter if (typeof(connector.version) !== 'undefined' && connector.version === 2) { scripts.unshift('core/content/connector.js'); scripts.unshift('core/content/filter.js'); scripts.unshift('core/content/reactor.js'); scripts.unshift('vendor/underscore-min.js'); scripts.unshift(config.JQUERY_PATH); scripts.push('core/content/starter.js'); // needs to be the last script injected } // for older connectors prepend older jQuery as a first loaded script else { scripts.unshift(config.JQUERY_1_6_PATH); } // waits for script to be fully injected before injecting another one var injectWorker = function () { if (scripts.length > 0) { var jsFile = scripts.shift(); var injectDetails = { file: jsFile, allFrames: connector.allFrames ? connector.allFrames : false }; console.log('\tinjecting ' + jsFile); chrome.tabs.executeScript(tabId, injectDetails, injectWorker); } else { // done successfully cb(new injectResult.InjectResult(injectResult.results.MATCHED_AND_INJECTED, tabId, connector)); } }; injectWorker(); } else { // no cb() call, useless to report this state console.log('-- subsequent ajax navigation, the scripts are already injected'); } }); } /** * Is triggered by chrome.tabs.onUpdated event * Checks for available connectors and injects matching connector into loaded page * while returning info about the connector * * @param {Number} tabId * @param {Object} changeInfo * @param {Object} tab * @param {Function} cb to be called to signalize the state of injecting */ function onTabsUpdated(tabId, changeInfo, tab, cb) { var onPatternsReady = function(customPatterns) { // run first available connector var anyMatch = !connectors.every(function (connector) { var matchOk = false, patterns = connector.matches || []; // if there are custom patterns use only them, otherwise use only predefined patterns if (customPatterns.hasOwnProperty(connector.label) && customPatterns[connector.label].length > 0) { patterns = customPatterns[connector.label]; } patterns.forEach(function (match) { matchOk = matchOk || createPattern(match).test(tab.url); }); if (matchOk === true) { if (!config.isConnectorEnabled(connector.label)) { // matched, but is not enabled cb(new injectResult.InjectResult(injectResult.results.MATCHED_BUT_DISABLED, tabId, connector)); return false; // break forEach connector } // checks if there's already injected connector and injects it if needed pingAndInject(tabId, connector, cb); } return !matchOk; }); // report no match if (!anyMatch) { cb(new injectResult.InjectResult(injectResult.results.NO_MATCH, tabId, null)); } }; // asynchronously preload all custom patterns and then start matching customPatterns.getAllPatterns(onPatternsReady); } return { onTabsUpdated: onTabsUpdated }; });
/** * Logger with winston * require: var log = require('log') * ex: log.info("something") * */ var winston = require('winston'); // log var logger = new (winston.Logger)({ transports: [ new (winston.transports.File)({ name: 'info-file', filename: './log/winston-info.log', level: 'info' }), new (winston.transports.File)({ name: 'error-file', filename: './log/winston-error.log', level: 'error' }) ] }); /** * dump request object with: * url, * cookies, * ip, * method, * body, * query, * path... * @param req request * */ logger.dumpReq = function (req) { if (__env !== 'development') { return; } console.log('===== DUMP ============'); console.log('base url: ' + req.baseUrl); console.log('cookies: ' + JSON.stringify(req.cookies)); console.log('signedCookies: ' + JSON.stringify(req.signedCookies)); console.log('cache-control: ' + (req.fresh ? 'no-cache' : 'has-cache')); console.log('hostname: ' + req.hostname); console.log('ip: ' + req.ip); console.log('subdomains: ' + JSON.stringify(req.subdomains)); console.log('xhr(jquery): ' + req.xhr); console.log('protocol: ' + req.protocol); console.log('route: ' + req.route); console.log('method: ' + req.method); console.log('originalUrl: ' + req.originalUrl); console.log('https: ' + req.secure); console.log('params: ' + JSON.stringify(req.params)); console.log('query: ' + JSON.stringify(req.query)); console.log('path: ' + req.path); console.log('body: ' + JSON.stringify(req.body)); }; /** * @param req request * @param field contain 'Content-Type', 'content-type' or 'Something' * */ logger.getField = function (req, field) { return req.get(field); }; module.exports = logger;
var asteroids = asteroids || {}; asteroids.Asteroid = function(ctx) { return { position: { x: 0, y: 0 }, parts: [ [ [0, 100], [75, 100], [100, 0], [75, 25], [50, -100], [0, -100], [-25, -100], [-25, -50], [-100, 0], [0, 100] ] ], render: function() { ctx.save(); ctx.translate(this.position.x, this.position.y); ctx.beginPath(); this.parts.forEach(function(part, index) { var first = true; part.forEach(function(segment, index) { var x = segment[0]; var y = segment[1]; if(first) { ctx.moveTo(x, y); first = false; } else { ctx.lineTo(x, y); } }); }); ctx.stroke(); ctx.restore(); } } };
module.exports = function(grunt){ "use strict"; require("matchdep").filterDev("grunt-*").forEach(grunt.loadNpmTasks); grunt.initConfig({ pkg: grunt.file.readJSON("package.json"), banner: '/*!\n' + '*@concat.min.css\n' + '*@CSS Document for Land Use Website @ MAG\n' + '*@For Production\n' + '*@<%= pkg.name %> - v<%= pkg.version %> | <%= grunt.template.today("mm-dd-yyyy") %>\n' + '*@author <%= pkg.author %>\n' + '*/\n', htmlhint: { build: { options: { "tag-pair": true, // Force tags to have a closing pair "tagname-lowercase": true, // Force tags to be lowercase "tag-self-close": true, // The empty tag must closed by self "attr-lowercase": true, // Force attribute names to be lowercase e.g. <div id="header"> is invalid "attr-value-double-quotes": true, // Force attributes to have double quotes rather than single "attr-value-not-empty": true, // Attribute must set value "doctype-first": true, // Force the DOCTYPE declaration to come first in the document "spec-char-escape": true, // Force special characters to be escaped "id-unique": true, // Prevent using the same ID multiple times in a document // "head-script-disabled": false, // Prevent script tags being loaded in the head for performance reasons "style-disabled": true, // Prevent style tags. CSS should be loaded through "src-not-empty": true, // src of img(script,link) must set value "img-alt-require": true, // Alt of img tag must be set value "csslint": true, // Scan css with csslint "jshint": true, // Scan script with jshint "force": false // Report HTMLHint errors but don't fail the task }, src: ["index.html"] } }, // CSSLint. Tests CSS code quality // https://github.com/gruntjs/grunt-contrib-csslint csslint: { // define the files to lint files: ["css/main.css"], strict: { options: { "import": 0, "empty-rules": 0, "display-property-grouping": 0, "shorthand": 0, "font-sizes": 0, "zero-units": 0, "important": 0, "duplicate-properties": 0, } } }, jshint: { files: ["js/main.js"], options: { // strict: true, sub: true, quotmark: "double", trailing: true, curly: true, eqeqeq: true, unused: true, scripturl: true, // This option defines globals exposed by the Dojo Toolkit. dojo: true, // This option defines globals exposed by the jQuery JavaScript library. jquery: true, // Set force to true to report JSHint errors but not fail the task. force: true, reporter: require("jshint-stylish-ex") } }, uglify: { options: { // add banner to top of output file banner: '/*! <%= pkg.name %> - v<%= pkg.version %> | <%= grunt.template.today("mm-dd-yyyy") %> */\n', // mangle: false, // compress: true, }, build: { files: { "js/main.min.js": ["js/main.js"], } } }, cssmin: { add_banner: { options: { // add banner to top of output file banner: '/* <%= pkg.name %> - v<%= pkg.version %> | <%= grunt.template.today("mm-dd-yyyy") %> */\n' }, files: { "css/main.min.css": ["css/main.css"], "css/normalize.min.css": ["css/normalize.css"], "css/bootstrapmap.min.css": ["css/bootstrapmap.css"] } } }, concat: { options: { stripBanners: true, banner: '<%= banner %>' }, dist: { src: ["css/normalize.min.css", "css/bootstrapmap.min.css", "css/main.min.css"], dest: 'app/resources/css/concat.min.css' } }, watch: { scripts: { files: ["js/main.js", "Gruntfile.js"], tasks: ["jshint"], options: { spawn: false, interrupt: true, }, }, }, }); // this would be run by typing "grunt test" on the command line grunt.registerTask("work", ["jshint"]); grunt.registerTask("buildcss", ["cssmin", "concat"]); grunt.registerTask("buildjs", ["uglify"]); // the default task can be run just by typing "grunt" on the command line grunt.registerTask("default", []); }; // ref // http://coding.smashingmagazine.com/2013/10/29/get-up-running-grunt/ // http://csslint.net/about.html // http://www.jshint.com/docs/options/
'use strict'; const Mongoose = require('mongoose'); const RestHapi = require('rest-hapi'); const Config = require('../config'); exports.register = function(server, options, next) { RestHapi.config = Config.get('/restHapiConfig'); server.register({ register: RestHapi, options: { mongoose: Mongoose } }, function(err) { if (err) { console.error('Failed to load plugin:', err); } next(); }); }; exports.register.attributes = { name: 'api' };
var gulp = require('gulp'); var del = require('del'); var connect = require('gulp-connect'); var gulpNgConfig = require('gulp-ng-config'); var includeSources = require('gulp-include-source'); var runSequence = require('run-sequence'); var proxy = require('http-proxy-middleware'); var inject = require('gulp-inject'); var minify = require('gulp-minify'); var sass = require('gulp-sass'); var less = require('gulp-less'); var path = require('path'); var gulpif = require('gulp-if'); var concat = require('gulp-concat'); var argv = require('yargs').argv; var uglifycss = require('gulp-uglifycss'); var sourcemaps = require('gulp-sourcemaps'); var buffer = require('vinyl-buffer'); var babel = require('gulp-babel'); var configList = require('./config'); var gutil = require('gulp-util'); var jshint = require('gulp-jshint'); var stylish = require('jshint-stylish'); var config = configList[argv.env || 'dev']; //dev, prod ... gulp.task('run-dev', function (callback) { config = configList['dev']; runSequence('build', 'watch', 'simple-server', 'jshint', callback); }); gulp.task('run-prod', function (callback) { config = configList['prod']; runSequence('build', 'jshint', callback); }); gulp.task('build', function (callback) { runSequence('clean', ['env', 'scripts', 'libs', 'bootstrap-fonts', 'font-awesome-fonts', 'images', 'sass', 'less', 'html'], 'index', callback); }); gulp.task('jshint', function () { return gulp.src('./src/**/*.js') .pipe(jshint()) .pipe(jshint.reporter(stylish)); }); gulp.task('clean', function () { return del.sync(config.bases.dist, { force : true }); }); gulp.task('env', function () { return gulp.src(config.env.src) .pipe(gulpNgConfig(config.appName, { environment : config.env.name, createModule : false })) .pipe(gulp.dest(config.env.dist)) }); gulp.task('scripts', function () { //app scripts: transpile, concat, minify & map return gulp.src(config.path.scripts.src) .pipe(gulpif(config.sourcemaps.scripts, sourcemaps.init({ loadMaps : true }))) .on('error', gutil.log) .pipe(gulpif(config.transpile.scripts, babel({ presets : ['es2015'] }))) .pipe(gulpif(config.concat.scripts, concat(config.path.scripts.source_file))) .pipe(gulpif(config.sourcemaps.scripts, sourcemaps.write('./maps'))) .pipe(gulpif(config.minify.scripts, minify({ noSource : true, ext : { min : '.js' } }))) .pipe(gulp.dest(config.path.scripts.dist)) .pipe(gulpif(config.reload.scripts, connect.reload())); }); gulp.task('libs-js', function () { //vendor scripts: concatination & minification return gulp.src(config.path.vendorScripts.src) .pipe(gulpif(config.concat.vendorScripts, concat(config.path.vendorScripts.source_file))) .pipe(gulpif(config.minify.vendorScripts, minify({ noSource : true, ext : { min : '.js' } }))) .pipe(gulp.dest(config.path.vendorScripts.dist)); }); gulp.task('libs-css', function () { //vendor styles to build/css return gulp.src(config.path.css.src) .pipe(gulp.dest(config.path.css.dist)); }); gulp.task('libs', ['libs-js', 'libs-css']); gulp.task('bootstrap-fonts', function () { return gulp.src(config.path.fonts.bootstrap.src) .pipe(gulp.dest(config.path.fonts.bootstrap.dist)); }); gulp.task('font-awesome-fonts', function () { return gulp.src(config.path.fonts.fontAwesome.src) .pipe(gulp.dest(config.path.fonts.fontAwesome.dist)); }); gulp.task('sass', function () { //all sass from src to stylesheet.css dest return gulp.src(config.path.sass.src) .pipe(sass().on('error', sass.logError)) .pipe(gulpif(config.concat.sass, concat(config.path.sass.source_file))) .pipe(gulpif(config.minify.sass, uglifycss())) .pipe(gulp.dest(config.path.sass.dist)) .pipe(gulpif(config.reload.css, connect.reload())); }); gulp.task('less', function () { ////all less from src to style.css dest return gulp.src(config.path.less.src) .pipe(less({ paths : [path.join(__dirname, 'less', 'includes')] })) .pipe(gulpif(config.concat.less, concat(config.path.less.source_file))) .pipe(gulpif(config.minify.less, uglifycss())) .pipe(gulp.dest(config.path.less.dist)); }); gulp.task('images', function () { return gulp.src(config.path.img.src) .pipe(gulp.dest(config.path.img.dist)); }); gulp.task('html', function () { return gulp.src(config.path.views.src) .pipe(gulp.dest(config.path.views.dist)) .pipe(gulpif(config.reload.html, connect.reload())); }); gulp.task('index', function () { var sources = gulp.src(config.path.index.sources); return gulp.src(config.path.index.src) .pipe(inject(sources, { ignorePath : config.path.index.ignorePath })) .pipe(gulp.dest(config.path.index.dist)) .pipe(gulpif(config.reload.index, connect.reload())); }); gulp.task('watch', function () { gulp.watch(config.path.scripts.src, ['jshint', 'index', 'scripts']); gulp.watch(config.path.sass.all, ['sass']); gulp.watch(config.path.views.src, ['index', 'html']); gulp.watch(config.path.index.src, ['index']); }); gulp.task('simple-server', function () { require('./server/backend.js'); connect.server({ root : config.server.root, livereload : true, port : 5000, middleware : function (connect, opt) { return [ proxy('/api', { target : 'http://localhost:3000', changeOrigin : true, ws : true // <-- set it to 'true' to proxy WebSockets }) ] } }); });
/* Copyright (c) 2013-2014 Richard Rodger, MIT License */ "use strict"; var _ = require('underscore') var express = require('express') var cookieparser = require('cookie-parser') var qs = require('qs') var bodyparser = require('body-parser') var session = require('express-session') // middleware // security var allowCrossDomain = require('./lib/middleware/security/cors'); // var xsrf = require('./lib/middleware/security/xsrf'); // var protectJSON = require('./lib/middleware/security/protectJSON'); var seneca = require('seneca')() process.on('uncaughtException', function(err) { console.error('uncaughtException:', err.message) console.error(err.stack) process.exit(1) }) seneca.use('options','options.mine.js') seneca.use('mem-store',{web:{dump:true}}) seneca.use('user',{confirm:true, tokensecret: 'thankyouverymuch' }) seneca.use('mail') // seneca.use('auth', {tokenkey:'Bearer',service:{bearer:{}}}) seneca.use('auth', {service: {bearer:{ session: false }}}) seneca.use('account') seneca.use('project') seneca.use('settings') seneca.use('data-editor') seneca.use('admin') seneca.ready(function(err){ if( err ) return process.exit( !console.error(err) ); var options = seneca.export('options') var u = seneca.pin({role:'user',cmd:'*'}) var projectpin = seneca.pin({role:'project',cmd:'*'}) u.register({ nick:'u1', name:'nu1', email:'u1@example.com', password:'u1', active:true}, function(err,out){ projectpin.save( {account:out.user.accounts[0],name:'p1'} ) seneca.act('role:settings, cmd:save, kind:user, settings:{a:"aaa"}, ref:"'+out.user.id+'"') } ) u.register({ nick:'matt', name:'matt', email:'matt@matt.com', password:'matt', active:true} ) u.register({ nick:'admin', name:'admin', email:'admin@matt.com', password:'admin', active:true, admin:true} ) seneca.act('role:settings, cmd:define_spec, kind:user',{spec:options.settings.spec}) var web = seneca.export('web') var app = express() app.use(allowCrossDomain); // app.use( cookieparser() ) app.use( bodyparser() ) // ????????????????????????????????????????????????? // What impact does this have? // app.use( session({secret:'seneca'}) ) app.use( web ) app.use( function( req, res, next ){ if( 0 == req.url.indexOf('/reset') || 0 == req.url.indexOf('/confirm') ) { req.url = '/' } next() }) app.use( express.static(__dirname+options.main.public) ) app.listen( options.main.port ) seneca.log.info('listen',options.main.port) seneca.listen() })
var options = { port_range_start:7000, port_range_end:7999, }; module.exports = options;
function grid(pattern){ this.currentGrid = pattern; this.nextGrid = []; this.details = { width : pattern[0].length, height : pattern[0].length }; this.generation = 0; } grid.prototype.isValidLocation = function(row, col){ var grid = this.currentGrid; var validLocation = true, rowLength = grid.length - 1, colLength = grid[0].length - 1; if( row > rowLength || col > colLength ) { validLocation = false; } else if( row < 0 || col < 0){ validLocation = false; } if( validLocation && grid[row][col] !== 1 ){ validLocation = false; } return validLocation; };
'use strict'; module.exports = Module._createSub('header'); module.exports.prototype.init = (function() { var setOptions = (function() { var params = { el: null, el_main: null, data: {} }; return function(options) { options = $.extend({}, params, options); return options; }; }()); var setSelectors = function($box) { return { $selector: $box, $header: $box.find('.m-header'), $container: $box.find('.container'), $logo: $box.find('.m-head-logo'), $menu: $box.find('.m-head-menu'), $colmd9: $box.find('.col-md-9'), $folder: $box.find('.floader'), $hiddenMenus: $box.find('.hidden-menus') }; }; var resizeHanding = function(instance) { var $tabs_ul = instance.selector.$menu.find('>ul'); instance.selector.$header.css('position', 'fixed'); instance.selector.$colmd9.show(); //var $offs = instance.selector.$colmd9.offset(); var $offs = $tabs_ul.find('>li:nth-child(3)').offset(); var flag = false; var scrollTop = $(window).scrollTop(); if ($offs.top-scrollTop >= instance.selector.$colmd9.height() / 2) { flag = true; } if (flag) { instance.selector.$folder.show(); instance.selector.$colmd9.hide(); instance.selector.$header.css('position', 'relative'); } else { instance.selector.$folder.hide(); } }; require('./_head.scss'); var template = require('./_head.ejs'); return function(options) { options = setOptions(options); this.selector = setSelectors($(template(options.data))); var that = this, main_selector = options.el_main; $(function() { $(window).resize(function() { U.debouncer(resizeHanding(that)); }); //var modules = []; that.selector.$menu.on('click', '>ul>li', function() { $(window.MainPicScroll).show(); $('<span class="line-top"></span>').appendTo($(this)); $(this).addClass('menu-active'); $(this).siblings().removeClass('menu-active'); $(this).siblings().find('span').remove(); var moduleName = $(this).data('module'); if (!U.checkModule(moduleName,true)) { if (moduleName === "m-questions") { require('../Questions/questions.js')().init({ el: main_selector, data: {} }); } if (moduleName === "m-company-introduce") { require('../Company/company.js')().init({ el: main_selector, data: {} }); } if (moduleName === "m-zhaoshang") { require('../ZhaoShang/zhaoshang.js')().init({ el: main_selector, data: {} }); } } }); $(that.selector.$folder[0]).on('click', 'span:nth-child(1)', function() { that.selector.$hiddenMenus.slideToggle(); }); that.selector.$selector.on('click', '>.hidden-menus', function() { $(this).slideUp(); }); that.selector.$hiddenMenus.on('click', '>ul>li', function() { $(window.MainPicScroll).show(); var moduleName = $(this).data('module'); if (!U.checkModule(moduleName)) { if (moduleName === "m-questions") { require('../Questions/questions.js')().init({ el: main_selector, data: {} }); } if (moduleName === "m-company-introduce") { require('../Company/company.js')().init({ el: main_selector, data: {} }); } if (moduleName === "m-zhaoshang") { require('../ZhaoShang/zhaoshang.js')().init({ el: main_selector, data: {} }); } } }); }); this.selector.$selector.appendTo(options.el); return this; }; }());
import Vue from 'vue' import Router from 'vue-router' import Cmd from '@/components/Cmd' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'Cmd', component: Cmd } ] })
'use strict'; const chai = require('chai'); const chaiStuff = require('chai-stuff'); const nock = require('nock'); const Taxjar = require('../dist/taxjar'); const rateMock = require('./mocks/rates'); const taxMock = require('./mocks/taxes'); const customerMock = require('./mocks/customers'); const orderMock = require('./mocks/orders'); const refundMock = require('./mocks/refunds'); const nexusRegionMock = require('./mocks/nexus_regions'); const validationMock = require('./mocks/validations'); const summaryRateMock = require('./mocks/summary_rates'); const assert = chai.assert; chai.use(chaiStuff); let taxjarClient = {}; beforeEach(() => { taxjarClient = new Taxjar({ apiKey: process.env.TAXJAR_API_KEY || 'test123', apiUrl: process.env.TAXJAR_API_URL || 'https://mockapi.taxjar.com' }); }); const envVars = [process.env.TAXJAR_API_KEY, process.env.TAXJAR_API_URL].filter(Boolean); const isLiveTestRun = envVars.length === 2; before(() => { const msg = 'to test live or sandbox environments, both TAXJAR_API_KEY and TAXJAR_API_URL environment variables are required'; assert.notLengthOf(envVars, 1, msg); }); describe('TaxJar API', () => { describe('client', () => { it('instantiates client with API token', () => { assert(taxjarClient.config.apiKey, 'no client'); }); it('returns error with no API token', () => { assert.throws(() => { taxjarClient = new Taxjar(); }, /Please provide a TaxJar API key/); }); it('rejects promise on API error', () => { const errorMocks = require('./mocks/errors'); return taxjarClient.categories().catch(err => { assert.instanceOf(err, Error); assert.instanceOf(err, Taxjar.Error); assert.sameProps(err, errorMocks.CATEGORY_ERROR_RES); }); }); it('rejects promise on non-API error', () => { const errorMocks = require('./mocks/errors'); taxjarClient.setApiConfig('apiUrl', 'invalidApiUrl'); return taxjarClient.nexusRegions().catch(err => { assert.instanceOf(err, Error); assert.notInstanceOf(err, Taxjar.Error); assert.include(err, errorMocks.NEXUS_REGIONS_ERROR_RES); }); }); it('gets api config', () => { assert.equal( taxjarClient.getApiConfig('apiUrl'), (process.env.TAXJAR_API_URL || 'https://mockapi.taxjar.com') + '/v2/' ); }); it('sets api config', () => { taxjarClient.setApiConfig('apiUrl', 'https://api.sandbox.taxjar.com'); assert.equal(taxjarClient.getApiConfig('apiUrl'), 'https://api.sandbox.taxjar.com/v2/'); }); it('includes appropriate headers', () => { nock(taxjarClient.getApiConfig('apiUrl'), {allowUnmocked: true}).get('/rates/12345').reply(function() { assert.match(this.req.headers.authorization, /^Bearer \w+$/); assert.equal(this.req.headers['content-type'], 'application/json'); assert.match(this.req.headers['user-agent'], /^TaxJar\/Node (.*) taxjar-node\/\d+\.\d+\.\d+$/); return [200, {}]; }); return taxjarClient.ratesForLocation('12345'); }); it('sets custom headers via instantiation', () => { taxjarClient = new Taxjar({ apiKey: 'test123', headers: { 'X-TJ-Expected-Response': '422' } }); assert.include(taxjarClient.getApiConfig('headers'), { 'X-TJ-Expected-Response': '422' }); }); it('sets custom headers via api config', () => { taxjarClient.setApiConfig('headers', { 'X-TJ-Expected-Response': '422' }); assert.include(taxjarClient.getApiConfig('headers'), { 'X-TJ-Expected-Response': '422' }); }); }); describe('categories', () => { if (isLiveTestRun) { it('returns successful response in sandbox', () => ( taxjarClient.categories().then(res => { assert.isOk(res.categories); }) )); } else { it('lists tax categories', () => { const categoryMock = require('./mocks/categories'); return taxjarClient.categories().then(res => { assert(res, 'no categories'); assert.deepEqual(res, categoryMock.CATEGORY_RES); }); }); } }); describe('rates', () => { const getLaRate = () => taxjarClient.ratesForLocation('90002', { city: 'Los Angeles', country: 'US' }); if (isLiveTestRun) { it('returns successful response in sandbox', () => ( getLaRate().then(res => { assert.isOk(res.rate); }) )); } else { it('shows tax rates for a location', () => ( taxjarClient.ratesForLocation('90002').then(res => { assert(res, 'no rates'); assert.deepEqual(res, rateMock.RATE_RES); }) )); it('shows tax rates for a location with additional params', () => ( getLaRate().then(res => { assert(res, 'no rates'); assert.deepEqual(res, rateMock.LA_RATE_RES); }) )); } }); describe('taxes', () => { const taxForOrder = () => taxjarClient.taxForOrder({ 'from_country': 'US', 'from_zip': '07001', 'from_state': 'NJ', 'to_country': 'US', 'to_zip': '07446', 'to_state': 'NJ', 'amount': 16.50, 'shipping': 1.5, 'exemption_type': 'non_exempt' }); if (isLiveTestRun) { it('returns successful response in sandbox', () => ( taxForOrder().then(res => { assert.isOk(res.tax); }) )); } else { it('calculates sales tax for an order', () => ( taxForOrder().then(res => { assert.deepEqual(res, taxMock.TAX_RES); }) )); } }); describe('transactions', () => { const listOrders = () => taxjarClient.listOrders({ 'from_transaction_date': '2015/05/01', 'to_transaction_date': '2015/05/31', 'provider': 'api' }); if (isLiveTestRun) { it('listOrders returns successful response in sandbox', () => ( listOrders().then(res => { assert.isOk(res.orders); }) )); } else { it('lists order transactions', () => ( listOrders().then(res => { assert.deepEqual(res, orderMock.LIST_ORDER_RES); }) )); } const createOrder = () => taxjarClient.createOrder({ 'transaction_id': '123', 'transaction_date': '2015/05/14', 'provider': 'api', 'to_country': 'US', 'to_zip': '90002', 'to_state': 'CA', 'to_city': 'Los Angeles', 'to_street': '123 Palm Grove Ln', 'amount': 16.5, 'shipping': 1.5, 'sales_tax': 0.95, 'exemption_type': 'non_exempt', 'line_items': [ { 'quantity': 1, 'product_identifier': '12-34243-9', 'description': 'Fuzzy Widget', 'unit_price': 15.0, 'sales_tax': 0.95 } ] }); if (isLiveTestRun) { it('createOrder returns successful response in sandbox', () => ( createOrder().then(res => { assert.isOk(res.order); }) )); } else { it('creates an order transaction', () => ( createOrder().then(res => { assert.deepEqual(res, orderMock.CREATE_ORDER_RES); }) )); } if (isLiveTestRun) { it('showOrder returns successful response in sandbox', () => ( taxjarClient.showOrder('123', {provider: 'api'}).then(res => { assert.isOk(res.order); }) )); } else { it('shows an order transaction', () => ( taxjarClient.showOrder('123', {provider: 'api'}).then(res => { assert.deepEqual(res, orderMock.SHOW_ORDER_RES); }) )); } const updateOrder = () => taxjarClient.updateOrder({ 'transaction_id': '123', 'amount': 16.5, 'shipping': 1.5, 'exemption_type': 'non_exempt', 'line_items': [ { 'quantity': 1, 'product_identifier': '12-34243-0', 'description': 'Heavy Widget', 'unit_price': 15.0, 'discount': 0.0, 'sales_tax': 0.95 } ] }); if (isLiveTestRun) { it('updateOrder returns successful response in sandbox', () => ( updateOrder().then(res => { assert.isOk(res.order); }) )); } else { it('updates an order transaction', () => ( updateOrder().then(res => { assert.deepEqual(res, orderMock.UPDATE_ORDER_RES); }) )); } if (isLiveTestRun) { it('deleteOrder returns successful response in sandbox', () => ( taxjarClient.deleteOrder('123', {provider: 'api'}).then(res => { assert.isOk(res.order); }) )); } else { it('deletes an order transaction', () => ( taxjarClient.deleteOrder('123', {provider: 'api'}).then(res => { assert.deepEqual(res, orderMock.DELETE_ORDER_RES); }) )); } const listRefunds = () => taxjarClient.listRefunds({ 'from_transaction_date': '2015/05/01', 'to_transaction_date': '2015/05/31', 'provider': 'api' }); if (isLiveTestRun) { it('listRefunds returns successful response in sandbox', () => ( listRefunds().then(res => { assert.isOk(res.refunds); }) )); } else { it('lists refund transactions', () => ( listRefunds().then(res => { assert.deepEqual(res, refundMock.LIST_REFUND_RES); }) )); } const createRefund = () => taxjarClient.createRefund({ 'transaction_id': '321', 'transaction_date': '2015/05/14', 'transaction_reference_id': '123', 'provider': 'api', 'to_country': 'US', 'to_zip': '90002', 'to_state': 'CA', 'to_city': 'Los Angeles', 'to_street': '123 Palm Grove Ln', 'amount': 16.5, 'shipping': 1.5, 'sales_tax': 0.95, 'exemption_type': 'non_exempt', 'line_items': [ { 'quantity': 1, 'product_identifier': '12-34243-9', 'description': 'Fuzzy Widget', 'unit_price': 15.0, 'sales_tax': 0.95 } ] }); if (isLiveTestRun) { it('createRefund returns successful response in sandbox', () => ( createRefund().then(res => { assert.isOk(res.refund); }) )); } else { it('creates a refund transaction', () => ( createRefund().then(res => { assert.deepEqual(res, refundMock.CREATE_REFUND_RES); }) )); } if (isLiveTestRun) { it('showRefund returns successful response in sandbox', () => ( taxjarClient.showRefund('321', {provider: 'api'}).then(res => { assert.isOk(res.refund); }) )); } else { it('shows a refund transaction', () => ( taxjarClient.showRefund('321', {provider: 'api'}).then(res => { assert.deepEqual(res, refundMock.SHOW_REFUND_RES); }) )); } const updateRefund = () => taxjarClient.updateRefund({ 'transaction_id': '321', 'amount': 17, 'shipping': 2.0, 'exemption_type': 'non_exempt', 'line_items': [ { 'quantity': 1, 'product_identifier': '12-34243-0', 'description': 'Heavy Widget', 'unit_price': 15.0, 'sales_tax': 0.95 } ] }); if (isLiveTestRun) { it('updateRefund returns successful response in sandbox', () => ( updateRefund().then(res => { assert.isOk(res.refund); }) )); } else { it('updates a refund transaction', () => ( updateRefund().then(res => { assert.deepEqual(res, refundMock.UPDATE_REFUND_RES); }) )); } if (isLiveTestRun) { it('deleteRefund returns successful response in sandbox', () => ( taxjarClient.deleteRefund('321', {provider: 'api'}).then(res => { assert.isOk(res.refund); }) )); } else { it('deletes a refund transaction', () => ( taxjarClient.deleteRefund('321', {provider: 'api'}).then(res => { assert.deepEqual(res, refundMock.DELETE_REFUND_RES); }) )); } }); describe('customers', () => { if (isLiveTestRun) { it.skip('listCustomers returns successful response in sandbox', () => ( taxjarClient.listCustomers().then(res => { assert.isOk(res.customers); }) )); } else { it('lists customers', () => ( taxjarClient.listCustomers().then(res => { assert.deepEqual(res, customerMock.LIST_CUSTOMER_RES); }) )); } if (isLiveTestRun) { it.skip('showCustomer returns successful response in sandbox', () => ( taxjarClient.showCustomer('123').then(res => { assert.isOk(res.customer); }) )); } else { it('shows a customer', () => ( taxjarClient.showCustomer('123').then(res => { assert.deepEqual(res, customerMock.SHOW_CUSTOMER_RES); }) )); } const createCustomer = () => taxjarClient.createCustomer({ customer_id: '123', exemption_type: 'wholesale', name: 'Dunder Mifflin Paper Company', exempt_regions: [ { country: 'US', state: 'FL' }, { country: 'US', state: 'PA' } ], country: 'US', state: 'PA', zip: '18504', city: 'Scranton', street: '1725 Slough Avenue' }); if (isLiveTestRun) { it.skip('createCustomer returns successful response in sandbox', () => ( createCustomer().then(res => { assert.isOk(res.customer); }) )); } else { it('creates a customer', () => ( createCustomer().then(res => { assert.deepEqual(res, customerMock.CREATE_CUSTOMER_RES); }) )); } const updateCustomer = () => taxjarClient.updateCustomer({ customer_id: '123', exemption_type: 'wholesale', name: 'Sterling Cooper', exempt_regions: [ { country: 'US', state: 'NY' } ], country: 'US', state: 'NY', zip: '10010', city: 'New York', street: '405 Madison Ave' }); if (isLiveTestRun) { it.skip('updateCustomer returns successful response in sandbox', () => ( updateCustomer().then(res => { assert.isOk(res.customer); }) )); } else { it('updates a customer', () => ( updateCustomer().then(res => { assert.deepEqual(res, customerMock.UPDATE_CUSTOMER_RES); }) )); } if (isLiveTestRun) { it.skip('deleteCustomer returns successful response in sandbox', () => ( taxjarClient.deleteCustomer('123').then(res => { assert.isOk(res.customer); }) )); } else { it('deletes a customer', () => ( taxjarClient.deleteCustomer('123').then(res => { assert.deepEqual(res, customerMock.DELETE_CUSTOMER_RES); }) )); } }); describe('nexus', () => { if (isLiveTestRun) { it('returns successful response in sandbox', () => ( taxjarClient.nexusRegions().then(res => { assert.isOk(res.regions); }) )); } else { it('lists nexus regions', () => ( taxjarClient.nexusRegions().then(res => { assert.deepEqual(res, nexusRegionMock.NEXUS_REGIONS_RES); }) )); } }); describe('validations', () => { const validateAddress = () => taxjarClient.validateAddress({ country: 'US', state: 'AZ', zip: '85297', city: 'Gilbert', street: '3301 South Greenfield Rd' }); if (isLiveTestRun) { it.skip('returns successful response in sandbox', () => ( validateAddress().then(res => { assert.isOk(res.validation); }) )).timeout(5000); } else { it('validates an address', () => ( validateAddress().then(res => { assert.deepEqual(res, validationMock.ADDRESS_VALIDATION_RES); }) )); } if (isLiveTestRun) { it('returns successful response in sandbox', () => ( taxjarClient.validate({ vat: 'FR40303265045' }).then(res => { assert.isOk(res.validation); }) )).timeout(5000); } else { it('validates a VAT number', () => ( taxjarClient.validate({ vat: 'FR40303265045' }).then(res => { assert.deepEqual(res, validationMock.VALIDATION_RES); }) )); } }); describe('summarized rates', () => { if (isLiveTestRun) { it('returns successful response in sandbox', () => ( taxjarClient.summaryRates().then(res => { assert.isOk(res.summary_rates); }) )); } else { it('lists summarized rates', () => ( taxjarClient.summaryRates().then(res => { assert.deepEqual(res, summaryRateMock.SUMMARY_RATES_RES); }) )); } }); });
import { expect } from 'chai'; import { parseDialogue } from '../../src/parser/dialogue.js'; import { compileDialogues } from '../../src/compiler/dialogues.js'; import { compileStyles } from '../../src/compiler/styles.js'; import { eventsFormat } from '../../src/utils.js'; describe('dialogues compiler', () => { const style = [ { Name: 'Default', Fontname: 'Arial', Fontsize: '20', PrimaryColour: '&H00FFFFFF', SecondaryColour: '&H000000FF', OutlineColour: '&H000000', BackColour: '&H00000000', Bold: '-1', Italic: '0', Underline: '0', StrikeOut: '0', ScaleX: '100', ScaleY: '100', Spacing: '0', Angle: '0', BorderStyle: '1', Outline: '2', Shadow: '2', Alignment: '2', MarginL: '10', MarginR: '10', MarginV: '10', Encoding: '0', }, { Name: 'alt', Fontname: 'Arial', Fontsize: '24', PrimaryColour: '&H00FFFFFF', SecondaryColour: '&H000000FF', OutlineColour: '&H000000', BackColour: '&H00000000', Bold: '-1', Italic: '0', Underline: '0', StrikeOut: '0', ScaleX: '100', ScaleY: '100', Spacing: '0', Angle: '0', BorderStyle: '3', Outline: '2', Shadow: '2', Alignment: '2', MarginL: '20', MarginR: '20', MarginV: '20', Encoding: '0', }, ]; const styles = compileStyles({ info: { WrapStyle: 0 }, style }); it('should compile dialogue', () => { const dialogue = parseDialogue('0,0:00:00.00,0:00:05.00,Default,,0,0,0,,text', eventsFormat); expect(compileDialogues({ styles, dialogues: [dialogue] })[0]).to.deep.equal({ layer: 0, start: 0, end: 5, style: 'Default', name: '', margin: { left: 10, right: 10, vertical: 10, }, effect: null, alignment: 2, slices: [{ style: 'Default', fragments: [{ tag: {}, text: 'text', drawing: null, }], }], }); }); it('should sort dialogues with start time and end time', () => { const dialogues = [ '2,0:00:05.00,0:00:07.00,Default,,0,0,0,,text2', '1,0:00:00.00,0:00:05.00,Default,,0,0,0,,text1', '0,0:00:00.00,0:00:03.00,Default,,0,0,0,,text0', ].map((dialogue) => parseDialogue(dialogue, eventsFormat)); const layers = compileDialogues({ styles, dialogues }).map((dia) => dia.layer); expect(layers).to.deep.equal([0, 1, 2]); }); it('should ignore dialogues when end > start', () => { const dialogues = [ '0,0:00:00.00,0:00:05.00,Default,,0,0,0,,text1', '0,0:07:00.00,0:00:05.00,Default,,0,0,0,,text2', ].map((dialogue) => parseDialogue(dialogue, eventsFormat)); expect(compileDialogues({ styles, dialogues })).to.have.lengthOf(1); }); it('should make layer be a non-negative number', () => { const dialogues = [ '-1,0:00:00.00,0:00:03.00,Default,,0,0,0,,text-1', '1,0:00:00.00,0:00:05.00,Default,,0,0,0,,text1', '2,0:00:05.00,0:00:07.00,Default,,0,0,0,,text2', ].map((dialogue) => parseDialogue(dialogue, eventsFormat)); const layers = compileDialogues({ styles, dialogues }).map((dia) => dia.layer); expect(layers).to.deep.equal([0, 2, 3]); }); it('should use Default Style when style name is not found', () => { const dialogue = parseDialogue('0,0:00:00.00,0:00:05.00,Unknown,,0,0,0,,text', eventsFormat); const { margin } = compileDialogues({ styles, dialogues: [dialogue] })[0]; expect(margin.left).to.equal(10); }); });
var STATES = { HOME: "home", COURSEINFO: "courseInfo", COURSEINFO_CREATE: "courseInfo.create", COURSEINFO_MANAGE: "courseInfo.manage", COURSEINFO_STUDENT: "courseInfo.student", COURSEINFO_SENDMAIL: "courseInfo.Sendmail", OTHERS: "others", OTHERS_CERTIFICATION: "others.certification", OTHERS_SENDMAIL: "others.sendMail", OTHERS_INVOICE: "others.invoice" } var app = angular.module('app', [ 'ui.router', 'ct.ui.router.extras', 'ngScrollbar', 'ngFileUpload', 'ui.bootstrap', 'angular-mousetrap', 'ngDropdown', 'inputDropdown' ]) .config(['$sceProvider', '$stateProvider', '$urlRouterProvider', '$locationProvider', '$animateProvider', '$stickyStateProvider', function($sceProvider, $stateProvider, $urlRouterProvider, $locationProvider, $animateProvider, $stickyStateProvider) { // ng-bind-html word $sceProvider.enabled(false); // Start Page $urlRouterProvider.otherwise("/courseInfo/manage"); $stickyStateProvider.enableDebug(false); // ui view setting $stateProvider .state(STATES.HOME, { url: "/", views: { 'home@': { templateUrl: "templates/home.html", controller: 'HomeController', } } }) .state(STATES.COURSEINFO, { url: "/courseInfo", views: { 'courseInfo@': { template: "<div ui-view=\"content\"></div>" } } }) .state(STATES.COURSEINFO_CREATE, { url: "/create", views: { 'content@courseInfo': { templateUrl: "templates/courseCreate.html", controller: 'CourseCreateController as ctrl' } } }) .state(STATES.COURSEINFO_MANAGE, { url: "/manage", views: { 'content@courseInfo': { templateUrl: "templates/courseManage.html", controller: 'CourseManageController' } } }) .state(STATES.COURSEINFO_STUDENT, { url: "/:courseId/manage", views: { 'content@courseInfo': { templateUrl: "templates/studentManage.html", controller: 'StudentManageController', } } }) .state(STATES.COURSEINFO_SENDMAIL, { url: "/:courseId/sendmail", views: { 'content@courseInfo': { templateUrl: "templates/studentSendmail.html", controller: 'StudentSendmailController', } } }) .state(STATES.OTHERS, { url: "/others", views: { 'others@': { template: "<div ui-view=\"content\"></div>" } } }) .state(STATES.OTHERS_CERTIFICATION, { url: "/certification", views: { 'content@others': { templateUrl: "templates/certificationPage.html", controller: 'CertificationController', } } }) .state(STATES.OTHERS_SENDMAIL, { url: "/sendMail", views: { 'content@others': { templateUrl: "templates/mailSendingPage.html", controller: 'MailSendingController', } } }) .state(STATES.OTHERS_INVOICE, { url: "/invoice", views: { 'content@others': { templateUrl: "templates/invoice.html", controller: 'InvoiceController', } } }) } ]) .controller("RootController",['$scope', '$state', '$timeout', '$rootScope', function($scope, $state, $timeout, $rootScope){ var isHomeView = function() { return $state.includes(STATES.HOME); } var isCourseInfoView = function() { return $state.includes(STATES.COURSEINFO); } var isOthersView = function() { return $state.includes(STATES.OTHERS); } var isStudentInfoView = function() { return $state.includes(STATES.STUDENTINFO); } var init = function() { } /*========================== Events ==========================*/ /*========================== Members ==========================*/ /*========================== Methods ==========================*/ $scope.isHomeView = isHomeView; $scope.isCourseInfoView = isCourseInfoView; $scope.isOthersView = isOthersView; $scope.isStudentInfoView = isStudentInfoView; /*========================== init ==========================*/ init(); } ]); app.directive('loading', ['$timeout', function($timeout){ return { restrict: 'E', templateUrl: "templates/directives/loading.html" }; }]); app.directive('spin', ['$timeout', function($timeout){ return { restrict: 'E', template: '<div class="spin"></div>', link: function(scope, element, attrs, ctrls) { var spinSize = attrs.spinSize; switch (spinSize) { case "large": element.children().addClass("spin-large"); break; case "medium": element.children().addClass("spin-medium"); break; case "small": element.children().addClass("spin-small"); break; default: element.children().addClass("spin-small"); break; } } }; }]);
import {customElement} from 'aurelia-templating'; @customElement('test-element') export class TestElement { }
// js/modules/search/shsearch.js define(['modules/media/jrpadHandler', 'indeed', 'indeedKey'], function(Ads) { // if there is a problem loading the Indeed tracking api, indeedTracking.js will be loaded as the fallback where var blocked is defined. if (typeof blocked !== 'undefined') { require(['modules/media/adblockmodal']); } var isMobile = false; if (window.navigator) { isMobile = navigator.userAgent.match(/(iPhone|iPod|iPad|Android|Windows Phone|BlackBerry|Mobile)/); } var IndeedSearch = { doSearch: function(dependencies) { var model = dependencies.model, collection = dependencies.collection, userModel = dependencies.userModel, options = {}, jto = model.get('jto'), // job title only chnl = '', user_id = 0, that = this; collection.reset(); $('.ad').remove(); options.q = model.get('keyword'); options.l = model.get('location'); options.fromage = model.get('daysBack'); options.radius = model.get('radius'); options.p = model.get('page'); options.jk = model.get('jobKey'); options.limit = 15; options.useragent = navigator.userAgent; options.start = options.p * options.limit - options.limit; // start 0 options.userip = '127.0.0.1'; options.chnl = chnl; // Wrap keyword with title:() if job title only is flagged true if (jto) { options.q = 'title:('+options.q+')'; } $.when(checkChannel(), checkIP()).done(function (channel, ip) { console.log('SUCCESS!!'); if (userModel.get('email') !== '') { chnl = isMobile ? channel[0].email.mobile : channel[0].email.desktop; user_id = userModel.get('_id'); } else { chnl = isMobile ? channel[0].organic.mobile : channel[0].organic.desktop; } options.userip = ip[0]; options.chnl = chnl; console.log('CHANNEL:', chnl); console.log('IP:', ip[0]); console.log('NEW QUERY OPTIONS:', options); getJobs(model, collection, user_id, options, userModel); }).fail(function() { console.log('FAIL!!'); getJobs(model, collection, user_id, options, userModel); }); } }; // Check the traffic type to determine the correct channel var checkChannel = function() { return $.jsonp({ url: location.protocol + "//api." + location.hostname + "/server/channel/", callbackParameter: "callback", timeout: 5000 }); }; // Get Client IP Address var checkIP = function() { return $.jsonp({ url: location.protocol + "//api." + location.hostname + "/server/ip/", callbackParameter: "callback", timeout: 5000 }); }; var getJobs = function(model, collection, user_id, options, userModel) { var indeed_client = new Indeed("7818408010772620"), // number of possible pagination buttons. pageList = 10, newJobs = []; if ($(window).width() <= 480) { pageList = 5; } indeed_client.search(options, function (response) { console.log('Indeed RESPONSE:', response); // if no results, handle SH response response = handleNoResults(response); // Set total results count response.totalResults = setTotalResults(options, response); var endRecord = setEndRecord(options.p, options.limit, response.totalResults), // total number of pages derived from number of results divided by results/page. lastPage = Math.ceil(response.totalResults / options.limit), // set the max page number for pagination set. maxPage = setMaxPage(lastPage, pageList), // the set (array) of page numbers. pageSet = setPagination(options.p, pageList, lastPage, maxPage); // Set all values attached to jobs model model.set({ numResults: addCommas(response.totalResults), totalRecords: addCommas(response.totalResults), startRecord: options.start + 1, endRecord: endRecord, pageSet: pageSet, lastPage: lastPage }); // CREATE JOB LIST // first check if there's a highlighted job from an email click if (options.jk !== '') { // Add Featured Job to Top of Results $.each(response.results, function(idx, val) { if (val.jk === options.jk) { console.log("JOBKEY ON FIRST PAGE"); newJobs = createJobList_featured(response.results, options.jk, newJobs); // Reset job collection with new data collection.add(newJobs); // Highlight the featured Job. $('.job').eq(0).addClass('active'); if (response.totalResults !== 0) { var adLocation = (model.get('location') || $.cookie('user_location')); var adOptions = { keyword: model.get('keyword'), page: model.get('page'), loc: adLocation }; var numResults = model.get('numResults'); placeAds(adOptions, numResults); } return false; } else if (idx === response.results.length-1) { var jobKeyPromise = jobKeyLookup(options); jobKeyPromise.done(function(jobKeyResult) { createJobList_jobKeyLookup(response.results, jobKeyResult, newJobs, collection); // Highlight the featured Job. $('.job').eq(0).addClass('active'); console.log('THE COOKIE', $.cookie('user_location')); if (response.totalResults !== 0) { var adLocation = (model.get('location') || $.cookie('user_location')); var adOptions = { keyword: model.get('keyword'), page: model.get('page'), loc: adLocation }; var numResults = model.get('numResults'); placeAds(adOptions, numResults); } }).fail(function() { require(['modules/tooltip'], function(Tooltip) { Tooltip.show("This job posting is no longer available. Here are other similar jobs in your area."); }); console.log('NO FEATURED JOB FOUND FROM JOB KEY LOOKUP'); newJobs = createJobList(response.results, newJobs); collection.add(newJobs); console.log('THE COOKIE', $.cookie('user_location')); if (response.totalResults !== 0) { var adLocation = (model.get('location') || $.cookie('user_location')); var adOptions = { keyword: model.get('keyword'), page: model.get('page'), loc: adLocation }; var numResults = model.get('numResults'); placeAds(adOptions, numResults); } }); } }); } else { // Normal Job Results List. newJobs = createJobList(response.results, newJobs); // Reset job collection with new data collection.add(newJobs); console.log('THE COOKIE', $.cookie('user_location')); if (response.totalResults !== 0) { var adLocation = (model.get('location') || $.cookie('user_location')); var adOptions = { keyword: model.get('keyword'), page: model.get('page'), loc: adLocation }; var numResults = model.get('numResults'); placeAds(adOptions, numResults); } } // Metrics collect for job search $.jsonp({ url: location.protocol + "//api." + location.hostname + "/metrics/search/", callbackParameter: "callback", data: { user_id:user_id, // 0 or string keyword:options.q, location:options.l, days_back:options.d, radius:options.r, ip:options.userip, provider:"Indeed", channel:options.chnl, page:options.p, page_result:response.results.length, total_result:response.totalResults }, success: function(result){ model.set({ _id: result // search id for result click tracking }); console.log(model.get('_id')); }, error: function(xOptions, textStatus) { console.log(textStatus); } }); }); }; // Handle Indeed no results response var handleNoResults = function(response) { if (response.results.length === 0) { response.results = [{}]; } return response; }; // adjust total results from Indeed var setTotalResults = function(options, response) { if (response.totalResults !== 0) { if (response.totalResults <= response.results.length) { response.totalResults = response.results.length; } else { // Indeed most of the time gives full page jobs response.totalResults = Math.ceil(response.totalResults / options.limit) * options.limit; } return response.totalResults; } else { return 0; } }; // Set end record var setEndRecord = function(currentPage, resultsPerPage, totalViewable) { var endRecord = currentPage * resultsPerPage; if (endRecord > totalViewable) { endRecord = totalViewable; } return endRecord; }; var setMaxPage = function (lastPage, pageList) { var maxPage; // If last page is greater than 10, set the max page (for pagination) to 10 if (lastPage > pageList) { maxPage = pageList; } else { maxPage = lastPage; } return maxPage; }; var setPagination = function(currentPage, pageList, lastPage, maxPage) { var pageSet = []; if (currentPage > pageList - 3) { if (pageList > 5) { pageSet = [1, 2, '...', currentPage-3, currentPage-2, currentPage-1, currentPage]; if (lastPage >= parseInt(currentPage, 10)+1) { pageSet.push(parseInt(currentPage, 10)+1); } if (lastPage >= parseInt(currentPage, 10)+2) { pageSet.push(parseInt(currentPage, 10)+2); } if (lastPage >= parseInt(currentPage, 10)+3) { pageSet.push(parseInt(currentPage, 10)+3); } } else { pageSet = [1, 2, '...', currentPage]; if (lastPage >= parseInt(currentPage, 10)+1) { pageSet.push(parseInt(currentPage, 10)+1); } } } else { for (var i = 1; i <= maxPage; i++) { pageSet.push(i); } } return pageSet; }; // Make results list var createJobList = function(rs, newJobs) { $.each(rs, function(idx, val) { newJobs.push({ jobKey: val.jobkey, jobTitle: val.jobtitle, company: val.company, city: val.city, state: val.state, formattedLoc: val.formattedLocation, wasAdded: val.formattedRelativeTime, description: val.snippet, link: val.url, onmousedown: $.trim(val.onmousedown.split("{")[1].split("}")[0]) }); }); return newJobs; }; // Make results list with a featured job when coming in from an email var createJobList_featured = function(rs, jk, newJobs) { // If featured job appears on page one. $.each(rs, function(idx, val) { var jobMap = { jobKey: val.jobkey, jobTitle: val.jobtitle, company: val.company, city: val.city, state: val.state, formattedLoc: val.formattedLocation, wasAdded: val.formattedRelativeTime, description: val.snippet, link: val.url, onmousedown: $.trim(val.onmousedown.split("{")[1].split("}")[0]) }; if (val.jk === jk) { newJobs.unshift(jobMap); } else { newJobs.push(jobMap); } }); return newJobs; }; // Make results list using Job Key lookup if featured job isn't in first set of results. var createJobList_jobKeyLookup = function(rs, jobkeyres, newJobs, collection) { console.log(jobkeyres); var val = jobkeyres; // Push the job from the Job-Key-Lookup to the beginning of the list newJobs.push({ jobKey: val.jobkey, jobTitle: val.jobtitle, company: val.company, city: val.city, state: val.state, formattedLoc: val.formattedLocation, wasAdded: val.formattedRelativeTime, description: val.snippet, link: val.url, onmousedown: $.trim(val.onmousedown.split("{")[1].split("}")[0]) }); // Add the rest of the jobs to the list from the Get-Jobs response. $.each(rs, function(idx, val) { if (idx < rs.length-1) { newJobs.push({ jobKey: val.jobkey, jobTitle: val.jobtitle, company: val.company, city: val.city, state: val.state, formattedLoc: val.formattedLocation, wasAdded: val.formattedRelativeTime, description: val.snippet, link: val.url, onmousedown: $.trim(val.onmousedown.split("{")[1].split("}")[0]) }); } }); console.log('THE FEATURED JOB LIST:', newJobs); // Reset job collection with new data collection.add(newJobs); }; var jobKeyLookup = function(options, clip) { console.log("CHECKING JOBKEY"); var indeed_jobkey = new IndeedKey("7818408010772620"), data = {jobkey: options.jk}; return $.when(indeed_jobkey.search(data)); }; var placeAds = function(options) { Ads.resultsPage(options); }; var addCommas = function(nStr) { nStr += ''; var x = nStr.split('.'), x1 = x[0], x2 = x.length > 1 ? '.' + x[1] : '', rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } return x1 + x2; }; return IndeedSearch; });
// Filename: models/comment define([ 'underscore', 'backbone', 'scripts/main/collections/comment' ], function (_, Backbone, CommentCollection) { var CommentModel = Backbone.Model.extend({ urlRoot : '/j/comment', url : function (url){return this.urlRoot + ( this.id ? ('/' + this.id ): '') + ( url ? ('/' + url ): '') ;}, /** * */ defaults : { up : '80', down : '20' }, /** * * @param {Object} options */ initialize : function (options){ //this.chapterId = this.collection.chapterId ; var comments = this.get("comments"); if (comments){ this.comments = new CommentCollection(comments); this.unset("comments"); } }, }); return CommentModel ; });
import { fabric } from 'fabric'; import extend from 'tui-code-snippet/object/extend'; import isExisty from 'tui-code-snippet/type/isExisty'; import forEach from 'tui-code-snippet/collection/forEach'; import Component from '@/interface/component'; import { stamp } from '@/util'; import { componentNames, eventNames as events, fObjectOptions } from '@/consts'; const defaultStyles = { fill: '#000000', left: 0, top: 0, }; const resetStyles = { fill: '#000000', fontStyle: 'normal', fontWeight: 'normal', textAlign: 'tie-text-align-left', underline: false, }; const DBCLICK_TIME = 500; /** * Text * @class Text * @param {Graphics} graphics - Graphics instance * @extends {Component} * @ignore */ class Text extends Component { constructor(graphics) { super(componentNames.TEXT, graphics); /** * Default text style * @type {Object} */ this._defaultStyles = defaultStyles; /** * Selected state * @type {boolean} */ this._isSelected = false; /** * Selected text object * @type {Object} */ this._selectedObj = {}; /** * Editing text object * @type {Object} */ this._editingObj = {}; /** * Listeners for fabric event * @type {Object} */ this._listeners = { mousedown: this._onFabricMouseDown.bind(this), select: this._onFabricSelect.bind(this), selectClear: this._onFabricSelectClear.bind(this), scaling: this._onFabricScaling.bind(this), textChanged: this._onFabricTextChanged.bind(this), }; /** * Textarea element for editing * @type {HTMLElement} */ this._textarea = null; /** * Ratio of current canvas * @type {number} */ this._ratio = 1; /** * Last click time * @type {Date} */ this._lastClickTime = new Date().getTime(); /** * Text object infos before editing * @type {Object} */ this._editingObjInfos = {}; /** * Previous state of editing * @type {boolean} */ this.isPrevEditing = false; } /** * Start input text mode */ start() { const canvas = this.getCanvas(); canvas.selection = false; canvas.defaultCursor = 'text'; canvas.on({ 'mouse:down': this._listeners.mousedown, 'selection:created': this._listeners.select, 'selection:updated': this._listeners.select, 'before:selection:cleared': this._listeners.selectClear, 'object:scaling': this._listeners.scaling, 'text:changed': this._listeners.textChanged, }); canvas.forEachObject((obj) => { if (obj.type === 'i-text') { this.adjustOriginPosition(obj, 'start'); } }); this.setCanvasRatio(); } /** * End input text mode */ end() { const canvas = this.getCanvas(); canvas.selection = true; canvas.defaultCursor = 'default'; canvas.forEachObject((obj) => { if (obj.type === 'i-text') { if (obj.text === '') { canvas.remove(obj); } else { this.adjustOriginPosition(obj, 'end'); } } }); canvas.off({ 'mouse:down': this._listeners.mousedown, 'selection:created': this._listeners.select, 'selection:updated': this._listeners.select, 'before:selection:cleared': this._listeners.selectClear, 'object:selected': this._listeners.select, 'object:scaling': this._listeners.scaling, 'text:changed': this._listeners.textChanged, }); } /** * Adjust the origin position * @param {fabric.Object} text - text object * @param {string} editStatus - 'start' or 'end' */ adjustOriginPosition(text, editStatus) { let [originX, originY] = ['center', 'center']; if (editStatus === 'start') { [originX, originY] = ['left', 'top']; } const { x: left, y: top } = text.getPointByOrigin(originX, originY); text.set({ left, top, originX, originY, }); text.setCoords(); } /** * Add new text on canvas image * @param {string} text - Initial input text * @param {Object} options - Options for generating text * @param {Object} [options.styles] Initial styles * @param {string} [options.styles.fill] Color * @param {string} [options.styles.fontFamily] Font type for text * @param {number} [options.styles.fontSize] Size * @param {string} [options.styles.fontStyle] Type of inclination (normal / italic) * @param {string} [options.styles.fontWeight] Type of thicker or thinner looking (normal / bold) * @param {string} [options.styles.textAlign] Type of text align (left / center / right) * @param {string} [options.styles.textDecoration] Type of line (underline / line-through / overline) * @param {{x: number, y: number}} [options.position] - Initial position * @returns {Promise} */ add(text, options) { return new Promise((resolve) => { const canvas = this.getCanvas(); let newText = null; let selectionStyle = fObjectOptions.SELECTION_STYLE; let styles = this._defaultStyles; this._setInitPos(options.position); if (options.styles) { styles = extend(styles, options.styles); } if (!isExisty(options.autofocus)) { options.autofocus = true; } newText = new fabric.IText(text, styles); selectionStyle = extend({}, selectionStyle, { originX: 'left', originY: 'top', }); newText.set(selectionStyle); newText.on({ mouseup: this._onFabricMouseUp.bind(this), }); canvas.add(newText); if (options.autofocus) { newText.enterEditing(); newText.selectAll(); } if (!canvas.getActiveObject()) { canvas.setActiveObject(newText); } this.isPrevEditing = true; resolve(this.graphics.createObjectProperties(newText)); }); } /** * Change text of activate object on canvas image * @param {Object} activeObj - Current selected text object * @param {string} text - Changed text * @returns {Promise} */ change(activeObj, text) { return new Promise((resolve) => { activeObj.set('text', text); this.getCanvas().renderAll(); resolve(); }); } /** * Set style * @param {Object} activeObj - Current selected text object * @param {Object} styleObj - Initial styles * @param {string} [styleObj.fill] Color * @param {string} [styleObj.fontFamily] Font type for text * @param {number} [styleObj.fontSize] Size * @param {string} [styleObj.fontStyle] Type of inclination (normal / italic) * @param {string} [styleObj.fontWeight] Type of thicker or thinner looking (normal / bold) * @param {string} [styleObj.textAlign] Type of text align (left / center / right) * @param {string} [styleObj.textDecoration] Type of line (underline / line-through / overline) * @returns {Promise} */ setStyle(activeObj, styleObj) { return new Promise((resolve) => { forEach( styleObj, (val, key) => { if (activeObj[key] === val && key !== 'fontSize') { styleObj[key] = resetStyles[key] || ''; } }, this ); if ('textDecoration' in styleObj) { extend(styleObj, this._getTextDecorationAdaptObject(styleObj.textDecoration)); } activeObj.set(styleObj); this.getCanvas().renderAll(); resolve(); }); } /** * Get the text * @param {Object} activeObj - Current selected text object * @returns {String} text */ getText(activeObj) { return activeObj.text; } /** * Set infos of the current selected object * @param {fabric.Text} obj - Current selected text object * @param {boolean} state - State of selecting */ setSelectedInfo(obj, state) { this._selectedObj = obj; this._isSelected = state; } /** * Whether object is selected or not * @returns {boolean} State of selecting */ isSelected() { return this._isSelected; } /** * Get current selected text object * @returns {fabric.Text} Current selected text object */ getSelectedObj() { return this._selectedObj; } /** * Set ratio value of canvas */ setCanvasRatio() { const canvasElement = this.getCanvasElement(); const cssWidth = parseInt(canvasElement.style.maxWidth, 10); const originWidth = canvasElement.width; this._ratio = originWidth / cssWidth; } /** * Get ratio value of canvas * @returns {number} Ratio value */ getCanvasRatio() { return this._ratio; } /** * Get text decoration adapt object * @param {string} textDecoration - text decoration option string * @returns {object} adapt object for override */ _getTextDecorationAdaptObject(textDecoration) { return { underline: textDecoration === 'underline', linethrough: textDecoration === 'line-through', overline: textDecoration === 'overline', }; } /** * Set initial position on canvas image * @param {{x: number, y: number}} [position] - Selected position * @private */ _setInitPos(position) { position = position || this.getCanvasImage().getCenterPoint(); this._defaultStyles.left = position.x; this._defaultStyles.top = position.y; } /** * Input event handler * @private */ _onInput() { const ratio = this.getCanvasRatio(); const obj = this._editingObj; const textareaStyle = this._textarea.style; textareaStyle.width = `${Math.ceil(obj.width / ratio)}px`; textareaStyle.height = `${Math.ceil(obj.height / ratio)}px`; } /** * Keydown event handler * @private */ _onKeyDown() { const ratio = this.getCanvasRatio(); const obj = this._editingObj; const textareaStyle = this._textarea.style; setTimeout(() => { obj.text(this._textarea.value); textareaStyle.width = `${Math.ceil(obj.width / ratio)}px`; textareaStyle.height = `${Math.ceil(obj.height / ratio)}px`; }, 0); } /** * Blur event handler * @private */ _onBlur() { const ratio = this.getCanvasRatio(); const editingObj = this._editingObj; const editingObjInfos = this._editingObjInfos; const textContent = this._textarea.value; let transWidth = editingObj.width / ratio - editingObjInfos.width / ratio; let transHeight = editingObj.height / ratio - editingObjInfos.height / ratio; if (ratio === 1) { transWidth /= 2; transHeight /= 2; } this._textarea.style.display = 'none'; editingObj.set({ left: editingObjInfos.left + transWidth, top: editingObjInfos.top + transHeight, }); if (textContent.length) { this.getCanvas().add(editingObj); const params = { id: stamp(editingObj), type: editingObj.type, text: textContent, }; this.fire(events.TEXT_CHANGED, params); } } /** * Scroll event handler * @private */ _onScroll() { this._textarea.scrollLeft = 0; this._textarea.scrollTop = 0; } /** * Fabric scaling event handler * @param {fabric.Event} fEvent - Current scaling event on selected object * @private */ _onFabricScaling(fEvent) { const obj = fEvent.target; obj.fontSize = obj.fontSize * obj.scaleY; obj.scaleX = 1; obj.scaleY = 1; } /** * textChanged event handler * @param {{target: fabric.Object}} props - changed text object * @private */ _onFabricTextChanged(props) { this.fire(events.TEXT_CHANGED, props.target); } /** * onSelectClear handler in fabric canvas * @param {{target: fabric.Object, e: MouseEvent}} fEvent - Fabric event * @private */ _onFabricSelectClear(fEvent) { const obj = this.getSelectedObj(); this.isPrevEditing = true; this.setSelectedInfo(fEvent.target, false); if (obj) { // obj is empty object at initial time, will be set fabric object if (obj.text === '') { this.getCanvas().remove(obj); } } } /** * onSelect handler in fabric canvas * @param {{target: fabric.Object, e: MouseEvent}} fEvent - Fabric event * @private */ _onFabricSelect(fEvent) { this.isPrevEditing = true; this.setSelectedInfo(fEvent.target, true); } /** * Fabric 'mousedown' event handler * @param {fabric.Event} fEvent - Current mousedown event on selected object * @private */ _onFabricMouseDown(fEvent) { const obj = fEvent.target; if (obj && !obj.isType('text')) { return; } if (this.isPrevEditing) { this.isPrevEditing = false; return; } this._fireAddText(fEvent); } /** * Fire 'addText' event if object is not selected. * @param {fabric.Event} fEvent - Current mousedown event on selected object * @private */ _fireAddText(fEvent) { const obj = fEvent.target; const e = fEvent.e || {}; const originPointer = this.getCanvas().getPointer(e); if (!obj) { this.fire(events.ADD_TEXT, { originPosition: { x: originPointer.x, y: originPointer.y, }, clientPosition: { x: e.clientX || 0, y: e.clientY || 0, }, }); } } /** * Fabric mouseup event handler * @param {fabric.Event} fEvent - Current mousedown event on selected object * @private */ _onFabricMouseUp(fEvent) { const { target } = fEvent; const newClickTime = new Date().getTime(); if (this._isDoubleClick(newClickTime) && !target.isEditing) { target.enterEditing(); } if (target.isEditing) { this.fire(events.TEXT_EDITING); // fire editing text event } this._lastClickTime = newClickTime; } /** * Get state of firing double click event * @param {Date} newClickTime - Current clicked time * @returns {boolean} Whether double clicked or not * @private */ _isDoubleClick(newClickTime) { return newClickTime - this._lastClickTime < DBCLICK_TIME; } } export default Text;
var {vowelsCount} = require('../questions/vowelsCount.js'); describe('统计给定的字符串中的元音被字母(a, e, i, o, u)的数量', function(){ it('null值返回', function(){ var count = vowelsCount(null); expect(count).toBe(0); }); it('不含元音字母的情况', function(){ var count = vowelsCount('b'); expect(count).toBe(0); }); it('含有元音字母a的情况', function(){ var count = vowelsCount('a'); expect(count).toBe(1); }); it('含有元音字母e的情况', function(){ var count = vowelsCount('e'); expect(count).toBe(1); }); it('含有元音字母i的情况', function(){ var count = vowelsCount('i'); expect(count).toBe(1); }); it('含有元音字母o的情况', function(){ var count = vowelsCount('o'); expect(count).toBe(1); }); it('含有元音字母u的情况', function(){ var count = vowelsCount('u'); expect(count).toBe(1); }); it('长字符串测试abcdefg', function(){ var count = vowelsCount('abcdefg'); expect(count).toBe(2); }); it('长字符串测试aceioudefzwkjr', function(){ var count = vowelsCount('aceioudefzwkjr'); expect(count).toBe(6); }); });
jQuery(document).ready(function($){ jQuery.ajax ({ type : "post", dataType : "html", url : AsposeDocParams['aspose_files_url'], data : {appSID: AsposeDocParams['appSID'], appKey : AsposeDocParams['appKey']}, success: function(response) { $('#aspose_cloud_doc').append(response); } }); $('#aspose_folder_name').live('change',function() { var selected_folder_name = $(this).val(); if(selected_folder_name != '') { jQuery.ajax ({ type : "post", dataType : "html", url : AsposeDocParams['aspose_files_url'], data : {appSID: AsposeDocParams['appSID'], appKey : AsposeDocParams['appKey'], aspose_folder : selected_folder_name}, success: function(response) { $('#aspose_cloud_doc').html(response); } }); } }); $('#tabs').tabs(); $('#aspose_doc_popup').live("click",function(){ $("#aspose_doc_popup_container").dialog('open'); }); $("#aspose_doc_popup_container").dialog({ autoOpen: false, resizable: false, modal: true, width:'auto', height:'300', }); $('#insert_doc_content').live('click',function(){ var filename = $('#doc_file_name').val(); $("#aspose_doc_popup_container").dialog('close'); $body = $("body"); $body.addClass("loading"); jQuery.ajax ({ type : "post", dataType : "html", url : AsposeDocParams['insert_doc_url'], data : {appSID: AsposeDocParams['appSID'], appKey : AsposeDocParams['appKey'], filename : filename, uploadpath: AsposeDocParams['uploadpath'] , uploadURI: AsposeDocParams['uploadURI']}, success: function(response) { $body.removeClass("loading"); window.send_to_editor(response); } }); }); $('#insert_aspose_doc_content').live('click',function(){ var filename = $('input[name="aspose_filename"]:checked').val(); $("#aspose_doc_popup_container").dialog('close'); $body = $("body"); $body.addClass("loading"); jQuery.ajax ({ type : "post", dataType : "html", url : AsposeDocParams['insert_doc_url'], data : {appSID: AsposeDocParams['appSID'], appKey : AsposeDocParams['appKey'], filename : filename, uploadpath: AsposeDocParams['uploadpath'] , uploadURI: AsposeDocParams['uploadURI'] , aspose : '1'}, success: function(response) { $body.removeClass("loading"); window.send_to_editor(response); } }); }); });
/* * Test File */ /* another comment on dancing.js */ var unused; /** * some more comments */ var x = function () { return 1 + 1; }; x(); // i am not important console.log('Yeyyy... this is great!')
// -------------------------------------------------------------------------------------------------------------------- // // coupon-code.js : An implementation of Perl's Algorithm::CouponCode for NodeJS. // // Author : Andrew Chilton // Web : http://www.chilts.org/blog/ // Email : <andychilton@gmail.com> // // Copyright (c) : AppsAttic Ltd 2011 // Web : http://www.appsattic.com/ // License : http://opensource.org/licenses/MIT // // Copyright (c) : Andrew Chilton 2013 // Web : http://chilts.org/ // License : http://opensource.org/licenses/MIT // // -------------------------------------------------------------------------------------------------------------------- // npm var xtend = require('xtend'); // -------------------------------------------------------------------------------------------------------------------- // constants var badWordsList = ('SHPX PHAG JNAX JNAT CVFF PBPX FUVG GJNG GVGF SNEG URYY ZHSS QVPX XABO ' + 'NEFR FUNT GBFF FYHG GHEQ FYNT PENC CBBC OHGG SRPX OBBO WVFZ WVMM CUNG') .replace(/[a-zA-Z]/g,function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+13)?c:c-26);}) .split(' '); var symbolsStr = '0123456789ABCDEFGHJKLMNPQRTUVWXY'; var symbolsArr = symbolsStr.split(''); var symbolsObj = {}; symbolsArr.forEach(function(c, i) { symbolsObj[c] = i; }); var defaults = { parts : 3, partLen : 4, }; // -------------------------------------------------------------------------------------------------------------------- // exports module.exports.generate = function(opts) { opts = xtend({}, defaults, opts); var parts = []; var part; var i; var j; // if we have a plaintext, generate a code from that if ( opts.plaintext ) { // not yet implemented return ''; } else { // default to a random code do { parts.length = 0; for( i = 0; i < opts.parts; i++ ) { part = ''; for ( j = 0; j < opts.partLen - 1; j++ ) { part += randomSymbol(); } part = part + checkDigitAlg1(part, i+1); parts.push(part); } } while (hasBadWord(parts.join(''))) } return parts.join('-'); }; module.exports.validate = function(code, opts) { if ( !code ) { throw new Error("Provide a code to be validated"); } opts = xtend({}, defaults, opts); // uppercase the code, take out any random chars and replace OIZS with 0125 code = code.toUpperCase() .replace(/[^0-9A-Z]+/g, '') .replace(/O/g, '0') .replace(/I/g, '1') .replace(/Z/g, '2') .replace(/S/g, '5'); // split in the different parts var parts = []; var tmp = code; while( tmp.length > 0 ) { parts.push( tmp.substr(0, opts.partLen) ); tmp = tmp.substr(opts.partLen); } // make sure we have been given the same number of parts as we are expecting if ( parts.length !== opts.parts ) { return ''; } // validate each part var part, str, check, data; for ( var i = 0; i < parts.length; i++ ) { part = parts[i]; // check this part has 4 chars if ( part.length !== opts.partLen ) { return ''; } // split out the data and the check data = part.substr(0, opts.partLen-1); check = part.substr(opts.partLen-1, 1); if ( check !== checkDigitAlg1(data, i+1) ) { return ''; } } // everything looked ok with this code return parts.join('-'); }; // -------------------------------------------------------------------------------------------------------------------- // internal helpers function randomSymbol() { return symbolsArr[parseInt(Math.random() * symbolsArr.length, 10)]; } // returns the checksum character for this (data/part) combination function checkDigitAlg1(data, check) { // check's initial value is the part number (e.g. 3 or above) // loop through the data chars data.split('').forEach(function(v) { var k = symbolsObj[v]; check = check * 19 + k; }); return symbolsArr[ check % 31 ]; } function hasBadWord(code) { var i; code = code.toUpperCase(); for( i = 0; i < badWordsList.length; i++ ) { if (code.indexOf(badWordsList[i]) > -1) return true; } return false; }; // also export this (for testing) module.exports.hasBadWord = hasBadWord // --------------------------------------------------------------------------------------------------------------------
import parseTemplate from '~/template'; import ValueType from './'; /** * @extends ValueType * @deprecated */ export default class TemplateType extends ValueType { static typeName = 'template'; getTemplate() { return this.options.get('template'); } getValue(renderData) { return parseTemplate(this.getTemplate(), renderData); } }
'use strict'; /** * @ngdoc function * @name todoApp.controller:MainCtrl * @description * # MainCtrl * Controller of the todoApp */ angular.module('todoApp') .controller('MainCtrl', function ($scope,localStorageService) { var todosInStore = localStorageService.get('todos'); $scope.todos = todosInStore || []; $scope.$watch('todos', function () { localStorageService.set('todos', $scope.todos); }, true); /* Add Function */ $scope.addTodo = function () { if($scope.todo){ $scope.todos.push($scope.todo); $scope.todo = ''; document.getElementById('alert').style.display='none'; } else{ document.getElementById('alert').style.display='block'; } }; /* Remove Function */ $scope.removeTodo = function (index) { $scope.todos.splice(index, 1); }; });
module.exports = function(grunt) { grunt.initConfig({ nodewebkit: { options: { build_dir: './build', // Where the build version of my node-webkit app is saved credits: './public/credits.html', mac: true, // We want to build it for mac win: false, // We want to build it for win linux32: false, // We don't need linux32 linux64: false, // We don't need linux64 }, src: './public/**/*' // Your node-wekit app }, }); grunt.loadNpmTasks('grunt-node-webkit-builder'); grunt.registerTask('default', ['nodewebkit']); };
/* eslint-env mocha */ import expect from 'expect'; import fFunction from '../../src/types/function.js'; describe('function', () => { context('.name', () => { it('is "function"', () => { expect(fFunction.name).toEqual('function'); }); }); context('.checker', () => { it('accepts a function', () => { expect(fFunction.checker(() => false)).toBe(true); }); it('refuses null', () => { expect(fFunction.checker(null)).toBe(false); }); it('refuses a string', () => { expect(fFunction.checker('abc')).toBe(false); }); }); context('.printer', () => { it('prints an anonymous function with no args correctly', () => { expect(fFunction.printer(() => '')).toBe('anonymous()'); }); it('prints an anonymous function with 1 arg correctly', () => { expect(fFunction.printer((_x) => '')).toBe('anonymous(1 argument)'); }); it('prints an anonymous function with multiple arg correctly', () => { expect(fFunction.printer((_x, _y, _z) => '')).toBe('anonymous(3 arguments)'); }); it('prints an named function with no args correctly', () => { function named() {} expect(fFunction.printer(named)).toBe('named()'); }); it('prints an named function with 1 arg correctly', () => { function named(_x) {} expect(fFunction.printer(named)).toBe('named(1 argument)'); }); it('prints an named function with multiple arg correctly', () => { function named(_x, _y, _z) {} expect(fFunction.printer(named)).toBe('named(3 arguments)'); }); }); });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getDevConfig = function (_wco) { return {}; }; //# sourceMappingURL=/users/johnny/myfiles/angular-cli/models/webpack-configs/development.js.map
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { options: { separator: ';' }, dist: { src: ['src/**/*.js', '!src/**/*.spec.js'], dest: 'dist/<%= pkg.name %>.js' } }, uglify: { options: { banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n' }, dist: { files: { 'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>'] } } }, karma: { unit: { options: { frameworks: ['jasmine'], singleRun: true, browsers: ['PhantomJS'], files: [ 'node_modules/sinon/pkg/sinon.js', 'bower_components/angular/angular.js', 'bower_components/angular-mocks/angular-mocks.js', 'src/**/*.js', 'test/**/*.spec.js' ] } } }, jshint: { files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js'], options: { // options here to override JSHint defaults reporter: require('jshint-stylish'), jshintrc: '.jshintrc' } }, watch: { files: ['<%= jshint.files %>'], tasks: ['jshint', 'karma'] } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-karma'); grunt.registerTask('test', ['jshint', 'karma']); grunt.registerTask('default', ['jshint', 'karma', 'concat', 'uglify']); };
// Posts export const LOAD_POSTS_REQUEST = 'LOAD_POSTS_REQUEST'; export const LOAD_POSTS_SUCCESS = 'LOAD_POSTS_SUCCESS'; export const LOAD_POSTS_FAILURE = 'LOAD_POSTS_FAILURE'; // Single Post export const LOAD_POST_REQUEST = 'LOAD_POST_REQUEST'; export const LOAD_POST_SUCCESS = 'LOAD_POST_SUCCESS'; export const LOAD_POST_FAILURE = 'LOAD_POST_FAILURE';
import React, { Component } from 'react'; import './index.scss' class SearchSuggestion extends Component { render() { return ( <div className="suggestionComponent" onClick={() => this.props.onAddSuggestion(this.props.suggestion)}> {this.props.suggestion} </div> ); } } // Export dependencies like this: export default SearchSuggestion;
version https://git-lfs.github.com/spec/v1 oid sha256:b356402019f09eac66a06773861cc287e74ce3639293742832155fa8316c6367 size 31143
/* Thing > CreativeWork > MediaObject - An image, video, or audio object embedded in a web page. Note that a creative work may have many media objects associated with it on the same web page. For example, a page about a single song (MusicRecording) may have a music video (VideoObject), and a high and low bandwidth audio stream (2 AudioObject's).. Generated automatically by the reactGenerator. */ var MediaObject= React.createClass({ getDefaultProps: function(){ return { } }, render: function(){ var props = this.props.props; var educationalUse; if( props.educationalUse ){ if( props.educationalUse instanceof Array ){ educationalUse = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] educationalUse = educationalUse.concat( props.educationalUse.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. educationalUse is a Text.'></div> ) }) ); educationalUse.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { educationalUse = ( <div data-advice='Put your HTML here. educationalUse is a Text.'></div> ); } } var producer; if( props.producer ){ if( props.producer instanceof Array ){ producer = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] producer = producer.concat( props.producer.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. producer is a Person or Organization.'></div> ) }) ); producer.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { producer = ( <div data-advice='Put your HTML here. producer is a Person or Organization.'></div> ); } } var text; if( props.text ){ if( props.text instanceof Array ){ text = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] text = text.concat( props.text.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. text is a Text.'></div> ) }) ); text.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { text = ( <div data-advice='Put your HTML here. text is a Text.'></div> ); } } var datePublished; if( props.datePublished ){ if( props.datePublished instanceof Array ){ datePublished = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] datePublished = datePublished.concat( props.datePublished.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. datePublished is a Date.'></div> ) }) ); datePublished.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { datePublished = ( <div data-advice='Put your HTML here. datePublished is a Date.'></div> ); } } var alternativeHeadline; if( props.alternativeHeadline ){ if( props.alternativeHeadline instanceof Array ){ alternativeHeadline = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] alternativeHeadline = alternativeHeadline.concat( props.alternativeHeadline.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. alternativeHeadline is a Text.'></div> ) }) ); alternativeHeadline.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { alternativeHeadline = ( <div data-advice='Put your HTML here. alternativeHeadline is a Text.'></div> ); } } var accountablePerson; if( props.accountablePerson ){ if( props.accountablePerson instanceof Array ){ accountablePerson = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] accountablePerson = accountablePerson.concat( props.accountablePerson.map( function(result, index){ return ( <Person {...result} key={index} /> ) }) ); accountablePerson.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { accountablePerson = ( <Person props={ props.accountablePerson } /> ); } } var keywords; if( props.keywords ){ if( props.keywords instanceof Array ){ keywords = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] keywords = keywords.concat( props.keywords.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. keywords is a Text.'></div> ) }) ); keywords.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { keywords = ( <div data-advice='Put your HTML here. keywords is a Text.'></div> ); } } var headline; if( props.headline ){ if( props.headline instanceof Array ){ headline = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] headline = headline.concat( props.headline.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. headline is a Text.'></div> ) }) ); headline.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { headline = ( <div data-advice='Put your HTML here. headline is a Text.'></div> ); } } var character; if( props.character ){ if( props.character instanceof Array ){ character = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] character = character.concat( props.character.map( function(result, index){ return ( <Person {...result} key={index} /> ) }) ); character.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { character = ( <Person props={ props.character } /> ); } } var contentRating; if( props.contentRating ){ if( props.contentRating instanceof Array ){ contentRating = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] contentRating = contentRating.concat( props.contentRating.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. contentRating is a Text.'></div> ) }) ); contentRating.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { contentRating = ( <div data-advice='Put your HTML here. contentRating is a Text.'></div> ); } } var associatedArticle; if( props.associatedArticle ){ if( props.associatedArticle instanceof Array ){ associatedArticle = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] associatedArticle = associatedArticle.concat( props.associatedArticle.map( function(result, index){ return ( <NewsArticle {...result} key={index} /> ) }) ); associatedArticle.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { associatedArticle = ( <NewsArticle props={ props.associatedArticle } /> ); } } var offers; if( props.offers ){ if( props.offers instanceof Array ){ offers = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] offers = offers.concat( props.offers.map( function(result, index){ return ( <Offer {...result} key={index} /> ) }) ); offers.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { offers = ( <Offer props={ props.offers } /> ); } } var publishingPrinciples; if( props.publishingPrinciples ){ if( props.publishingPrinciples instanceof Array ){ publishingPrinciples = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] publishingPrinciples = publishingPrinciples.concat( props.publishingPrinciples.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. publishingPrinciples is a URL.'></div> ) }) ); publishingPrinciples.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { publishingPrinciples = ( <div data-advice='Put your HTML here. publishingPrinciples is a URL.'></div> ); } } var embedUrl; if( props.embedUrl ){ if( props.embedUrl instanceof Array ){ embedUrl = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] embedUrl = embedUrl.concat( props.embedUrl.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. embedUrl is a URL.'></div> ) }) ); embedUrl.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { embedUrl = ( <div data-advice='Put your HTML here. embedUrl is a URL.'></div> ); } } var dateCreated; if( props.dateCreated ){ if( props.dateCreated instanceof Array ){ dateCreated = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] dateCreated = dateCreated.concat( props.dateCreated.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. dateCreated is a Date.'></div> ) }) ); dateCreated.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { dateCreated = ( <div data-advice='Put your HTML here. dateCreated is a Date.'></div> ); } } var potentialAction; if( props.potentialAction ){ if( props.potentialAction instanceof Array ){ potentialAction = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] potentialAction = potentialAction.concat( props.potentialAction.map( function(result, index){ return ( <Action {...result} key={index} /> ) }) ); potentialAction.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { potentialAction = ( <Action props={ props.potentialAction } /> ); } } var name; if( props.name ){ if( props.name instanceof Array ){ name = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] name = name.concat( props.name.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. name is a Text.'></div> ) }) ); name.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { name = ( <div data-advice='Put your HTML here. name is a Text.'></div> ); } } var associatedMedia; if( props.associatedMedia ){ if( props.associatedMedia instanceof Array ){ associatedMedia = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] associatedMedia = associatedMedia.concat( props.associatedMedia.map( function(result, index){ return ( <MediaObject {...result} key={index} /> ) }) ); associatedMedia.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { associatedMedia = ( <MediaObject props={ props.associatedMedia } /> ); } } var audience; if( props.audience ){ if( props.audience instanceof Array ){ audience = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] audience = audience.concat( props.audience.map( function(result, index){ return ( <Audience {...result} key={index} /> ) }) ); audience.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { audience = ( <Audience props={ props.audience } /> ); } } var accessibilityControl; if( props.accessibilityControl ){ if( props.accessibilityControl instanceof Array ){ accessibilityControl = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] accessibilityControl = accessibilityControl.concat( props.accessibilityControl.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. accessibilityControl is a Text.'></div> ) }) ); accessibilityControl.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { accessibilityControl = ( <div data-advice='Put your HTML here. accessibilityControl is a Text.'></div> ); } } var copyrightYear; if( props.copyrightYear ){ if( props.copyrightYear instanceof Array ){ copyrightYear = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] copyrightYear = copyrightYear.concat( props.copyrightYear.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. copyrightYear is a Number.'></div> ) }) ); copyrightYear.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { copyrightYear = ( <div data-advice='Put your HTML here. copyrightYear is a Number.'></div> ); } } var encodesCreativeWork; if( props.encodesCreativeWork ){ if( props.encodesCreativeWork instanceof Array ){ encodesCreativeWork = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] encodesCreativeWork = encodesCreativeWork.concat( props.encodesCreativeWork.map( function(result, index){ return ( <CreativeWork {...result} key={index} /> ) }) ); encodesCreativeWork.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { encodesCreativeWork = ( <CreativeWork props={ props.encodesCreativeWork } /> ); } } var creator; if( props.creator ){ if( props.creator instanceof Array ){ creator = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] creator = creator.concat( props.creator.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. creator is a Person or Organization.'></div> ) }) ); creator.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { creator = ( <div data-advice='Put your HTML here. creator is a Person or Organization.'></div> ); } } var commentCount; if( props.commentCount ){ if( props.commentCount instanceof Array ){ commentCount = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] commentCount = commentCount.concat( props.commentCount.map( function(result, index){ return ( <Integer {...result} key={index} /> ) }) ); commentCount.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { commentCount = ( <Integer props={ props.commentCount } /> ); } } var video; if( props.video ){ if( props.video instanceof Array ){ video = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] video = video.concat( props.video.map( function(result, index){ return ( <VideoObject {...result} key={index} /> ) }) ); video.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { video = ( <VideoObject props={ props.video } /> ); } } var typicalAgeRange; if( props.typicalAgeRange ){ if( props.typicalAgeRange instanceof Array ){ typicalAgeRange = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] typicalAgeRange = typicalAgeRange.concat( props.typicalAgeRange.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. typicalAgeRange is a Text.'></div> ) }) ); typicalAgeRange.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { typicalAgeRange = ( <div data-advice='Put your HTML here. typicalAgeRange is a Text.'></div> ); } } var duration; if( props.duration ){ if( props.duration instanceof Array ){ duration = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] duration = duration.concat( props.duration.map( function(result, index){ return ( <Duration {...result} key={index} /> ) }) ); duration.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { duration = ( <Duration props={ props.duration } /> ); } } var discussionUrl; if( props.discussionUrl ){ if( props.discussionUrl instanceof Array ){ discussionUrl = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] discussionUrl = discussionUrl.concat( props.discussionUrl.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. discussionUrl is a URL.'></div> ) }) ); discussionUrl.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { discussionUrl = ( <div data-advice='Put your HTML here. discussionUrl is a URL.'></div> ); } } var productionCompany; if( props.productionCompany ){ if( props.productionCompany instanceof Array ){ productionCompany = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] productionCompany = productionCompany.concat( props.productionCompany.map( function(result, index){ return ( <Organization {...result} key={index} /> ) }) ); productionCompany.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { productionCompany = ( <Organization props={ props.productionCompany } /> ); } } var review; if( props.review ){ if( props.review instanceof Array ){ review = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] review = review.concat( props.review.map( function(result, index){ return ( <Review {...result} key={index} /> ) }) ); review.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { review = ( <Review props={ props.review } /> ); } } var isFamilyFriendly; if( props.isFamilyFriendly ){ if( props.isFamilyFriendly instanceof Array ){ isFamilyFriendly = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] isFamilyFriendly = isFamilyFriendly.concat( props.isFamilyFriendly.map( function(result, index){ return ( <Boolean {...result} key={index} /> ) }) ); isFamilyFriendly.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { isFamilyFriendly = ( <Boolean props={ props.isFamilyFriendly } /> ); } } var version; if( props.version ){ if( props.version instanceof Array ){ version = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] version = version.concat( props.version.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. version is a Number.'></div> ) }) ); version.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { version = ( <div data-advice='Put your HTML here. version is a Number.'></div> ); } } var provider; if( props.provider ){ if( props.provider instanceof Array ){ provider = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] provider = provider.concat( props.provider.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. provider is a Person or Organization.'></div> ) }) ); provider.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { provider = ( <div data-advice='Put your HTML here. provider is a Person or Organization.'></div> ); } } var isPartOf; if( props.isPartOf ){ if( props.isPartOf instanceof Array ){ isPartOf = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] isPartOf = isPartOf.concat( props.isPartOf.map( function(result, index){ return ( <CreativeWork {...result} key={index} /> ) }) ); isPartOf.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { isPartOf = ( <CreativeWork props={ props.isPartOf } /> ); } } var accessibilityHazard; if( props.accessibilityHazard ){ if( props.accessibilityHazard instanceof Array ){ accessibilityHazard = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] accessibilityHazard = accessibilityHazard.concat( props.accessibilityHazard.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. accessibilityHazard is a Text.'></div> ) }) ); accessibilityHazard.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { accessibilityHazard = ( <div data-advice='Put your HTML here. accessibilityHazard is a Text.'></div> ); } } var contentSize; if( props.contentSize ){ if( props.contentSize instanceof Array ){ contentSize = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] contentSize = contentSize.concat( props.contentSize.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. contentSize is a Text.'></div> ) }) ); contentSize.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { contentSize = ( <div data-advice='Put your HTML here. contentSize is a Text.'></div> ); } } var contentUrl; if( props.contentUrl ){ if( props.contentUrl instanceof Array ){ contentUrl = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] contentUrl = contentUrl.concat( props.contentUrl.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. contentUrl is a URL.'></div> ) }) ); contentUrl.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { contentUrl = ( <div data-advice='Put your HTML here. contentUrl is a URL.'></div> ); } } var educationalAlignment; if( props.educationalAlignment ){ if( props.educationalAlignment instanceof Array ){ educationalAlignment = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] educationalAlignment = educationalAlignment.concat( props.educationalAlignment.map( function(result, index){ return ( <AlignmentObject {...result} key={index} /> ) }) ); educationalAlignment.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { educationalAlignment = ( <AlignmentObject props={ props.educationalAlignment } /> ); } } var genre; if( props.genre ){ if( props.genre instanceof Array ){ genre = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] genre = genre.concat( props.genre.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. genre is a Text.'></div> ) }) ); genre.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { genre = ( <div data-advice='Put your HTML here. genre is a Text.'></div> ); } } var bitrate; if( props.bitrate ){ if( props.bitrate instanceof Array ){ bitrate = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] bitrate = bitrate.concat( props.bitrate.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. bitrate is a Text.'></div> ) }) ); bitrate.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { bitrate = ( <div data-advice='Put your HTML here. bitrate is a Text.'></div> ); } } var publisher; if( props.publisher ){ if( props.publisher instanceof Array ){ publisher = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] publisher = publisher.concat( props.publisher.map( function(result, index){ return ( <Organization {...result} key={index} /> ) }) ); publisher.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { publisher = ( <Organization props={ props.publisher } /> ); } } var about; if( props.about ){ if( props.about instanceof Array ){ about = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] about = about.concat( props.about.map( function(result, index){ return ( <Thing {...result} key={index} /> ) }) ); about.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { about = ( <Thing props={ props.about } /> ); } } var license; if( props.license ){ if( props.license instanceof Array ){ license = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] license = license.concat( props.license.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. license is a CreativeWork or URL.'></div> ) }) ); license.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { license = ( <div data-advice='Put your HTML here. license is a CreativeWork or URL.'></div> ); } } var workExample; if( props.workExample ){ if( props.workExample instanceof Array ){ workExample = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] workExample = workExample.concat( props.workExample.map( function(result, index){ return ( <CreativeWork {...result} key={index} /> ) }) ); workExample.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { workExample = ( <CreativeWork props={ props.workExample } /> ); } } var encodingFormat; if( props.encodingFormat ){ if( props.encodingFormat instanceof Array ){ encodingFormat = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] encodingFormat = encodingFormat.concat( props.encodingFormat.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. encodingFormat is a Text.'></div> ) }) ); encodingFormat.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { encodingFormat = ( <div data-advice='Put your HTML here. encodingFormat is a Text.'></div> ); } } var mentions; if( props.mentions ){ if( props.mentions instanceof Array ){ mentions = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] mentions = mentions.concat( props.mentions.map( function(result, index){ return ( <Thing {...result} key={index} /> ) }) ); mentions.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { mentions = ( <Thing props={ props.mentions } /> ); } } var comment; if( props.comment ){ if( props.comment instanceof Array ){ comment = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] comment = comment.concat( props.comment.map( function(result, index){ return ( <Comment {...result} key={index} /> ) }) ); comment.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { comment = ( <Comment props={ props.comment } /> ); } } var isBasedOnUrl; if( props.isBasedOnUrl ){ if( props.isBasedOnUrl instanceof Array ){ isBasedOnUrl = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] isBasedOnUrl = isBasedOnUrl.concat( props.isBasedOnUrl.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. isBasedOnUrl is a URL.'></div> ) }) ); isBasedOnUrl.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { isBasedOnUrl = ( <div data-advice='Put your HTML here. isBasedOnUrl is a URL.'></div> ); } } var encoding; if( props.encoding ){ if( props.encoding instanceof Array ){ encoding = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] encoding = encoding.concat( props.encoding.map( function(result, index){ return ( <MediaObject {...result} key={index} /> ) }) ); encoding.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { encoding = ( <MediaObject props={ props.encoding } /> ); } } var sameAs; if( props.sameAs ){ if( props.sameAs instanceof Array ){ sameAs = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] sameAs = sameAs.concat( props.sameAs.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. sameAs is a URL.'></div> ) }) ); sameAs.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { sameAs = ( <div data-advice='Put your HTML here. sameAs is a URL.'></div> ); } } var image; if( props.image ){ if( props.image instanceof Array ){ image = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] image = image.concat( props.image.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. image is a URL or ImageObject.'></div> ) }) ); image.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { image = ( <div data-advice='Put your HTML here. image is a URL or ImageObject.'></div> ); } } var height; if( props.height ){ if( props.height instanceof Array ){ height = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] height = height.concat( props.height.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. height is a Distance or QuantitativeValue.'></div> ) }) ); height.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { height = ( <div data-advice='Put your HTML here. height is a Distance or QuantitativeValue.'></div> ); } } var aggregateRating; if( props.aggregateRating ){ if( props.aggregateRating instanceof Array ){ aggregateRating = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] aggregateRating = aggregateRating.concat( props.aggregateRating.map( function(result, index){ return ( <AggregateRating {...result} key={index} /> ) }) ); aggregateRating.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { aggregateRating = ( <AggregateRating props={ props.aggregateRating } /> ); } } var contributor; if( props.contributor ){ if( props.contributor instanceof Array ){ contributor = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] contributor = contributor.concat( props.contributor.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. contributor is a Person or Organization.'></div> ) }) ); contributor.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { contributor = ( <div data-advice='Put your HTML here. contributor is a Person or Organization.'></div> ); } } var thumbnailUrl; if( props.thumbnailUrl ){ if( props.thumbnailUrl instanceof Array ){ thumbnailUrl = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] thumbnailUrl = thumbnailUrl.concat( props.thumbnailUrl.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. thumbnailUrl is a URL.'></div> ) }) ); thumbnailUrl.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { thumbnailUrl = ( <div data-advice='Put your HTML here. thumbnailUrl is a URL.'></div> ); } } var mainEntity; if( props.mainEntity ){ if( props.mainEntity instanceof Array ){ mainEntity = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] mainEntity = mainEntity.concat( props.mainEntity.map( function(result, index){ return ( <Thing {...result} key={index} /> ) }) ); mainEntity.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { mainEntity = ( <Thing props={ props.mainEntity } /> ); } } var schemaVersion; if( props.schemaVersion ){ if( props.schemaVersion instanceof Array ){ schemaVersion = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] schemaVersion = schemaVersion.concat( props.schemaVersion.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. schemaVersion is a URL or Text.'></div> ) }) ); schemaVersion.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { schemaVersion = ( <div data-advice='Put your HTML here. schemaVersion is a URL or Text.'></div> ); } } var accessibilityFeature; if( props.accessibilityFeature ){ if( props.accessibilityFeature instanceof Array ){ accessibilityFeature = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] accessibilityFeature = accessibilityFeature.concat( props.accessibilityFeature.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. accessibilityFeature is a Text.'></div> ) }) ); accessibilityFeature.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { accessibilityFeature = ( <div data-advice='Put your HTML here. accessibilityFeature is a Text.'></div> ); } } var interactivityType; if( props.interactivityType ){ if( props.interactivityType instanceof Array ){ interactivityType = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] interactivityType = interactivityType.concat( props.interactivityType.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. interactivityType is a Text.'></div> ) }) ); interactivityType.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { interactivityType = ( <div data-advice='Put your HTML here. interactivityType is a Text.'></div> ); } } var publication; if( props.publication ){ if( props.publication instanceof Array ){ publication = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] publication = publication.concat( props.publication.map( function(result, index){ return ( <PublicationEvent {...result} key={index} /> ) }) ); publication.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { publication = ( <PublicationEvent props={ props.publication } /> ); } } var width; if( props.width ){ if( props.width instanceof Array ){ width = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] width = width.concat( props.width.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. width is a Distance or QuantitativeValue.'></div> ) }) ); width.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { width = ( <div data-advice='Put your HTML here. width is a Distance or QuantitativeValue.'></div> ); } } var requiresSubscription; if( props.requiresSubscription ){ if( props.requiresSubscription instanceof Array ){ requiresSubscription = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] requiresSubscription = requiresSubscription.concat( props.requiresSubscription.map( function(result, index){ return ( <Boolean {...result} key={index} /> ) }) ); requiresSubscription.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { requiresSubscription = ( <Boolean props={ props.requiresSubscription } /> ); } } var editor; if( props.editor ){ if( props.editor instanceof Array ){ editor = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] editor = editor.concat( props.editor.map( function(result, index){ return ( <Person {...result} key={index} /> ) }) ); editor.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { editor = ( <Person props={ props.editor } /> ); } } var mainEntityOfPage; if( props.mainEntityOfPage ){ if( props.mainEntityOfPage instanceof Array ){ mainEntityOfPage = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] mainEntityOfPage = mainEntityOfPage.concat( props.mainEntityOfPage.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. mainEntityOfPage is a CreativeWork or URL.'></div> ) }) ); mainEntityOfPage.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { mainEntityOfPage = ( <div data-advice='Put your HTML here. mainEntityOfPage is a CreativeWork or URL.'></div> ); } } var recordedAt; if( props.recordedAt ){ if( props.recordedAt instanceof Array ){ recordedAt = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] recordedAt = recordedAt.concat( props.recordedAt.map( function(result, index){ return ( <Event {...result} key={index} /> ) }) ); recordedAt.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { recordedAt = ( <Event props={ props.recordedAt } /> ); } } var hasPart; if( props.hasPart ){ if( props.hasPart instanceof Array ){ hasPart = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] hasPart = hasPart.concat( props.hasPart.map( function(result, index){ return ( <CreativeWork {...result} key={index} /> ) }) ); hasPart.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { hasPart = ( <CreativeWork props={ props.hasPart } /> ); } } var award; if( props.award ){ if( props.award instanceof Array ){ award = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] award = award.concat( props.award.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. award is a Text.'></div> ) }) ); award.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { award = ( <div data-advice='Put your HTML here. award is a Text.'></div> ); } } var exampleOfWork; if( props.exampleOfWork ){ if( props.exampleOfWork instanceof Array ){ exampleOfWork = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] exampleOfWork = exampleOfWork.concat( props.exampleOfWork.map( function(result, index){ return ( <CreativeWork {...result} key={index} /> ) }) ); exampleOfWork.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { exampleOfWork = ( <CreativeWork props={ props.exampleOfWork } /> ); } } var copyrightHolder; if( props.copyrightHolder ){ if( props.copyrightHolder instanceof Array ){ copyrightHolder = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] copyrightHolder = copyrightHolder.concat( props.copyrightHolder.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. copyrightHolder is a Person or Organization.'></div> ) }) ); copyrightHolder.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { copyrightHolder = ( <div data-advice='Put your HTML here. copyrightHolder is a Person or Organization.'></div> ); } } var accessibilityAPI; if( props.accessibilityAPI ){ if( props.accessibilityAPI instanceof Array ){ accessibilityAPI = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] accessibilityAPI = accessibilityAPI.concat( props.accessibilityAPI.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. accessibilityAPI is a Text.'></div> ) }) ); accessibilityAPI.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { accessibilityAPI = ( <div data-advice='Put your HTML here. accessibilityAPI is a Text.'></div> ); } } var learningResourceType; if( props.learningResourceType ){ if( props.learningResourceType instanceof Array ){ learningResourceType = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] learningResourceType = learningResourceType.concat( props.learningResourceType.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. learningResourceType is a Text.'></div> ) }) ); learningResourceType.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { learningResourceType = ( <div data-advice='Put your HTML here. learningResourceType is a Text.'></div> ); } } var sourceOrganization; if( props.sourceOrganization ){ if( props.sourceOrganization instanceof Array ){ sourceOrganization = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] sourceOrganization = sourceOrganization.concat( props.sourceOrganization.map( function(result, index){ return ( <Organization {...result} key={index} /> ) }) ); sourceOrganization.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { sourceOrganization = ( <Organization props={ props.sourceOrganization } /> ); } } var regionsAllowed; if( props.regionsAllowed ){ if( props.regionsAllowed instanceof Array ){ regionsAllowed = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] regionsAllowed = regionsAllowed.concat( props.regionsAllowed.map( function(result, index){ return ( <Place {...result} key={index} /> ) }) ); regionsAllowed.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { regionsAllowed = ( <Place props={ props.regionsAllowed } /> ); } } var inLanguage; if( props.inLanguage ){ if( props.inLanguage instanceof Array ){ inLanguage = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] inLanguage = inLanguage.concat( props.inLanguage.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. inLanguage is a Language or Text.'></div> ) }) ); inLanguage.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { inLanguage = ( <div data-advice='Put your HTML here. inLanguage is a Language or Text.'></div> ); } } var citation; if( props.citation ){ if( props.citation instanceof Array ){ citation = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] citation = citation.concat( props.citation.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. citation is a CreativeWork or Text.'></div> ) }) ); citation.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { citation = ( <div data-advice='Put your HTML here. citation is a CreativeWork or Text.'></div> ); } } var additionalType; if( props.additionalType ){ if( props.additionalType instanceof Array ){ additionalType = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] additionalType = additionalType.concat( props.additionalType.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. additionalType is a URL.'></div> ) }) ); additionalType.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { additionalType = ( <div data-advice='Put your HTML here. additionalType is a URL.'></div> ); } } var author; if( props.author ){ if( props.author instanceof Array ){ author = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] author = author.concat( props.author.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. author is a Person or Organization.'></div> ) }) ); author.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { author = ( <div data-advice='Put your HTML here. author is a Person or Organization.'></div> ); } } var dateModified; if( props.dateModified ){ if( props.dateModified instanceof Array ){ dateModified = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] dateModified = dateModified.concat( props.dateModified.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. dateModified is a Date.'></div> ) }) ); dateModified.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { dateModified = ( <div data-advice='Put your HTML here. dateModified is a Date.'></div> ); } } var description; if( props.description ){ if( props.description instanceof Array ){ description = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] description = description.concat( props.description.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. description is a Text.'></div> ) }) ); description.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { description = ( <div data-advice='Put your HTML here. description is a Text.'></div> ); } } var expires; if( props.expires ){ if( props.expires instanceof Array ){ expires = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] expires = expires.concat( props.expires.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. expires is a Date.'></div> ) }) ); expires.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { expires = ( <div data-advice='Put your HTML here. expires is a Date.'></div> ); } } var releasedEvent; if( props.releasedEvent ){ if( props.releasedEvent instanceof Array ){ releasedEvent = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] releasedEvent = releasedEvent.concat( props.releasedEvent.map( function(result, index){ return ( <PublicationEvent {...result} key={index} /> ) }) ); releasedEvent.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { releasedEvent = ( <PublicationEvent props={ props.releasedEvent } /> ); } } var translator; if( props.translator ){ if( props.translator instanceof Array ){ translator = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] translator = translator.concat( props.translator.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. translator is a Person or Organization.'></div> ) }) ); translator.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { translator = ( <div data-advice='Put your HTML here. translator is a Person or Organization.'></div> ); } } var uploadDate; if( props.uploadDate ){ if( props.uploadDate instanceof Array ){ uploadDate = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] uploadDate = uploadDate.concat( props.uploadDate.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. uploadDate is a Date.'></div> ) }) ); uploadDate.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { uploadDate = ( <div data-advice='Put your HTML here. uploadDate is a Date.'></div> ); } } var alternateName; if( props.alternateName ){ if( props.alternateName instanceof Array ){ alternateName = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] alternateName = alternateName.concat( props.alternateName.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. alternateName is a Text.'></div> ) }) ); alternateName.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { alternateName = ( <div data-advice='Put your HTML here. alternateName is a Text.'></div> ); } } var contentLocation; if( props.contentLocation ){ if( props.contentLocation instanceof Array ){ contentLocation = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] contentLocation = contentLocation.concat( props.contentLocation.map( function(result, index){ return ( <Place {...result} key={index} /> ) }) ); contentLocation.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { contentLocation = ( <Place props={ props.contentLocation } /> ); } } var timeRequired; if( props.timeRequired ){ if( props.timeRequired instanceof Array ){ timeRequired = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] timeRequired = timeRequired.concat( props.timeRequired.map( function(result, index){ return ( <Duration {...result} key={index} /> ) }) ); timeRequired.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { timeRequired = ( <Duration props={ props.timeRequired } /> ); } } var playerType; if( props.playerType ){ if( props.playerType instanceof Array ){ playerType = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] playerType = playerType.concat( props.playerType.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. playerType is a Text.'></div> ) }) ); playerType.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { playerType = ( <div data-advice='Put your HTML here. playerType is a Text.'></div> ); } } var url; if( props.url ){ if( props.url instanceof Array ){ url = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] url = url.concat( props.url.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. url is a URL.'></div> ) }) ); url.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { url = ( <div data-advice='Put your HTML here. url is a URL.'></div> ); } } var position; if( props.position ){ if( props.position instanceof Array ){ position = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] position = position.concat( props.position.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. position is a Integer or Text.'></div> ) }) ); position.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { position = ( <div data-advice='Put your HTML here. position is a Integer or Text.'></div> ); } } var audio; if( props.audio ){ if( props.audio instanceof Array ){ audio = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] audio = audio.concat( props.audio.map( function(result, index){ return ( <AudioObject {...result} key={index} /> ) }) ); audio.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { audio = ( <AudioObject props={ props.audio } /> ); } } return (<div title='MediaObject' className='MediaObject entity'> { educationalUse } { producer } { text } { datePublished } { alternativeHeadline } { accountablePerson } { keywords } { headline } { character } { contentRating } { associatedArticle } { offers } { publishingPrinciples } { embedUrl } { dateCreated } { potentialAction } { name } { associatedMedia } { audience } { accessibilityControl } { copyrightYear } { encodesCreativeWork } { creator } { commentCount } { video } { typicalAgeRange } { duration } { discussionUrl } { productionCompany } { review } { isFamilyFriendly } { version } { provider } { isPartOf } { accessibilityHazard } { contentSize } { contentUrl } { educationalAlignment } { genre } { bitrate } { publisher } { about } { license } { workExample } { encodingFormat } { mentions } { comment } { isBasedOnUrl } { encoding } { sameAs } { image } { height } { aggregateRating } { contributor } { thumbnailUrl } { mainEntity } { schemaVersion } { accessibilityFeature } { interactivityType } { publication } { width } { requiresSubscription } { editor } { mainEntityOfPage } { recordedAt } { hasPart } { award } { exampleOfWork } { copyrightHolder } { accessibilityAPI } { learningResourceType } { sourceOrganization } { regionsAllowed } { inLanguage } { citation } { additionalType } { author } { dateModified } { description } { expires } { releasedEvent } { translator } { uploadDate } { alternateName } { contentLocation } { timeRequired } { playerType } { url } { position } { audio } </div>); } });
// All symbols in the `Katakana` script as per Unicode v4.1.0: [ '\u30A1', '\u30A2', '\u30A3', '\u30A4', '\u30A5', '\u30A6', '\u30A7', '\u30A8', '\u30A9', '\u30AA', '\u30AB', '\u30AC', '\u30AD', '\u30AE', '\u30AF', '\u30B0', '\u30B1', '\u30B2', '\u30B3', '\u30B4', '\u30B5', '\u30B6', '\u30B7', '\u30B8', '\u30B9', '\u30BA', '\u30BB', '\u30BC', '\u30BD', '\u30BE', '\u30BF', '\u30C0', '\u30C1', '\u30C2', '\u30C3', '\u30C4', '\u30C5', '\u30C6', '\u30C7', '\u30C8', '\u30C9', '\u30CA', '\u30CB', '\u30CC', '\u30CD', '\u30CE', '\u30CF', '\u30D0', '\u30D1', '\u30D2', '\u30D3', '\u30D4', '\u30D5', '\u30D6', '\u30D7', '\u30D8', '\u30D9', '\u30DA', '\u30DB', '\u30DC', '\u30DD', '\u30DE', '\u30DF', '\u30E0', '\u30E1', '\u30E2', '\u30E3', '\u30E4', '\u30E5', '\u30E6', '\u30E7', '\u30E8', '\u30E9', '\u30EA', '\u30EB', '\u30EC', '\u30ED', '\u30EE', '\u30EF', '\u30F0', '\u30F1', '\u30F2', '\u30F3', '\u30F4', '\u30F5', '\u30F6', '\u30F7', '\u30F8', '\u30F9', '\u30FA', '\u30FD', '\u30FE', '\u30FF', '\u31F0', '\u31F1', '\u31F2', '\u31F3', '\u31F4', '\u31F5', '\u31F6', '\u31F7', '\u31F8', '\u31F9', '\u31FA', '\u31FB', '\u31FC', '\u31FD', '\u31FE', '\u31FF', '\uFF66', '\uFF67', '\uFF68', '\uFF69', '\uFF6A', '\uFF6B', '\uFF6C', '\uFF6D', '\uFF6E', '\uFF6F', '\uFF71', '\uFF72', '\uFF73', '\uFF74', '\uFF75', '\uFF76', '\uFF77', '\uFF78', '\uFF79', '\uFF7A', '\uFF7B', '\uFF7C', '\uFF7D', '\uFF7E', '\uFF7F', '\uFF80', '\uFF81', '\uFF82', '\uFF83', '\uFF84', '\uFF85', '\uFF86', '\uFF87', '\uFF88', '\uFF89', '\uFF8A', '\uFF8B', '\uFF8C', '\uFF8D', '\uFF8E', '\uFF8F', '\uFF90', '\uFF91', '\uFF92', '\uFF93', '\uFF94', '\uFF95', '\uFF96', '\uFF97', '\uFF98', '\uFF99', '\uFF9A', '\uFF9B', '\uFF9C', '\uFF9D' ];
import React from 'react' import { shallow } from 'enzyme' import LoadingDots from './LoadingDots' describe('ClassName', () => { test('Applies custom className if specified', () => { const customClass = 'piano-key-neck-tie' const wrapper = shallow(<LoadingDots className={customClass} />) expect(wrapper.prop('className')).toContain(customClass) }) }) test('Renders 3 dots', () => { const wrapper = shallow(<LoadingDots />) expect(wrapper.children().length).toBe(3) }) describe('Align', () => { test('Does not apply an alignment class by default', () => { const wrapper = shallow(<LoadingDots />) expect(wrapper.hasClass('is-left')).not.toBeTruthy() expect(wrapper.hasClass('is-center')).not.toBeTruthy() expect(wrapper.hasClass('is-right')).not.toBeTruthy() }) test('Can apply alignment class', () => { const wrapper = shallow(<LoadingDots align="center" />) expect(wrapper.hasClass('is-left')).not.toBeTruthy() expect(wrapper.hasClass('is-center')).toBeTruthy() expect(wrapper.hasClass('is-right')).not.toBeTruthy() }) })
import * as THREE from "three"; import * as Tags from "../tags"; import * as MathUtil from "../util/math"; import mouseWheel from "mouse-wheel"; import query from "../util/query-string"; export default function UserZoomSystem(world, props) { const e = world.entity("UserZoomEntity").add(Tags.UserZoom, props); let y = 0; let listener; if (query.zoom) { listener = mouseWheel( world.findTag(Tags.Canvas), (dx, dy, dz, ev) => { y += dy; }, true ); } return { dispose() { if (listener) window.removeEventListener("wheel", listener); }, process, }; function process(dt) { const userZoom = e.get(Tags.UserZoom); const { allowMouseZoom, distance, zoomPowFactor, zoomPixelsToWorld, zoomPowTarget, minDistance, maxDistance, } = userZoom; if (allowMouseZoom) userZoom.currentWheelOffset += y; y = 0; const zoomFactor = Math.pow(distance / zoomPowTarget, zoomPowFactor); userZoom.distance += userZoom.currentWheelOffset * zoomPixelsToWorld * zoomFactor; userZoom.currentWheelOffset = 0; userZoom.distance = MathUtil.clamp( userZoom.distance, minDistance, maxDistance ); } }
import React from 'react'; import PropTypes from 'prop-types'; const DeveloperTopStarredRepos = ({ data }) => ( <div> <h1 className="title">En Çok Star Alan Repolar</h1> <h2 className="subtitle"> Bu geliştiricinin en çok start alan repoları </h2> <hr /> {data.length > 0 && <table className="table is-striped is-narrow"> <thead> <tr> <th style={{ width: '10%' }}>Sıra</th> <th style={{ width: '40%' }}>Repo</th> <th style={{ width: '20%' }}>Dil</th> <th style={{ width: '15%' }}>Star</th> <th style={{ width: '15%' }}>Fork</th> </tr> </thead> <tbody> {data.map((repo, index) => ( <tr key={repo.fullName}> <th>{index + 1}</th> <td> <a href={`https://github.com/${repo.fullName}`} target="_blank" rel="noopener noreferrer" > {repo.name} </a> </td> <td>{repo.language || '-'}</td> <td>{repo.stars.toLocaleString()}</td> <td>{repo.forks.toLocaleString()}</td> </tr> ))} </tbody> </table>} {data.length === 0 && <p>{name} için bu bilgisi bulunmuyor.</p>} </div> ); DeveloperTopStarredRepos.propTypes = { data: PropTypes.array.isRequired, }; export default DeveloperTopStarredRepos;
module.exports = { 'list|10': [{ name: 'name' }], content: 'Hello M1!' };
'use strict'; // -------------------------------------------------------------------- // Imports // -------------------------------------------------------------------- const assert = require('../src/common').assert; // -------------------------------------------------------------------- // Private stuff // -------------------------------------------------------------------- // Helpers function getProp(name, thing, fn) { return fn(thing[name]); } function mapProp(name, thing, fn) { return thing[name].map(fn); } // Returns a function that will walk a single property of a node. // `descriptor` is a string indicating the property name, optionally ending // with '[]' (e.g., 'children[]'). function getPropWalkFn(descriptor) { const parts = descriptor.split(/ ?\[\]/); if (parts.length === 2) { return mapProp.bind(null, parts[0]); } return getProp.bind(null, descriptor); } function getProps(walkFns, thing, fn) { return walkFns.map(walkFn => walkFn(thing, fn)); } function getWalkFn(shape) { if (typeof shape === 'string') { return getProps.bind(null, [getPropWalkFn(shape)]); } else if (Array.isArray(shape)) { return getProps.bind(null, shape.map(getPropWalkFn)); } else { assert(typeof shape === 'function', 'Expected a string, Array, or function'); assert(shape.length === 2, 'Expected a function of arity 2, got ' + shape.length); return shape; } } function isRestrictedIdentifier(str) { return /^[a-zA-Z_][0-9a-zA-Z_]*$/.test(str); } function trim(s) { return s.trim(); } function parseSignature(sig) { const parts = sig.split(/[()]/).map(trim); if (parts.length === 3 && parts[2] === '') { const name = parts[0]; let params = []; if (parts[1].length > 0) { params = parts[1].split(',').map(trim); } if (isRestrictedIdentifier(name) && params.every(isRestrictedIdentifier)) { return {name, formals: params}; } } throw new Error('Invalid operation signature: ' + sig); } /* A VisitorFamily contains a set of recursive operations that are defined over some kind of tree structure. The `config` parameter specifies how to walk the tree: - 'getTag' is function which, given a node in the tree, returns the node's 'tag' (type) - 'shapes' an object that maps from a tag to a value that describes how to recursively evaluate the operation for nodes of that type. The value can be: * a string indicating the property name that holds that node's only child * an Array of property names (or an empty array indicating a leaf type), or * a function taking two arguments (node, fn), and returning an Array which is the result of apply `fn` to each of the node's children. */ function VisitorFamily(config) { this._shapes = config.shapes; this._getTag = config.getTag; this.Adapter = function(thing, family) { this._adaptee = thing; this._family = family; }; this.Adapter.prototype.valueOf = function() { throw new Error('heeey!'); }; this.operations = {}; this._arities = Object.create(null); this._getChildren = Object.create(null); Object.keys(this._shapes).forEach(k => { const shape = this._shapes[k]; this._getChildren[k] = getWalkFn(shape); // A function means the arity isn't fixed, so don't put an entry in the arity map. if (typeof shape !== 'function') { this._arities[k] = Array.isArray(shape) ? shape.length : 1; } }); this._wrap = thing => new this.Adapter(thing, this); } VisitorFamily.prototype.wrap = function(thing) { return this._wrap(thing); }; VisitorFamily.prototype._checkActionDict = function(dict) { Object.keys(dict).forEach(k => { assert(k in this._getChildren, "Unrecognized action name '" + k + "'"); const action = dict[k]; assert(typeof action === 'function', "Key '" + k + "': expected function, got " + action); if (k in this._arities) { const expected = this._arities[k]; const actual = dict[k].length; assert( actual === expected, "Action '" + k + "' has the wrong arity: expected " + expected + ', got ' + actual ); } }); }; VisitorFamily.prototype.addOperation = function(signature, actions) { const sig = parseSignature(signature); const name = sig.name; this._checkActionDict(actions); this.operations[name] = { name, formals: sig.formals, actions }; const family = this; this.Adapter.prototype[name] = function() { const tag = family._getTag(this._adaptee); assert(tag in family._getChildren, "getTag returned unrecognized tag '" + tag + "'"); assert(tag in actions, "No action for '" + tag + "' in operation '" + name + "'"); // Create an "arguments object" from the arguments that were passed to this // operation / attribute. const args = Object.create(null); for (let i = 0; i < arguments.length; i++) { args[sig.formals[i]] = arguments[i]; } const oldArgs = this.args; this.args = args; const ans = actions[tag].apply( this, family._getChildren[tag](this._adaptee, family._wrap) ); this.args = oldArgs; return ans; }; return this; }; // -------------------------------------------------------------------- // Exports // -------------------------------------------------------------------- module.exports = VisitorFamily;
(function() { 'use strict'; var module = angular.module('ui.grid.filldown', ['ui.grid']); module.directive('uiGridFilldown', ['$timeout', 'gridUtil', 'uiGridConstants', function ($timeout, gridUtil, uiGridConstants) { return { require: 'uiGrid', scope: false, link: function ($scope, $elm, $attrs, uiGridCtrl) { /***************************** * VARIABLES *****************************/ var storedStartCell = {}; var storedStopCell = {}; var settings = {additionalField: null}; if ($attrs.uiGridFilldown != "") { $.extend(settings, $scope[$attrs.uiGridFilldown]); } var overlayDecorator = null; /***************************** * EVENTS *****************************/ function init() { var viewPort = $elm.find(".ui-grid-render-container"); viewPort.on('mousedown', mousedown); viewPort.on('dragover', onDragOver); viewPort.on('drop', onDrop); viewPort.on('keydown', reset) overlayDecorator = new OverlayDecorator(viewPort); overlayDecorator.bindHandleEvent('dragstart', onDragStart); } $timeout(init, 1000); // wait a while for the viewport to be created.. better solution anyone? function mousedown(evt) { var clickedCell = getCellFromEvent(evt); var cellScope = angular.element(clickedCell).scope(); if (!isValidStartCell(cellScope)) { return; } setStoredStartCell(cellScope); var start = getCellBox(storedStartCell.rowIdx, storedStartCell.colIdx); overlayDecorator.show(start, start); } function onDragStart(event) { event.originalEvent.dataTransfer.setData('text/html', null); //cannot be empty string in firefox! } function onDragOver(event) { event.preventDefault(); var hoverCell = getCellFromEvent(event); var hoverCellScope = angular.element(hoverCell).scope(); if (hoverCellScope) { setStoredStopCell(hoverCellScope); var start = getCellBox(storedStartCell.rowIdx, storedStartCell.colIdx); var stop = getCellBox(storedStopCell.rowIdx, storedStopCell.colIdx); overlayDecorator.show(start, stop); } } function onDrop() { var prevCell = storedStartCell; var currCell = storedStopCell; if (currCell && isValidEndCell(currCell.scope, prevCell)) { setCellData(prevCell, currCell); resetStoredStartCell(); resetStoredStopCell(); } overlayDecorator.hide(); } function reset() { overlayDecorator.hide(); } /***************************** * LOGIC *****************************/ function resetStoredStartCell() { storedStartCell = undefined; } function resetStoredStopCell() { storedStopCell = undefined; } function refreshGrid() { uiGridCtrl.grid.api.core.refresh(); } /***************************** * SETTER AND GETTERS *****************************/ function getCellBox(rowIdx, colIdx) { var heightOffset = (rowIdx+1)*uiGridCtrl.grid.options.rowHeight; var widthOffset = 0; for(var j = 0; j < colIdx; ++j) { if (uiGridCtrl.grid.columns[j].visible) { widthOffset += uiGridCtrl.grid.columns[j].drawnWidth; } } return { top: heightOffset, bottom: heightOffset + uiGridCtrl.grid.options.rowHeight, left: widthOffset, right: widthOffset + uiGridCtrl.grid.columns[colIdx].drawnWidth } } function getCellFromEvent(event) { return $(event.target).closest('.ui-grid-cell'); } function getValueFromGrid(cellScope, colField) { return getValueFromPath(cellScope.$parent.$parent.row.entity, colField); } function getValueFromPath(data, path) { path = path.split("[").join(".").split("]").join("").split("'").join(""); var fields = path.split("."); var dataValue = data[fields[0]]; for (var i = 1; i < fields.length; i++) { dataValue = dataValue[fields[i]]; } return dataValue; } function setValueOnPath(data, path, newValue) { path = path.split("[").join(".").split("]").join("").split("'").join(""); var fields = path.split("."); for (var i = 0; i < fields.length - 1; i++) { data = data[fields[i]]; } if (settings.additionalField) { data[fields[fields.length-1]][settings.additionalField] = newValue; } else { data[fields[fields.length-1]] = newValue; } } function getVisibleDataRow(rowIdx) { var visibleRows = uiGridCtrl.grid.api.core.getVisibleRows(); return visibleRows[rowIdx]; } function getColumnIndex(column) { return uiGridCtrl.grid.columns.indexOf(column); } function getRowIndex(row) { return uiGridCtrl.grid.api.core.getVisibleRows().indexOf(row); } function getFirstIndexOfCells(currCell, prevCell, startIndex) { var visibleRows = uiGridCtrl.grid.api.core.getVisibleRows(); for(var i = startIndex; i < visibleRows.length; ++i) { if (currCell.scope.$parent.$parent.row === visibleRows[i] || prevCell.scope.$parent.$parent.row === visibleRows[i]) { return i; } } throw "Unable to find index of cell for filldown"; } function setStoredStartCell(cellScope) { var rowIdx = getRowIndex(cellScope.$parent.$parent.row); var colIdx = getColumnIndex(cellScope.col); var colField = cellScope.col.field; var value = getValueFromGrid(cellScope, colField); storedStartCell = { rowIdx: rowIdx, colIdx: colIdx, colField: colField, value: value, scope: cellScope }; } function setStoredStopCell(cellScope) { var rowIdx = getRowIndex(cellScope.$parent.$parent.row); var colIdx = getColumnIndex(cellScope.col); var colField = cellScope.col.field; var value = getValueFromGrid(cellScope, colField); storedStopCell = { rowIdx: rowIdx, colIdx: colIdx, colField: colField, value: value, scope: cellScope }; } function setCellData(prevCell, currCell) { var offset = uiGridCtrl.grid.options.enableRowSelection ? 1 : 0; var startIndex = getFirstIndexOfCells(currCell, prevCell, 0); var stopIndex = getFirstIndexOfCells(currCell, prevCell, startIndex+1); var column = uiGridCtrl.grid.options.columnDefs[prevCell.colIdx - offset]; if (!column.disableFilldown) { var colField = column.field; for(var j = startIndex; j <= stopIndex; ++j) { var rowToUpdate = getVisibleDataRow(j); setValueOnPath(rowToUpdate.entity, colField, angular.copy(prevCell.value)); } } refreshGrid(); } /***************************** * VALIDATION ****************************/ function isValidEndCell(cellScope, prevCell) { return prevCell != undefined && cellScope != undefined && cellScope.col.colDef['enableCellEdit'] } function isValidStartCell(cellScope) { return cellScope; } /***************************** * GRAPHIC OVERLAY ****************************/ function Overlay(grid) { this.$left = $('<div>').addClass('cell-overlay').addClass('left').appendTo(grid); this.$right = $('<div>').addClass('cell-overlay').addClass('right').appendTo(grid); this.$top = $('<div>').addClass('cell-overlay').addClass('top').appendTo(grid); this.$bottom = $('<div>').addClass('cell-overlay').addClass('bottom').appendTo(grid); this.$handle = $('<div>').addClass("handle-overlay").attr('draggable', 'true').appendTo(grid); } function OverlayDecorator(grid) { var instance; function setVisibility(visibility) { instance.$left.toggle(visibility); instance.$right.toggle(visibility); instance.$top.toggle(visibility); instance.$bottom.toggle(visibility); instance.$handle.toggle(visibility); } function show(from, to) { if (!instance) { instance = new Overlay(grid) } var top = Math.min(from.top, to.top); var bottom = Math.max(from.bottom, to.bottom); setVisibility(true); instance.$left.css({ top: top, left: from.left, height: Math.max(from.bottom, to.bottom) - Math.min(from.top, to.top), width: 1 }); instance.$right.css({ top: top, left: from.right , height: Math.max(from.bottom, to.bottom) - Math.min(from.top, to.top), width: 1 }); instance.$top.css({ top: top, left: from.left , height: 1, width: from.right - from.left }); instance.$bottom.css({ top: bottom, left: from.left, height: 1, width: from.right - from.left }); instance.$handle.css({ top: bottom - 3, left: from.right - 4, height: 2, width: 2 }); } function bindHandleEvent(evt, fn) { if (!instance) { instance = new Overlay(grid) } instance.$handle.bind(evt, fn); } return { show: show, hide: function() { setVisibility(false); }, bindHandleEvent: bindHandleEvent } } } }; }]); })();
export default async function constructReport(results) { const report = []; results.forEach(({ name: target, result }) => { result.forEach(({ component, variant, url, width, height, snapRequestId }) => { report.push({ component, variant, url, width, height, target, snapRequestId, }); }); }); return report; }
process.env.NODE_ENV = process.env.NODE_ENV || 'testing'; process.env.WEBHOOK_SECRET = process.env.WEBHOOK_SECRET || 'TEST_STRIPE_WEBHOOK_SECRET'; require('../../core/server/overrides'); const {mochaHooks} = require('@tryghost/express-test').snapshot; exports.mochaHooks = mochaHooks;
/** * * - send: 1210 ----------- * - send: 1723 ----------|---- * - send: 1513 ----------|---|---- * ---- recv: 1723 <------|---- * - send: 1164 ----------|------------ * - send: 1146 ----------|---------------- * - send: 1926 ----------|-------------------- * ---- recv: 1164 | * - send: 1841 ----------|------------------------ * ---- recv: 1513 | * - send: 1844 ----------|---------------------------- * - send: 1430 ----------|-------------------------------- * ---- recv: 1210 <------- * ---- recv: 1926 * ---- recv: 1841 * ---- recv: 1146 * ---- recv: 1430 * ---- recv: 1844 */ 'use strict'; var zmq = require('zmq'); var ran = require('./random').ran; var color = require('./random').color2; var ADDR = 'inproc://exhibit-b'; var push = zmq.socket('push'); var pull1 = zmq.socket('pull'); var pull2 = zmq.socket('pull'); var pull3 = zmq.socket('pull'); pull1.connect(ADDR); pull2.connect(ADDR); pull3.connect(ADDR); pull1.on('message', handle(1)); pull2.on('message', handle(3)); pull3.on('message', handle(4)); function handle(code) { return function (msg) { setTimeout(function () { msg = msg.toString(); console.log('---- recv: ' + msg[color(code)]); }, ran(5000, 500)); } } push.bind(ADDR); var intHandler = setInterval(function () { var msg = ran(1000, 1000) + ''; console.log('- send: ' + msg); push.send(msg); }, 500); setTimeout(function () { clearInterval(intHandler); }, 5000);
'use strict'; angular.module('grtyrApp') .factory('Auth', function Auth($rootScope, $http, User, $cookieStore, $q) { /** * Return a callback or noop function * * @param {Function|*} cb - a 'potential' function * @return {Function} */ var safeCb = function(cb) { return (angular.isFunction(cb)) ? cb : angular.noop; }, currentUser = {}; if ($cookieStore.get('token')) { currentUser = User.get(); } return { /** * Authenticate user and save token * * @param {Object} user - login info * @param {Function} callback - optional, function(error) * @return {Promise} */ login: function(user, callback) { return $http.post('/auth/local', { email: user.email, password: user.password }) .then(function(res) { $cookieStore.put('token', res.data.token); currentUser = User.get(); safeCb(callback)(); $rootScope.$emit('loggedIn'); return res.data; }, function(err) { this.logout(); safeCb(callback)(err.data); return $q.reject(err.data); }.bind(this)); }, /** * Delete access token and user info */ logout: function() { $cookieStore.remove('token'); currentUser = {}; $rootScope.$emit('loggedOut'); }, /** * Create a new user * * @param {Object} user - user info * @param {Function} callback - optional, function(error, user) * @return {Promise} */ createUser: function(user, callback) { return User.save(user, function(data) { $cookieStore.put('token', data.token); currentUser = User.get(); $rootScope.$emit('loggedIn'); return safeCb(callback)(null, user); }, function(err) { this.logout(); return safeCb(callback)(err); }.bind(this)).$promise; }, /** * Change password * * @param {String} oldPassword * @param {String} newPassword * @param {Function} callback - optional, function(error, user) * @return {Promise} */ changePassword: function(oldPassword, newPassword, callback) { return User.changePassword({ id: currentUser._id }, { oldPassword: oldPassword, newPassword: newPassword }, function(user) { return safeCb(callback)(null, user); }, function(err) { return safeCb(callback)(err); }).$promise; }, /** * Gets all available info on a user * (synchronous|asynchronous) * * @param {Function|*} callback - optional, funciton(user) * @return {Object|Promise} */ getCurrentUser: function(callback) { if (arguments.length === 0) { return currentUser; } var value = (currentUser.hasOwnProperty('$promise')) ? currentUser.$promise : currentUser; return $q.when(value) .then(function(user) { safeCb(callback)(user); return user; }, function() { safeCb(callback)({}); return {}; }); }, /** * Check if a user is logged in * (synchronous|asynchronous) * * @param {Function|*} callback - optional, function(is) * @return {Bool|Promise} */ isLoggedIn: function(callback) { if (arguments.length === 0) { return currentUser.hasOwnProperty('role'); } return this.getCurrentUser(null) .then(function(user) { var is = user.hasOwnProperty('role'); safeCb(callback)(is); return is; }); }, /** * Check if a user is an admin * (synchronous|asynchronous) * * @param {Function|*} callback - optional, function(is) * @return {Bool|Promise} */ isAdmin: function(callback) { if (arguments.length === 0) { return currentUser.role === 'admin'; } return this.getCurrentUser(null) .then(function(user) { var is = user.role === 'admin'; safeCb(callback)(is); return is; }); }, /** * Check if a user is local * (synchronous|asynchronous) * * @param {Function|*} callback - optional, function(is) * @return {Bool|Promise} */ isLocal: function(callback) { if (arguments.length === 0) { return currentUser.provider === 'local'; } return this.getCurrentUser(null) .then(function(user) { var is = user.provider === 'local'; safeCb(callback)(is); return is; }); }, /** * Get auth token * * @return {String} - a token string used for authenticating */ getToken: function() { return $cookieStore.get('token'); } }; });
const { ValidationError } = require("moleculer").Errors; module.exports = async function(ctx) { const userId = ctx.meta.user ? ctx.meta.user.id : null; if(!userId) { throw new ValidationError('Not Authorized!', 401); } const scriptId = ctx.params.id let response = await ctx.call('league.get', { id: scriptId, fields: [ "id", "ownerName", "scriptName", "code" ] }); return { id: response.id, scriptName: response.ownerName + '/' + response.scriptName, code: response.code }; }
import { CancellableAction } from './Action' export default function trifurcate (f, r, c, p, promise) { // assert: promise.token == null p._when(p._whenToken(new Trifurcation(f, r, c, promise))) return promise } class Trifurcation extends CancellableAction { constructor (f, r, c, promise) { super(f, promise) this.r = r this.c = c } cancel (res) { // assert: cancelled() is called later, before rejected() is called } fulfilled (p) { this.runTee(this.f, p) } rejected (p) { return this.runTee(this.r, p) } cancelled (p) { if (typeof this.c !== 'function') { this.end()._reject(p.near().value) } else { this.runTee(this.c, p.near()) } // assert: this.promise == null, so that rejected won't run } runTee (f, p) { /* eslint complexity:[2,4] */ const hasHandler = (this.f != null || this.r != null || this.c != null) && typeof f === 'function' if (hasHandler) { this.r = null this.c = null this.tryCall(f, p.value) } else { this.put(p) } return hasHandler } end () { const promise = this.promise this.promise = null return promise } }
/** * @fileOverview * @module weekTool * @author hisland hisland@qq.com * @description 周选择控件 * <pre><code> * API: * $.week(); //获得对象,默认使用当前时间 * $.week(2001);, $.week('2001'); //获得对象,使用2001年和第1周 * $.week(2001, 5);, $.week('2001', 5); //获得对象,使用2001年和第5周 * $.week('2011-5-6'); //获得对象,使用2011-5-6进行初始化 * * var w = $.week(); * w.next(); //移动到下一周 * w.prev(); //移动到上一周 * w.next(5); //移动到下5周 * w.prev(5); //移动到上5周 * w.year(2010);, w.year('2010'); //设置年 * w.week(25);, w.week('25'); //设置周 * w.setDate('2009-5-4'); //设置时间 * w.setDate(new Date()); //设置时间,用日期对象 * w.year(); //取年 * w.week(); //取周 * w.maxWeek(); //当年最大周 * w.start(); //取当周的开始时间 * w.end(); //取当周的结束时间 * * $(':text.start').weekTool(); //初始化周控件,有弹出层显示 * $(':text.start').weekTool({year_range: [2005, 2009]}); //初始化周控件,年范围为2005-2009 * $(':text.start').weekTool('off'); //禁用 * $(':text.start').weekTool('on'); //启用 * * TODO: * 2011-08-08 10:25:49 * 增加next(n), prev(n)方法进行周的移动 * * 2011-09-15 18:07:38 * 各方法的边界检测 * </code></pre> */ KISSY.add('weekTool', function(S, undef) { var msg_please_check = '请选择', msg_ok = '确定', msg_close_title = '双击选择并关闭'; msg_start = '第{startWeek}周 {startTime}'; msg_end = '第{endWeek}周 {endTime}'; //JS国际化信息覆盖 if(window.JS_I18N){ msg_please_check = JS_I18N['js.common.weekTool.msg_please_check']; msg_ok = JS_I18N['js.common.weekTool.msg_ok']; msg_close_title = JS_I18N['js.common.weekTool.msg_close_title']; msg_start = JS_I18N['js.common.weekTool.msg_start']; msg_end = JS_I18N['js.common.weekTool.msg_end']; } var $ = jQuery, $EMPTY = $(''), pop = $.popWin.init(), $info = $('<div class="weektool-tip">您选择的时间是:<span class="weektool-range">第8周 2012-02-09 17:11:10</span>到<span class="weektool-range">第8周 2012-02-09 17:11:10</span></div>'), $legend = $('<div class="weektool-legend"><span class="weektool-legend1">年</span><span class="weektool-legend2">周</span><span class="weektool-legend3">时间</span><span class="weektool-legend4">周</span><span class="weektool-legend5">时间</span></div>'), $range_start = $info.find('span:first'), $range_end = $info.find('span:eq(1)'), $box_left = $('<div class="weektool" style="width:100px;"></div>'), $box_wrap = $('<div class="weektool" style="margin-left:5px;width:340px;"></div>'), $box_mid = $('<div style="float:left;width:160px;"></div>').appendTo($box_wrap), $box_right = $('<div style="float:left;width:160px;" title="' + msg_close_title + '"></div>').appendTo($box_wrap), $btn_wrap = $('<div class="win1-btns"><input type="submit" value="' + msg_ok + '" class="win1-btn-ok"></div>'), $btn_ok = $btn_wrap.find('input'), $ipt_start = $EMPTY, $ipt_end = $EMPTY, setting; var default_setting = { year_range: [2000, 2030], enable: true } /** * 周对象, 可方便传入年和周 * @memberOf jQuery * @class * @name week */ function WeekUtil(year, week){ //更改为构造方式 if(!(this instanceof WeekUtil)){ return new WeekUtil(year, week); } //从字符串预处理 if(S.isString(year)){ //可转换成日期对象 if(year.getDate()){ year = year.getDate(); } //可转换成数字 else if(S.isNumber(year-0)){ year -= 0; } //其它情况 else{ year = null; } } //为日期对象,直接使用 if(year instanceof Date){ this.setDate(year); } //为数字设置年,默认第1周 else if(S.isNumber(year)){ this.year(year); this.week(week-0 || 1); } //其它情况使用当时时间 else{ this.setDate(new Date()); } return this; } /** * 设置原型方法 * @lends jQuery.week# */ S.augment(WeekUtil, { /** * 传y表示设置, 不传y表示取值 * <pre><code> * var w = $.week(); * w.year(); 返回年数字 * w.year(2011); 设置为2011年, 返回this * w.year('2011'); 设置为2011年, 返回this * </code></pre> */ year: function(y){ if(y !== undefined){ this.__year = y-0; this.__baseDate(); return this; }else{ return this.__year; } }, /** * 传n表示设置, 不传n表示取值 * <pre><code> * var w = $.week(); * w.week(); 返回周数字 * w.week(3); 设置为第3周, 返回this * w.week('3'); 设置为第3周, 返回this * </code></pre> */ week: function(n){ if(n !== undefined){ this.__week = n-0; return this; }else{ return this.__week; } }, /** * 取得当年最大周 */ maxWeek: function(){ var bak = this.week(), max; //一年正常有53周,最多有54周,从52周开始增加,直到停止 this.week(52); while(this.start().getFullYear() === this.year()){ this.next(); } max = this.prev().week(); this.week(bak); return max; }, /** * 将对象的内部值后移n(默认1)周 * <pre><code> * var w = $.week(); * w.week(3); 设置为第3周 * w.next(); 后移一周 * w.week(); 返回4 * w.next(5); 后移5周 * w.week(); 返回9 * </code></pre> */ next: function(n){ n = n<1 || 1; return this.week(this.__week + n); }, /** * 将对象的内部值前移n(默认1)周 * <pre><code> * var w = $.week(); * w.week(10); 设置为第3周 * w.prev(); 前移一周 * w.week(); 返回9 * w.prev(3); 前移3周 * w.week(); 返回6 * </code></pre> */ prev: function(n){ n = n<1 || 1; return this.week(this.__week - n); }, /** * 将对象的内部值设置为指定日期对象 * <pre><code> * var w = $.week(); * w.setDate('2011-01-31'); 设置为指定日期 * </code></pre> */ setDate: function(date){ //从String转换成Date if(S.isString(date)){ date = date.getDate(); } if(date instanceof Date){ this.year(date.getFullYear()); //1年最多53自然周 for(var i=1; i<55; i++){ this.week(i); //当start大于时,表示date属于上周 if(this.start() > date){ this.week(i-1); break; } } }else{ S.log('$.week().setDate(date): date must be a valid Date or dateString!'); } return this; }, /** * 返回当前周的开始日期对象 */ start: function(){ return new Date(+this.base_date + (this.__week-1)*7*86400000); }, /** * 返回当前周的结束日期对象 */ end: function(){ return new Date(+this.base_date + this.__week*7*86400000-1); }, __baseDate: function(){ var base_date = new Date(this.__year+'/1/1'), first_day = base_date.getDay() || 7, lost_days = first_day > 1 ? 8-first_day : 0; //+base_date, 会将Date对象转换成数字值 this.base_date = lost_days ? new Date(+base_date + (lost_days-7)*86400000) : base_date; return this; } }); //初始化弹出层结构 pop.$content.append($info).append($legend).append($box_left).append($box_wrap).append($btn_wrap); pop.setTitle(msg_please_check); pop.setInnerWidth(450); pop.manager.$div.addClass('not-remove'); //生成年列表 function makeYearList(now){ var b = [], from = setting.year_range[0], to = setting.year_range[1]; //修正当前年 if(now < from){ now = from; }else if(now > to){ now = to; } for(; from <= to; from++){ if(from != now){ b.push('<a href="#">', from, '</a>'); }else{ b.push('<a href="#" class="hover">', from, '</a>'); } } $box_left.html(b.join('')); } //生成开始结束时间列表 function makeOtherList(year){ var week = WeekUtil(year), max = week.maxWeek(); var b_start = [], b_end = []; for(var i=1; i<=max; i++){ b_start.push('<a href="#"><strong>', i, '</strong><span>', week.week(i).start().dateTimeString(), '</span></a>') b_end.push('<a href="#"><strong>', i, '</strong><span>', week.end().dateTimeString(), '</span></a>') } $box_mid.html(b_start.join('')); $box_right.html(b_end.join('')); } //年点击更新右侧时间列表 $box_left.click(function(e){ var dt = $(e.target); if(dt.is('a')){ dt.addClass('hover').siblings('.hover').removeClass('hover'); //保存前面的索引 var start = $box_mid.find('a.hover').index(); var end = $box_right.find('a.hover').index(); //修正在末尾的情况,因为从0开始,所以是53 if(start == 53){ start = 52; } if(end == 53){ end = 52; } //生成列表并还原选中状态 makeOtherList(dt.text()); $box_mid.find('a').eq(start).click(); $box_right.find('a').eq(end).click(); dt.blur(); e.preventDefault(); } }); //点击开始时间,修正结束时间范围 function resetRight(i){ var as = $box_right.find('a'); as.eq(i).prevAll().addClass('disabled').end().nextAll().andSelf().removeClass('disabled'); //当选中的是禁用的时候.修改为开始时间对应的结束时间 if(as.filter('.hover').is('.disabled')){ as.eq(i).click(); } } $box_mid.click(function(e){ var dt = $(e.target).closest('a', this); if(dt.is('a')){ dt.addClass('hover').siblings('.hover').removeClass('hover'); resetRight(dt.index()); dt.blur(); refreshInfo(); e.preventDefault(); } }); //点击结束时间的操作,双击填入并关闭 $box_right.click(function(e){ var dt = $(e.target).closest('a', this); if(dt.is('a')){ if(!dt.is('.disabled')){ dt.addClass('hover').siblings('.hover').removeClass('hover'); } dt.blur(); refreshInfo(); e.preventDefault(); } }).dblclick(function(e){ if(!$(e.target).closest('a', this).is('.disabled')){ $btn_ok.click(); } }); //确定按钮点击时放回去 $btn_ok.click(function(){ var start = $box_mid.find('.hover'); var end = $box_right.find('.hover'); $ipt_start.val(start.find('span').text()); $ipt_end.val(end.find('span').text()); pop.hide(); $ipt_start = $ipt_end = $EMPTY; }); function refreshInfo(){ var start = $box_mid.find('.hover'); var end = $box_right.find('.hover'); var rs = { startWeek: start.find('strong').text(), startTime: start.find('span').text(), endWeek: end.find('strong').text(), endTime: end.find('span').text() }; $range_start.html(S.substitute(msg_start, rs)); $range_end.html(S.substitute(msg_end, rs)); } function showPop(){ var date_start, date_end, week; setting = $ipt_start.data('week-tool-setting'); //禁用时不打开 if(!setting.enable){ return ; } pop.show(); //从输入框获得时间,不成功则使用当前时间 if($ipt_start.val().isValidDate()){ date_start = $ipt_start.val().getDate(); }else{ date_start = new Date(); } if($ipt_end.val().isValidDate()){ date_end = $ipt_end.val().getDate(); }else{ date_end = date_start; } //修正当前选择年 week = WeekUtil(date_start); makeYearList(week.year()); $box_left.find('.hover').focus().click(); //填入对应的周 $box_mid.find('a').eq(week.week()-1).click(); week.setDate(date_end); $box_right.find('a').eq(week.week()-1).focus().click(); } //开始或者结束时间点击时将内部变量设置为正确的引用 function iptStartFocus(e){ $ipt_start = $(this); $ipt_end = $ipt_start.next(); showPop(); } function iptEndFocus(e){ $ipt_end = $(this); $ipt_start = $ipt_end.prev(); showPop(); } /** * @memberOf jQuery# */ function weekTool(setting){ if(!S.isPlainObject(setting)){ if(S.isUndefined(setting)){ setting = {}; }else if(setting === 'off'){ setting = {enable: false}; }else if(setting === 'on'){ setting = {enable: true}; }else{ setting = {}; } } return this.filter(':text').each(function(i, v){ //初始化配置 if(!$(v).data('week-tool-setting')){ $(v).click(iptStartFocus).next().click(iptEndFocus); //copy一份新的.否则会导致使用默认对象 $(v).data('week-tool-setting', S.mix({}, default_setting)); } //修改配置,只能覆盖白名单指定的属性 S.mix($(v).data('week-tool-setting'), setting, ['year_range', 'enable']); }); } $.extend({ week: WeekUtil }); $.fn.extend({ weekTool: weekTool }); }, { requires: ['jquery-1.4.2', 'builtin', 'adjustElement', 'popWin+css'] });
;( function ( root, factory ) { "use strict"; // UMD for a Backbone plugin. Supports AMD, Node.js, CommonJS and globals. // // - Code lives in the Backbone namespace. // - The module does not export a meaningful value. // - The module does not create a global. var supportsExports = typeof exports === "object" && exports && !exports.nodeType && typeof module === "object" && module && !module.nodeType; // AMD: // - Some AMD build optimizers like r.js check for condition patterns like the AMD check below, so keep it as is. // - Check for `exports` after `define` in case a build optimizer adds an `exports` object. // - The AMD spec requires the dependencies to be an array **literal** of module IDs. Don't use a variable there, // or optimizers may fail. if ( typeof define === "function" && typeof define.amd === "object" && define.amd ) { // AMD module define( [ "exports", "underscore", "backbone", "backbone.declarative.views" ], factory ); } else if ( supportsExports ) { // Node module, CommonJS module factory( exports, require( "underscore" ), require( "backbone" ), require( "backbone.declarative.views" ) ); } else { // Global (browser or Rhino) factory( {}, _, Backbone ); } }( this, function ( exports, _, Backbone ) { "use strict"; var $ = Backbone.$, $document = $( document ), pluginNamespace = Backbone.InlineTemplate = { hasInlineEl: _hasInlineEl, updateTemplateSource: false, version: "__COMPONENT_VERSION_PLACEHOLDER__" }, rxLeadingComments = /^(\s*<!--[\s\S]*?-->)+/, rxTrailingComments = /(<!--[\s\S]*?-->\s*)+$/, rxOutermostHtmlTagWithContent = /(<\s*[a-zA-Z][\s\S]*?>)([\s\S]*)(<\s*\/\s*[a-zA-Z]+\s*>)/, rxSelfClosingHtmlTag = /<\s*[a-zA-Z][\s\S]*?\/?\s*>/, bbdvLoadTemplate = Backbone.DeclarativeViews.defaults.loadTemplate; // // Initialization // -------------- Backbone.DeclarativeViews.plugins.registerDataAttribute( "el-definition" ); Backbone.DeclarativeViews.plugins.registerDataAttribute( "bbit-internal-template-status" ); Backbone.DeclarativeViews.plugins.registerCacheAlias( pluginNamespace, "inlineTemplate" ); Backbone.DeclarativeViews.plugins.enforceTemplateLoading(); // // Template loader //---------------- Backbone.DeclarativeViews.defaults.loadTemplate = function ( templateProperty ) { var parsedTemplateData, $resultTemplate, // Check Backbone.InlineTemplate.custom.hasInlineEl first, even though it is undocumented, to catch // accidental assignments. hasInlineEl = pluginNamespace.custom.hasInlineEl || pluginNamespace.hasInlineEl || _hasInlineEl, updateTemplateContainer = pluginNamespace.updateTemplateSource, $inputTemplate = bbdvLoadTemplate( templateProperty ); if ( _isMarkedAsUpdated( $inputTemplate ) || !hasInlineEl( $inputTemplate ) ) { // No inline el definition. Just return the template as is. $resultTemplate = $inputTemplate; } else { // Parse the template data. // // NB Errors are not handled here and bubble up further. Try-catch is just used to enhance the error message // for easier debugging. try { parsedTemplateData = _parseTemplateHtml( $inputTemplate.html() ); } catch ( err ) { err.message += '\nThe template was requested for template property "' + templateProperty + '"'; throw err; } if ( updateTemplateContainer ) { // For updating the template container, it has to be a node in the DOM. Throw an error if it has been // passed in as a raw HTML string. if ( !existsInDOM( templateProperty ) ) throw new Backbone.DeclarativeViews.TemplateError( "Backbone.Inline.Template: Can't update the template container because it doesn't exist in the DOM. The template property must be a valid selector (and not, for instance, a raw HTML string). Instead, we got \"" + templateProperty + '"' ); $resultTemplate = $inputTemplate; // The template is updated and the inline `el` removed. Set a flag on the template to make sure the // template is never processed again as having an inline `el`. _markAsUpdated( $resultTemplate ); } else { // No updating of the input template. Create a new template node which will stay out of the DOM, but is // passed to the cache. $resultTemplate = $( "<script />" ).attr( "type", "text/x-template" ); } _mapElementToDataAttributes( parsedTemplateData.$elSample, $resultTemplate ); $resultTemplate.empty().text( parsedTemplateData.templateContent ); } return $resultTemplate; }; /** * Checks if a template is marked as having an inline `el`. Is also exposed as Backbone.InlineTemplate.hasInlineEl(). * * By default, a template is recognized as having an inline `el` when the container has the following data attribute: * `data-el-definition: "inline"`. * * The check can be changed by overriding Backbone.InlineTemplate.hasInlineEl with a custom function. In order to * treat all templates as having an inline `el`, for instance, the custom function just has to return true: * * Backbone.InlineTemplate.hasInlineEl = function () { return true; }; * * @param {jQuery} $templateContainer the template node (usually a <script> or a <template> tag) * @returns {boolean} */ function _hasInlineEl ( $templateContainer ) { return $templateContainer.data( "el-definition" ) === "inline"; } /** * Marks a template as updated and no longer having an inline `el`. Henceforth, the template node is treated like an * ordinary, non-inline template. * * ## Rationale: * * A template is updated when the `updateTemplateSource` option is set. After the update, the `el` markup has been * removed from the template content, and only the inner HTML of the `el` is still present in the template. * * Therefore, the template must not be processed again for having an inline `el`, even though it is still marked as * such. (The inline `el` marker - e.g. data-el-definition: "inline" - is still present.) Repeated processing would * garble the remaining template content. * * That is prevented by setting a second flag in a data attribute which is considered internal. A template which is * marked as updated, with that flag, is not processed and updated again. * * ## jQuery data cache: * * The jQuery data cache doesn't have to be updated here. That happens automatically while the template is checked * for data attributes in Backbone.Declarative.Views. * * @param {jQuery} $templateContainer */ function _markAsUpdated ( $templateContainer ) { $templateContainer.attr( "data-bbit-internal-template-status", "updated" ); } /** * Checks if a template is marked as having been updated. * * @param {jQuery} $templateContainer * @returns {boolean} */ function _isMarkedAsUpdated ( $templateContainer ) { return $templateContainer.data( "bbit-internal-template-status" ) === "updated"; } /** * Takes the raw text content of the template tag, extracts the inline `el` as well as its content, turns the `el` * string into a sample node and, finally, returns the $el sample and the inner content in a hash. * * @param {string} templateText * @returns {ParsedTemplateData} */ function _parseTemplateHtml ( templateText ) { var elDefinition, $elSample, templateContent = "", normalizedTemplateText = templateText.replace( rxLeadingComments, "" ).replace( rxTrailingComments, "" ), matches = rxOutermostHtmlTagWithContent.exec( normalizedTemplateText ) || rxSelfClosingHtmlTag.exec( normalizedTemplateText ); if ( !matches ) throw new Backbone.DeclarativeViews.TemplateError( 'Backbone.Inline.Template: Failed to parse template with inline `el` definition. No matching content found.\nTemplate text is "' + templateText + '"' ); if ( matches[3] ) { // Applied regex for outermost HTML tag with content, capturing 3 groups elDefinition = matches[1] + matches[3]; templateContent = matches[2]; } else { // Applied regex for self-closing `el` tag without template content, not capturing any groups. elDefinition = matches[0]; } try { $elSample = $( elDefinition ); } catch ( err ) { throw new Backbone.DeclarativeViews.TemplateError( 'Backbone.Inline.Template: Failed to parse template with inline `el` definition. Extracted `el` could not be turned into a sample node.\nExtracted `el` definition string is "' + elDefinition + '", full template text is "' + templateText + '"' ); } return { templateContent: templateContent, $elSample: $elSample }; } /** * Takes an element node and maps its defining characteristics - tag name, classes, id, other attributes - to data * attributes on another node, in the format used by Backbone.Declarative.Views. * * In other words, it transforms an actual `el` sample node into a set of descriptive data attributes on a template. * * @param {jQuery} $sourceNode the `el` sample node * @param {jQuery} $target the template node */ function _mapElementToDataAttributes ( $sourceNode, $target ) { var sourceProps = { tagName: $sourceNode.prop("tagName").toLowerCase(), className: $.trim( $sourceNode.attr( "class" ) ), id: $.trim( $sourceNode.attr( "id" ) ), otherAttributes: {} }; _.each( $sourceNode[0].attributes, function ( attrNode ) { var name = attrNode.nodeName, value = attrNode.nodeValue, include = value !== undefined && name !== "class" && name !== "id"; if ( include ) sourceProps.otherAttributes[attrNode.nodeName] = value; } ); if ( sourceProps.tagName !== "div" ) $target.attr( "data-tag-name", sourceProps.tagName ); if ( sourceProps.className ) $target.attr( "data-class-name", sourceProps.className ); if ( sourceProps.id ) $target.attr( "data-id", sourceProps.id ); if ( _.size( sourceProps.otherAttributes ) ) $target.attr( "data-attributes", JSON.stringify( sourceProps.otherAttributes ) ); } // // Generic helpers // --------------- /** * Checks if an entity can be passed to jQuery successfully and be resolved to a node which exists in the DOM. * * Can be used to verify * - that a string is a selector, and that it selects at least one existing element * - that a node is part of the document * * Returns false if passed e.g. a raw HTML string, or invalid data, or a detached node. * * @param {*} testedEntity can be pretty much anything, usually a string (selector) or a node * @returns {boolean} */ function existsInDOM ( testedEntity ) { try { return $document.find( testedEntity ).length !== 0; } catch ( err ) { return false; } } // Module return value // ------------------- // // A return value may be necessary for AMD to detect that the module is loaded. It ony exists for that reason and is // purely symbolic. Don't use it in client code. The functionality of this module lives in the Backbone namespace. exports.info = "Backbone.Inline.Template has loaded. Don't use the exported value of the module. Its functionality is available inside the Backbone namespace."; // // Custom types // ------------ // // For easier documentation and type inference. /** * @name ParsedTemplateData * @type {Object} * * @property {jQuery} $elSample * @property {string} templateContent */ } ) );
import _GenresHandler from './GenresHandler'; export { _GenresHandler as GenresHandler }; import _RecommendationsHandler from './RecommendationsHandler'; export { _RecommendationsHandler as RecommendationsHandler };
'use strict'; angular.module('mean.demo') .directive('myDirective', function() { return { restrict: 'EA', replace: false, scope: { myUrl: '@', myLinkText: '@' }, template: '<a href="{{ myUrl }}"> {{ myLinkText }}</a>' }; });
import Ember from 'ember'; export default Ember.Component.extend({ /** The CSS properties for the 'spotlight' element over the current target element @property spotlightCSS @type String */ spotlightCSS: '', /** The point at which the tour will start @property firstTourStep @type Integer @default 0 */ firstTourStep: 0, /** The number of the active stop stop @property currentStopStep @type Integer @default null */ currentStopStep: null, /** Set to true if the tour is between stops @property transitioning @type Integer @default false */ transitioning: false, /** The previous tour stop @property previousStop @type previousStop @default null */ previousStop: null, /** When in transition, the stop to which the tour is transitioning @property transitionStop @type Object @default null */ transitionStop: null, /** The height of the window @property windowHeight @type Integer */ windowHeight: null, /** The width of the window @property windowWidth @type Integer */ windowWidth: null, /** @property tourStops @type Object */ tourStops: Ember.computed.alias('model.tourStops'), /** The Ember currentPath @property currentPath @type String */ currentPath: Ember.computed.alias('parentView.controller.currentPath'), /** Set to true when the tour has been started. @property started @type Boolean */ started: Ember.computed.alias('parentView.controller.tourStarted'), /** The model of the tour @property model @type Object */ model: Ember.computed.alias('parentView.controller.tour'), /** Starts the tour when `started` is changed to true @private @method _startTour */ _startTour: (function(){ if(this.get('started')){ this.setProperties({ transitionStop: null, currentStop: null }); var startingStep = this.get('firstTourStep') || 0; this.set('currentStopStep', startingStep); this.notifyPropertyChange('currentStopStep'); } }).observes('started'), /** Set to true if there are stops after the `currentStop` in `tourStops` @property moreForwardSteps @type Boolean */ moreForwardSteps: Ember.computed('currentStopStep', 'sortedTourStops', function(){ return this.get('currentStopStep') + 1 < this.get('sortedTourStops.length'); } ), /** Set to true if there are stops before the `currentStop` in `tourStops` @property moreBackwardStops @type Boolean */ moreBackwardSteps: Ember.computed('currentStopStep', function(){ return this.get('currentStopStep') > 0; } ), /** When the current path changes, call a check to see if the user changed the path @method pathChange */ pathChange: (function(){ if(this.get('currentStop') && this.get('started')) { Ember.run.scheduleOnce('afterRender', this, this._checkForUserInitiatedTransition); } }).observes('currentPath'), /** Exits the tour if the user initiated a route change, instead of the tour. Checks to see if the target element is still in the page after the transition; if not the tour ends. @method _checkForUserInitiatedTransition */ _checkForUserInitiatedTransition: (function(){ var transitioning = this.get('transitioning'); var element = this.get('currentStop.element'); var elementOnPage = $(element); if (!transitioning && Ember.isBlank(elementOnPage)) { this.exitTour(); } }), /** The tour's stops, sorted by the step number @property sortedTourStops @type Object */ sortedTourStops: Ember.computed('tourStops', function(){ var tourStops = this.get('tourStops'); if(tourStops && tourStops.get('length')){ return tourStops.sortBy('step'); } } ), /** When the `currentStopStep` changes, the transitionStop is set to the object at that position. @private @method _setTransitionStop */ _setTransitionStop: (function(){ var step = this.get('currentStopStep'); var transitionStop = this.get('sortedTourStops').objectAt(step); this.set('transitionStop', transitionStop); } ).observes('currentStopStep'), /** Observes when the transitonStop changes, and initiates the transition to that stop. @private @method _startTourStopTransition */ _startTourStopTransition: (function(){ var transitionStop = this.get('transitionStop'), currentStop = this.get('currentStop'); if(currentStop){ currentStop.set('active', false); } if(transitionStop) { this.set('transitioning', true); var previousStop = this.get('previousStop'), targetRoute = transitionStop.get('targetRoute'), router = this.container.lookup('router:main').router, renderedProperty = 'lastRenderedTemplate', targetElement = transitionStop.get('element'), route; var allRoutes = Ember.keys(router.recognizer.names); var routeExists = allRoutes.indexOf(targetRoute) !== -1; if (routeExists) { route = this.container.lookup('route:' + targetRoute); } var currentRouteDifferent = !previousStop || previousStop.get('targetRoute') !== targetRoute; var routePresent = routeExists && route.get(renderedProperty); if (routeExists && (!routePresent || currentRouteDifferent)) { route.transitionTo(targetRoute); if (targetElement) { this._finishWhenElementInPage(targetElement); } else { this._finishTransition(); } } else { this._finishTransition(); } } }).observes('transitionStop'), /** Waits for the target element to render before finishing the transition. If it times out, it initiates the transition to the next stop. @private @param element {Object} the target element @param waitTime {Integer} the length of time before timing out */ _finishWhenElementInPage: function(element, waitTime) { var component = this; if(!(typeof waitTime === "number")){ waitTime = 5000 } if(!Ember.isBlank($(element))){ this._finishTransition(); } else if(waitTime > 0) { Ember.run.later(function () { component._finishWhenElementInPage(element, waitTime - 20); },20); } else { this.incrementProperty('currentStopStep'); } }, /** Moves the `currentStop` to `previousStop`, and the `transitionStop` to the `currentStop`. Also activates the (soon to be) `currentStop` @private @method _finishTransition */ _finishTransition: function() { var transitionStop = this.get('transitionStop'), currentStop = this.get('currentStop'); transitionStop.set('active', true); this.setProperties({ currentStop: transitionStop, previousStop: currentStop }); Ember.run.scheduleOnce('afterRender', this, function(){this.set('transitioning', false)}); }, /** Initializes a listener to track window height and width @private @method _windowSize */ _windowSize: (function(){ var component = this; component.setProperties({ windowWidth: $(window).width(), windowHeight: $(window).height() }); if(this.get('started')){ Ember.$(window).on('resize.tour', function(){ Ember.run(function() { component.setProperties({ windowWidth: $(window).width(), windowHeight: $(window).height() }); }); }); Ember.$(window).on('scroll.tour', function(){ component.set('scrollTop', $(window).scrollTop()); }); } else { Ember.$(window).off('resize.tour'); Ember.$(window).off('scroll.tour'); } }).observes('started').on('init'), /** Deactivates the tour and sends action `endTour` @method exitTour */ exitTour: function(){ this.set('started', false); this.set('transitionStop.active', false); this.set('currentStop.active', false); this.set('previousStop', null); this.sendAction('endTour'); }, actions: { /** Exits the tour @method exitTour */ exitTour: function(){ this.exitTour(); }, /** Move forward by 1 @method advance */ advance: function(){ this.incrementProperty('currentStopStep', 1); }, /** Move back by 1 @method reverse */ reverse: function(){ this.decrementProperty('currentStopStep', 1); }, /** Go to a specific stop number in the tour @method goToStep @param number {Integer} the position of the stop */ goToStep: function(number){ this.set('currentStopStep', number); }, /** Go to a stop by id @method goToStop @param id */ goToStop: function(id){ var sortedTourStops = this.get('sortedTourStops'); var tourStop = sortedTourStops.findBy('id', id); var position = sortedTourStops.indexOf(tourStop); this.set('currentStopStep', position); } } });
'use strict'; (function () { angular.module('app', ['ngRoute']).config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) { $routeProvider.when('/dashboard', { template: '<dashboard></dashboard>' }).when('/register', { template: '<register></register>' }).when('/products', { template: '<products></products>' }).otherwise({ redirectTo: '/dashboard' }); }]); })(); 'use strict'; (function () { angular.module('app').component('dashboard', { templateUrl: 'dashboard/dashboard.html', controller: DashboardController, controllerAs: 'vm' }); DashboardController.$inject = ['LoggedinUserService']; function DashboardController(LoggedinUserService) { var vm = this; vm.user = LoggedinUserService.get(); } })(); 'use strict'; (function () { angular.module('app').component('appHeader', { templateUrl: 'header/header.html', controller: HeaderController, controllerAs: 'vm' }); HeaderController.$inject = ['$rootScope', '$location']; function HeaderController($rootScope, $location) { var vm = this; vm.menu = $location.path().slice(1); $rootScope.$on('$routeChangeSuccess', function (e, current, pre) { vm.menu = $location.path().slice(1); }); } })(); 'use strict'; (function () { angular.module('app').component('products', { templateUrl: 'products/products.html', controller: ProductsController, controllerAs: 'vm' }); ProductsController.$inject = ['LoggedinUserService', 'ProductsService']; function ProductsController(LoggedinUserService, ProductsService) { var vm = this; vm.user = {}; vm.products = {}; vm.user = LoggedinUserService.get(); ProductsService.getProducts(vm.user.access_token).then(successHandler); function successHandler(response) { var data = response.data.split('data":')[1]; vm.products = data.slice(0, data.length - 1); vm.products = JSON.parse(vm.products); } } })(); 'use strict'; (function () { angular.module('app').component('register', { templateUrl: 'register/register.html', controller: RegisterController, controllerAs: 'vm' }); RegisterController.$inject = ['$rootScope', '$location', 'RegisterService', 'LoggedinUserService']; function RegisterController($rootScope, $location, RegisterService, LoggedinUserService) { var vm = this; vm.user = {}; vm.register = register; vm.login = login; function register() { RegisterService.registerUser(vm.user).then(successHandler); vm.user = {}; } function login() { RegisterService.loginUser(vm.existingUser).then(successHandler); } function successHandler(response) { LoggedinUserService.set(response); $location.path('#!/dashboard'); } // function successfulRegistration() { // LoggedinUserService.set(vm.user); // $location.path('#!/dashboard'); // } } })(); 'use strict'; (function () { 'use strict'; angular.module('app').factory('LoggedinUserService', LoggedinUserService); LoggedinUserService.$inject = ['$http']; function LoggedinUserService($http) { var loggedUser = {}; function set(data) { loggedUser = data; } function get() { return loggedUser; } return { set: set, get: get }; } })(); // // app.factory('myService', function() { // var savedData = {} // function set(data) { // savedData = data; // } // function get() { // return savedData; // } // // return { // set: set, // get: get // } // // }); 'use strict'; (function () { 'use strict'; angular.module('app').factory('ProductsService', ProductsService); ProductsService.$inject = ['$http']; function ProductsService($http) { var svc = {}; svc.getProducts = getProducts; return svc; // ////////// function getProducts(access_token) { var auth = {}; auth.access_token = access_token; return $http.post('/api/v1/products', auth).then(successHandler, errorHandler); } function successHandler(response) { return response; } function errorHandler(error) { console.log(error); } } })(); 'use strict'; (function () { 'use strict'; angular.module('app').factory('RegisterService', RegisterService); RegisterService.$inject = ['$http']; function RegisterService($http) { var svc = {}; svc.registerUser = registerUser; svc.loginUser = loginUser; return svc; // ////////// function registerUser(user) { return $http.post('/api/v1/user/register', user).then(successHandler, errorHandler); } function loginUser(user) { return $http.post('/api/v1/user/login', user).then(successHandler, errorHandler); } function successHandler(response) { return response.data; } function errorHandler(error) { console.log(error); } } })();
/** * Add delayed event of setting velocity for an object * @param {Number} delay dekay * @param {String} objectId object's id * @param {Number} velX x velocity * @param {Number} velY y velocity */ SituationStage.prototype.addEventVelocity = function (delay, objectId, velX, velY, accelX, accelY) { this.addEvent(delay, this.setVelocity, objectId, velX, velY, accelX, accelY); } SituationStage.prototype.addEventStartTurn = function (delay, objectId, pivotObject, targetAngle, velocity, callback, callbackContext) { this.addEvent(delay, this.startObjectTurn, objectId, pivotObject, targetAngle, velocity, callback, callbackContext); } /** * Add event (function) which will be invoked after given delay. * @param {Number} delay Delay after which function will be invoked. * @param {Function} callback Function invoked after given delay. * @param {Array} callback arguments */ SituationStage.prototype.addEvent = function (delay, event) { callArgs = Array.prototype.splice.call(arguments, 2); // add event as a first argument to passed callback arguments callArgs.splice(0, 0, event); this.game.time.events.add(Phaser.Timer.SECOND * delay, this.fireEvent, this, callArgs); }; /** * Events should be invoked through this function, because there's possibility, * that situation is already finished, and event should not be invoked. */ SituationStage.prototype.fireEvent = function (event) { args = Array.prototype.splice.call(arguments[0], 1); fun = event[0]; fun.apply(this, args); }; SituationStage.prototype.setVelocity = function (objectId, velX, velY, accelX, accelY) { this.getObject(objectId).setVelocity(velX, velY, accelX, accelY); }; SituationStage.prototype.startObjectTurn = function (objectId, pivotObject, targetAngle, velocity, callback, callbackContext) { this.getObject(objectId).startObjectTurn(pivotObject, targetAngle, velocity, callback, callbackContext); };
(function () { 'use strict'; var module = angular.module('sticky', []); // Directive: sticky // module.directive('sticky', ['$window', function ($window) { return { restrict: 'A', // this directive can only be used as an attribute. link: function linkFn($scope, $elem, $attrs) { var mediaQuery, stickyClass, unstickyClass, bodyClass, elem, $body, doc, initialCSS, initialStyle, isSticking, stickyLine, stickyBottomLine, offset, anchor, confine, prevOffset, matchMedia, usePlaceholder, placeholder; $scope.initSticky = function () { isSticking = false; matchMedia = $window.matchMedia; // elements $body = angular.element(document.body); elem = $elem[0]; doc = document.documentElement; // attributes mediaQuery = $attrs.mediaQuery || false; stickyClass = $attrs.stickyClass || ''; unstickyClass = $attrs.unstickyClass || ''; bodyClass = $attrs.bodyClass || ''; usePlaceholder = $attrs.useplaceholder !== undefined; initialStyle = $elem.attr('style') || ''; offset = typeof $attrs.offset === 'string' ? parseInt($attrs.offset.replace(/px;?/, '')) : 0; anchor = typeof $attrs.anchor === 'string' ? $attrs.anchor.toLowerCase().trim() : 'top'; // Define the confine attribute - will confine sticky to it's parent confine = typeof $attrs.confine === 'string' ? $attrs.confine.toLowerCase().trim() : 'false'; confine = (confine === 'true'); // initial style initialCSS = { top: $elem.css('top'), width: $elem.css('width'), position: $elem.css('position'), marginTop: $elem.css('margin-top'), cssLeft: $elem.css('left') }; switch (anchor) { case 'top': case 'bottom': break; default: anchor = 'top'; break; } // Watcher // prevOffset = $scope.getTopOffset(elem); // Listeners // angular.element($window).on('scroll', $scope.checkIfShouldStick); angular.element($window).on('resize', $scope.$apply.bind($scope, $scope.onResize)); $scope.$on('$destroy', $scope.onDestroy); }; $scope.getScrollTop = function () { if (typeof $window.pageYOffset !== 'undefined') { //most browsers except IE before #9 return $window.pageYOffset; } else { var B = document.body; //IE 'quirks' var D = document.documentElement; //IE with doctype D = (D.clientHeight) ? D : B; return D.scrollTop; } }; $scope.getTopOffset = function (element) { if (element.getBoundingClientRect) { // Using getBoundingClientRect is vastly faster, if it's available return element.getBoundingClientRect().top; } else { var pixels = 0; if (element.offsetParent) { do { pixels += element.offsetTop; element = element.offsetParent; } while (element); } return pixels; } }; $scope.getBottomOffset = function (element) { return element.offsetTop + element.clientHeight; }; $scope.shouldStickWithLimit = function (shouldApplyWithLimit) { if (shouldApplyWithLimit === 'true') { var elementHeight = elem.offsetHeight; var windowHeight = $window.innerHeight; return (windowHeight - (elementHeight + parseInt(offset)) < 0); } else { return false; } }; $scope.onResize = function () { initialCSS.offsetWidth = elem.offsetWidth; $scope.unStickElement(); $scope.checkIfShouldStick(); if (isSticking) { var parent = $window.getComputedStyle(elem.parentElement, null), initialOffsetWidth = elem.parentElement.offsetWidth - parent.getPropertyValue('padding-right').replace('px', '') - parent.getPropertyValue('padding-left').replace('px', ''); $elem.css('width', initialOffsetWidth + 'px'); } }; $scope.onDestroy = function () { angular.element($window).off('scroll', $scope.checkIfShouldStick); angular.element($window).off('resize', $scope.onResize); if (bodyClass) { $body.removeClass(bodyClass); } if (placeholder) { placeholder.remove(); } }; // Methods // // Simple helper function to find closest value // from a set of numbers in an array $scope.getClosest = function (array, num) { var minDiff = 1000; var ans; for (var i in array) { var m = Math.abs(num - array[i]); if (m < minDiff) { minDiff = m; ans = array[i]; } } return ans; }; $scope.stickElement = function () { var rect, absoluteLeft; rect = $elem[0].getBoundingClientRect(); absoluteLeft = rect.left; initialCSS.offsetWidth = elem.offsetWidth; isSticking = true; if (bodyClass) { $body.addClass(bodyClass); } if (unstickyClass) { if ($elem.hasClass(unstickyClass)) { $elem.removeClass(unstickyClass); } } if (stickyClass) { $elem.addClass(stickyClass); } //create placeholder to avoid jump if (usePlaceholder) { placeholder = angular.element('<div>'); var elementsHeight = $elem[0].offsetHeight; placeholder.css('height', elementsHeight + 'px'); $elem.after(placeholder); } $elem .css('width', elem.offsetWidth + 'px') .css('position', 'fixed') .css(anchor, offset + 'px') .css('left', absoluteLeft + 'px') .css('margin-top', 0); if (anchor === 'bottom') { $elem.css('margin-bottom', 0); } }; $scope.checkIfShouldStick = function () { var scrollTop, shouldStick, scrollBottom, scrolledDistance; if (mediaQuery && !(matchMedia('(' + mediaQuery + ')').matches || matchMedia(mediaQuery).matches)) { // Make sure to unstick element if media query no longer matches if (isSticking) { $scope.unStickElement(); } return; } if (anchor === 'top') { scrolledDistance = $window.pageYOffset || doc.scrollTop; scrollTop = scrolledDistance - (doc.clientTop || 0); if (confine === true) { shouldStick = scrollTop >= stickyLine && scrollTop <= stickyBottomLine; } else { shouldStick = scrollTop >= stickyLine; } } else { scrollBottom = $window.pageYOffset + $window.innerHeight; shouldStick = scrollBottom <= stickyLine; } // Switch the sticky mode if the element crosses the sticky line // $attrs.stickLimit - when it's equal to true it enables the user // to turn off the sticky function when the elem height is // bigger then the viewport if (shouldStick && !$scope.shouldStickWithLimit($attrs.stickLimit) && !isSticking) { $scope.stickElement(); } else if (!shouldStick && isSticking) { // could probably do this better var from, compare, closest; compare = [stickyLine, stickyBottomLine]; closest = $scope.getClosest(compare, scrollTop); // Check to see if we are closer to the top or bottom confines // and set from to let the unstick element know the origin if (closest === stickyLine) { from = 'top'; } else if (closest === stickyBottomLine) { from = 'bottom'; } $scope.unStickElement(from, scrollTop); } }; // Passing in scrolltop and directional origin to help // with some math later $scope.unStickElement = function (fromDirection) { $elem.attr('style', initialStyle); isSticking = false; if (bodyClass) { $body.removeClass(bodyClass); } if (stickyClass) { $elem.removeClass(stickyClass); } if (unstickyClass) { $elem.addClass(unstickyClass); } if (fromDirection === 'top') { $elem .css('width', '') .css('top', initialCSS.top) .css('position', initialCSS.position) .css('left', initialCSS.cssLeft) .css('margin-top', initialCSS.marginTop); } else if (fromDirection === 'bottom' && confine === true) { // make sure we are checking to see if the element is confined to the parent $elem .css('width', '') .css('top', '') .css('bottom', 0) .css('position', 'absolute') .css('left', initialCSS.cssLeft) .css('margin-top', initialCSS.marginTop) .css('margin-bottom', initialCSS.marginBottom); } if (placeholder) { placeholder.remove(); } }; $scope.$watch(function () { // triggered on load and on digest cycle if (isSticking) { return prevOffset + $scope.getScrollTop(); } prevOffset = (anchor === 'top') ? $scope.getTopOffset(elem) : $scope.getBottomOffset(elem); return prevOffset + $scope.getScrollTop(); }, function (newVal, oldVal) { if (( newVal !== oldVal || typeof stickyLine === 'undefined' ) && newVal !== 0 && !isSticking) { stickyLine = newVal - offset; // IF the sticky is confined, we want to make sure the parent is relatively positioned, // otherwise it won't bottom out properly if (confine) { $elem.parent().css({ 'position': 'relative' }); } // Get Parent height, so we know when to bottom out for confined stickies var parent = $elem.parent()[0]; var parentHeight = parseInt(parent.offsetHeight); // and now lets ensure we adhere to the bottom margins // TODO: make this an attribute? Maybe like ignore-margin? var marginBottom = parseInt($elem.css('margin-bottom').replace(/px;?/, '')) || 0; // specify the bottom out line for the sticky to unstick stickyBottomLine = parentHeight - (elem.offsetTop + elem.offsetHeight) + offset + marginBottom; $scope.checkIfShouldStick(); } }); // Init the directive $scope.initSticky(); } }; }] ); // Shiv: matchMedia // window.matchMedia = window.matchMedia || (function () { var warning = 'angular-sticky: This browser does not support ' + 'matchMedia, therefore the minWidth option will not work on ' + 'this browser. Polyfill matchMedia to fix this issue.'; if (window.console && console.warn) { console.warn(warning); } return function () { return { matches: true }; }; }()); }());
/** * Copyright (c) 2017-present, Liu Jinyong * All rights reserved. * * https://github.com/huanxsd/MeiTuan * @flow */ //import liraries import React, { Component } from 'react'; import { View, Text, StyleSheet, ScrollView, TouchableOpacity, ListView, Image, InteractionManager } from 'react-native'; import { color, Button, NavigationItem, RefreshListView, RefreshState, Separator, SpacingView } from '../../widget' import { Heading1, Heading2, Paragraph, HeadingBig } from '../../widget/Text' import { screen, system, tool } from '../../common' import api, { recommendUrlWithId, groupPurchaseDetailWithId } from '../../api' import GroupPurchaseCell from './GroupPurchaseCell' // create a component class GroupPurchaseScene extends Component { static navigationOptions = ({ navigation }) => ({ headerTitle: '团购详情', headerStyle: { backgroundColor: 'white' }, headerRight: ( <NavigationItem icon={require('../../img/Public/icon_navigationItem_share@2x.png')} onPress={() => { }} /> ), }); state: { info: Object, dataSource: ListView.DataSource } constructor(props: Object) { super(props); let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 }) this.state = { info: {}, dataSource: ds.cloneWithRows([]), } } componentDidMount() { InteractionManager.runAfterInteractions(() => { if (this.refs.listView) { this.refs.listView.startHeaderRefreshing(); } }); } render() { return ( <View style={styles.container}> <RefreshListView ref='listView' dataSource={this.state.dataSource} renderHeader={() => this.renderHeader()} renderRow={(rowData) => <GroupPurchaseCell info={rowData} onPress={() => this.props.navigation.navigate('GroupPurchase', { info: rowData })} /> } onHeaderRefresh={() => this.requestData()} /> </View> ) } renderHeader() { let info = this.props.navigation.state.params.info return ( <View> <View> <Image style={styles.banner} source={{ uri: info.imageUrl.replace('w.h', '480.0') }} /> <View style={styles.topContainer}> <Heading1 style={{ color: color.theme }}>¥</Heading1> <HeadingBig style={{ marginBottom: -8 }}>{info.price}</HeadingBig> <Paragraph style={{ marginLeft: 10 }}>门市价:¥{(info.price * 1.1).toFixed(0)}</Paragraph> <View style={{ flex: 1 }} /> <Button title='立即抢购' style={{ color: 'white', fontSize: 18 }} containerStyle={styles.buyButton} /> </View> </View> <Separator /> <View> <View style={styles.tagContainer}> <Image style={{ width: 20, height: 20 }} source={require('../../img/Home/icon_deal_anytime_refund.png')} /> <Paragraph style={{ color: '#89B24F' }}> 随时退</Paragraph> <View style={{ flex: 1 }} /> <Paragraph>已售{1234}</Paragraph> </View> </View> <SpacingView /> <View style={styles.tipHeader}> <Heading2>看了本团购的用户还看了</Heading2> </View> </View> ) } requestData() { this.requestDetail() this.requestRecommend() } requestDetail() { //原详情接口已经被美团关掉,这里暂时从上一级列表中获取详情数据 } requestRecommend() { let info = this.props.navigation.state.params.info fetch(recommendUrlWithId(info.id)) .then((response) => response.json()) .then((json) => { console.log(JSON.stringify(json)); let dataList = json.data.deals.map((info) => { return { id: info.id, imageUrl: info.imgurl, title: info.brandname, subtitle: `[${info.range}]${info.title}`, price: info.price } }) this.setState({ dataSource: this.state.dataSource.cloneWithRows(dataList) }) setTimeout(() => { this.refs.listView.endRefreshing(RefreshState.NoMoreData) }, 500); }) .catch((error) => { this.refs.listView.endRefreshing(RefreshState.Failure) }) } } // define your styles const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'white', }, banner: { width: screen.width, height: screen.width * 0.5 }, topContainer: { padding: 10, flexDirection: 'row', alignItems: 'flex-end', }, buyButton: { backgroundColor: '#fc9e28', width: 94, height: 36, borderRadius: 7, }, tagContainer: { flexDirection: 'row', padding: 10, alignItems: 'center' }, tipHeader: { height: 35, justifyContent: 'center', borderWidth: screen.onePixel, borderColor: color.border, paddingVertical: 8, paddingLeft: 20, backgroundColor: 'white' } }); //make this component available to the app export default GroupPurchaseScene;
module.exports={A:{A:{"2":"K C G E B WB","132":"A"},B:{"1":"D u Y I M H"},C:{"2":"UB z SB","4":"0 1 2 3 4 5 6 7 K C G E B A D u Y I M H N O P Q R S T U V W X w Z a b c d e f L h i j k l m n o p q r s t y v","8":"F J RB"},D:{"2":"F J K","4":"0 1 2 3 4 5 6 7 C G E B A D u Y I M H N O P Q R S T U V W X w Z a b c d e f L h i j k l m n o p q r s t y v GB g DB VB EB"},E:{"2":"F J K C G E B A FB AB HB IB JB KB LB MB"},F:{"2":"8 9 E A D NB OB PB QB TB x","4":"I M H N O P Q R S T U V W X w Z a b c d e f L h i j k l m n o p q r s t"},G:{"2":"AB CB","4":"G A BB XB YB ZB aB bB cB dB eB"},H:{"2":"fB"},I:{"2":"gB hB iB","4":"z F g jB BB kB lB"},J:{"2":"C","4":"B"},K:{"1":"D x","2":"8 9 B A","4":"L"},L:{"4":"g"},M:{"4":"v"},N:{"1":"A","2":"B"},O:{"4":"mB"},P:{"4":"F J"},Q:{"4":"nB"},R:{"4":"oB"}},B:4,C:"DeviceOrientation & DeviceMotion events"};
// ==UserScript== // @name Slack Full Theme plugin // @namespace http://mrkannah.com/ // @version 1.0.2 // @description Applies the side bar colors for slack to the entire application // @author Fadee Kannah // @match https://*.slack.com/* // @grant GM_setValue // @grant GM_getValue // @run-at document-end // ==/UserScript== $(document).ready(function(){ var checkInterval = setInterval(function(){ if(Ready()){ var colors = GM_getValue('ST_Colors').toString().split(','); clearInterval(checkInterval); if(colors){ setUp(colors); } else{ setTimeout(function(){ colors = getColors(); setTimeout(setUp(colors),300); },100); } } },200); }); function setUp(colors){ applyColors(colors); addListner(); } function Ready(){ return parseInt($('#loading_welcome').css('opacity')) ? 0 : 1; } function getColors(){ $('#team_menu')[0].click(); $('#member_prefs_item > a')[0].click(); var colors = $('#sidebar_theme_custom').val().toString().split(','); $('.dialog_go ')[0].click(); return colors; /* Array Index 0 Col BG 1 Menu BG 2 Active Item 3 Active Text 4 Hover Item 5 Text Color 6 Active precesne 7 mention Badge */ } function applyColors(colors){ GM_setValue('ST_Colors',colors); console.log(colors); var head = document.getElementsByTagName('head')[0]; var style = document.createElement('style'); style.type = 'text/css'; style.id = 'fullThemePlugin'; //header & footer styles style.innerHTML = '#header{ background:'+colors[1]+'}' + '#end_div{background:'+colors[1]+'}' + '#channel_members_toggle{ background:'+colors[1]+'!important}'+ '#footer{background:'+colors[0]+'}'+ '#primary_file_button:hover {background:'+colors[4]+';color: '+colors[5]+';border-color:'+colors[4]+'}'; //divier styles style.innerHTML +='.day_divider{background:'+colors[0]+' !important}' + '.day_divider_label{background:'+colors[0] +'!important;color:'+colors[3]+'}'; //messages styles style.innerHTML += '.msgs_holder{background:'+colors[0]+'}'+ '.mention{color:'+colors[1]+';background:'+colors[7]+'!important}' + '.light_theme .message_sender {color:'+colors[3]+' !important}' + '.message_content{color:'+colors[5]+'}'; //Global Styles style.innerHTML += 'a{color:'+colors[2]+'!important}'+ '.msg_inline_file_preview_title{color:'+colors[2]+'!important}'+ 'body{background:'+colors[0]+'}'; //scroll bar styles style.innerHTML += '.monkey_scroll_handle_inner{background:'+colors[2]+'!important;border:0!important}' + '.monkey_scroll_handle{position:relative;left:-1px!important;width:10px!important}'; head.appendChild(style); return $(style); } function addListner(){ $('#team_menu').on('click',function(){ $('#member_prefs_item > a').on('click',function(){ setTimeout(function(){ $('.color_hex').on('input',function(){ changeColors(); }); $('input[name="sidebar_theme_rd"]').on('change',function(){ changeColors(); }); $('#sidebar_theme_custom').on('input change',function() { changeColors(); }); $('.color_swatch').on('click', function(){ setTimeout(function(){ changeColors(); },700); }); },500); }); }); } function changeColors(){ var colors = $('#sidebar_theme_custom').val().split(','); $('#fullThemePlugin').remove(); applyColors(colors); }
search_result['1033']=["topic_000000000000025D.html","SystemManagementController.SetStatusOrganizationSite Method",""];
import {StickyStatesPlugin} from '@uirouter/sticky-states'; import {DSRPlugin} from '@uirouter/dsr'; import {visualizer} from "@uirouter/visualizer"; import {app} from './app.states'; /* @ngInject */ export function uiRouterPluginsConfig($uiRouterProvider) { $uiRouterProvider.plugin(StickyStatesPlugin); $uiRouterProvider.plugin(DSRPlugin); if (process.env.NODE_ENV === 'development') { visualizer($uiRouterProvider); } } /* @ngInject */ export function uiRouterConfig($uiRouterProvider) { // If the user enters a URL that doesn't match any known URL (state), send them to '/hello' const $urlService = $uiRouterProvider.urlService; $urlService.rules.otherwise({state: 'hello'}); const $stateRegistry = $uiRouterProvider.stateRegistry; $stateRegistry.register(app); }
'use strict'; app.factory("DataFactory", ($http, $q) => { const getAllPlayers = function () { return $q((resolve,reject) => { $http({ method: 'GET', url: 'https://nss-pingpong-api20161212012918.azurewebsites.net/api/Players/' }).then(function successCallback(data) { console.log(data) resolve(data) }, function errorCallback(error) { console.log(error) }); }) } const getSinglePlayer = function (id) { return $q((resolve,reject) => { $http({ method: 'GET', url: `https://nss-pingpong-api20161212012918.azurewebsites.net/api/Players/${id}` }).then(function successCallback(data) { console.log(data) resolve(data) }, function errorCallback(error) { console.log(error) }); }) } const getAverageStats = function () { return $q((resolve,reject) => { $http({ method: 'GET', url: `https://nss-pingpong-api20161212012918.azurewebsites.net/api/Reports/GetAverageStats` }).then(function successCallback(data) { console.log(data) resolve(data) }, function errorCallback(error) { console.log(error) }); }) } const postSinglesGame = function (game) { return $q((resolve,reject) => { $http.post("https://nss-pingpong-api20161212012918.azurewebsites.net/api/Reports/TwoPlayerGame", game) .then(function successCallback(data) { console.log(data) resolve(data) }, function errorCallback(error) { console.log(error) }); }) } const postDoublesGame = function (game) { return $q((resolve,reject) => { $http.post("https://nss-pingpong-api20161212012918.azurewebsites.net/api/Reports/FourPlayerGame", game) .then(function successCallback(data) { console.log(data) resolve(data) }, function errorCallback(error) { console.log(error) }); }) } const postPlayer = function (player) { return $q((resolve,reject) => { $http.post("https://nss-pingpong-api20161212012918.azurewebsites.net/api/Players", player) .then(function successCallback(data) { console.log(data) resolve(data) }, function errorCallback(error ) { console.log(error) }); }) } return {getAllPlayers, getSinglePlayer, getAverageStats, postSinglesGame, postDoublesGame, postPlayer} })
/** * Created by Obsidean on 06/11/2015. */ var mod = angular.module('Vp.YearPart', []); mod.directive('vpYearPart', function(){ return { restrict: 'E', scope:{YearInfo:'=yearinfo'}, templateUrl: 'app/Partials/Directives/YearPart.html', controller:function($scope,$attrs){ } }; });
'use strict'; var constants = require('../lifx').constants; var packets = require('./packets'); var utils = require('../lifx').utils; var _ = require('lodash'); /* Package headers 36 bit in total consisting of size - 2 bit frameDescription - 2 bit source - 4 bit target - 6 bit 00 00 - site - 6 bit frameAddressDescription - 1 bit sequence - 1 bit time - 8 bit type - 2 bit 00 00 */ var Packet = {}; /** * Mapping for types * @type {Array} */ Packet.typeList = [ {id: 2, name: 'getService'}, {id: 3, name: 'stateService'}, {id: 12, name: 'getHostInfo'}, {id: 13, name: 'stateHostInfo'}, {id: 14, name: 'getHostFirmware'}, {id: 15, name: 'stateHostFirmware'}, {id: 16, name: 'getWifiInfo'}, {id: 17, name: 'stateWifiInfo'}, {id: 18, name: 'getWifiFirmware'}, {id: 19, name: 'stateWifiFirmware'}, // {id: 20, name: 'getPower'}, // These are for device level // {id: 21, name: 'setPower'}, // and do not support duration value // {id: 22, name: 'statePower'}, // since that we don't use them {id: 23, name: 'getLabel'}, {id: 24, name: 'setLabel'}, {id: 25, name: 'stateLabel'}, {id: 32, name: 'getVersion'}, {id: 33, name: 'stateVersion'}, {id: 45, name: 'acknowledgement'}, {id: 48, name: 'getLocation'}, {id: 50, name: 'stateLocation'}, {id: 51, name: 'getGroup'}, {id: 53, name: 'stateGroup'}, {id: 54, name: 'getOwner'}, {id: 56, name: 'stateOwner'}, {id: 58, name: 'echoRequest'}, {id: 59, name: 'echoResponse'}, {id: 69, name: 'getTemperature'}, {id: 70, name: 'stateTemperature'}, {id: 101, name: 'getLight'}, {id: 102, name: 'setColor'}, {id: 103, name: 'setWaveform'}, {id: 107, name: 'stateLight'}, {id: 111, name: 'stateTemperature'}, // {id: 113, name: 'setSimpleEvent'}, // {id: 114, name: 'getSimpleEvent'}, // {id: 115, name: 'stateSimpleEvent'}, {id: 116, name: 'getPower'}, {id: 117, name: 'setPower'}, {id: 118, name: 'statePower'}, // {id: 119, name: 'setWaveformOptional'}, {id: 120, name: 'getInfrared'}, {id: 121, name: 'stateInfrared'}, {id: 122, name: 'setInfrared'}, {id: 401, name: 'getAmbientLight'}, {id: 402, name: 'stateAmbientLight'} // {id: 403, name: 'getDimmerVoltage'}, // {id: 404, name: 'stateDimmerVoltage'} ]; /** * Parses a lifx packet header * @param {Buffer} buf Buffer containg lifx packet including header * @return {Object} parsed packet header */ Packet.headerToObject = function(buf) { var obj = {}; var offset = 0; // Frame obj.size = buf.readUInt16LE(offset); offset += 2; var frameDescription = buf.readUInt16LE(offset); obj.addressable = (frameDescription & constants.ADDRESSABLE_BIT) !== 0; obj.tagged = (frameDescription & constants.TAGGED_BIT) !== 0; obj.origin = ((frameDescription & constants.ORIGIN_BITS) >> 14) !== 0; obj.protocolVersion = (frameDescription & constants.PROTOCOL_VERSION_BITS); offset += 2; obj.source = buf.toString('hex', offset, offset + 4); offset += 4; // Frame address obj.target = buf.toString('hex', offset, offset + 6); offset += 6; obj.reserved1 = buf.slice(offset, offset + 2); offset += 2; obj.site = buf.toString('utf8', offset, offset + 6); obj.site = obj.site.replace(/\0/g, ''); offset += 6; var frameAddressDescription = buf.readUInt8(offset); obj.ackRequired = (frameAddressDescription & constants.ACK_REQUIRED_BIT) !== 0; obj.resRequired = (frameAddressDescription & constants.RESPONSE_REQUIRED_BIT) !== 0; offset += 1; obj.sequence = buf.readUInt8(offset); offset += 1; // Protocol header obj.time = utils.readUInt64LE(buf, offset); offset += 8; obj.type = buf.readUInt16LE(offset); offset += 2; obj.reserved2 = buf.slice(offset, offset + 2); offset += 2; return obj; }; /** * Parses a lifx packet * @param {Buffer} buf Buffer with lifx packet * @return {Object} parsed packet */ Packet.toObject = function(buf) { var obj = {}; // Try to read header of packet try { obj = this.headerToObject(buf); } catch (err) { // If this fails return with error return err; } if (obj.type !== undefined) { var typeName = _.result(_.find(this.typeList, {id: obj.type}), 'name'); if (packets[typeName] !== undefined) { if (typeof packets[typeName].toObject === 'function') { var specificObj = packets[typeName].toObject(buf.slice(constants.PACKET_HEADER_SIZE)); obj = _.extend(obj, specificObj); } } } return obj; }; /** * Creates a lifx packet header from a given object * @param {Object} obj Object containg header configuration for packet * @return {Buffer} packet header buffer */ Packet.headerToBuffer = function(obj) { var buf = new Buffer(36); buf.fill(0); var offset = 0; // Frame buf.writeUInt16LE(obj.size, offset); offset += 2; if (obj.protocolVersion === undefined) { obj.protocolVersion = constants.PROTOCOL_VERSION_CURRENT; } var frameDescription = obj.protocolVersion; if (obj.addressable !== undefined && obj.addressable === true) { frameDescription |= constants.ADDRESSABLE_BIT; } else if (obj.source !== undefined && obj.source.length > 0 && obj.source !== '00000000') { frameDescription |= constants.ADDRESSABLE_BIT; } if (obj.tagged !== undefined && obj.tagged === true) { frameDescription |= constants.TAGGED_BIT; } if (obj.origin !== undefined && obj.origin === true) { // 0 or 1 to the 14 bit frameDescription |= (1 << 14); } buf.writeUInt16LE(frameDescription, offset); offset += 2; if (obj.source !== undefined && obj.source.length > 0) { if (obj.source.length === 8) { buf.write(obj.source, offset, 4, 'hex'); } else { throw new RangeError('LIFX source must be given in 8 characters'); } } offset += 4; // Frame address if (obj.target !== undefined && obj.target !== null) { buf.write(obj.target, offset, 6, 'hex'); } offset += 6; // reserved1 offset += 2; if (obj.site !== undefined && obj.site !== null) { buf.write(obj.site, offset, 6, 'utf8'); } offset += 6; var frameAddressDescription = 0; if (obj.ackRequired !== undefined && obj.ackRequired === true) { frameAddressDescription |= constants.ACK_REQUIRED_BIT; } if (obj.resRequired !== undefined && obj.resRequired === true) { frameAddressDescription |= constants.RESPONSE_REQUIRED_BIT; } buf.writeUInt8(frameAddressDescription, offset); offset += 1; if (typeof obj.sequence === 'number') { buf.writeUInt8(obj.sequence, offset); } offset += 1; // Protocol header if (obj.time !== undefined) { utils.writeUInt64LE(buf, offset, obj.time); } offset += 8; if (typeof obj.type === 'number') { obj.type = _.result(_.find(this.typeList, {id: obj.type}), 'id'); } else if (typeof obj.type === 'string' || obj.type instanceof String) { obj.type = _.result(_.find(this.typeList, {name: obj.type}), 'id'); } if (obj.type === undefined) { throw new Error('Unknown lifx packet of type: ' + obj.type); } buf.writeUInt16LE(obj.type, offset); offset += 2; // reserved2 offset += 2; return buf; }; /** * Creates a packet from a configuration object * @param {Object} obj Object with configuration for packet * @return {Buffer|Boolean} the packet or false in case of error */ Packet.toBuffer = function(obj) { if (obj.type !== undefined) { // Map id to string if needed if (typeof obj.type === 'number') { obj.type = _.result(_.find(this.typeList, {id: obj.type}), 'name'); } else if (typeof obj.type === 'string' || obj.type instanceof String) { obj.type = _.result(_.find(this.typeList, {name: obj.type}), 'name'); } if (obj.type !== undefined) { if (typeof packets[obj.type].toBuffer === 'function') { var packetTypeData = packets[obj.type].toBuffer(obj); return Buffer.concat([ this.headerToBuffer(obj), packetTypeData ]); } return this.headerToBuffer(obj); } } return false; }; /** * Creates a new packet by the given type * Note: This does not validate the given params * @param {String|Number} type the type of packet to create as number or string * @param {Object} params further settings to pass * @param {String} [source] the source of the packet, length 8 * @param {String} [target] the target of the packet, length 12 * @return {Object} The prepared packet object including header */ Packet.create = function(type, params, source, target) { var obj = {}; if (type !== undefined) { // Check if type is valid if (typeof type === 'string' || type instanceof String) { obj.type = _.result(_.find(this.typeList, {name: type}), 'id'); } else if (typeof type === 'number') { var typeMatch = _.find(this.typeList, {id: type}); obj.type = _.result(typeMatch, 'id'); type = _.result(typeMatch, 'name'); } if (obj.type === undefined) { return false; } } else { return false; } obj.size = constants.PACKET_HEADER_SIZE + packets[type].size; if (source !== undefined) { obj.source = source; } if (target !== undefined) { obj.target = target; } if (packets[type].tagged !== undefined) { obj.tagged = packets[type].tagged; } return _.assign(obj, params); }; module.exports = Packet;
typeof window !== "undefined" && (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["Hls"] = factory(); else root["Hls"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./src/hls.ts"); /******/ }) /************************************************************************/ /******/ ({ /***/ "./node_modules/eventemitter3/index.js": /*!*********************************************!*\ !*** ./node_modules/eventemitter3/index.js ***! \*********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var has = Object.prototype.hasOwnProperty , prefix = '~'; /** * Constructor to create a storage for our `EE` objects. * An `Events` instance is a plain object whose properties are event names. * * @constructor * @private */ function Events() {} // // We try to not inherit from `Object.prototype`. In some engines creating an // instance in this way is faster than calling `Object.create(null)` directly. // If `Object.create(null)` is not supported we prefix the event names with a // character to make sure that the built-in object properties are not // overridden or used as an attack vector. // if (Object.create) { Events.prototype = Object.create(null); // // This hack is needed because the `__proto__` property is still inherited in // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. // if (!new Events().__proto__) prefix = false; } /** * Representation of a single event listener. * * @param {Function} fn The listener function. * @param {*} context The context to invoke the listener with. * @param {Boolean} [once=false] Specify if the listener is a one-time listener. * @constructor * @private */ function EE(fn, context, once) { this.fn = fn; this.context = context; this.once = once || false; } /** * Add a listener for a given event. * * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} context The context to invoke the listener with. * @param {Boolean} once Specify if the listener is a one-time listener. * @returns {EventEmitter} * @private */ function addListener(emitter, event, fn, context, once) { if (typeof fn !== 'function') { throw new TypeError('The listener must be a function'); } var listener = new EE(fn, context || emitter, once) , evt = prefix ? prefix + event : event; if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); else emitter._events[evt] = [emitter._events[evt], listener]; return emitter; } /** * Clear event by name. * * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. * @param {(String|Symbol)} evt The Event name. * @private */ function clearEvent(emitter, evt) { if (--emitter._eventsCount === 0) emitter._events = new Events(); else delete emitter._events[evt]; } /** * Minimal `EventEmitter` interface that is molded against the Node.js * `EventEmitter` interface. * * @constructor * @public */ function EventEmitter() { this._events = new Events(); this._eventsCount = 0; } /** * Return an array listing the events for which the emitter has registered * listeners. * * @returns {Array} * @public */ EventEmitter.prototype.eventNames = function eventNames() { var names = [] , events , name; if (this._eventsCount === 0) return names; for (name in (events = this._events)) { if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); } if (Object.getOwnPropertySymbols) { return names.concat(Object.getOwnPropertySymbols(events)); } return names; }; /** * Return the listeners registered for a given event. * * @param {(String|Symbol)} event The event name. * @returns {Array} The registered listeners. * @public */ EventEmitter.prototype.listeners = function listeners(event) { var evt = prefix ? prefix + event : event , handlers = this._events[evt]; if (!handlers) return []; if (handlers.fn) return [handlers.fn]; for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { ee[i] = handlers[i].fn; } return ee; }; /** * Return the number of listeners listening to a given event. * * @param {(String|Symbol)} event The event name. * @returns {Number} The number of listeners. * @public */ EventEmitter.prototype.listenerCount = function listenerCount(event) { var evt = prefix ? prefix + event : event , listeners = this._events[evt]; if (!listeners) return 0; if (listeners.fn) return 1; return listeners.length; }; /** * Calls each of the listeners registered for a given event. * * @param {(String|Symbol)} event The event name. * @returns {Boolean} `true` if the event had listeners, else `false`. * @public */ EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return false; var listeners = this._events[evt] , len = arguments.length , args , i; if (listeners.fn) { if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); switch (len) { case 1: return listeners.fn.call(listeners.context), true; case 2: return listeners.fn.call(listeners.context, a1), true; case 3: return listeners.fn.call(listeners.context, a1, a2), true; case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; } for (i = 1, args = new Array(len -1); i < len; i++) { args[i - 1] = arguments[i]; } listeners.fn.apply(listeners.context, args); } else { var length = listeners.length , j; for (i = 0; i < length; i++) { if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); switch (len) { case 1: listeners[i].fn.call(listeners[i].context); break; case 2: listeners[i].fn.call(listeners[i].context, a1); break; case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; default: if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { args[j - 1] = arguments[j]; } listeners[i].fn.apply(listeners[i].context, args); } } } return true; }; /** * Add a listener for a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.on = function on(event, fn, context) { return addListener(this, event, fn, context, false); }; /** * Add a one-time listener for a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.once = function once(event, fn, context) { return addListener(this, event, fn, context, true); }; /** * Remove the listeners of a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn Only remove the listeners that match this function. * @param {*} context Only remove the listeners that have this context. * @param {Boolean} once Only remove one-time listeners. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return this; if (!fn) { clearEvent(this, evt); return this; } var listeners = this._events[evt]; if (listeners.fn) { if ( listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context) ) { clearEvent(this, evt); } } else { for (var i = 0, events = [], length = listeners.length; i < length; i++) { if ( listeners[i].fn !== fn || (once && !listeners[i].once) || (context && listeners[i].context !== context) ) { events.push(listeners[i]); } } // // Reset the array, or remove it completely if we have no more listeners. // if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; else clearEvent(this, evt); } return this; }; /** * Remove all listeners, or those of the specified event. * * @param {(String|Symbol)} [event] The event name. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { var evt; if (event) { evt = prefix ? prefix + event : event; if (this._events[evt]) clearEvent(this, evt); } else { this._events = new Events(); this._eventsCount = 0; } return this; }; // // Alias methods names because people roll like that. // EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.addListener = EventEmitter.prototype.on; // // Expose the prefix. // EventEmitter.prefixed = prefix; // // Allow `EventEmitter` to be imported as module namespace. // EventEmitter.EventEmitter = EventEmitter; // // Expose the module. // if (true) { module.exports = EventEmitter; } /***/ }), /***/ "./node_modules/url-toolkit/src/url-toolkit.js": /*!*****************************************************!*\ !*** ./node_modules/url-toolkit/src/url-toolkit.js ***! \*****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // see https://tools.ietf.org/html/rfc1808 (function (root) { var URL_REGEX = /^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#[^]*)?$/; var FIRST_SEGMENT_REGEX = /^([^\/?#]*)([^]*)$/; var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g; var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g; var URLToolkit = { // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or // // E.g // With opts.alwaysNormalize = false (default, spec compliant) // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g // With opts.alwaysNormalize = true (not spec compliant) // http://a.com/b/cd + /e/f/../g => http://a.com/e/g buildAbsoluteURL: function (baseURL, relativeURL, opts) { opts = opts || {}; // remove any remaining space and CRLF baseURL = baseURL.trim(); relativeURL = relativeURL.trim(); if (!relativeURL) { // 2a) If the embedded URL is entirely empty, it inherits the // entire base URL (i.e., is set equal to the base URL) // and we are done. if (!opts.alwaysNormalize) { return baseURL; } var basePartsForNormalise = URLToolkit.parseURL(baseURL); if (!basePartsForNormalise) { throw new Error('Error trying to parse base URL.'); } basePartsForNormalise.path = URLToolkit.normalizePath( basePartsForNormalise.path ); return URLToolkit.buildURLFromParts(basePartsForNormalise); } var relativeParts = URLToolkit.parseURL(relativeURL); if (!relativeParts) { throw new Error('Error trying to parse relative URL.'); } if (relativeParts.scheme) { // 2b) If the embedded URL starts with a scheme name, it is // interpreted as an absolute URL and we are done. if (!opts.alwaysNormalize) { return relativeURL; } relativeParts.path = URLToolkit.normalizePath(relativeParts.path); return URLToolkit.buildURLFromParts(relativeParts); } var baseParts = URLToolkit.parseURL(baseURL); if (!baseParts) { throw new Error('Error trying to parse base URL.'); } if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') { // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a' var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path); baseParts.netLoc = pathParts[1]; baseParts.path = pathParts[2]; } if (baseParts.netLoc && !baseParts.path) { baseParts.path = '/'; } var builtParts = { // 2c) Otherwise, the embedded URL inherits the scheme of // the base URL. scheme: baseParts.scheme, netLoc: relativeParts.netLoc, path: null, params: relativeParts.params, query: relativeParts.query, fragment: relativeParts.fragment, }; if (!relativeParts.netLoc) { // 3) If the embedded URL's <net_loc> is non-empty, we skip to // Step 7. Otherwise, the embedded URL inherits the <net_loc> // (if any) of the base URL. builtParts.netLoc = baseParts.netLoc; // 4) If the embedded URL path is preceded by a slash "/", the // path is not relative and we skip to Step 7. if (relativeParts.path[0] !== '/') { if (!relativeParts.path) { // 5) If the embedded URL path is empty (and not preceded by a // slash), then the embedded URL inherits the base URL path builtParts.path = baseParts.path; // 5a) if the embedded URL's <params> is non-empty, we skip to // step 7; otherwise, it inherits the <params> of the base // URL (if any) and if (!relativeParts.params) { builtParts.params = baseParts.params; // 5b) if the embedded URL's <query> is non-empty, we skip to // step 7; otherwise, it inherits the <query> of the base // URL (if any) and we skip to step 7. if (!relativeParts.query) { builtParts.query = baseParts.query; } } } else { // 6) The last segment of the base URL's path (anything // following the rightmost slash "/", or the entire path if no // slash is present) is removed and the embedded URL's path is // appended in its place. var baseURLPath = baseParts.path; var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path; builtParts.path = URLToolkit.normalizePath(newPath); } } } if (builtParts.path === null) { builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path; } return URLToolkit.buildURLFromParts(builtParts); }, parseURL: function (url) { var parts = URL_REGEX.exec(url); if (!parts) { return null; } return { scheme: parts[1] || '', netLoc: parts[2] || '', path: parts[3] || '', params: parts[4] || '', query: parts[5] || '', fragment: parts[6] || '', }; }, normalizePath: function (path) { // The following operations are // then applied, in order, to the new path: // 6a) All occurrences of "./", where "." is a complete path // segment, are removed. // 6b) If the path ends with "." as a complete path segment, // that "." is removed. path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, ''); // 6c) All occurrences of "<segment>/../", where <segment> is a // complete path segment not equal to "..", are removed. // Removal of these path segments is performed iteratively, // removing the leftmost matching pattern on each iteration, // until no matching pattern remains. // 6d) If the path ends with "<segment>/..", where <segment> is a // complete path segment not equal to "..", that // "<segment>/.." is removed. while ( path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length ) {} return path.split('').reverse().join(''); }, buildURLFromParts: function (parts) { return ( parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment ); }, }; if (true) module.exports = URLToolkit; else {} })(this); /***/ }), /***/ "./node_modules/webworkify-webpack/index.js": /*!**************************************************!*\ !*** ./node_modules/webworkify-webpack/index.js ***! \**************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { function webpackBootstrapFunc (modules) { /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.l = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/"; /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; var f = __webpack_require__(__webpack_require__.s = ENTRY_MODULE) return f.default || f // try to call default if defined to also support babel esmodule exports } var moduleNameReqExp = '[\\.|\\-|\\+|\\w|\/|@]+' var dependencyRegExp = '\\(\\s*(\/\\*.*?\\*\/)?\\s*.*?(' + moduleNameReqExp + ').*?\\)' // additional chars when output.pathinfo is true // http://stackoverflow.com/a/2593661/130442 function quoteRegExp (str) { return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&') } function isNumeric(n) { return !isNaN(1 * n); // 1 * n converts integers, integers as string ("123"), 1e3 and "1e3" to integers and strings to NaN } function getModuleDependencies (sources, module, queueName) { var retval = {} retval[queueName] = [] var fnString = module.toString() var wrapperSignature = fnString.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/) if (!wrapperSignature) return retval var webpackRequireName = wrapperSignature[1] // main bundle deps var re = new RegExp('(\\\\n|\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g') var match while ((match = re.exec(fnString))) { if (match[3] === 'dll-reference') continue retval[queueName].push(match[3]) } // dll deps re = new RegExp('\\(' + quoteRegExp(webpackRequireName) + '\\("(dll-reference\\s(' + moduleNameReqExp + '))"\\)\\)' + dependencyRegExp, 'g') while ((match = re.exec(fnString))) { if (!sources[match[2]]) { retval[queueName].push(match[1]) sources[match[2]] = __webpack_require__(match[1]).m } retval[match[2]] = retval[match[2]] || [] retval[match[2]].push(match[4]) } // convert 1e3 back to 1000 - this can be important after uglify-js converted 1000 to 1e3 var keys = Object.keys(retval); for (var i = 0; i < keys.length; i++) { for (var j = 0; j < retval[keys[i]].length; j++) { if (isNumeric(retval[keys[i]][j])) { retval[keys[i]][j] = 1 * retval[keys[i]][j]; } } } return retval } function hasValuesInQueues (queues) { var keys = Object.keys(queues) return keys.reduce(function (hasValues, key) { return hasValues || queues[key].length > 0 }, false) } function getRequiredModules (sources, moduleId) { var modulesQueue = { main: [moduleId] } var requiredModules = { main: [] } var seenModules = { main: {} } while (hasValuesInQueues(modulesQueue)) { var queues = Object.keys(modulesQueue) for (var i = 0; i < queues.length; i++) { var queueName = queues[i] var queue = modulesQueue[queueName] var moduleToCheck = queue.pop() seenModules[queueName] = seenModules[queueName] || {} if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue seenModules[queueName][moduleToCheck] = true requiredModules[queueName] = requiredModules[queueName] || [] requiredModules[queueName].push(moduleToCheck) var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName) var newModulesKeys = Object.keys(newModules) for (var j = 0; j < newModulesKeys.length; j++) { modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || [] modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]]) } } } return requiredModules } module.exports = function (moduleId, options) { options = options || {} var sources = { main: __webpack_require__.m } var requiredModules = options.all ? { main: Object.keys(sources.main) } : getRequiredModules(sources, moduleId) var src = '' Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) { var entryModule = 0 while (requiredModules[module][entryModule]) { entryModule++ } requiredModules[module].push(entryModule) sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })' src = src + 'var ' + module + ' = (' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(entryModule)) + ')({' + requiredModules[module].map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[module][id].toString() }).join(',') + '});\n' }) src = src + 'new ((' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.main.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources.main[id].toString() }).join(',') + '}))(self);' var blob = new window.Blob([src], { type: 'text/javascript' }) if (options.bare) { return blob } var URL = window.URL || window.webkitURL || window.mozURL || window.msURL var workerUrl = URL.createObjectURL(blob) var worker = new window.Worker(workerUrl) worker.objectURL = workerUrl return worker } /***/ }), /***/ "./src/config.ts": /*!***********************!*\ !*** ./src/config.ts ***! \***********************/ /*! exports provided: hlsDefaultConfig, mergeConfig, enableStreamingMode */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hlsDefaultConfig", function() { return hlsDefaultConfig; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeConfig", function() { return mergeConfig; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableStreamingMode", function() { return enableStreamingMode; }); /* harmony import */ var _controller_abr_controller__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./controller/abr-controller */ "./src/controller/abr-controller.ts"); /* harmony import */ var _controller_audio_stream_controller__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./controller/audio-stream-controller */ "./src/controller/audio-stream-controller.ts"); /* harmony import */ var _controller_audio_track_controller__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./controller/audio-track-controller */ "./src/controller/audio-track-controller.ts"); /* harmony import */ var _controller_subtitle_stream_controller__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./controller/subtitle-stream-controller */ "./src/controller/subtitle-stream-controller.ts"); /* harmony import */ var _controller_subtitle_track_controller__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./controller/subtitle-track-controller */ "./src/controller/subtitle-track-controller.ts"); /* harmony import */ var _controller_buffer_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./controller/buffer-controller */ "./src/controller/buffer-controller.ts"); /* harmony import */ var _controller_timeline_controller__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./controller/timeline-controller */ "./src/controller/timeline-controller.ts"); /* harmony import */ var _controller_cap_level_controller__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./controller/cap-level-controller */ "./src/controller/cap-level-controller.ts"); /* harmony import */ var _controller_fps_controller__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./controller/fps-controller */ "./src/controller/fps-controller.ts"); /* harmony import */ var _controller_eme_controller__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./controller/eme-controller */ "./src/controller/eme-controller.ts"); /* harmony import */ var _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./utils/xhr-loader */ "./src/utils/xhr-loader.ts"); /* harmony import */ var _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./utils/fetch-loader */ "./src/utils/fetch-loader.ts"); /* harmony import */ var _utils_cues__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./utils/cues */ "./src/utils/cues.ts"); /* harmony import */ var _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./utils/mediakeys-helper */ "./src/utils/mediakeys-helper.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./utils/logger */ "./src/utils/logger.ts"); function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } // If possible, keep hlsDefaultConfig shallow // It is cloned whenever a new Hls instance is created, by keeping the config // shallow the properties are cloned, and we don't end up manipulating the default var hlsDefaultConfig = _objectSpread(_objectSpread({ autoStartLoad: true, // used by stream-controller startPosition: -1, // used by stream-controller defaultAudioCodec: undefined, // used by stream-controller debug: false, // used by logger capLevelOnFPSDrop: false, // used by fps-controller capLevelToPlayerSize: false, // used by cap-level-controller initialLiveManifestSize: 1, // used by stream-controller maxBufferLength: 30, // used by stream-controller backBufferLength: Infinity, // used by buffer-controller maxBufferSize: 60 * 1000 * 1000, // used by stream-controller maxBufferHole: 0.1, // used by stream-controller highBufferWatchdogPeriod: 2, // used by stream-controller nudgeOffset: 0.1, // used by stream-controller nudgeMaxRetry: 3, // used by stream-controller maxFragLookUpTolerance: 0.25, // used by stream-controller liveSyncDurationCount: 3, // used by latency-controller liveMaxLatencyDurationCount: Infinity, // used by latency-controller liveSyncDuration: undefined, // used by latency-controller liveMaxLatencyDuration: undefined, // used by latency-controller maxLiveSyncPlaybackRate: 1, // used by latency-controller liveDurationInfinity: false, // used by buffer-controller liveBackBufferLength: null, // used by buffer-controller maxMaxBufferLength: 600, // used by stream-controller enableWorker: true, // used by demuxer enableSoftwareAES: true, // used by decrypter manifestLoadingTimeOut: 10000, // used by playlist-loader manifestLoadingMaxRetry: 1, // used by playlist-loader manifestLoadingRetryDelay: 1000, // used by playlist-loader manifestLoadingMaxRetryTimeout: 64000, // used by playlist-loader startLevel: undefined, // used by level-controller levelLoadingTimeOut: 10000, // used by playlist-loader levelLoadingMaxRetry: 4, // used by playlist-loader levelLoadingRetryDelay: 1000, // used by playlist-loader levelLoadingMaxRetryTimeout: 64000, // used by playlist-loader fragLoadingTimeOut: 20000, // used by fragment-loader fragLoadingMaxRetry: 6, // used by fragment-loader fragLoadingRetryDelay: 1000, // used by fragment-loader fragLoadingMaxRetryTimeout: 64000, // used by fragment-loader startFragPrefetch: false, // used by stream-controller fpsDroppedMonitoringPeriod: 5000, // used by fps-controller fpsDroppedMonitoringThreshold: 0.2, // used by fps-controller appendErrorMaxRetry: 3, // used by buffer-controller loader: _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_10__["default"], // loader: FetchLoader, fLoader: undefined, // used by fragment-loader pLoader: undefined, // used by playlist-loader xhrSetup: undefined, // used by xhr-loader licenseXhrSetup: undefined, // used by eme-controller licenseResponseCallback: undefined, // used by eme-controller abrController: _controller_abr_controller__WEBPACK_IMPORTED_MODULE_0__["default"], bufferController: _controller_buffer_controller__WEBPACK_IMPORTED_MODULE_5__["default"], capLevelController: _controller_cap_level_controller__WEBPACK_IMPORTED_MODULE_7__["default"], fpsController: _controller_fps_controller__WEBPACK_IMPORTED_MODULE_8__["default"], stretchShortVideoTrack: false, // used by mp4-remuxer maxAudioFramesDrift: 1, // used by mp4-remuxer forceKeyFrameOnDiscontinuity: true, // used by ts-demuxer abrEwmaFastLive: 3, // used by abr-controller abrEwmaSlowLive: 9, // used by abr-controller abrEwmaFastVoD: 3, // used by abr-controller abrEwmaSlowVoD: 9, // used by abr-controller abrEwmaDefaultEstimate: 5e5, // 500 kbps // used by abr-controller abrBandWidthFactor: 0.95, // used by abr-controller abrBandWidthUpFactor: 0.7, // used by abr-controller abrMaxWithRealBitrate: false, // used by abr-controller maxStarvationDelay: 4, // used by abr-controller maxLoadingDelay: 4, // used by abr-controller minAutoBitrate: 0, // used by hls emeEnabled: false, // used by eme-controller widevineLicenseUrl: undefined, // used by eme-controller drmSystemOptions: {}, // used by eme-controller requestMediaKeySystemAccessFunc: _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_13__["requestMediaKeySystemAccess"], // used by eme-controller testBandwidth: true, progressive: false, lowLatencyMode: true }, timelineConfig()), {}, { subtitleStreamController: true ? _controller_subtitle_stream_controller__WEBPACK_IMPORTED_MODULE_3__["SubtitleStreamController"] : undefined, subtitleTrackController: true ? _controller_subtitle_track_controller__WEBPACK_IMPORTED_MODULE_4__["default"] : undefined, timelineController: true ? _controller_timeline_controller__WEBPACK_IMPORTED_MODULE_6__["TimelineController"] : undefined, audioStreamController: true ? _controller_audio_stream_controller__WEBPACK_IMPORTED_MODULE_1__["default"] : undefined, audioTrackController: true ? _controller_audio_track_controller__WEBPACK_IMPORTED_MODULE_2__["default"] : undefined, emeController: true ? _controller_eme_controller__WEBPACK_IMPORTED_MODULE_9__["default"] : undefined }); function timelineConfig() { return { cueHandler: _utils_cues__WEBPACK_IMPORTED_MODULE_12__["default"], // used by timeline-controller enableCEA708Captions: true, // used by timeline-controller enableWebVTT: true, // used by timeline-controller enableIMSC1: true, // used by timeline-controller captionsTextTrack1Label: 'English', // used by timeline-controller captionsTextTrack1LanguageCode: 'en', // used by timeline-controller captionsTextTrack2Label: 'Spanish', // used by timeline-controller captionsTextTrack2LanguageCode: 'es', // used by timeline-controller captionsTextTrack3Label: 'Unknown CC', // used by timeline-controller captionsTextTrack3LanguageCode: '', // used by timeline-controller captionsTextTrack4Label: 'Unknown CC', // used by timeline-controller captionsTextTrack4LanguageCode: '', // used by timeline-controller renderTextTracksNatively: true }; } function mergeConfig(defaultConfig, userConfig) { if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) { throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration"); } if (userConfig.liveMaxLatencyDurationCount !== undefined && (userConfig.liveSyncDurationCount === undefined || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) { throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"'); } if (userConfig.liveMaxLatencyDuration !== undefined && (userConfig.liveSyncDuration === undefined || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) { throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"'); } return _extends({}, defaultConfig, userConfig); } function enableStreamingMode(config) { var currentLoader = config.loader; if (currentLoader !== _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_11__["default"] && currentLoader !== _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_10__["default"]) { // If a developer has configured their own loader, respect that choice _utils_logger__WEBPACK_IMPORTED_MODULE_14__["logger"].log('[config]: Custom loader detected, cannot enable progressive streaming'); config.progressive = false; } else { var canStreamProgressively = Object(_utils_fetch_loader__WEBPACK_IMPORTED_MODULE_11__["fetchSupported"])(); if (canStreamProgressively) { config.loader = _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_11__["default"]; config.progressive = true; config.enableSoftwareAES = true; _utils_logger__WEBPACK_IMPORTED_MODULE_14__["logger"].log('[config]: Progressive streaming enabled, using FetchLoader'); } } } /***/ }), /***/ "./src/controller/abr-controller.ts": /*!******************************************!*\ !*** ./src/controller/abr-controller.ts ***! \******************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _utils_ewma_bandwidth_estimator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/ewma-bandwidth-estimator */ "./src/utils/ewma-bandwidth-estimator.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var AbrController = /*#__PURE__*/function () { function AbrController(hls) { this.hls = void 0; this.lastLoadedFragLevel = 0; this._nextAutoLevel = -1; this.timer = void 0; this.onCheck = this._abandonRulesCheck.bind(this); this.fragCurrent = null; this.partCurrent = null; this.bitrateTestDelay = 0; this.bwEstimator = void 0; this.hls = hls; var config = hls.config; this.bwEstimator = new _utils_ewma_bandwidth_estimator__WEBPACK_IMPORTED_MODULE_1__["default"](config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate); this.registerListeners(); } var _proto = AbrController.prototype; _proto.registerListeners = function registerListeners() { var hls = this.hls; hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADING, this.onFragLoading, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADED, this.onFragLoaded, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, this.onFragBuffered, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].LEVEL_LOADED, this.onLevelLoaded, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, this.onError, this); }; _proto.unregisterListeners = function unregisterListeners() { var hls = this.hls; hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADING, this.onFragLoading, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADED, this.onFragLoaded, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, this.onFragBuffered, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].LEVEL_LOADED, this.onLevelLoaded, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, this.onError, this); }; _proto.destroy = function destroy() { this.unregisterListeners(); this.clearTimer(); // @ts-ignore this.hls = this.onCheck = null; this.fragCurrent = this.partCurrent = null; }; _proto.onFragLoading = function onFragLoading(event, data) { var frag = data.frag; if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_5__["PlaylistLevelType"].MAIN) { if (!this.timer) { var _data$part; this.fragCurrent = frag; this.partCurrent = (_data$part = data.part) != null ? _data$part : null; this.timer = self.setInterval(this.onCheck, 100); } } }; _proto.onLevelLoaded = function onLevelLoaded(event, data) { var config = this.hls.config; if (data.details.live) { this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive); } else { this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD); } } /* This method monitors the download rate of the current fragment, and will downswitch if that fragment will not load quickly enough to prevent underbuffering */ ; _proto._abandonRulesCheck = function _abandonRulesCheck() { var frag = this.fragCurrent, part = this.partCurrent, hls = this.hls; var autoLevelEnabled = hls.autoLevelEnabled, config = hls.config, media = hls.media; if (!frag || !media) { return; } var stats = part ? part.stats : frag.stats; var duration = part ? part.duration : frag.duration; // If loading has been aborted and not in lowLatencyMode, stop timer and return if (stats.aborted) { _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn('frag loader destroy or aborted, disarm abandonRules'); this.clearTimer(); // reset forced auto level value so that next level will be selected this._nextAutoLevel = -1; return; } // This check only runs if we're in ABR mode and actually playing if (!autoLevelEnabled || media.paused || !media.playbackRate || !media.readyState) { return; } var requestDelay = performance.now() - stats.loading.start; var playbackRate = Math.abs(media.playbackRate); // In order to work with a stable bandwidth, only begin monitoring bandwidth after half of the fragment has been loaded if (requestDelay <= 500 * duration / playbackRate) { return; } var levels = hls.levels, minAutoLevel = hls.minAutoLevel; var level = levels[frag.level]; var expectedLen = stats.total || Math.max(stats.loaded, Math.round(duration * level.maxBitrate / 8)); var loadRate = Math.max(1, stats.bwEstimate ? stats.bwEstimate / 8 : stats.loaded * 1000 / requestDelay); // fragLoadDelay is an estimate of the time (in seconds) it will take to buffer the entire fragment var fragLoadedDelay = (expectedLen - stats.loaded) / loadRate; var pos = media.currentTime; // bufferStarvationDelay is an estimate of the amount time (in seconds) it will take to exhaust the buffer var bufferStarvationDelay = (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(media, pos, config.maxBufferHole).end - pos) / playbackRate; // Attempt an emergency downswitch only if less than 2 fragment lengths are buffered, and the time to finish loading // the current fragment is greater than the amount of buffer we have left if (bufferStarvationDelay >= 2 * duration / playbackRate || fragLoadedDelay <= bufferStarvationDelay) { return; } var fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY; var nextLoadLevel; // Iterate through lower level and try to find the largest one that avoids rebuffering for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) { // compute time to load next fragment at lower level // 0.8 : consider only 80% of current bw to be conservative // 8 = bits per byte (bps/Bps) var levelNextBitrate = levels[nextLoadLevel].maxBitrate; fragLevelNextLoadedDelay = duration * levelNextBitrate / (8 * 0.8 * loadRate); if (fragLevelNextLoadedDelay < bufferStarvationDelay) { break; } } // Only emergency switch down if it takes less time to load a new fragment at lowest level instead of continuing // to load the current one if (fragLevelNextLoadedDelay >= fragLoadedDelay) { return; } var bwEstimate = this.bwEstimator.getEstimate(); _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn("Fragment " + frag.sn + (part ? ' part ' + part.index : '') + " of level " + frag.level + " is loading too slowly and will cause an underbuffer; aborting and switching to level " + nextLoadLevel + "\n Current BW estimate: " + (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(bwEstimate) ? (bwEstimate / 1024).toFixed(3) : 'Unknown') + " Kb/s\n Estimated load time for current fragment: " + fragLoadedDelay.toFixed(3) + " s\n Estimated load time for the next fragment: " + fragLevelNextLoadedDelay.toFixed(3) + " s\n Time to underbuffer: " + bufferStarvationDelay.toFixed(3) + " s"); hls.nextLoadLevel = nextLoadLevel; this.bwEstimator.sample(requestDelay, stats.loaded); this.clearTimer(); if (frag.loader) { this.fragCurrent = this.partCurrent = null; frag.loader.abort(); } hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOAD_EMERGENCY_ABORTED, { frag: frag, part: part, stats: stats }); }; _proto.onFragLoaded = function onFragLoaded(event, _ref) { var frag = _ref.frag, part = _ref.part; if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_5__["PlaylistLevelType"].MAIN && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.sn)) { var stats = part ? part.stats : frag.stats; var duration = part ? part.duration : frag.duration; // stop monitoring bw once frag loaded this.clearTimer(); // store level id after successful fragment load this.lastLoadedFragLevel = frag.level; // reset forced auto level value so that next level will be selected this._nextAutoLevel = -1; // compute level average bitrate if (this.hls.config.abrMaxWithRealBitrate) { var level = this.hls.levels[frag.level]; var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded; var loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration; level.loaded = { bytes: loadedBytes, duration: loadedDuration }; level.realBitrate = Math.round(8 * loadedBytes / loadedDuration); } if (frag.bitrateTest) { var fragBufferedData = { stats: stats, frag: frag, part: part, id: frag.type }; this.onFragBuffered(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, fragBufferedData); frag.bitrateTest = false; } } }; _proto.onFragBuffered = function onFragBuffered(event, data) { var frag = data.frag, part = data.part; var stats = part ? part.stats : frag.stats; if (stats.aborted) { return; } // Only count non-alt-audio frags which were actually buffered in our BW calculations if (frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_5__["PlaylistLevelType"].MAIN || frag.sn === 'initSegment') { return; } // Use the difference between parsing and request instead of buffering and request to compute fragLoadingProcessing; // rationale is that buffer appending only happens once media is attached. This can happen when config.startFragPrefetch // is used. If we used buffering in that case, our BW estimate sample will be very large. var processingMs = stats.parsing.end - stats.loading.start; this.bwEstimator.sample(processingMs, stats.loaded); stats.bwEstimate = this.bwEstimator.getEstimate(); if (frag.bitrateTest) { this.bitrateTestDelay = processingMs / 1000; } else { this.bitrateTestDelay = 0; } }; _proto.onError = function onError(event, data) { // stop timer in case of frag loading error switch (data.details) { case _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].FRAG_LOAD_ERROR: case _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].FRAG_LOAD_TIMEOUT: this.clearTimer(); break; default: break; } }; _proto.clearTimer = function clearTimer() { self.clearInterval(this.timer); this.timer = undefined; } // return next auto level ; _proto.getNextABRAutoLevel = function getNextABRAutoLevel() { var fragCurrent = this.fragCurrent, partCurrent = this.partCurrent, hls = this.hls; var maxAutoLevel = hls.maxAutoLevel, config = hls.config, minAutoLevel = hls.minAutoLevel, media = hls.media; var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0; var pos = media ? media.currentTime : 0; // playbackRate is the absolute value of the playback rate; if media.playbackRate is 0, we use 1 to load as // if we're playing back at the normal rate. var playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1.0; var avgbw = this.bwEstimator ? this.bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate; // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted. var bufferStarvationDelay = (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(media, pos, config.maxBufferHole).end - pos) / playbackRate; // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all var bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor); if (bestLevel >= 0) { return bestLevel; } _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].trace((bufferStarvationDelay ? 'rebuffering expected' : 'buffer is empty') + ", finding optimal quality level"); // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering // if no matching level found, logic will return 0 var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay; var bwFactor = config.abrBandWidthFactor; var bwUpFactor = config.abrBandWidthUpFactor; if (!bufferStarvationDelay) { // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test var bitrateTestDelay = this.bitrateTestDelay; if (bitrateTestDelay) { // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value // max video loading delay used in automatic start level selection : // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level + // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` ) // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay; maxStarvationDelay = maxLoadingDelay - bitrateTestDelay; _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].trace("bitrate test took " + Math.round(1000 * bitrateTestDelay) + "ms, set first fragment max fetchDuration to " + Math.round(1000 * maxStarvationDelay) + " ms"); // don't use conservative factor on bitrate test bwFactor = bwUpFactor = 1; } } bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor); return Math.max(bestLevel, 0); }; _proto.findBestLevel = function findBestLevel(currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor) { var _level$details; var fragCurrent = this.fragCurrent, partCurrent = this.partCurrent, currentLevel = this.lastLoadedFragLevel; var levels = this.hls.levels; var level = levels[currentLevel]; var live = !!(level !== null && level !== void 0 && (_level$details = level.details) !== null && _level$details !== void 0 && _level$details.live); var currentCodecSet = level === null || level === void 0 ? void 0 : level.codecSet; var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0; for (var i = maxAutoLevel; i >= minAutoLevel; i--) { var levelInfo = levels[i]; if (!levelInfo || currentCodecSet && levelInfo.codecSet !== currentCodecSet) { continue; } var levelDetails = levelInfo.details; var avgDuration = (partCurrent ? levelDetails === null || levelDetails === void 0 ? void 0 : levelDetails.partTarget : levelDetails === null || levelDetails === void 0 ? void 0 : levelDetails.averagetargetduration) || currentFragDuration; var adjustedbw = void 0; // follow algorithm captured from stagefright : // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp // Pick the highest bandwidth stream below or equal to estimated bandwidth. // consider only 80% of the available bandwidth, but if we are switching up, // be even more conservative (70%) to avoid overestimating and immediately // switching back. if (i <= currentLevel) { adjustedbw = bwFactor * currentBw; } else { adjustedbw = bwUpFactor * currentBw; } var bitrate = levels[i].maxBitrate; var fetchDuration = bitrate * avgDuration / adjustedbw; _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: " + i + "/" + Math.round(adjustedbw) + "/" + bitrate + "/" + avgDuration + "/" + maxFetchDuration + "/" + fetchDuration); // if adjusted bw is greater than level bitrate AND if (adjustedbw > bitrate && (!fetchDuration || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration)) { // as we are looping from highest to lowest, this will return the best achievable quality level return i; } } // not enough time budget even with quality level 0 ... rebuffering might happen return -1; }; _createClass(AbrController, [{ key: "nextAutoLevel", get: function get() { var forcedAutoLevel = this._nextAutoLevel; var bwEstimator = this.bwEstimator; // in case next auto level has been forced, and bw not available or not reliable, return forced value if (forcedAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) { return forcedAutoLevel; } // compute next level using ABR logic var nextABRAutoLevel = this.getNextABRAutoLevel(); // if forced auto level has been defined, use it to cap ABR computed quality level if (forcedAutoLevel !== -1) { nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel); } return nextABRAutoLevel; }, set: function set(nextLevel) { this._nextAutoLevel = nextLevel; } }]); return AbrController; }(); /* harmony default export */ __webpack_exports__["default"] = (AbrController); /***/ }), /***/ "./src/controller/audio-stream-controller.ts": /*!***************************************************!*\ !*** ./src/controller/audio-stream-controller.ts ***! \***************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base-stream-controller */ "./src/controller/base-stream-controller.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts"); /* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts"); /* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts"); /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts"); /* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts"); /* harmony import */ var _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../demux/chunk-cache */ "./src/demux/chunk-cache.ts"); /* harmony import */ var _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../demux/transmuxer-interface */ "./src/demux/transmuxer-interface.ts"); /* harmony import */ var _types_transmuxer__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../types/transmuxer */ "./src/types/transmuxer.ts"); /* harmony import */ var _fragment_finders__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./fragment-finders */ "./src/controller/fragment-finders.ts"); /* harmony import */ var _utils_discontinuities__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/discontinuities */ "./src/utils/discontinuities.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var TICK_INTERVAL = 100; // how often to tick in ms var AudioStreamController = /*#__PURE__*/function (_BaseStreamController) { _inheritsLoose(AudioStreamController, _BaseStreamController); function AudioStreamController(hls, fragmentTracker) { var _this; _this = _BaseStreamController.call(this, hls, fragmentTracker, '[audio-stream-controller]') || this; _this.videoBuffer = null; _this.videoTrackCC = -1; _this.waitingVideoCC = -1; _this.audioSwitch = false; _this.trackId = -1; _this.waitingData = null; _this.mainDetails = null; _this.bufferFlushed = false; _this._registerListeners(); return _this; } var _proto = AudioStreamController.prototype; _proto.onHandlerDestroying = function onHandlerDestroying() { this._unregisterListeners(); this.mainDetails = null; }; _proto._registerListeners = function _registerListeners() { var hls = this.hls; hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MANIFEST_LOADING, this.onManifestLoading, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].LEVEL_LOADED, this.onLevelLoaded, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, this.onError, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_RESET, this.onBufferReset, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_CREATED, this.onBufferCreated, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_FLUSHED, this.onBufferFlushed, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].INIT_PTS_FOUND, this.onInitPtsFound, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, this.onFragBuffered, this); }; _proto._unregisterListeners = function _unregisterListeners() { var hls = this.hls; hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MANIFEST_LOADING, this.onManifestLoading, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].LEVEL_LOADED, this.onLevelLoaded, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, this.onError, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_RESET, this.onBufferReset, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_CREATED, this.onBufferCreated, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_FLUSHED, this.onBufferFlushed, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].INIT_PTS_FOUND, this.onInitPtsFound, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, this.onFragBuffered, this); } // INIT_PTS_FOUND is triggered when the video track parsed in the stream-controller has a new PTS value ; _proto.onInitPtsFound = function onInitPtsFound(event, _ref) { var frag = _ref.frag, id = _ref.id, initPTS = _ref.initPTS; // Always update the new INIT PTS // Can change due level switch if (id === 'main') { var cc = frag.cc; this.initPTS[frag.cc] = initPTS; this.log("InitPTS for cc: " + cc + " found from main: " + initPTS); this.videoTrackCC = cc; // If we are waiting, tick immediately to unblock audio fragment transmuxing if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS) { this.tick(); } } }; _proto.startLoad = function startLoad(startPosition) { if (!this.levels) { this.startPosition = startPosition; this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].STOPPED; return; } var lastCurrentTime = this.lastCurrentTime; this.stopLoad(); this.setInterval(TICK_INTERVAL); this.fragLoadError = 0; if (lastCurrentTime > 0 && startPosition === -1) { this.log("Override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3)); this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; } else { this.loadedmetadata = false; this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_TRACK; } this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition; this.tick(); }; _proto.doTick = function doTick() { switch (this.state) { case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE: this.doTickIdle(); break; case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_TRACK: { var _levels$trackId; var levels = this.levels, trackId = this.trackId; var details = levels === null || levels === void 0 ? void 0 : (_levels$trackId = levels[trackId]) === null || _levels$trackId === void 0 ? void 0 : _levels$trackId.details; if (details) { if (this.waitForCdnTuneIn(details)) { break; } this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS; } break; } case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING_WAITING_RETRY: { var _this$media; var now = performance.now(); var retryDate = this.retryDate; // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading if (!retryDate || now >= retryDate || (_this$media = this.media) !== null && _this$media !== void 0 && _this$media.seeking) { this.log('RetryDate reached, switch back to IDLE state'); this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; } break; } case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS: { // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS var waitingData = this.waitingData; if (waitingData) { var frag = waitingData.frag, part = waitingData.part, cache = waitingData.cache, complete = waitingData.complete; if (this.initPTS[frag.cc] !== undefined) { this.waitingData = null; this.waitingVideoCC = -1; this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING; var payload = cache.flush(); var data = { frag: frag, part: part, payload: payload, networkDetails: null }; this._handleFragmentLoadProgress(data); if (complete) { _BaseStreamController.prototype._handleFragmentLoadComplete.call(this, data); } } else if (this.videoTrackCC !== this.waitingVideoCC) { // Drop waiting fragment if videoTrackCC has changed since waitingFragment was set and initPTS was not found _utils_logger__WEBPACK_IMPORTED_MODULE_14__["logger"].log("Waiting fragment cc (" + frag.cc + ") cancelled because video is at cc " + this.videoTrackCC); this.clearWaitingFragment(); } else { // Drop waiting fragment if an earlier fragment is needed var pos = this.getLoadPosition(); var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(this.mediaBuffer, pos, this.config.maxBufferHole); var waitingFragmentAtPosition = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_11__["fragmentWithinToleranceTest"])(bufferInfo.end, this.config.maxFragLookUpTolerance, frag); if (waitingFragmentAtPosition < 0) { _utils_logger__WEBPACK_IMPORTED_MODULE_14__["logger"].log("Waiting fragment cc (" + frag.cc + ") @ " + frag.start + " cancelled because another fragment at " + bufferInfo.end + " is needed"); this.clearWaitingFragment(); } } } else { this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; } } } this.onTickEnd(); }; _proto.clearWaitingFragment = function clearWaitingFragment() { var waitingData = this.waitingData; if (waitingData) { this.fragmentTracker.removeFragment(waitingData.frag); this.waitingData = null; this.waitingVideoCC = -1; this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; } }; _proto.onTickEnd = function onTickEnd() { var media = this.media; if (!media || !media.readyState) { // Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0) return; } var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media; var buffered = mediaBuffer.buffered; if (!this.loadedmetadata && buffered.length) { this.loadedmetadata = true; } this.lastCurrentTime = media.currentTime; }; _proto.doTickIdle = function doTickIdle() { var _frag$decryptdata, _frag$decryptdata2; var hls = this.hls, levels = this.levels, media = this.media, trackId = this.trackId; var config = hls.config; if (!levels || !levels[trackId]) { return; } // if video not attached AND // start fragment already requested OR start frag prefetch not enabled // exit loop // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop if (!media && (this.startFragRequested || !config.startFragPrefetch)) { return; } var levelInfo = levels[trackId]; var trackDetails = levelInfo.details; if (!trackDetails || trackDetails.live && this.levelLastLoaded !== trackId || this.waitForCdnTuneIn(trackDetails)) { this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_TRACK; return; } if (this.bufferFlushed) { this.bufferFlushed = false; this.afterBufferFlushed(this.mediaBuffer ? this.mediaBuffer : this.media, _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO); } var bufferInfo = this.getFwdBufferInfo(this.mediaBuffer ? this.mediaBuffer : this.media, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO); if (bufferInfo === null) { return; } var bufferLen = bufferInfo.len; var maxBufLen = this.getMaxBufferLength(); var audioSwitch = this.audioSwitch; // if buffer length is less than maxBufLen try to load a new fragment if (bufferLen >= maxBufLen && !audioSwitch) { return; } if (!audioSwitch && this._streamEnded(bufferInfo, trackDetails)) { hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_EOS, { type: 'audio' }); this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ENDED; return; } var fragments = trackDetails.fragments; var start = fragments[0].start; var targetBufferTime = bufferInfo.end; if (audioSwitch) { var pos = this.getLoadPosition(); targetBufferTime = pos; // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime if (trackDetails.PTSKnown && pos < start) { // if everything is buffered from pos to start or if audio buffer upfront, let's seek to start if (bufferInfo.end > start || bufferInfo.nextStart) { this.log('Alt audio track ahead of main track, seek to start of alt audio track'); media.currentTime = start + 0.05; } } } var frag = this.getNextFragment(targetBufferTime, trackDetails); if (!frag) { this.bufferFlushed = true; return; } if (((_frag$decryptdata = frag.decryptdata) === null || _frag$decryptdata === void 0 ? void 0 : _frag$decryptdata.keyFormat) === 'identity' && !((_frag$decryptdata2 = frag.decryptdata) !== null && _frag$decryptdata2 !== void 0 && _frag$decryptdata2.key)) { this.loadKey(frag, trackDetails); } else { this.loadFragment(frag, trackDetails, targetBufferTime); } }; _proto.getMaxBufferLength = function getMaxBufferLength() { var maxConfigBuffer = _BaseStreamController.prototype.getMaxBufferLength.call(this); var mainBufferInfo = this.getFwdBufferInfo(this.videoBuffer ? this.videoBuffer : this.media, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN); if (mainBufferInfo === null) { return maxConfigBuffer; } return Math.max(maxConfigBuffer, mainBufferInfo.len); }; _proto.onMediaDetaching = function onMediaDetaching() { this.videoBuffer = null; _BaseStreamController.prototype.onMediaDetaching.call(this); }; _proto.onAudioTracksUpdated = function onAudioTracksUpdated(event, _ref2) { var audioTracks = _ref2.audioTracks; this.resetTransmuxer(); this.levels = audioTracks.map(function (mediaPlaylist) { return new _types_level__WEBPACK_IMPORTED_MODULE_5__["Level"](mediaPlaylist); }); }; _proto.onAudioTrackSwitching = function onAudioTrackSwitching(event, data) { // if any URL found on new audio track, it is an alternate audio track var altAudio = !!data.url; this.trackId = data.id; var fragCurrent = this.fragCurrent; if (fragCurrent !== null && fragCurrent !== void 0 && fragCurrent.loader) { fragCurrent.loader.abort(); } this.fragCurrent = null; this.clearWaitingFragment(); // destroy useless transmuxer when switching audio to main if (!altAudio) { this.resetTransmuxer(); } else { // switching to audio track, start timer if not already started this.setInterval(TICK_INTERVAL); } // should we switch tracks ? if (altAudio) { this.audioSwitch = true; // main audio track are handled by stream-controller, just do something if switching to alt audio track this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; } else { this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].STOPPED; } this.tick(); }; _proto.onManifestLoading = function onManifestLoading() { this.mainDetails = null; this.fragmentTracker.removeAllFragments(); this.startPosition = this.lastCurrentTime = 0; this.bufferFlushed = false; }; _proto.onLevelLoaded = function onLevelLoaded(event, data) { this.mainDetails = data.details; }; _proto.onAudioTrackLoaded = function onAudioTrackLoaded(event, data) { var _track$details; var levels = this.levels; var newDetails = data.details, trackId = data.id; if (!levels) { this.warn("Audio tracks were reset while loading level " + trackId); return; } this.log("Track " + trackId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "],duration:" + newDetails.totalduration); var track = levels[trackId]; var sliding = 0; if (newDetails.live || (_track$details = track.details) !== null && _track$details !== void 0 && _track$details.live) { var mainDetails = this.mainDetails; if (!newDetails.fragments[0]) { newDetails.deltaUpdateFailed = true; } if (newDetails.deltaUpdateFailed || !mainDetails) { return; } if (!track.details && newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) { Object(_utils_discontinuities__WEBPACK_IMPORTED_MODULE_12__["alignPDT"])(newDetails, mainDetails); sliding = newDetails.fragments[0].start; } else { sliding = this.alignPlaylists(newDetails, track.details); } } track.details = newDetails; this.levelLastLoaded = trackId; // compute start position if we are aligned with the main playlist if (!this.startFragRequested && (this.mainDetails || !newDetails.live)) { this.setStartPosition(track.details, sliding); } // only switch back to IDLE state if we were waiting for track to start downloading a new fragment if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_TRACK && !this.waitForCdnTuneIn(newDetails)) { this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; } // trigger handler right now this.tick(); }; _proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(data) { var _frag$initSegment; var frag = data.frag, part = data.part, payload = data.payload; var config = this.config, trackId = this.trackId, levels = this.levels; if (!levels) { this.warn("Audio tracks were reset while fragment load was in progress. Fragment " + frag.sn + " of level " + frag.level + " will not be buffered"); return; } var track = levels[trackId]; console.assert(track, 'Audio track is defined on fragment load progress'); var details = track.details; console.assert(details, 'Audio track details are defined on fragment load progress'); var audioCodec = config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2'; var transmuxer = this.transmuxer; if (!transmuxer) { transmuxer = this.transmuxer = new _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_9__["default"](this.hls, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this)); } // Check if we have video initPTS // If not we need to wait for it var initPTS = this.initPTS[frag.cc]; var initSegmentData = (_frag$initSegment = frag.initSegment) === null || _frag$initSegment === void 0 ? void 0 : _frag$initSegment.data; if (initPTS !== undefined) { // this.log(`Transmuxing ${sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`); // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live) var accurateTimeOffset = false; // details.PTSKnown || !details.live; var partIndex = part ? part.index : -1; var partial = partIndex !== -1; var chunkMeta = new _types_transmuxer__WEBPACK_IMPORTED_MODULE_10__["ChunkMetadata"](frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial); transmuxer.push(payload, initSegmentData, audioCodec, '', frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS); } else { _utils_logger__WEBPACK_IMPORTED_MODULE_14__["logger"].log("Unknown video PTS for cc " + frag.cc + ", waiting for video PTS before demuxing audio frag " + frag.sn + " of [" + details.startSN + " ," + details.endSN + "],track " + trackId); var _this$waitingData = this.waitingData = this.waitingData || { frag: frag, part: part, cache: new _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_8__["default"](), complete: false }, cache = _this$waitingData.cache; cache.push(new Uint8Array(payload)); this.waitingVideoCC = this.videoTrackCC; this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS; } }; _proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedData) { if (this.waitingData) { this.waitingData.complete = true; return; } _BaseStreamController.prototype._handleFragmentLoadComplete.call(this, fragLoadedData); }; _proto.onBufferReset = function onBufferReset() { // reset reference to sourcebuffers this.mediaBuffer = this.videoBuffer = null; this.loadedmetadata = false; }; _proto.onBufferCreated = function onBufferCreated(event, data) { var audioTrack = data.tracks.audio; if (audioTrack) { this.mediaBuffer = audioTrack.buffer; } if (data.tracks.video) { this.videoBuffer = data.tracks.video.buffer; } }; _proto.onFragBuffered = function onFragBuffered(event, data) { var frag = data.frag, part = data.part; if (frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO) { return; } if (this.fragContextChanged(frag)) { // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion // Avoid setting state back to IDLE or concluding the audio switch; otherwise, the switched-to track will not buffer this.warn("Fragment " + frag.sn + (part ? ' p: ' + part.index : '') + " of level " + frag.level + " finished buffering, but was aborted. state: " + this.state + ", audioSwitch: " + this.audioSwitch); return; } if (frag.sn !== 'initSegment') { this.fragPrevious = frag; if (this.audioSwitch) { this.audioSwitch = false; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_SWITCHED, { id: this.trackId }); } } this.fragBufferedComplete(frag, part); }; _proto.onError = function onError(event, data) { switch (data.details) { case _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].FRAG_LOAD_ERROR: case _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].FRAG_LOAD_TIMEOUT: case _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].KEY_LOAD_ERROR: case _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].KEY_LOAD_TIMEOUT: // TODO: Skip fragments that do not belong to this.fragCurrent audio-group id this.onFragmentOrKeyLoadError(_types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO, data); break; case _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR: case _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].AUDIO_TRACK_LOAD_TIMEOUT: // when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ERROR && this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].STOPPED) { // if fatal error, stop processing, otherwise move to IDLE to retry loading this.state = data.fatal ? _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ERROR : _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; this.warn(data.details + " while loading frag, switching to " + this.state + " state"); } break; case _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].BUFFER_FULL_ERROR: // if in appending state if (data.parent === 'audio' && (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSED)) { var flushBuffer = true; var bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO); // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end // reduce max buf len if current position is buffered if (bufferedInfo && bufferedInfo.len > 0.5) { flushBuffer = !this.reduceMaxBufferLength(bufferedInfo.len); } if (flushBuffer) { // current position is not buffered, but browser is still complaining about buffer full error // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708 // in that case flush the whole audio buffer to recover this.warn('Buffer full error also media.currentTime is not buffered, flush audio buffer'); this.fragCurrent = null; _BaseStreamController.prototype.flushMainBuffer.call(this, 0, Number.POSITIVE_INFINITY, 'audio'); } this.resetLoadingState(); } break; default: break; } }; _proto.onBufferFlushed = function onBufferFlushed(event, _ref3) { var type = _ref3.type; if (type === _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO) { this.bufferFlushed = true; } }; _proto._handleTransmuxComplete = function _handleTransmuxComplete(transmuxResult) { var _id3$samples; var id = 'audio'; var hls = this.hls; var remuxResult = transmuxResult.remuxResult, chunkMeta = transmuxResult.chunkMeta; var context = this.getCurrentContext(chunkMeta); if (!context) { this.warn("The loading context changed while buffering fragment " + chunkMeta.sn + " of level " + chunkMeta.level + ". This chunk will not be buffered."); this.resetLiveStartWhenNotLoaded(chunkMeta.level); return; } var frag = context.frag, part = context.part; var audio = remuxResult.audio, text = remuxResult.text, id3 = remuxResult.id3, initSegment = remuxResult.initSegment; // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level. // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed. if (this.fragContextChanged(frag)) { return; } this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING; if (this.audioSwitch && audio) { this.completeAudioSwitch(); } if (initSegment !== null && initSegment !== void 0 && initSegment.tracks) { this._bufferInitSegment(initSegment.tracks, frag, chunkMeta); hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_PARSING_INIT_SEGMENT, { frag: frag, id: id, tracks: initSegment.tracks }); // Only flush audio from old audio tracks when PTS is known on new audio track } if (audio) { var startPTS = audio.startPTS, endPTS = audio.endPTS, startDTS = audio.startDTS, endDTS = audio.endDTS; if (part) { part.elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO] = { startPTS: startPTS, endPTS: endPTS, startDTS: startDTS, endDTS: endDTS }; } frag.setElementaryStreamInfo(_loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO, startPTS, endPTS, startDTS, endDTS); this.bufferFragmentData(audio, frag, part, chunkMeta); } if (id3 !== null && id3 !== void 0 && (_id3$samples = id3.samples) !== null && _id3$samples !== void 0 && _id3$samples.length) { var emittedID3 = _extends({ frag: frag, id: id }, id3); hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_PARSING_METADATA, emittedID3); } if (text) { var emittedText = _extends({ frag: frag, id: id }, text); hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_PARSING_USERDATA, emittedText); } }; _proto._bufferInitSegment = function _bufferInitSegment(tracks, frag, chunkMeta) { if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING) { return; } // delete any video track found on audio transmuxer if (tracks.video) { delete tracks.video; } // include levelCodec in audio and video tracks var track = tracks.audio; if (!track) { return; } track.levelCodec = track.codec; track.id = 'audio'; this.log("Init audio buffer, container:" + track.container + ", codecs[parsed]=[" + track.codec + "]"); this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_CODECS, tracks); var initSegment = track.initSegment; if (initSegment !== null && initSegment !== void 0 && initSegment.byteLength) { var segment = { type: 'audio', frag: frag, part: null, chunkMeta: chunkMeta, parent: frag.type, data: initSegment }; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_APPENDING, segment); } // trigger handler right now this.tick(); }; _proto.loadFragment = function loadFragment(frag, trackDetails, targetBufferTime) { // only load if fragment is not loaded or if in audio switch var fragState = this.fragmentTracker.getState(frag); this.fragCurrent = frag; // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch if (this.audioSwitch || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_4__["FragmentState"].NOT_LOADED || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_4__["FragmentState"].PARTIAL) { if (frag.sn === 'initSegment') { this._loadInitSegment(frag); } else if (trackDetails.live && !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.initPTS[frag.cc])) { this.log("Waiting for video PTS in continuity counter " + frag.cc + " of live stream before loading audio fragment " + frag.sn + " of level " + this.trackId); this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS; } else { this.startFragRequested = true; _BaseStreamController.prototype.loadFragment.call(this, frag, trackDetails, targetBufferTime); } } }; _proto.completeAudioSwitch = function completeAudioSwitch() { var hls = this.hls, media = this.media, trackId = this.trackId; if (media) { this.log('Switching audio track : flushing all audio'); _BaseStreamController.prototype.flushMainBuffer.call(this, 0, Number.POSITIVE_INFINITY, 'audio'); } this.audioSwitch = false; hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_SWITCHED, { id: trackId }); }; return AudioStreamController; }(_base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["default"]); /* harmony default export */ __webpack_exports__["default"] = (AudioStreamController); /***/ }), /***/ "./src/controller/audio-track-controller.ts": /*!**************************************************!*\ !*** ./src/controller/audio-track-controller.ts ***! \**************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _base_playlist_controller__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base-playlist-controller */ "./src/controller/base-playlist-controller.ts"); /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts"); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var AudioTrackController = /*#__PURE__*/function (_BasePlaylistControll) { _inheritsLoose(AudioTrackController, _BasePlaylistControll); function AudioTrackController(hls) { var _this; _this = _BasePlaylistControll.call(this, hls, '[audio-track-controller]') || this; _this.tracks = []; _this.groupId = null; _this.tracksInGroup = []; _this.trackId = -1; _this.trackName = ''; _this.selectDefaultTrack = true; _this.registerListeners(); return _this; } var _proto = AudioTrackController.prototype; _proto.registerListeners = function registerListeners() { var hls = this.hls; hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADING, this.onLevelLoading, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_SWITCHING, this.onLevelSwitching, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this); }; _proto.unregisterListeners = function unregisterListeners() { var hls = this.hls; hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADING, this.onLevelLoading, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_SWITCHING, this.onLevelSwitching, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this); }; _proto.destroy = function destroy() { this.unregisterListeners(); this.tracks.length = 0; this.tracksInGroup.length = 0; _BasePlaylistControll.prototype.destroy.call(this); }; _proto.onManifestLoading = function onManifestLoading() { this.tracks = []; this.groupId = null; this.tracksInGroup = []; this.trackId = -1; this.trackName = ''; this.selectDefaultTrack = true; }; _proto.onManifestParsed = function onManifestParsed(event, data) { this.tracks = data.audioTracks || []; }; _proto.onAudioTrackLoaded = function onAudioTrackLoaded(event, data) { var id = data.id, details = data.details; var currentTrack = this.tracksInGroup[id]; if (!currentTrack) { this.warn("Invalid audio track id " + id); return; } var curDetails = currentTrack.details; currentTrack.details = data.details; this.log("audioTrack " + id + " loaded [" + details.startSN + "-" + details.endSN + "]"); if (id === this.trackId) { this.retryCount = 0; this.playlistLoaded(id, data, curDetails); } }; _proto.onLevelLoading = function onLevelLoading(event, data) { this.switchLevel(data.level); }; _proto.onLevelSwitching = function onLevelSwitching(event, data) { this.switchLevel(data.level); }; _proto.switchLevel = function switchLevel(levelIndex) { var levelInfo = this.hls.levels[levelIndex]; if (!(levelInfo !== null && levelInfo !== void 0 && levelInfo.audioGroupIds)) { return; } var audioGroupId = levelInfo.audioGroupIds[levelInfo.urlId]; if (this.groupId !== audioGroupId) { this.groupId = audioGroupId; var audioTracks = this.tracks.filter(function (track) { return !audioGroupId || track.groupId === audioGroupId; }); // Disable selectDefaultTrack if there are no default tracks if (this.selectDefaultTrack && !audioTracks.some(function (track) { return track.default; })) { this.selectDefaultTrack = false; } this.tracksInGroup = audioTracks; var audioTracksUpdated = { audioTracks: audioTracks }; this.log("Updating audio tracks, " + audioTracks.length + " track(s) found in \"" + audioGroupId + "\" group-id"); this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACKS_UPDATED, audioTracksUpdated); this.selectInitialTrack(); } }; _proto.onError = function onError(event, data) { _BasePlaylistControll.prototype.onError.call(this, event, data); if (data.fatal || !data.context) { return; } if (data.context.type === _types_loader__WEBPACK_IMPORTED_MODULE_3__["PlaylistContextType"].AUDIO_TRACK && data.context.id === this.trackId && data.context.groupId === this.groupId) { this.retryLoadingOrFail(data); } }; _proto.setAudioTrack = function setAudioTrack(newId) { var tracks = this.tracksInGroup; // check if level idx is valid if (newId < 0 || newId >= tracks.length) { this.warn('Invalid id passed to audio-track controller'); return; } // stopping live reloading timer if any this.clearTimer(); var lastTrack = tracks[this.trackId]; this.log("Now switching to audio-track index " + newId); var track = tracks[newId]; var id = track.id, _track$groupId = track.groupId, groupId = _track$groupId === void 0 ? '' : _track$groupId, name = track.name, type = track.type, url = track.url; this.trackId = newId; this.trackName = name; this.selectDefaultTrack = false; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACK_SWITCHING, { id: id, groupId: groupId, name: name, type: type, url: url }); // Do not reload track unless live if (track.details && !track.details.live) { return; } var hlsUrlParameters = this.switchParams(track.url, lastTrack === null || lastTrack === void 0 ? void 0 : lastTrack.details); this.loadPlaylist(hlsUrlParameters); }; _proto.selectInitialTrack = function selectInitialTrack() { var audioTracks = this.tracksInGroup; console.assert(audioTracks.length, 'Initial audio track should be selected when tracks are known'); var currentAudioTrackName = this.trackName; var trackId = this.findTrackId(currentAudioTrackName) || this.findTrackId(); if (trackId !== -1) { this.setAudioTrack(trackId); } else { this.warn("No track found for running audio group-ID: " + this.groupId); this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR, fatal: true }); } }; _proto.findTrackId = function findTrackId(name) { var audioTracks = this.tracksInGroup; for (var i = 0; i < audioTracks.length; i++) { var track = audioTracks[i]; if (!this.selectDefaultTrack || track.default) { if (!name || name === track.name) { return track.id; } } } return -1; }; _proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) { var audioTrack = this.tracksInGroup[this.trackId]; if (this.shouldLoadTrack(audioTrack)) { var id = audioTrack.id; var groupId = audioTrack.groupId; var url = audioTrack.url; if (hlsUrlParameters) { try { url = hlsUrlParameters.addDirectives(url); } catch (error) { this.warn("Could not construct new URL with HLS Delivery Directives: " + error); } } // track not retrieved yet, or live playlist we need to (re)load it this.log("loading audio-track playlist for id: " + id); this.clearTimer(); this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACK_LOADING, { url: url, id: id, groupId: groupId, deliveryDirectives: hlsUrlParameters || null }); } }; _createClass(AudioTrackController, [{ key: "audioTracks", get: function get() { return this.tracksInGroup; } }, { key: "audioTrack", get: function get() { return this.trackId; }, set: function set(newId) { // If audio track is selected from API then don't choose from the manifest default track this.selectDefaultTrack = false; this.setAudioTrack(newId); } }]); return AudioTrackController; }(_base_playlist_controller__WEBPACK_IMPORTED_MODULE_2__["default"]); /* harmony default export */ __webpack_exports__["default"] = (AudioTrackController); /***/ }), /***/ "./src/controller/base-playlist-controller.ts": /*!****************************************************!*\ !*** ./src/controller/base-playlist-controller.ts ***! \****************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BasePlaylistController; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts"); /* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); var BasePlaylistController = /*#__PURE__*/function () { function BasePlaylistController(hls, logPrefix) { this.hls = void 0; this.timer = -1; this.canLoad = false; this.retryCount = 0; this.log = void 0; this.warn = void 0; this.log = _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"], logPrefix + ":"); this.warn = _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"], logPrefix + ":"); this.hls = hls; } var _proto = BasePlaylistController.prototype; _proto.destroy = function destroy() { this.clearTimer(); // @ts-ignore this.hls = this.log = this.warn = null; }; _proto.onError = function onError(event, data) { if (data.fatal && data.type === _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].NETWORK_ERROR) { this.clearTimer(); } }; _proto.clearTimer = function clearTimer() { clearTimeout(this.timer); this.timer = -1; }; _proto.startLoad = function startLoad() { this.canLoad = true; this.retryCount = 0; this.loadPlaylist(); }; _proto.stopLoad = function stopLoad() { this.canLoad = false; this.clearTimer(); }; _proto.switchParams = function switchParams(playlistUri, previous) { var renditionReports = previous === null || previous === void 0 ? void 0 : previous.renditionReports; if (renditionReports) { for (var i = 0; i < renditionReports.length; i++) { var attr = renditionReports[i]; var uri = '' + attr.URI; if (uri === playlistUri.substr(-uri.length)) { var msn = parseInt(attr['LAST-MSN']); var part = parseInt(attr['LAST-PART']); if (previous && this.hls.config.lowLatencyMode) { var currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration); if (part !== undefined && currentGoal > previous.partTarget) { part += 1; } } if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(msn)) { return new _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsUrlParameters"](msn, Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(part) ? part : undefined, _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsSkip"].No); } } } } }; _proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {}; _proto.shouldLoadTrack = function shouldLoadTrack(track) { return this.canLoad && track && !!track.url && (!track.details || track.details.live); }; _proto.playlistLoaded = function playlistLoaded(index, data, previousDetails) { var _this = this; var details = data.details, stats = data.stats; // Set last updated date-time var elapsed = stats.loading.end ? Math.max(0, self.performance.now() - stats.loading.end) : 0; details.advancedDateTime = Date.now() - elapsed; // if current playlist is a live playlist, arm a timer to reload it if (details.live || previousDetails !== null && previousDetails !== void 0 && previousDetails.live) { details.reloaded(previousDetails); if (previousDetails) { this.log("live playlist " + index + " " + (details.advanced ? 'REFRESHED ' + details.lastPartSn + '-' + details.lastPartIndex : 'MISSED')); } // Merge live playlists to adjust fragment starts and fill in delta playlist skipped segments if (previousDetails && details.fragments.length > 0) { Object(_level_helper__WEBPACK_IMPORTED_MODULE_2__["mergeDetails"])(previousDetails, details); } if (!this.canLoad || !details.live) { return; } var deliveryDirectives; var msn = undefined; var part = undefined; if (details.canBlockReload && details.endSN && details.advanced) { // Load level with LL-HLS delivery directives var lowLatencyMode = this.hls.config.lowLatencyMode; var lastPartSn = details.lastPartSn; var endSn = details.endSN; var lastPartIndex = details.lastPartIndex; var hasParts = lastPartIndex !== -1; var lastPart = lastPartSn === endSn; // When low latency mode is disabled, we'll skip part requests once the last part index is found var nextSnStartIndex = lowLatencyMode ? 0 : lastPartIndex; if (hasParts) { msn = lastPart ? endSn + 1 : lastPartSn; part = lastPart ? nextSnStartIndex : lastPartIndex + 1; } else { msn = endSn + 1; } // Low-Latency CDN Tune-in: "age" header and time since load indicates we're behind by more than one part // Update directives to obtain the Playlist that has the estimated additional duration of media var lastAdvanced = details.age; var cdnAge = lastAdvanced + details.ageHeader; var currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5); if (currentGoal > 0) { if (previousDetails && currentGoal > previousDetails.tuneInGoal) { // If we attempted to get the next or latest playlist update, but currentGoal increased, // then we either can't catchup, or the "age" header cannot be trusted. this.warn("CDN Tune-in goal increased from: " + previousDetails.tuneInGoal + " to: " + currentGoal + " with playlist age: " + details.age); currentGoal = 0; } else { var segments = Math.floor(currentGoal / details.targetduration); msn += segments; if (part !== undefined) { var parts = Math.round(currentGoal % details.targetduration / details.partTarget); part += parts; } this.log("CDN Tune-in age: " + details.ageHeader + "s last advanced " + lastAdvanced.toFixed(2) + "s goal: " + currentGoal + " skip sn " + segments + " to part " + part); } details.tuneInGoal = currentGoal; } deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part); if (lowLatencyMode || !lastPart) { this.loadPlaylist(deliveryDirectives); return; } } else { deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part); } var reloadInterval = Object(_level_helper__WEBPACK_IMPORTED_MODULE_2__["computeReloadInterval"])(details, stats); if (msn !== undefined && details.canBlockReload) { reloadInterval -= details.partTarget || 1; } this.log("reload live playlist " + index + " in " + Math.round(reloadInterval) + " ms"); this.timer = self.setTimeout(function () { return _this.loadPlaylist(deliveryDirectives); }, reloadInterval); } else { this.clearTimer(); } }; _proto.getDeliveryDirectives = function getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) { var skip = Object(_types_level__WEBPACK_IMPORTED_MODULE_1__["getSkipValue"])(details, msn); if (previousDeliveryDirectives !== null && previousDeliveryDirectives !== void 0 && previousDeliveryDirectives.skip && details.deltaUpdateFailed) { msn = previousDeliveryDirectives.msn; part = previousDeliveryDirectives.part; skip = _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsSkip"].No; } return new _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsUrlParameters"](msn, part, skip); }; _proto.retryLoadingOrFail = function retryLoadingOrFail(errorEvent) { var _this2 = this; var config = this.hls.config; var retry = this.retryCount < config.levelLoadingMaxRetry; if (retry) { var _errorEvent$context; this.retryCount++; if (errorEvent.details.indexOf('LoadTimeOut') > -1 && (_errorEvent$context = errorEvent.context) !== null && _errorEvent$context !== void 0 && _errorEvent$context.deliveryDirectives) { // The LL-HLS request already timed out so retry immediately this.warn("retry playlist loading #" + this.retryCount + " after \"" + errorEvent.details + "\""); this.loadPlaylist(); } else { // exponential backoff capped to max retry timeout var delay = Math.min(Math.pow(2, this.retryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout); // Schedule level/track reload this.timer = self.setTimeout(function () { return _this2.loadPlaylist(); }, delay); this.warn("retry playlist loading #" + this.retryCount + " in " + delay + " ms after \"" + errorEvent.details + "\""); } } else { this.warn("cannot recover from error \"" + errorEvent.details + "\""); // stopping live reloading timer if any this.clearTimer(); // switch error to fatal errorEvent.fatal = true; } return retry; }; return BasePlaylistController; }(); /***/ }), /***/ "./src/controller/base-stream-controller.ts": /*!**************************************************!*\ !*** ./src/controller/base-stream-controller.ts ***! \**************************************************/ /*! exports provided: State, default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "State", function() { return State; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BaseStreamController; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _task_loop__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../task-loop */ "./src/task-loop.ts"); /* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts"); /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _types_transmuxer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../types/transmuxer */ "./src/types/transmuxer.ts"); /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts"); /* harmony import */ var _utils_discontinuities__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/discontinuities */ "./src/utils/discontinuities.ts"); /* harmony import */ var _fragment_finders__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./fragment-finders */ "./src/controller/fragment-finders.ts"); /* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts"); /* harmony import */ var _loader_fragment_loader__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../loader/fragment-loader */ "./src/loader/fragment-loader.ts"); /* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.ts"); /* harmony import */ var _utils_time_ranges__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/time-ranges */ "./src/utils/time-ranges.ts"); /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts"); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var State = { STOPPED: 'STOPPED', IDLE: 'IDLE', KEY_LOADING: 'KEY_LOADING', FRAG_LOADING: 'FRAG_LOADING', FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY', WAITING_TRACK: 'WAITING_TRACK', PARSING: 'PARSING', PARSED: 'PARSED', BACKTRACKING: 'BACKTRACKING', ENDED: 'ENDED', ERROR: 'ERROR', WAITING_INIT_PTS: 'WAITING_INIT_PTS', WAITING_LEVEL: 'WAITING_LEVEL' }; var BaseStreamController = /*#__PURE__*/function (_TaskLoop) { _inheritsLoose(BaseStreamController, _TaskLoop); function BaseStreamController(hls, fragmentTracker, logPrefix) { var _this; _this = _TaskLoop.call(this) || this; _this.hls = void 0; _this.fragPrevious = null; _this.fragCurrent = null; _this.fragmentTracker = void 0; _this.transmuxer = null; _this._state = State.STOPPED; _this.media = void 0; _this.mediaBuffer = void 0; _this.config = void 0; _this.bitrateTest = false; _this.lastCurrentTime = 0; _this.nextLoadPosition = 0; _this.startPosition = 0; _this.loadedmetadata = false; _this.fragLoadError = 0; _this.retryDate = 0; _this.levels = null; _this.fragmentLoader = void 0; _this.levelLastLoaded = null; _this.startFragRequested = false; _this.decrypter = void 0; _this.initPTS = []; _this.onvseeking = null; _this.onvended = null; _this.logPrefix = ''; _this.log = void 0; _this.warn = void 0; _this.logPrefix = logPrefix; _this.log = _utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"].log.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"], logPrefix + ":"); _this.warn = _utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"].warn.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"], logPrefix + ":"); _this.hls = hls; _this.fragmentLoader = new _loader_fragment_loader__WEBPACK_IMPORTED_MODULE_12__["default"](hls.config); _this.fragmentTracker = fragmentTracker; _this.config = hls.config; _this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_13__["default"](hls, hls.config); hls.on(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].KEY_LOADED, _this.onKeyLoaded, _assertThisInitialized(_this)); return _this; } var _proto = BaseStreamController.prototype; _proto.doTick = function doTick() { this.onTickEnd(); }; _proto.onTickEnd = function onTickEnd() {} // eslint-disable-next-line @typescript-eslint/no-unused-vars ; _proto.startLoad = function startLoad(startPosition) {}; _proto.stopLoad = function stopLoad() { this.fragmentLoader.abort(); var frag = this.fragCurrent; if (frag) { this.fragmentTracker.removeFragment(frag); } this.resetTransmuxer(); this.fragCurrent = null; this.fragPrevious = null; this.clearInterval(); this.clearNextTick(); this.state = State.STOPPED; }; _proto._streamEnded = function _streamEnded(bufferInfo, levelDetails) { var fragCurrent = this.fragCurrent, fragmentTracker = this.fragmentTracker; // we just got done loading the final fragment and there is no other buffered range after ... // rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between // so we should not switch to ENDED in that case, to be able to buffer them if (!levelDetails.live && fragCurrent && fragCurrent.sn === levelDetails.endSN && !bufferInfo.nextStart) { var fragState = fragmentTracker.getState(fragCurrent); return fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].PARTIAL || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].OK; } return false; }; _proto.onMediaAttached = function onMediaAttached(event, data) { var media = this.media = this.mediaBuffer = data.media; this.onvseeking = this.onMediaSeeking.bind(this); this.onvended = this.onMediaEnded.bind(this); media.addEventListener('seeking', this.onvseeking); media.addEventListener('ended', this.onvended); var config = this.config; if (this.levels && config.autoStartLoad && this.state === State.STOPPED) { this.startLoad(config.startPosition); } }; _proto.onMediaDetaching = function onMediaDetaching() { var media = this.media; if (media !== null && media !== void 0 && media.ended) { this.log('MSE detaching and video ended, reset startPosition'); this.startPosition = this.lastCurrentTime = 0; } // remove video listeners if (media) { media.removeEventListener('seeking', this.onvseeking); media.removeEventListener('ended', this.onvended); this.onvseeking = this.onvended = null; } this.media = this.mediaBuffer = null; this.loadedmetadata = false; this.fragmentTracker.removeAllFragments(); this.stopLoad(); }; _proto.onMediaSeeking = function onMediaSeeking() { var config = this.config, fragCurrent = this.fragCurrent, media = this.media, mediaBuffer = this.mediaBuffer, state = this.state; var currentTime = media ? media.currentTime : 0; var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(mediaBuffer || media, currentTime, config.maxBufferHole); this.log("media seeking to " + (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(currentTime) ? currentTime.toFixed(3) : currentTime) + ", state: " + state); if (state === State.ENDED) { this.resetLoadingState(); } else if (fragCurrent && !bufferInfo.len) { // check if we are seeking to a unbuffered area AND if frag loading is in progress var tolerance = config.maxFragLookUpTolerance; var fragStartOffset = fragCurrent.start - tolerance; var fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance; var pastFragment = currentTime > fragEndOffset; // check if the seek position is past current fragment, and if so abort loading if (currentTime < fragStartOffset || pastFragment) { if (pastFragment && fragCurrent.loader) { this.log('seeking outside of buffer while fragment load in progress, cancel fragment load'); fragCurrent.loader.abort(); } this.resetLoadingState(); } } if (media) { this.lastCurrentTime = currentTime; } // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target if (!this.loadedmetadata && !bufferInfo.len) { this.nextLoadPosition = this.startPosition = currentTime; } // Async tick to speed up processing this.tickImmediate(); }; _proto.onMediaEnded = function onMediaEnded() { // reset startPosition and lastCurrentTime to restart playback @ stream beginning this.startPosition = this.lastCurrentTime = 0; }; _proto.onKeyLoaded = function onKeyLoaded(event, data) { if (this.state !== State.KEY_LOADING || data.frag !== this.fragCurrent || !this.levels) { return; } this.state = State.IDLE; var levelDetails = this.levels[data.frag.level].details; if (levelDetails) { this.loadFragment(data.frag, levelDetails, data.frag.start); } }; _proto.onHandlerDestroying = function onHandlerDestroying() { this.stopLoad(); _TaskLoop.prototype.onHandlerDestroying.call(this); }; _proto.onHandlerDestroyed = function onHandlerDestroyed() { this.state = State.STOPPED; this.hls.off(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].KEY_LOADED, this.onKeyLoaded, this); if (this.fragmentLoader) { this.fragmentLoader.destroy(); } if (this.decrypter) { this.decrypter.destroy(); } this.hls = this.log = this.warn = this.decrypter = this.fragmentLoader = this.fragmentTracker = null; _TaskLoop.prototype.onHandlerDestroyed.call(this); }; _proto.loadKey = function loadKey(frag, details) { this.log("Loading key for " + frag.sn + " of [" + details.startSN + "-" + details.endSN + "], " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + " " + frag.level); this.state = State.KEY_LOADING; this.fragCurrent = frag; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].KEY_LOADING, { frag: frag }); }; _proto.loadFragment = function loadFragment(frag, levelDetails, targetBufferTime) { this._loadFragForPlayback(frag, levelDetails, targetBufferTime); }; _proto._loadFragForPlayback = function _loadFragForPlayback(frag, levelDetails, targetBufferTime) { var _this2 = this; var progressCallback = function progressCallback(data) { if (_this2.fragContextChanged(frag)) { _this2.warn("Fragment " + frag.sn + (data.part ? ' p: ' + data.part.index : '') + " of level " + frag.level + " was dropped during download."); _this2.fragmentTracker.removeFragment(frag); return; } frag.stats.chunkCount++; _this2._handleFragmentLoadProgress(data); }; this._doFragLoad(frag, levelDetails, targetBufferTime, progressCallback).then(function (data) { if (!data) { // if we're here we probably needed to backtrack or are waiting for more parts return; } _this2.fragLoadError = 0; var state = _this2.state; if (_this2.fragContextChanged(frag)) { if (state === State.FRAG_LOADING || state === State.BACKTRACKING || !_this2.fragCurrent && state === State.PARSING) { _this2.fragmentTracker.removeFragment(frag); _this2.state = State.IDLE; } return; } if ('payload' in data) { _this2.log("Loaded fragment " + frag.sn + " of level " + frag.level); _this2.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADED, data); // Tracker backtrack must be called after onFragLoaded to update the fragment entity state to BACKTRACKED // This happens after handleTransmuxComplete when the worker or progressive is disabled if (_this2.state === State.BACKTRACKING) { _this2.fragmentTracker.backtrack(frag, data); _this2.resetFragmentLoading(frag); return; } } // Pass through the whole payload; controllers not implementing progressive loading receive data from this callback _this2._handleFragmentLoadComplete(data); }).catch(function (reason) { _this2.warn(reason); _this2.resetFragmentLoading(frag); }); }; _proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset, type) { if (type === void 0) { type = null; } if (!(startOffset - endOffset)) { return; } // When alternate audio is playing, the audio-stream-controller is responsible for the audio buffer. Otherwise, // passing a null type flushes both buffers var flushScope = { startOffset: startOffset, endOffset: endOffset, type: type }; // Reset load errors on flush this.fragLoadError = 0; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].BUFFER_FLUSHING, flushScope); }; _proto._loadInitSegment = function _loadInitSegment(frag) { var _this3 = this; this._doFragLoad(frag).then(function (data) { if (!data || _this3.fragContextChanged(frag) || !_this3.levels) { throw new Error('init load aborted'); } return data; }).then(function (data) { var hls = _this3.hls; var payload = data.payload; var decryptData = frag.decryptdata; // check to see if the payload needs to be decrypted if (payload && payload.byteLength > 0 && decryptData && decryptData.key && decryptData.iv && decryptData.method === 'AES-128') { var startTime = self.performance.now(); // decrypt the subtitles return _this3.decrypter.webCryptoDecrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer).then(function (decryptedData) { var endTime = self.performance.now(); hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_DECRYPTED, { frag: frag, payload: decryptedData, stats: { tstart: startTime, tdecrypt: endTime } }); data.payload = decryptedData; return data; }); } return data; }).then(function (data) { var fragCurrent = _this3.fragCurrent, hls = _this3.hls, levels = _this3.levels; if (!levels) { throw new Error('init load aborted, missing levels'); } var details = levels[frag.level].details; console.assert(details, 'Level details are defined when init segment is loaded'); var stats = frag.stats; _this3.state = State.IDLE; _this3.fragLoadError = 0; frag.data = new Uint8Array(data.payload); stats.parsing.start = stats.buffering.start = self.performance.now(); stats.parsing.end = stats.buffering.end = self.performance.now(); // Silence FRAG_BUFFERED event if fragCurrent is null if (data.frag === fragCurrent) { hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_BUFFERED, { stats: stats, frag: fragCurrent, part: null, id: frag.type }); } _this3.tick(); }).catch(function (reason) { _this3.warn(reason); _this3.resetFragmentLoading(frag); }); }; _proto.fragContextChanged = function fragContextChanged(frag) { var fragCurrent = this.fragCurrent; return !frag || !fragCurrent || frag.level !== fragCurrent.level || frag.sn !== fragCurrent.sn || frag.urlId !== fragCurrent.urlId; }; _proto.fragBufferedComplete = function fragBufferedComplete(frag, part) { var media = this.mediaBuffer ? this.mediaBuffer : this.media; this.log("Buffered " + frag.type + " sn: " + frag.sn + (part ? ' part: ' + part.index : '') + " of " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + " " + frag.level + " " + _utils_time_ranges__WEBPACK_IMPORTED_MODULE_14__["default"].toString(_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].getBuffered(media))); this.state = State.IDLE; this.tick(); }; _proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedEndData) { var transmuxer = this.transmuxer; if (!transmuxer) { return; } var frag = fragLoadedEndData.frag, part = fragLoadedEndData.part, partsLoaded = fragLoadedEndData.partsLoaded; // If we did not load parts, or loaded all parts, we have complete (not partial) fragment data var complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some(function (fragLoaded) { return !fragLoaded; }); var chunkMeta = new _types_transmuxer__WEBPACK_IMPORTED_MODULE_7__["ChunkMetadata"](frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete); transmuxer.flush(chunkMeta); } // eslint-disable-next-line @typescript-eslint/no-unused-vars ; _proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(frag) {}; _proto._doFragLoad = function _doFragLoad(frag, details, targetBufferTime, progressCallback) { var _this4 = this; if (targetBufferTime === void 0) { targetBufferTime = null; } if (!this.levels) { throw new Error('frag load aborted, missing levels'); } targetBufferTime = Math.max(frag.start, targetBufferTime || 0); if (this.config.lowLatencyMode && details) { var partList = details.partList; if (partList && progressCallback) { if (targetBufferTime > frag.end && details.fragmentHint) { frag = details.fragmentHint; } var partIndex = this.getNextPart(partList, frag, targetBufferTime); if (partIndex > -1) { var part = partList[partIndex]; this.log("Loading part sn: " + frag.sn + " p: " + part.index + " cc: " + frag.cc + " of playlist [" + details.startSN + "-" + details.endSN + "] parts [0-" + partIndex + "-" + (partList.length - 1) + "] " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + ": " + frag.level + ", target: " + parseFloat(targetBufferTime.toFixed(3))); this.nextLoadPosition = part.start + part.duration; this.state = State.FRAG_LOADING; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADING, { frag: frag, part: partList[partIndex], targetBufferTime: targetBufferTime }); return this.doFragPartsLoad(frag, partList, partIndex, progressCallback).catch(function (error) { return _this4.handleFragLoadError(error); }); } else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) { // Fragment hint has no parts return Promise.resolve(null); } } } this.log("Loading fragment " + frag.sn + " cc: " + frag.cc + " " + (details ? 'of [' + details.startSN + '-' + details.endSN + '] ' : '') + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + ": " + frag.level + ", target: " + parseFloat(targetBufferTime.toFixed(3))); // Don't update nextLoadPosition for fragments which are not buffered if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.sn) && !this.bitrateTest) { this.nextLoadPosition = frag.start + frag.duration; } this.state = State.FRAG_LOADING; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADING, { frag: frag, targetBufferTime: targetBufferTime }); return this.fragmentLoader.load(frag, progressCallback).catch(function (error) { return _this4.handleFragLoadError(error); }); }; _proto.doFragPartsLoad = function doFragPartsLoad(frag, partList, partIndex, progressCallback) { var _this5 = this; return new Promise(function (resolve, reject) { var partsLoaded = []; var loadPartIndex = function loadPartIndex(index) { var part = partList[index]; _this5.fragmentLoader.loadPart(frag, part, progressCallback).then(function (partLoadedData) { partsLoaded[part.index] = partLoadedData; var loadedPart = partLoadedData.part; _this5.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADED, partLoadedData); var nextPart = partList[index + 1]; if (nextPart && nextPart.fragment === frag) { loadPartIndex(index + 1); } else { return resolve({ frag: frag, part: loadedPart, partsLoaded: partsLoaded }); } }).catch(reject); }; loadPartIndex(partIndex); }); }; _proto.handleFragLoadError = function handleFragLoadError(_ref) { var data = _ref.data; if (data && data.details === _errors__WEBPACK_IMPORTED_MODULE_6__["ErrorDetails"].INTERNAL_ABORTED) { this.handleFragLoadAborted(data.frag, data.part); } else { this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, data); } return null; }; _proto._handleTransmuxerFlush = function _handleTransmuxerFlush(chunkMeta) { var context = this.getCurrentContext(chunkMeta); if (!context || this.state !== State.PARSING) { if (!this.fragCurrent) { this.state = State.IDLE; } return; } var frag = context.frag, part = context.part, level = context.level; var now = self.performance.now(); frag.stats.parsing.end = now; if (part) { part.stats.parsing.end = now; } this.updateLevelTiming(frag, part, level, chunkMeta.partial); }; _proto.getCurrentContext = function getCurrentContext(chunkMeta) { var levels = this.levels; var levelIndex = chunkMeta.level, sn = chunkMeta.sn, partIndex = chunkMeta.part; if (!levels || !levels[levelIndex]) { this.warn("Levels object was unset while buffering fragment " + sn + " of level " + levelIndex + ". The current chunk will not be buffered."); return null; } var level = levels[levelIndex]; var part = partIndex > -1 ? Object(_level_helper__WEBPACK_IMPORTED_MODULE_11__["getPartWith"])(level, sn, partIndex) : null; var frag = part ? part.fragment : Object(_level_helper__WEBPACK_IMPORTED_MODULE_11__["getFragmentWithSN"])(level, sn, this.fragCurrent); if (!frag) { return null; } return { frag: frag, part: part, level: level }; }; _proto.bufferFragmentData = function bufferFragmentData(data, frag, part, chunkMeta) { if (!data || this.state !== State.PARSING) { return; } var data1 = data.data1, data2 = data.data2; var buffer = data1; if (data1 && data2) { // Combine the moof + mdat so that we buffer with a single append buffer = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_8__["appendUint8Array"])(data1, data2); } if (!buffer || !buffer.length) { return; } var segment = { type: data.type, frag: frag, part: part, chunkMeta: chunkMeta, parent: frag.type, data: buffer }; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].BUFFER_APPENDING, segment); if (data.dropped && data.independent && !part) { // Clear buffer so that we reload previous segments sequentially if required this.flushBufferGap(frag); } }; _proto.flushBufferGap = function flushBufferGap(frag) { var media = this.media; if (!media) { return; } // If currentTime is not buffered, clear the back buffer so that we can backtrack as much as needed if (!_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].isBuffered(media, media.currentTime)) { this.flushMainBuffer(0, frag.start); return; } // Remove back-buffer without interrupting playback to allow back tracking var currentTime = media.currentTime; var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(media, currentTime, 0); var fragDuration = frag.duration; var segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25); var start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction); if (frag.start - start > segmentFraction) { this.flushMainBuffer(start, frag.start); } }; _proto.getFwdBufferInfo = function getFwdBufferInfo(bufferable, type) { var config = this.config; var pos = this.getLoadPosition(); if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(pos)) { return null; } var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(bufferable, pos, config.maxBufferHole); // Workaround flaw in getting forward buffer when maxBufferHole is smaller than gap at current pos if (bufferInfo.len === 0 && bufferInfo.nextStart !== undefined) { var bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type); if (bufferedFragAtPos && bufferInfo.nextStart < bufferedFragAtPos.end) { return _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(bufferable, pos, Math.max(bufferInfo.nextStart, config.maxBufferHole)); } } return bufferInfo; }; _proto.getMaxBufferLength = function getMaxBufferLength(levelBitrate) { var config = this.config; var maxBufLen; if (levelBitrate) { maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength); } else { maxBufLen = config.maxBufferLength; } return Math.min(maxBufLen, config.maxMaxBufferLength); }; _proto.reduceMaxBufferLength = function reduceMaxBufferLength(threshold) { var config = this.config; var minLength = threshold || config.maxBufferLength; if (config.maxMaxBufferLength >= minLength) { // reduce max buffer length as it might be too high. we do this to avoid loop flushing ... config.maxMaxBufferLength /= 2; this.warn("Reduce max buffer length to " + config.maxMaxBufferLength + "s"); return true; } return false; }; _proto.getNextFragment = function getNextFragment(pos, levelDetails) { var _frag, _frag2; var fragments = levelDetails.fragments; var fragLen = fragments.length; if (!fragLen) { return null; } // find fragment index, contiguous with end of buffer position var config = this.config; var start = fragments[0].start; var frag; if (levelDetails.live) { var initialLiveManifestSize = config.initialLiveManifestSize; if (fragLen < initialLiveManifestSize) { this.warn("Not enough fragments to start playback (have: " + fragLen + ", need: " + initialLiveManifestSize + ")"); return null; } // The real fragment start times for a live stream are only known after the PTS range for that level is known. // In order to discover the range, we load the best matching fragment for that level and demux it. // Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that // we get the fragment matching that start time if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1) { frag = this.getInitialLiveFragment(levelDetails, fragments); this.startPosition = frag ? this.hls.liveSyncPosition || frag.start : pos; } } else if (pos <= start) { // VoD playlist: if loadPosition before start of playlist, load first fragment frag = fragments[0]; } // If we haven't run into any special cases already, just load the fragment most closely matching the requested position if (!frag) { var end = config.lowLatencyMode ? levelDetails.partEnd : levelDetails.fragmentEnd; frag = this.getFragmentAtPosition(pos, end, levelDetails); } // If an initSegment is present, it must be buffered first if ((_frag = frag) !== null && _frag !== void 0 && _frag.initSegment && !((_frag2 = frag) !== null && _frag2 !== void 0 && _frag2.initSegment.data) && !this.bitrateTest) { frag = frag.initSegment; } return frag; }; _proto.getNextPart = function getNextPart(partList, frag, targetBufferTime) { var nextPart = -1; var contiguous = false; var independentAttrOmitted = true; for (var i = 0, len = partList.length; i < len; i++) { var part = partList[i]; independentAttrOmitted = independentAttrOmitted && !part.independent; if (nextPart > -1 && targetBufferTime < part.start) { break; } var loaded = part.loaded; if (!loaded && (contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) { nextPart = i; } contiguous = loaded; } return nextPart; }; _proto.loadedEndOfParts = function loadedEndOfParts(partList, targetBufferTime) { var lastPart = partList[partList.length - 1]; return lastPart && targetBufferTime > lastPart.start && lastPart.loaded; } /* This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the "sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real start and end times for each fragment in the playlist (after which this method will not need to be called). */ ; _proto.getInitialLiveFragment = function getInitialLiveFragment(levelDetails, fragments) { var fragPrevious = this.fragPrevious; var frag = null; if (fragPrevious) { if (levelDetails.hasProgramDateTime) { // Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding this.log("Live playlist, switching playlist, load frag with same PDT: " + fragPrevious.programDateTime); frag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_10__["findFragmentByPDT"])(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance); } if (!frag) { // SN does not need to be accurate between renditions, but depending on the packaging it may be so. var targetSN = fragPrevious.sn + 1; if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) { var fragNext = fragments[targetSN - levelDetails.startSN]; // Ensure that we're staying within the continuity range, since PTS resets upon a new range if (fragPrevious.cc === fragNext.cc) { frag = fragNext; this.log("Live playlist, switching playlist, load frag with next SN: " + frag.sn); } } // It's important to stay within the continuity range if available; otherwise the fragments in the playlist // will have the wrong start times if (!frag) { frag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_10__["findFragWithCC"])(fragments, fragPrevious.cc); if (frag) { this.log("Live playlist, switching playlist, load frag with same CC: " + frag.sn); } } } } else { // Find a new start fragment when fragPrevious is null var liveStart = this.hls.liveSyncPosition; if (liveStart !== null) { frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails); } } return frag; } /* This method finds the best matching fragment given the provided position. */ ; _proto.getFragmentAtPosition = function getFragmentAtPosition(bufferEnd, end, levelDetails) { var config = this.config, fragPrevious = this.fragPrevious; var fragments = levelDetails.fragments, endSN = levelDetails.endSN; var fragmentHint = levelDetails.fragmentHint; var tolerance = config.maxFragLookUpTolerance; var loadingParts = !!(config.lowLatencyMode && levelDetails.partList && fragmentHint); if (loadingParts && fragmentHint && !this.bitrateTest) { // Include incomplete fragment with parts at end fragments = fragments.concat(fragmentHint); endSN = fragmentHint.sn; } var frag; if (bufferEnd < end) { var lookupTolerance = bufferEnd > end - tolerance ? 0 : tolerance; // Remove the tolerance if it would put the bufferEnd past the actual end of stream // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE) frag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_10__["findFragmentByPTS"])(fragPrevious, fragments, bufferEnd, lookupTolerance); } else { // reach end of playlist frag = fragments[fragments.length - 1]; } if (frag) { var curSNIdx = frag.sn - levelDetails.startSN; var sameLevel = fragPrevious && frag.level === fragPrevious.level; var nextFrag = fragments[curSNIdx + 1]; var fragState = this.fragmentTracker.getState(frag); if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].BACKTRACKED) { frag = null; var i = curSNIdx; while (fragments[i] && this.fragmentTracker.getState(fragments[i]) === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].BACKTRACKED) { // When fragPrevious is null, backtrack to first the first fragment is not BACKTRACKED for loading // When fragPrevious is set, we want the first BACKTRACKED fragment for parsing and buffering if (!fragPrevious) { frag = fragments[--i]; } else { frag = fragments[i--]; } } if (!frag) { frag = nextFrag; } } else if (fragPrevious && frag.sn === fragPrevious.sn && !loadingParts) { // Force the next fragment to load if the previous one was already selected. This can occasionally happen with // non-uniform fragment durations if (sameLevel) { if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].OK) { this.log("SN " + frag.sn + " just loaded, load next one: " + nextFrag.sn); frag = nextFrag; } else { frag = null; } } } } return frag; }; _proto.synchronizeToLiveEdge = function synchronizeToLiveEdge(levelDetails) { var config = this.config, media = this.media; if (!media) { return; } var liveSyncPosition = this.hls.liveSyncPosition; var currentTime = media.currentTime; var start = levelDetails.fragments[0].start; var end = levelDetails.edge; var withinSlidingWindow = currentTime >= start - config.maxFragLookUpTolerance && currentTime <= end; // Continue if we can seek forward to sync position or if current time is outside of sliding window if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) { // Continue if buffer is starving or if current time is behind max latency var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration; if (!withinSlidingWindow && media.readyState < 4 || currentTime < end - maxLatency) { if (!this.loadedmetadata) { this.nextLoadPosition = liveSyncPosition; } // Only seek if ready and there is not a significant forward buffer available for playback if (media.readyState) { this.warn("Playback: " + currentTime.toFixed(3) + " is located too far from the end of live sliding playlist: " + end + ", reset currentTime to : " + liveSyncPosition.toFixed(3)); media.currentTime = liveSyncPosition; } } } }; _proto.alignPlaylists = function alignPlaylists(details, previousDetails) { var levels = this.levels, levelLastLoaded = this.levelLastLoaded, fragPrevious = this.fragPrevious; var lastLevel = levelLastLoaded !== null ? levels[levelLastLoaded] : null; // FIXME: If not for `shouldAlignOnDiscontinuities` requiring fragPrevious.cc, // this could all go in level-helper mergeDetails() var length = details.fragments.length; if (!length) { this.warn("No fragments in live playlist"); return 0; } var slidingStart = details.fragments[0].start; var firstLevelLoad = !previousDetails; var aligned = details.alignedSliding && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(slidingStart); if (firstLevelLoad || !aligned && !slidingStart) { Object(_utils_discontinuities__WEBPACK_IMPORTED_MODULE_9__["alignStream"])(fragPrevious, lastLevel, details); var alignedSlidingStart = details.fragments[0].start; this.log("Live playlist sliding: " + alignedSlidingStart.toFixed(2) + " start-sn: " + (previousDetails ? previousDetails.startSN : 'na') + "->" + details.startSN + " prev-sn: " + (fragPrevious ? fragPrevious.sn : 'na') + " fragments: " + length); return alignedSlidingStart; } return slidingStart; }; _proto.waitForCdnTuneIn = function waitForCdnTuneIn(details) { // Wait for Low-Latency CDN Tune-in to get an updated playlist var advancePartLimit = 3; return details.live && details.canBlockReload && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit); }; _proto.setStartPosition = function setStartPosition(details, sliding) { // compute start position if set to -1. use it straight away if value is defined var startPosition = this.startPosition; if (startPosition < sliding) { startPosition = -1; } if (startPosition === -1 || this.lastCurrentTime === -1) { // first, check if start time offset has been set in playlist, if yes, use this value var startTimeOffset = details.startTimeOffset; if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(startTimeOffset)) { startPosition = sliding + startTimeOffset; if (startTimeOffset < 0) { startPosition += details.totalduration; } startPosition = Math.min(Math.max(sliding, startPosition), sliding + details.totalduration); this.log("Start time offset " + startTimeOffset + " found in playlist, adjust startPosition to " + startPosition); this.startPosition = startPosition; } else if (details.live) { // Leave this.startPosition at -1, so that we can use `getInitialLiveFragment` logic when startPosition has // not been specified via the config or an as an argument to startLoad (#3736). startPosition = this.hls.liveSyncPosition || sliding; } else { this.startPosition = startPosition = 0; } this.lastCurrentTime = startPosition; } this.nextLoadPosition = startPosition; }; _proto.getLoadPosition = function getLoadPosition() { var media = this.media; // if we have not yet loaded any fragment, start loading from start position var pos = 0; if (this.loadedmetadata && media) { pos = media.currentTime; } else if (this.nextLoadPosition) { pos = this.nextLoadPosition; } return pos; }; _proto.handleFragLoadAborted = function handleFragLoadAborted(frag, part) { if (this.transmuxer && frag.sn !== 'initSegment' && frag.stats.aborted) { this.warn("Fragment " + frag.sn + (part ? ' part' + part.index : '') + " of level " + frag.level + " was aborted"); this.resetFragmentLoading(frag); } }; _proto.resetFragmentLoading = function resetFragmentLoading(frag) { if (!this.fragCurrent || !this.fragContextChanged(frag)) { this.state = State.IDLE; } }; _proto.onFragmentOrKeyLoadError = function onFragmentOrKeyLoadError(filterType, data) { if (data.fatal) { return; } var frag = data.frag; // Handle frag error related to caller's filterType if (!frag || frag.type !== filterType) { return; } var fragCurrent = this.fragCurrent; console.assert(fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level && frag.urlId === fragCurrent.urlId, 'Frag load error must match current frag to retry'); var config = this.config; // keep retrying until the limit will be reached if (this.fragLoadError + 1 <= config.fragLoadingMaxRetry) { if (this.resetLiveStartWhenNotLoaded(frag.level)) { return; } // exponential backoff capped to config.fragLoadingMaxRetryTimeout var delay = Math.min(Math.pow(2, this.fragLoadError) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout); this.warn("Fragment " + frag.sn + " of " + filterType + " " + frag.level + " failed to load, retrying in " + delay + "ms"); this.retryDate = self.performance.now() + delay; this.fragLoadError++; this.state = State.FRAG_LOADING_WAITING_RETRY; } else if (data.levelRetry) { if (filterType === _types_loader__WEBPACK_IMPORTED_MODULE_15__["PlaylistLevelType"].AUDIO) { // Reset current fragment since audio track audio is essential and may not have a fail-over track this.fragCurrent = null; } // Fragment errors that result in a level switch or redundant fail-over // should reset the stream controller state to idle this.fragLoadError = 0; this.state = State.IDLE; } else { _utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"].error(data.details + " reaches max retry, redispatch as fatal ..."); // switch error to fatal data.fatal = true; this.hls.stopLoad(); this.state = State.ERROR; } }; _proto.afterBufferFlushed = function afterBufferFlushed(media, bufferType, playlistType) { if (!media) { return; } // After successful buffer flushing, filter flushed fragments from bufferedFrags use mediaBuffered instead of media // (so that we will check against video.buffered ranges in case of alt audio track) var bufferedTimeRanges = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].getBuffered(media); this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType); if (this.state === State.ENDED) { this.resetLoadingState(); } }; _proto.resetLoadingState = function resetLoadingState() { this.fragCurrent = null; this.fragPrevious = null; this.state = State.IDLE; }; _proto.resetLiveStartWhenNotLoaded = function resetLiveStartWhenNotLoaded(level) { // if loadedmetadata is not set, it means that we are emergency switch down on first frag // in that case, reset startFragRequested flag if (!this.loadedmetadata) { this.startFragRequested = false; var details = this.levels ? this.levels[level].details : null; if (details !== null && details !== void 0 && details.live) { // We can't afford to retry after a delay in a live scenario. Update the start position and return to IDLE. this.startPosition = -1; this.setStartPosition(details, 0); this.resetLoadingState(); return true; } this.nextLoadPosition = this.startPosition; } return false; }; _proto.updateLevelTiming = function updateLevelTiming(frag, part, level, partial) { var _this6 = this; var details = level.details; console.assert(!!details, 'level.details must be defined'); var parsed = Object.keys(frag.elementaryStreams).reduce(function (result, type) { var info = frag.elementaryStreams[type]; if (info) { var parsedDuration = info.endPTS - info.startPTS; if (parsedDuration <= 0) { // Destroy the transmuxer after it's next time offset failed to advance because duration was <= 0. // The new transmuxer will be configured with a time offset matching the next fragment start, // preventing the timeline from shifting. _this6.warn("Could not parse fragment " + frag.sn + " " + type + " duration reliably (" + parsedDuration + ") resetting transmuxer to fallback to playlist timing"); _this6.resetTransmuxer(); return result || false; } var drift = partial ? 0 : Object(_level_helper__WEBPACK_IMPORTED_MODULE_11__["updateFragPTSDTS"])(details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS); _this6.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].LEVEL_PTS_UPDATED, { details: details, level: level, drift: drift, type: type, frag: frag, start: info.startPTS, end: info.endPTS }); return true; } return result; }, false); if (parsed) { this.state = State.PARSED; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_PARSED, { frag: frag, part: part }); } else { this.resetLoadingState(); } }; _proto.resetTransmuxer = function resetTransmuxer() { if (this.transmuxer) { this.transmuxer.destroy(); this.transmuxer = null; } }; _createClass(BaseStreamController, [{ key: "state", get: function get() { return this._state; }, set: function set(nextState) { var previousState = this._state; if (previousState !== nextState) { this._state = nextState; this.log(previousState + "->" + nextState); } } }]); return BaseStreamController; }(_task_loop__WEBPACK_IMPORTED_MODULE_1__["default"]); /***/ }), /***/ "./src/controller/buffer-controller.ts": /*!*********************************************!*\ !*** ./src/controller/buffer-controller.ts ***! \*********************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BufferController; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts"); /* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/mediasource-helper */ "./src/utils/mediasource-helper.ts"); /* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts"); /* harmony import */ var _buffer_operation_queue__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./buffer-operation-queue */ "./src/controller/buffer-operation-queue.ts"); var MediaSource = Object(_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__["getMediaSource"])(); var VIDEO_CODEC_PROFILE_REPACE = /([ha]vc.)(?:\.[^.,]+)+/; var BufferController = /*#__PURE__*/function () { // The level details used to determine duration, target-duration and live // cache the self generated object url to detect hijack of video tag // A queue of buffer operations which require the SourceBuffer to not be updating upon execution // References to event listeners for each SourceBuffer, so that they can be referenced for event removal // The number of BUFFER_CODEC events received before any sourceBuffers are created // The total number of BUFFER_CODEC events received // A reference to the attached media element // A reference to the active media source // counters function BufferController(_hls) { var _this = this; this.details = null; this._objectUrl = null; this.operationQueue = void 0; this.listeners = void 0; this.hls = void 0; this.bufferCodecEventsExpected = 0; this._bufferCodecEventsTotal = 0; this.media = null; this.mediaSource = null; this.appendError = 0; this.tracks = {}; this.pendingTracks = {}; this.sourceBuffer = void 0; this._onMediaSourceOpen = function () { var hls = _this.hls, media = _this.media, mediaSource = _this.mediaSource; _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media source opened'); if (media) { _this.updateMediaElementDuration(); hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHED, { media: media }); } if (mediaSource) { // once received, don't listen anymore to sourceopen event mediaSource.removeEventListener('sourceopen', _this._onMediaSourceOpen); } _this.checkPendingTracks(); }; this._onMediaSourceClose = function () { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media source closed'); }; this._onMediaSourceEnded = function () { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media source ended'); }; this.hls = _hls; this._initSourceBuffer(); this.registerListeners(); } var _proto = BufferController.prototype; _proto.hasSourceTypes = function hasSourceTypes() { return this.getSourceBufferTypes().length > 0 || Object.keys(this.pendingTracks).length > 0; }; _proto.destroy = function destroy() { this.unregisterListeners(); this.details = null; }; _proto.registerListeners = function registerListeners() { var hls = this.hls; hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_PARSED, this.onManifestParsed, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_RESET, this.onBufferReset, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_APPENDING, this.onBufferAppending, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_CODECS, this.onBufferCodecs, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_EOS, this.onBufferEos, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_PARSED, this.onFragParsed, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_CHANGED, this.onFragChanged, this); }; _proto.unregisterListeners = function unregisterListeners() { var hls = this.hls; hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_PARSED, this.onManifestParsed, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_RESET, this.onBufferReset, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_APPENDING, this.onBufferAppending, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_CODECS, this.onBufferCodecs, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_EOS, this.onBufferEos, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_PARSED, this.onFragParsed, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_CHANGED, this.onFragChanged, this); }; _proto._initSourceBuffer = function _initSourceBuffer() { this.sourceBuffer = {}; this.operationQueue = new _buffer_operation_queue__WEBPACK_IMPORTED_MODULE_7__["default"](this.sourceBuffer); this.listeners = { audio: [], video: [], audiovideo: [] }; }; _proto.onManifestParsed = function onManifestParsed(event, data) { // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller // sourcebuffers will be created all at once when the expected nb of tracks will be reached // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller // it will contain the expected nb of source buffers, no need to compute it var codecEvents = 2; if (data.audio && !data.video || !data.altAudio) { codecEvents = 1; } this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents; this.details = null; _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log(this.bufferCodecEventsExpected + " bufferCodec event(s) expected"); }; _proto.onMediaAttaching = function onMediaAttaching(event, data) { var media = this.media = data.media; if (media && MediaSource) { var ms = this.mediaSource = new MediaSource(); // MediaSource listeners are arrow functions with a lexical scope, and do not need to be bound ms.addEventListener('sourceopen', this._onMediaSourceOpen); ms.addEventListener('sourceended', this._onMediaSourceEnded); ms.addEventListener('sourceclose', this._onMediaSourceClose); // link video and media Source media.src = self.URL.createObjectURL(ms); // cache the locally generated object url this._objectUrl = media.src; } }; _proto.onMediaDetaching = function onMediaDetaching() { var media = this.media, mediaSource = this.mediaSource, _objectUrl = this._objectUrl; if (mediaSource) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: media source detaching'); if (mediaSource.readyState === 'open') { try { // endOfStream could trigger exception if any sourcebuffer is in updating state // we don't really care about checking sourcebuffer state here, // as we are anyway detaching the MediaSource // let's just avoid this exception to propagate mediaSource.endOfStream(); } catch (err) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: onMediaDetaching: " + err.message + " while calling endOfStream"); } } // Clean up the SourceBuffers by invoking onBufferReset this.onBufferReset(); mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen); mediaSource.removeEventListener('sourceended', this._onMediaSourceEnded); mediaSource.removeEventListener('sourceclose', this._onMediaSourceClose); // Detach properly the MediaSource from the HTMLMediaElement as // suggested in https://github.com/w3c/media-source/issues/53. if (media) { if (_objectUrl) { self.URL.revokeObjectURL(_objectUrl); } // clean up video tag src only if it's our own url. some external libraries might // hijack the video tag and change its 'src' without destroying the Hls instance first if (media.src === _objectUrl) { media.removeAttribute('src'); media.load(); } else { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('[buffer-controller]: media.src was changed by a third party - skip cleanup'); } } this.mediaSource = null; this.media = null; this._objectUrl = null; this.bufferCodecEventsExpected = this._bufferCodecEventsTotal; this.pendingTracks = {}; this.tracks = {}; } this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHED, undefined); }; _proto.onBufferReset = function onBufferReset() { var _this2 = this; this.getSourceBufferTypes().forEach(function (type) { var sb = _this2.sourceBuffer[type]; try { if (sb) { _this2.removeBufferListeners(type); if (_this2.mediaSource) { _this2.mediaSource.removeSourceBuffer(sb); } // Synchronously remove the SB from the map before the next call in order to prevent an async function from // accessing it _this2.sourceBuffer[type] = undefined; } } catch (err) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Failed to reset the " + type + " buffer", err); } }); this._initSourceBuffer(); }; _proto.onBufferCodecs = function onBufferCodecs(event, data) { var _this3 = this; var sourceBufferCount = this.getSourceBufferTypes().length; Object.keys(data).forEach(function (trackName) { if (sourceBufferCount) { // check if SourceBuffer codec needs to change var track = _this3.tracks[trackName]; if (track && typeof track.buffer.changeType === 'function') { var _data$trackName = data[trackName], codec = _data$trackName.codec, levelCodec = _data$trackName.levelCodec, container = _data$trackName.container; var currentCodec = (track.levelCodec || track.codec).replace(VIDEO_CODEC_PROFILE_REPACE, '$1'); var nextCodec = (levelCodec || codec).replace(VIDEO_CODEC_PROFILE_REPACE, '$1'); if (currentCodec !== nextCodec) { var mimeType = container + ";codecs=" + (levelCodec || codec); _this3.appendChangeType(trackName, mimeType); } } } else { // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks _this3.pendingTracks[trackName] = data[trackName]; } }); // if sourcebuffers already created, do nothing ... if (sourceBufferCount) { return; } this.bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0); if (this.mediaSource && this.mediaSource.readyState === 'open') { this.checkPendingTracks(); } }; _proto.appendChangeType = function appendChangeType(type, mimeType) { var _this4 = this; var operationQueue = this.operationQueue; var operation = { execute: function execute() { var sb = _this4.sourceBuffer[type]; if (sb) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: changing " + type + " sourceBuffer type to " + mimeType); sb.changeType(mimeType); } operationQueue.shiftAndExecuteNext(type); }, onStart: function onStart() {}, onComplete: function onComplete() {}, onError: function onError(e) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Failed to change " + type + " SourceBuffer type", e); } }; operationQueue.append(operation, type); }; _proto.onBufferAppending = function onBufferAppending(event, eventData) { var _this5 = this; var hls = this.hls, operationQueue = this.operationQueue, tracks = this.tracks; var data = eventData.data, type = eventData.type, frag = eventData.frag, part = eventData.part, chunkMeta = eventData.chunkMeta; var chunkStats = chunkMeta.buffering[type]; var bufferAppendingStart = self.performance.now(); chunkStats.start = bufferAppendingStart; var fragBuffering = frag.stats.buffering; var partBuffering = part ? part.stats.buffering : null; if (fragBuffering.start === 0) { fragBuffering.start = bufferAppendingStart; } if (partBuffering && partBuffering.start === 0) { partBuffering.start = bufferAppendingStart; } // TODO: Only update timestampOffset when audio/mpeg fragment or part is not contiguous with previously appended // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended) // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset` // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos). // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486 var audioTrack = tracks.audio; var checkTimestampOffset = type === 'audio' && chunkMeta.id === 1 && (audioTrack === null || audioTrack === void 0 ? void 0 : audioTrack.container) === 'audio/mpeg'; var operation = { execute: function execute() { chunkStats.executeStart = self.performance.now(); if (checkTimestampOffset) { var sb = _this5.sourceBuffer[type]; if (sb) { var delta = frag.start - sb.timestampOffset; if (Math.abs(delta) >= 0.1) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: Updating audio SourceBuffer timestampOffset to " + frag.start + " (delta: " + delta + ") sn: " + frag.sn + ")"); sb.timestampOffset = frag.start; } } } _this5.appendExecutor(data, type); }, onStart: function onStart() {// logger.debug(`[buffer-controller]: ${type} SourceBuffer updatestart`); }, onComplete: function onComplete() { // logger.debug(`[buffer-controller]: ${type} SourceBuffer updateend`); var end = self.performance.now(); chunkStats.executeEnd = chunkStats.end = end; if (fragBuffering.first === 0) { fragBuffering.first = end; } if (partBuffering && partBuffering.first === 0) { partBuffering.first = end; } var sourceBuffer = _this5.sourceBuffer; var timeRanges = {}; for (var _type in sourceBuffer) { timeRanges[_type] = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(sourceBuffer[_type]); } _this5.appendError = 0; _this5.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_APPENDED, { type: type, frag: frag, part: part, chunkMeta: chunkMeta, parent: frag.type, timeRanges: timeRanges }); }, onError: function onError(err) { // in case any error occured while appending, put back segment in segments table _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: Error encountered while trying to append to the " + type + " SourceBuffer", err); var event = { type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR, parent: frag.type, details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_APPEND_ERROR, err: err, fatal: false }; if (err.code === DOMException.QUOTA_EXCEEDED_ERR) { // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror // let's stop appending any segments, and report BUFFER_FULL_ERROR error event.details = _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_FULL_ERROR; } else { _this5.appendError++; event.details = _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_APPEND_ERROR; /* with UHD content, we could get loop of quota exceeded error until browser is able to evict some data from sourcebuffer. Retrying can help recover. */ if (_this5.appendError > hls.config.appendErrorMaxRetry) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: Failed " + hls.config.appendErrorMaxRetry + " times to append segment in sourceBuffer"); event.fatal = true; } } hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, event); } }; operationQueue.append(operation, type); }; _proto.onBufferFlushing = function onBufferFlushing(event, data) { var _this6 = this; var operationQueue = this.operationQueue; var flushOperation = function flushOperation(type) { return { execute: _this6.removeExecutor.bind(_this6, type, data.startOffset, data.endOffset), onStart: function onStart() {// logger.debug(`[buffer-controller]: Started flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`); }, onComplete: function onComplete() { // logger.debug(`[buffer-controller]: Finished flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`); _this6.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHED, { type: type }); }, onError: function onError(e) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Failed to remove from " + type + " SourceBuffer", e); } }; }; if (data.type) { operationQueue.append(flushOperation(data.type), data.type); } else { this.getSourceBufferTypes().forEach(function (type) { operationQueue.append(flushOperation(type), type); }); } }; _proto.onFragParsed = function onFragParsed(event, data) { var _this7 = this; var frag = data.frag, part = data.part; var buffersAppendedTo = []; var elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams; if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__["ElementaryStreamTypes"].AUDIOVIDEO]) { buffersAppendedTo.push('audiovideo'); } else { if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__["ElementaryStreamTypes"].AUDIO]) { buffersAppendedTo.push('audio'); } if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__["ElementaryStreamTypes"].VIDEO]) { buffersAppendedTo.push('video'); } } var onUnblocked = function onUnblocked() { var now = self.performance.now(); frag.stats.buffering.end = now; if (part) { part.stats.buffering.end = now; } var stats = part ? part.stats : frag.stats; _this7.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_BUFFERED, { frag: frag, part: part, stats: stats, id: frag.type }); }; if (buffersAppendedTo.length === 0) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("Fragments must have at least one ElementaryStreamType set. type: " + frag.type + " level: " + frag.level + " sn: " + frag.sn); } this.blockBuffers(onUnblocked, buffersAppendedTo); }; _proto.onFragChanged = function onFragChanged(event, data) { this.flushBackBuffer(); } // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos() // an undefined data.type will mark all buffers as EOS. ; _proto.onBufferEos = function onBufferEos(event, data) { var _this8 = this; var ended = this.getSourceBufferTypes().reduce(function (acc, type) { var sb = _this8.sourceBuffer[type]; if (!data.type || data.type === type) { if (sb && !sb.ended) { sb.ended = true; _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: " + type + " sourceBuffer now EOS"); } } return acc && !!(!sb || sb.ended); }, true); if (ended) { this.blockBuffers(function () { var mediaSource = _this8.mediaSource; if (!mediaSource || mediaSource.readyState !== 'open') { return; } // Allow this to throw and be caught by the enqueueing function mediaSource.endOfStream(); }); } }; _proto.onLevelUpdated = function onLevelUpdated(event, _ref) { var details = _ref.details; if (!details.fragments.length) { return; } this.details = details; if (this.getSourceBufferTypes().length) { this.blockBuffers(this.updateMediaElementDuration.bind(this)); } else { this.updateMediaElementDuration(); } }; _proto.flushBackBuffer = function flushBackBuffer() { var hls = this.hls, details = this.details, media = this.media, sourceBuffer = this.sourceBuffer; if (!media || details === null) { return; } var sourceBufferTypes = this.getSourceBufferTypes(); if (!sourceBufferTypes.length) { return; } // Support for deprecated liveBackBufferLength var backBufferLength = details.live && hls.config.liveBackBufferLength !== null ? hls.config.liveBackBufferLength : hls.config.backBufferLength; if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(backBufferLength) || backBufferLength < 0) { return; } var currentTime = media.currentTime; var targetDuration = details.levelTargetDuration; var maxBackBufferLength = Math.max(backBufferLength, targetDuration); var targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength; sourceBufferTypes.forEach(function (type) { var sb = sourceBuffer[type]; if (sb) { var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(sb); // when target buffer start exceeds actual buffer start if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) { hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BACK_BUFFER_REACHED, { bufferEnd: targetBackBufferPosition }); // Support for deprecated event: if (details.live) { hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LIVE_BACK_BUFFER_REACHED, { bufferEnd: targetBackBufferPosition }); } hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, { startOffset: 0, endOffset: targetBackBufferPosition, type: type }); } } }); } /** * Update Media Source duration to current level duration or override to Infinity if configuration parameter * 'liveDurationInfinity` is set to `true` * More details: https://github.com/video-dev/hls.js/issues/355 */ ; _proto.updateMediaElementDuration = function updateMediaElementDuration() { if (!this.details || !this.media || !this.mediaSource || this.mediaSource.readyState !== 'open') { return; } var details = this.details, hls = this.hls, media = this.media, mediaSource = this.mediaSource; var levelDuration = details.fragments[0].start + details.totalduration; var mediaDuration = media.duration; var msDuration = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mediaSource.duration) ? mediaSource.duration : 0; if (details.live && hls.config.liveDurationInfinity) { // Override duration to Infinity _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media Source duration is set to Infinity'); mediaSource.duration = Infinity; this.updateSeekableRange(details); } else if (levelDuration > msDuration && levelDuration > mediaDuration || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mediaDuration)) { // levelDuration was the last value we set. // not using mediaSource.duration as the browser may tweak this value // only update Media Source duration if its value increase, this is to avoid // flushing already buffered portion when switching between quality level _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: Updating Media Source duration to " + levelDuration.toFixed(3)); mediaSource.duration = levelDuration; } }; _proto.updateSeekableRange = function updateSeekableRange(levelDetails) { var mediaSource = this.mediaSource; var fragments = levelDetails.fragments; var len = fragments.length; if (len && levelDetails.live && mediaSource !== null && mediaSource !== void 0 && mediaSource.setLiveSeekableRange) { var start = Math.max(0, fragments[0].start); var end = Math.max(start, start + levelDetails.totalduration); mediaSource.setLiveSeekableRange(start, end); } }; _proto.checkPendingTracks = function checkPendingTracks() { var bufferCodecEventsExpected = this.bufferCodecEventsExpected, operationQueue = this.operationQueue, pendingTracks = this.pendingTracks; // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once. // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after // data has been appended to existing ones. // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers. var pendingTracksCount = Object.keys(pendingTracks).length; if (pendingTracksCount && !bufferCodecEventsExpected || pendingTracksCount === 2) { // ok, let's create them now ! this.createSourceBuffers(pendingTracks); this.pendingTracks = {}; // append any pending segments now ! var buffers = this.getSourceBufferTypes(); if (buffers.length === 0) { this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_INCOMPATIBLE_CODECS_ERROR, fatal: true, reason: 'could not create source buffer for media codec(s)' }); return; } buffers.forEach(function (type) { operationQueue.executeNext(type); }); } }; _proto.createSourceBuffers = function createSourceBuffers(tracks) { var sourceBuffer = this.sourceBuffer, mediaSource = this.mediaSource; if (!mediaSource) { throw Error('createSourceBuffers called when mediaSource was null'); } var tracksCreated = 0; for (var trackName in tracks) { if (!sourceBuffer[trackName]) { var track = tracks[trackName]; if (!track) { throw Error("source buffer exists for track " + trackName + ", however track does not"); } // use levelCodec as first priority var codec = track.levelCodec || track.codec; var mimeType = track.container + ";codecs=" + codec; _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: creating sourceBuffer(" + mimeType + ")"); try { var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType); var sbName = trackName; this.addBufferListener(sbName, 'updatestart', this._onSBUpdateStart); this.addBufferListener(sbName, 'updateend', this._onSBUpdateEnd); this.addBufferListener(sbName, 'error', this._onSBUpdateError); this.tracks[trackName] = { buffer: sb, codec: codec, container: track.container, levelCodec: track.levelCodec, id: track.id }; tracksCreated++; } catch (err) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: error while trying to add sourceBuffer: " + err.message); this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_ADD_CODEC_ERROR, fatal: false, error: err, mimeType: mimeType }); } } } if (tracksCreated) { this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_CREATED, { tracks: this.tracks }); } } // Keep as arrow functions so that we can directly reference these functions directly as event listeners ; _proto._onSBUpdateStart = function _onSBUpdateStart(type) { var operationQueue = this.operationQueue; var operation = operationQueue.current(type); operation.onStart(); }; _proto._onSBUpdateEnd = function _onSBUpdateEnd(type) { var operationQueue = this.operationQueue; var operation = operationQueue.current(type); operation.onComplete(); operationQueue.shiftAndExecuteNext(type); }; _proto._onSBUpdateError = function _onSBUpdateError(type, event) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: " + type + " SourceBuffer error", event); // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error // SourceBuffer errors are not necessarily fatal; if so, the HTMLMediaElement will fire an error event this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_APPENDING_ERROR, fatal: false }); // updateend is always fired after error, so we'll allow that to shift the current operation off of the queue var operation = this.operationQueue.current(type); if (operation) { operation.onError(event); } } // This method must result in an updateend event; if remove is not called, _onSBUpdateEnd must be called manually ; _proto.removeExecutor = function removeExecutor(type, startOffset, endOffset) { var media = this.media, mediaSource = this.mediaSource, operationQueue = this.operationQueue, sourceBuffer = this.sourceBuffer; var sb = sourceBuffer[type]; if (!media || !mediaSource || !sb) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Attempting to remove from the " + type + " SourceBuffer, but it does not exist"); operationQueue.shiftAndExecuteNext(type); return; } var mediaDuration = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(media.duration) ? media.duration : Infinity; var msDuration = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mediaSource.duration) ? mediaSource.duration : Infinity; var removeStart = Math.max(0, startOffset); var removeEnd = Math.min(endOffset, mediaDuration, msDuration); if (removeEnd > removeStart) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: Removing [" + removeStart + "," + removeEnd + "] from the " + type + " SourceBuffer"); console.assert(!sb.updating, type + " sourceBuffer must not be updating"); sb.remove(removeStart, removeEnd); } else { // Cycle the queue operationQueue.shiftAndExecuteNext(type); } } // This method must result in an updateend event; if append is not called, _onSBUpdateEnd must be called manually ; _proto.appendExecutor = function appendExecutor(data, type) { var operationQueue = this.operationQueue, sourceBuffer = this.sourceBuffer; var sb = sourceBuffer[type]; if (!sb) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Attempting to append to the " + type + " SourceBuffer, but it does not exist"); operationQueue.shiftAndExecuteNext(type); return; } sb.ended = false; console.assert(!sb.updating, type + " sourceBuffer must not be updating"); sb.appendBuffer(data); } // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue // upon completion, since we already do it here ; _proto.blockBuffers = function blockBuffers(onUnblocked, buffers) { var _this9 = this; if (buffers === void 0) { buffers = this.getSourceBufferTypes(); } if (!buffers.length) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Blocking operation requested, but no SourceBuffers exist'); Promise.resolve(onUnblocked); return; } var operationQueue = this.operationQueue; // logger.debug(`[buffer-controller]: Blocking ${buffers} SourceBuffer`); var blockingOperations = buffers.map(function (type) { return operationQueue.appendBlocker(type); }); Promise.all(blockingOperations).then(function () { // logger.debug(`[buffer-controller]: Blocking operation resolved; unblocking ${buffers} SourceBuffer`); onUnblocked(); buffers.forEach(function (type) { var sb = _this9.sourceBuffer[type]; // Only cycle the queue if the SB is not updating. There's a bug in Chrome which sets the SB updating flag to // true when changing the MediaSource duration (https://bugs.chromium.org/p/chromium/issues/detail?id=959359&can=2&q=mediasource%20duration) // While this is a workaround, it's probably useful to have around if (!sb || !sb.updating) { operationQueue.shiftAndExecuteNext(type); } }); }); }; _proto.getSourceBufferTypes = function getSourceBufferTypes() { return Object.keys(this.sourceBuffer); }; _proto.addBufferListener = function addBufferListener(type, event, fn) { var buffer = this.sourceBuffer[type]; if (!buffer) { return; } var listener = fn.bind(this, type); this.listeners[type].push({ event: event, listener: listener }); buffer.addEventListener(event, listener); }; _proto.removeBufferListeners = function removeBufferListeners(type) { var buffer = this.sourceBuffer[type]; if (!buffer) { return; } this.listeners[type].forEach(function (l) { buffer.removeEventListener(l.event, l.listener); }); }; return BufferController; }(); /***/ }), /***/ "./src/controller/buffer-operation-queue.ts": /*!**************************************************!*\ !*** ./src/controller/buffer-operation-queue.ts ***! \**************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BufferOperationQueue; }); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); var BufferOperationQueue = /*#__PURE__*/function () { function BufferOperationQueue(sourceBufferReference) { this.buffers = void 0; this.queues = { video: [], audio: [], audiovideo: [] }; this.buffers = sourceBufferReference; } var _proto = BufferOperationQueue.prototype; _proto.append = function append(operation, type) { var queue = this.queues[type]; queue.push(operation); if (queue.length === 1 && this.buffers[type]) { this.executeNext(type); } }; _proto.insertAbort = function insertAbort(operation, type) { var queue = this.queues[type]; queue.unshift(operation); this.executeNext(type); }; _proto.appendBlocker = function appendBlocker(type) { var execute; var promise = new Promise(function (resolve) { execute = resolve; }); var operation = { execute: execute, onStart: function onStart() {}, onComplete: function onComplete() {}, onError: function onError() {} }; this.append(operation, type); return promise; }; _proto.executeNext = function executeNext(type) { var buffers = this.buffers, queues = this.queues; var sb = buffers[type]; var queue = queues[type]; if (queue.length) { var operation = queue[0]; try { // Operations are expected to result in an 'updateend' event being fired. If not, the queue will lock. Operations // which do not end with this event must call _onSBUpdateEnd manually operation.execute(); } catch (e) { _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].warn('[buffer-operation-queue]: Unhandled exception executing the current operation'); operation.onError(e); // Only shift the current operation off, otherwise the updateend handler will do this for us if (!sb || !sb.updating) { queue.shift(); this.executeNext(type); } } } }; _proto.shiftAndExecuteNext = function shiftAndExecuteNext(type) { this.queues[type].shift(); this.executeNext(type); }; _proto.current = function current(type) { return this.queues[type][0]; }; return BufferOperationQueue; }(); /***/ }), /***/ "./src/controller/cap-level-controller.ts": /*!************************************************!*\ !*** ./src/controller/cap-level-controller.ts ***! \************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts"); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } /* * cap stream level to media size dimension controller */ var CapLevelController = /*#__PURE__*/function () { function CapLevelController(hls) { this.autoLevelCapping = void 0; this.firstLevel = void 0; this.media = void 0; this.restrictedLevels = void 0; this.timer = void 0; this.hls = void 0; this.streamController = void 0; this.clientRect = void 0; this.hls = hls; this.autoLevelCapping = Number.POSITIVE_INFINITY; this.firstLevel = -1; this.media = null; this.restrictedLevels = []; this.timer = undefined; this.clientRect = null; this.registerListeners(); } var _proto = CapLevelController.prototype; _proto.setStreamController = function setStreamController(streamController) { this.streamController = streamController; }; _proto.destroy = function destroy() { this.unregisterListener(); if (this.hls.config.capLevelToPlayerSize) { this.stopCapping(); } this.media = null; this.clientRect = null; // @ts-ignore this.hls = this.streamController = null; }; _proto.registerListeners = function registerListeners() { var hls = this.hls; hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_CODECS, this.onBufferCodecs, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); }; _proto.unregisterListener = function unregisterListener() { var hls = this.hls; hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_CODECS, this.onBufferCodecs, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); }; _proto.onFpsDropLevelCapping = function onFpsDropLevelCapping(event, data) { // Don't add a restricted level more than once if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) { this.restrictedLevels.push(data.droppedLevel); } }; _proto.onMediaAttaching = function onMediaAttaching(event, data) { this.media = data.media instanceof HTMLVideoElement ? data.media : null; }; _proto.onManifestParsed = function onManifestParsed(event, data) { var hls = this.hls; this.restrictedLevels = []; this.firstLevel = data.firstLevel; if (hls.config.capLevelToPlayerSize && data.video) { // Start capping immediately if the manifest has signaled video codecs this.startCapping(); } } // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted // to the first level ; _proto.onBufferCodecs = function onBufferCodecs(event, data) { var hls = this.hls; if (hls.config.capLevelToPlayerSize && data.video) { // If the manifest did not signal a video codec capping has been deferred until we're certain video is present this.startCapping(); } }; _proto.onMediaDetaching = function onMediaDetaching() { this.stopCapping(); }; _proto.detectPlayerSize = function detectPlayerSize() { if (this.media && this.mediaHeight > 0 && this.mediaWidth > 0) { var levels = this.hls.levels; if (levels.length) { var hls = this.hls; hls.autoLevelCapping = this.getMaxLevel(levels.length - 1); if (hls.autoLevelCapping > this.autoLevelCapping && this.streamController) { // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch // usually happen when the user go to the fullscreen mode. this.streamController.nextLevelSwitch(); } this.autoLevelCapping = hls.autoLevelCapping; } } } /* * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled) */ ; _proto.getMaxLevel = function getMaxLevel(capLevelIndex) { var _this = this; var levels = this.hls.levels; if (!levels.length) { return -1; } var validLevels = levels.filter(function (level, index) { return CapLevelController.isLevelAllowed(index, _this.restrictedLevels) && index <= capLevelIndex; }); this.clientRect = null; return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight); }; _proto.startCapping = function startCapping() { if (this.timer) { // Don't reset capping if started twice; this can happen if the manifest signals a video codec return; } this.autoLevelCapping = Number.POSITIVE_INFINITY; this.hls.firstLevel = this.getMaxLevel(this.firstLevel); self.clearInterval(this.timer); this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1000); this.detectPlayerSize(); }; _proto.stopCapping = function stopCapping() { this.restrictedLevels = []; this.firstLevel = -1; this.autoLevelCapping = Number.POSITIVE_INFINITY; if (this.timer) { self.clearInterval(this.timer); this.timer = undefined; } }; _proto.getDimensions = function getDimensions() { if (this.clientRect) { return this.clientRect; } var media = this.media; var boundsRect = { width: 0, height: 0 }; if (media) { var clientRect = media.getBoundingClientRect(); boundsRect.width = clientRect.width; boundsRect.height = clientRect.height; if (!boundsRect.width && !boundsRect.height) { // When the media element has no width or height (equivalent to not being in the DOM), // then use its width and height attributes (media.width, media.height) boundsRect.width = clientRect.right - clientRect.left || media.width || 0; boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0; } } this.clientRect = boundsRect; return boundsRect; }; CapLevelController.isLevelAllowed = function isLevelAllowed(level, restrictedLevels) { if (restrictedLevels === void 0) { restrictedLevels = []; } return restrictedLevels.indexOf(level) === -1; }; CapLevelController.getMaxLevelByMediaSize = function getMaxLevelByMediaSize(levels, width, height) { if (!levels || !levels.length) { return -1; } // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next // to determine whether we've chosen the greatest bandwidth for the media's dimensions var atGreatestBandiwdth = function atGreatestBandiwdth(curLevel, nextLevel) { if (!nextLevel) { return true; } return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height; }; // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to // the max level var maxLevelIndex = levels.length - 1; for (var i = 0; i < levels.length; i += 1) { var level = levels[i]; if ((level.width >= width || level.height >= height) && atGreatestBandiwdth(level, levels[i + 1])) { maxLevelIndex = i; break; } } return maxLevelIndex; }; _createClass(CapLevelController, [{ key: "mediaWidth", get: function get() { return this.getDimensions().width * CapLevelController.contentScaleFactor; } }, { key: "mediaHeight", get: function get() { return this.getDimensions().height * CapLevelController.contentScaleFactor; } }], [{ key: "contentScaleFactor", get: function get() { var pixelRatio = 1; try { pixelRatio = self.devicePixelRatio; } catch (e) { /* no-op */ } return pixelRatio; } }]); return CapLevelController; }(); /* harmony default export */ __webpack_exports__["default"] = (CapLevelController); /***/ }), /***/ "./src/controller/eme-controller.ts": /*!******************************************!*\ !*** ./src/controller/eme-controller.ts ***! \******************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/mediakeys-helper */ "./src/utils/mediakeys-helper.ts"); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } /** * @author Stephan Hesse <disparat@gmail.com> | <tchakabam@gmail.com> * * DRM support for Hls.js */ var MAX_LICENSE_REQUEST_FAILURES = 3; /** * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration * @param {Array<string>} audioCodecs List of required audio codecs to support * @param {Array<string>} videoCodecs List of required video codecs to support * @param {object} drmSystemOptions Optional parameters/requirements for the key-system * @returns {Array<MediaSystemConfiguration>} An array of supported configurations */ var createWidevineMediaKeySystemConfigurations = function createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs, drmSystemOptions) { /* jshint ignore:line */ var baseConfig = { // initDataTypes: ['keyids', 'mp4'], // label: "", // persistentState: "not-allowed", // or "required" ? // distinctiveIdentifier: "not-allowed", // or "required" ? // sessionTypes: ['temporary'], audioCapabilities: [], // { contentType: 'audio/mp4; codecs="mp4a.40.2"' } videoCapabilities: [] // { contentType: 'video/mp4; codecs="avc1.42E01E"' } }; audioCodecs.forEach(function (codec) { baseConfig.audioCapabilities.push({ contentType: "audio/mp4; codecs=\"" + codec + "\"", robustness: drmSystemOptions.audioRobustness || '' }); }); videoCodecs.forEach(function (codec) { baseConfig.videoCapabilities.push({ contentType: "video/mp4; codecs=\"" + codec + "\"", robustness: drmSystemOptions.videoRobustness || '' }); }); return [baseConfig]; }; /** * The idea here is to handle key-system (and their respective platforms) specific configuration differences * in order to work with the local requestMediaKeySystemAccess method. * * We can also rule-out platform-related key-system support at this point by throwing an error. * * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum * @param {Array<string>} audioCodecs List of required audio codecs to support * @param {Array<string>} videoCodecs List of required video codecs to support * @throws will throw an error if a unknown key system is passed * @returns {Array<MediaSystemConfiguration>} A non-empty Array of MediaKeySystemConfiguration objects */ var getSupportedMediaKeySystemConfigurations = function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, drmSystemOptions) { switch (keySystem) { case _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__["KeySystems"].WIDEVINE: return createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs, drmSystemOptions); default: throw new Error("Unknown key-system: " + keySystem); } }; /** * Controller to deal with encrypted media extensions (EME) * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API * * @class * @constructor */ var EMEController = /*#__PURE__*/function () { /** * @constructs * @param {Hls} hls Our Hls.js instance */ function EMEController(hls) { this.hls = void 0; this._widevineLicenseUrl = void 0; this._licenseXhrSetup = void 0; this._licenseResponseCallback = void 0; this._emeEnabled = void 0; this._requestMediaKeySystemAccess = void 0; this._drmSystemOptions = void 0; this._config = void 0; this._mediaKeysList = []; this._media = null; this._hasSetMediaKeys = false; this._requestLicenseFailureCount = 0; this.mediaKeysPromise = null; this._onMediaEncrypted = this.onMediaEncrypted.bind(this); this.hls = hls; this._config = hls.config; this._widevineLicenseUrl = this._config.widevineLicenseUrl; this._licenseXhrSetup = this._config.licenseXhrSetup; this._licenseResponseCallback = this._config.licenseResponseCallback; this._emeEnabled = this._config.emeEnabled; this._requestMediaKeySystemAccess = this._config.requestMediaKeySystemAccessFunc; this._drmSystemOptions = this._config.drmSystemOptions; this._registerListeners(); } var _proto = EMEController.prototype; _proto.destroy = function destroy() { this._unregisterListeners(); // @ts-ignore this.hls = this._onMediaEncrypted = null; this._requestMediaKeySystemAccess = null; }; _proto._registerListeners = function _registerListeners() { this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this); this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHED, this.onMediaDetached, this); this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this); }; _proto._unregisterListeners = function _unregisterListeners() { this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this); this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHED, this.onMediaDetached, this); this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this); } /** * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum * @returns {string} License server URL for key-system (if any configured, otherwise causes error) * @throws if a unsupported keysystem is passed */ ; _proto.getLicenseServerUrl = function getLicenseServerUrl(keySystem) { switch (keySystem) { case _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__["KeySystems"].WIDEVINE: if (!this._widevineLicenseUrl) { break; } return this._widevineLicenseUrl; } throw new Error("no license server URL configured for key-system \"" + keySystem + "\""); } /** * Requests access object and adds it to our list upon success * @private * @param {string} keySystem System ID (see `KeySystems`) * @param {Array<string>} audioCodecs List of required audio codecs to support * @param {Array<string>} videoCodecs List of required video codecs to support * @throws When a unsupported KeySystem is passed */ ; _proto._attemptKeySystemAccess = function _attemptKeySystemAccess(keySystem, audioCodecs, videoCodecs) { var _this = this; // This can throw, but is caught in event handler callpath var mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, this._drmSystemOptions); _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('Requesting encrypted media key-system access'); // expecting interface like window.navigator.requestMediaKeySystemAccess var keySystemAccessPromise = this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs); this.mediaKeysPromise = keySystemAccessPromise.then(function (mediaKeySystemAccess) { return _this._onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess); }); keySystemAccessPromise.catch(function (err) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("Failed to obtain key-system \"" + keySystem + "\" access:", err); }); }; /** * Handles obtaining access to a key-system * @private * @param {string} keySystem * @param {MediaKeySystemAccess} mediaKeySystemAccess https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemAccess */ _proto._onMediaKeySystemAccessObtained = function _onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess) { var _this2 = this; _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Access for key-system \"" + keySystem + "\" obtained"); var mediaKeysListItem = { mediaKeysSessionInitialized: false, mediaKeySystemAccess: mediaKeySystemAccess, mediaKeySystemDomain: keySystem }; this._mediaKeysList.push(mediaKeysListItem); var mediaKeysPromise = Promise.resolve().then(function () { return mediaKeySystemAccess.createMediaKeys(); }).then(function (mediaKeys) { mediaKeysListItem.mediaKeys = mediaKeys; _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Media-keys created for key-system \"" + keySystem + "\""); _this2._onMediaKeysCreated(); return mediaKeys; }); mediaKeysPromise.catch(function (err) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Failed to create media-keys:', err); }); return mediaKeysPromise; } /** * Handles key-creation (represents access to CDM). We are going to create key-sessions upon this * for all existing keys where no session exists yet. * * @private */ ; _proto._onMediaKeysCreated = function _onMediaKeysCreated() { var _this3 = this; // check for all key-list items if a session exists, otherwise, create one this._mediaKeysList.forEach(function (mediaKeysListItem) { if (!mediaKeysListItem.mediaKeysSession) { // mediaKeys is definitely initialized here mediaKeysListItem.mediaKeysSession = mediaKeysListItem.mediaKeys.createSession(); _this3._onNewMediaKeySession(mediaKeysListItem.mediaKeysSession); } }); } /** * @private * @param {*} keySession */ ; _proto._onNewMediaKeySession = function _onNewMediaKeySession(keySession) { var _this4 = this; _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("New key-system session " + keySession.sessionId); keySession.addEventListener('message', function (event) { _this4._onKeySessionMessage(keySession, event.message); }, false); } /** * @private * @param {MediaKeySession} keySession * @param {ArrayBuffer} message */ ; _proto._onKeySessionMessage = function _onKeySessionMessage(keySession, message) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('Got EME message event, creating license request'); this._requestLicense(message, function (data) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Received license data (length: " + (data ? data.byteLength : data) + "), updating key-session"); keySession.update(data); }); } /** * @private * @param e {MediaEncryptedEvent} */ ; _proto.onMediaEncrypted = function onMediaEncrypted(e) { var _this5 = this; _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Media is encrypted using \"" + e.initDataType + "\" init data type"); if (!this.mediaKeysPromise) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal: Media is encrypted but no CDM access or no keys have been requested'); this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_KEYS, fatal: true }); return; } var finallySetKeyAndStartSession = function finallySetKeyAndStartSession(mediaKeys) { if (!_this5._media) { return; } _this5._attemptSetMediaKeys(mediaKeys); _this5._generateRequestWithPreferredKeySession(e.initDataType, e.initData); }; // Could use `Promise.finally` but some Promise polyfills are missing it this.mediaKeysPromise.then(finallySetKeyAndStartSession).catch(finallySetKeyAndStartSession); } /** * @private */ ; _proto._attemptSetMediaKeys = function _attemptSetMediaKeys(mediaKeys) { if (!this._media) { throw new Error('Attempted to set mediaKeys without first attaching a media element'); } if (!this._hasSetMediaKeys) { // FIXME: see if we can/want/need-to really to deal with several potential key-sessions? var keysListItem = this._mediaKeysList[0]; if (!keysListItem || !keysListItem.mediaKeys) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal: Media is encrypted but no CDM access or no keys have been obtained yet'); this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_KEYS, fatal: true }); return; } _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('Setting keys for encrypted media'); this._media.setMediaKeys(keysListItem.mediaKeys); this._hasSetMediaKeys = true; } } /** * @private */ ; _proto._generateRequestWithPreferredKeySession = function _generateRequestWithPreferredKeySession(initDataType, initData) { var _this6 = this; // FIXME: see if we can/want/need-to really to deal with several potential key-sessions? var keysListItem = this._mediaKeysList[0]; if (!keysListItem) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal: Media is encrypted but not any key-system access has been obtained yet'); this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_ACCESS, fatal: true }); return; } if (keysListItem.mediaKeysSessionInitialized) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('Key-Session already initialized but requested again'); return; } var keySession = keysListItem.mediaKeysSession; if (!keySession) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal: Media is encrypted but no key-session existing'); this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_SESSION, fatal: true }); return; } // initData is null if the media is not CORS-same-origin if (!initData) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('Fatal: initData required for generating a key session is null'); this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_INIT_DATA, fatal: true }); return; } _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Generating key-session request for \"" + initDataType + "\" init data type"); keysListItem.mediaKeysSessionInitialized = true; keySession.generateRequest(initDataType, initData).then(function () { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].debug('Key-session generation succeeded'); }).catch(function (err) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Error generating key-session request:', err); _this6.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_SESSION, fatal: false }); }); } /** * @private * @param {string} url License server URL * @param {ArrayBuffer} keyMessage Message data issued by key-system * @param {function} callback Called when XHR has succeeded * @returns {XMLHttpRequest} Unsent (but opened state) XHR object * @throws if XMLHttpRequest construction failed */ ; _proto._createLicenseXhr = function _createLicenseXhr(url, keyMessage, callback) { var xhr = new XMLHttpRequest(); xhr.responseType = 'arraybuffer'; xhr.onreadystatechange = this._onLicenseRequestReadyStageChange.bind(this, xhr, url, keyMessage, callback); var licenseXhrSetup = this._licenseXhrSetup; if (licenseXhrSetup) { try { licenseXhrSetup.call(this.hls, xhr, url); licenseXhrSetup = undefined; } catch (e) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error(e); } } try { // if licenseXhrSetup did not yet call open, let's do it now if (!xhr.readyState) { xhr.open('POST', url, true); } if (licenseXhrSetup) { licenseXhrSetup.call(this.hls, xhr, url); } } catch (e) { // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS throw new Error("issue setting up KeySystem license XHR " + e); } return xhr; } /** * @private * @param {XMLHttpRequest} xhr * @param {string} url License server URL * @param {ArrayBuffer} keyMessage Message data issued by key-system * @param {function} callback Called when XHR has succeeded */ ; _proto._onLicenseRequestReadyStageChange = function _onLicenseRequestReadyStageChange(xhr, url, keyMessage, callback) { switch (xhr.readyState) { case 4: if (xhr.status === 200) { this._requestLicenseFailureCount = 0; _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('License request succeeded'); var _data = xhr.response; var licenseResponseCallback = this._licenseResponseCallback; if (licenseResponseCallback) { try { _data = licenseResponseCallback.call(this.hls, xhr, url); } catch (e) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error(e); } } callback(_data); } else { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("License Request XHR failed (" + url + "). Status: " + xhr.status + " (" + xhr.statusText + ")"); this._requestLicenseFailureCount++; if (this._requestLicenseFailureCount > MAX_LICENSE_REQUEST_FAILURES) { this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_LICENSE_REQUEST_FAILED, fatal: true }); return; } var attemptsLeft = MAX_LICENSE_REQUEST_FAILURES - this._requestLicenseFailureCount + 1; _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("Retrying license request, " + attemptsLeft + " attempts left"); this._requestLicense(keyMessage, callback); } break; } } /** * @private * @param {MediaKeysListItem} keysListItem * @param {ArrayBuffer} keyMessage * @returns {ArrayBuffer} Challenge data posted to license server * @throws if KeySystem is unsupported */ ; _proto._generateLicenseRequestChallenge = function _generateLicenseRequestChallenge(keysListItem, keyMessage) { switch (keysListItem.mediaKeySystemDomain) { // case KeySystems.PLAYREADY: // from https://github.com/MicrosoftEdge/Demos/blob/master/eme/scripts/demo.js /* if (this.licenseType !== this.LICENSE_TYPE_WIDEVINE) { // For PlayReady CDMs, we need to dig the Challenge out of the XML. var keyMessageXml = new DOMParser().parseFromString(String.fromCharCode.apply(null, new Uint16Array(keyMessage)), 'application/xml'); if (keyMessageXml.getElementsByTagName('Challenge')[0]) { challenge = atob(keyMessageXml.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue); } else { throw 'Cannot find <Challenge> in key message'; } var headerNames = keyMessageXml.getElementsByTagName('name'); var headerValues = keyMessageXml.getElementsByTagName('value'); if (headerNames.length !== headerValues.length) { throw 'Mismatched header <name>/<value> pair in key message'; } for (var i = 0; i < headerNames.length; i++) { xhr.setRequestHeader(headerNames[i].childNodes[0].nodeValue, headerValues[i].childNodes[0].nodeValue); } } break; */ case _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__["KeySystems"].WIDEVINE: // For Widevine CDMs, the challenge is the keyMessage. return keyMessage; } throw new Error("unsupported key-system: " + keysListItem.mediaKeySystemDomain); } /** * @private * @param keyMessage * @param callback */ ; _proto._requestLicense = function _requestLicense(keyMessage, callback) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('Requesting content license for key-system'); var keysListItem = this._mediaKeysList[0]; if (!keysListItem) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal error: Media is encrypted but no key-system access has been obtained yet'); this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_ACCESS, fatal: true }); return; } try { var _url = this.getLicenseServerUrl(keysListItem.mediaKeySystemDomain); var _xhr = this._createLicenseXhr(_url, keyMessage, callback); _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Sending license request to URL: " + _url); var challenge = this._generateLicenseRequestChallenge(keysListItem, keyMessage); _xhr.send(challenge); } catch (e) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("Failure requesting DRM license: " + e); this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_LICENSE_REQUEST_FAILED, fatal: true }); } }; _proto.onMediaAttached = function onMediaAttached(event, data) { if (!this._emeEnabled) { return; } var media = data.media; // keep reference of media this._media = media; media.addEventListener('encrypted', this._onMediaEncrypted); }; _proto.onMediaDetached = function onMediaDetached() { var media = this._media; var mediaKeysList = this._mediaKeysList; if (!media) { return; } media.removeEventListener('encrypted', this._onMediaEncrypted); this._media = null; this._mediaKeysList = []; // Close all sessions and remove media keys from the video element. Promise.all(mediaKeysList.map(function (mediaKeysListItem) { if (mediaKeysListItem.mediaKeysSession) { return mediaKeysListItem.mediaKeysSession.close().catch(function () {// Ignore errors when closing the sessions. Closing a session that // generated no key requests will throw an error. }); } })).then(function () { return media.setMediaKeys(null); }).catch(function () {// Ignore any failures while removing media keys from the video element. }); }; _proto.onManifestParsed = function onManifestParsed(event, data) { if (!this._emeEnabled) { return; } var audioCodecs = data.levels.map(function (level) { return level.audioCodec; }).filter(function (audioCodec) { return !!audioCodec; }); var videoCodecs = data.levels.map(function (level) { return level.videoCodec; }).filter(function (videoCodec) { return !!videoCodec; }); this._attemptKeySystemAccess(_utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__["KeySystems"].WIDEVINE, audioCodecs, videoCodecs); }; _createClass(EMEController, [{ key: "requestMediaKeySystemAccess", get: function get() { if (!this._requestMediaKeySystemAccess) { throw new Error('No requestMediaKeySystemAccess function configured'); } return this._requestMediaKeySystemAccess; } }]); return EMEController; }(); /* harmony default export */ __webpack_exports__["default"] = (EMEController); /***/ }), /***/ "./src/controller/fps-controller.ts": /*!******************************************!*\ !*** ./src/controller/fps-controller.ts ***! \******************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); var FPSController = /*#__PURE__*/function () { // stream controller must be provided as a dependency! function FPSController(hls) { this.hls = void 0; this.isVideoPlaybackQualityAvailable = false; this.timer = void 0; this.media = null; this.lastTime = void 0; this.lastDroppedFrames = 0; this.lastDecodedFrames = 0; this.streamController = void 0; this.hls = hls; this.registerListeners(); } var _proto = FPSController.prototype; _proto.setStreamController = function setStreamController(streamController) { this.streamController = streamController; }; _proto.registerListeners = function registerListeners() { this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this); }; _proto.unregisterListeners = function unregisterListeners() { this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching); }; _proto.destroy = function destroy() { if (this.timer) { clearInterval(this.timer); } this.unregisterListeners(); this.isVideoPlaybackQualityAvailable = false; this.media = null; }; _proto.onMediaAttaching = function onMediaAttaching(event, data) { var config = this.hls.config; if (config.capLevelOnFPSDrop) { var media = data.media instanceof self.HTMLVideoElement ? data.media : null; this.media = media; if (media && typeof media.getVideoPlaybackQuality === 'function') { this.isVideoPlaybackQualityAvailable = true; } self.clearInterval(this.timer); this.timer = self.setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod); } }; _proto.checkFPS = function checkFPS(video, decodedFrames, droppedFrames) { var currentTime = performance.now(); if (decodedFrames) { if (this.lastTime) { var currentPeriod = currentTime - this.lastTime; var currentDropped = droppedFrames - this.lastDroppedFrames; var currentDecoded = decodedFrames - this.lastDecodedFrames; var droppedFPS = 1000 * currentDropped / currentPeriod; var hls = this.hls; hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP, { currentDropped: currentDropped, currentDecoded: currentDecoded, totalDroppedFrames: droppedFrames }); if (droppedFPS > 0) { // logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod)); if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) { var currentLevel = hls.currentLevel; _utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel); if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) { currentLevel = currentLevel - 1; hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP_LEVEL_CAPPING, { level: currentLevel, droppedLevel: hls.currentLevel }); hls.autoLevelCapping = currentLevel; this.streamController.nextLevelSwitch(); } } } } this.lastTime = currentTime; this.lastDroppedFrames = droppedFrames; this.lastDecodedFrames = decodedFrames; } }; _proto.checkFPSInterval = function checkFPSInterval() { var video = this.media; if (video) { if (this.isVideoPlaybackQualityAvailable) { var videoPlaybackQuality = video.getVideoPlaybackQuality(); this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames); } else { // HTMLVideoElement doesn't include the webkit types this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount); } } }; return FPSController; }(); /* harmony default export */ __webpack_exports__["default"] = (FPSController); /***/ }), /***/ "./src/controller/fragment-finders.ts": /*!********************************************!*\ !*** ./src/controller/fragment-finders.ts ***! \********************************************/ /*! exports provided: findFragmentByPDT, findFragmentByPTS, fragmentWithinToleranceTest, pdtWithinToleranceTest, findFragWithCC */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFragmentByPDT", function() { return findFragmentByPDT; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFragmentByPTS", function() { return findFragmentByPTS; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fragmentWithinToleranceTest", function() { return fragmentWithinToleranceTest; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pdtWithinToleranceTest", function() { return pdtWithinToleranceTest; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFragWithCC", function() { return findFragWithCC; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/binary-search */ "./src/utils/binary-search.ts"); /** * Returns first fragment whose endPdt value exceeds the given PDT. * @param {Array<Fragment>} fragments - The array of candidate fragments * @param {number|null} [PDTValue = null] - The PDT value which must be exceeded * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start/end can be within in order to be considered contiguous * @returns {*|null} fragment - The best matching fragment */ function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) { if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(PDTValue)) { return null; } // if less than start var startPDT = fragments[0].programDateTime; if (PDTValue < (startPDT || 0)) { return null; } var endPDT = fragments[fragments.length - 1].endProgramDateTime; if (PDTValue >= (endPDT || 0)) { return null; } maxFragLookUpTolerance = maxFragLookUpTolerance || 0; for (var seg = 0; seg < fragments.length; ++seg) { var frag = fragments[seg]; if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) { return frag; } } return null; } /** * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer. * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus * breaking any traps which would cause the same fragment to be continuously selected within a small range. * @param {*} fragPrevious - The last frag successfully appended * @param {Array} fragments - The array of candidate fragments * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within * @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous * @returns {*} foundFrag - The best matching fragment */ function findFragmentByPTS(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance) { if (bufferEnd === void 0) { bufferEnd = 0; } if (maxFragLookUpTolerance === void 0) { maxFragLookUpTolerance = 0; } var fragNext = null; if (fragPrevious) { fragNext = fragments[fragPrevious.sn - fragments[0].sn + 1] || null; } else if (bufferEnd === 0 && fragments[0].start === 0) { fragNext = fragments[0]; } // Prefer the next fragment if it's within tolerance if (fragNext && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0) { return fragNext; } // We might be seeking past the tolerance so find the best match var foundFragment = _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__["default"].search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance)); if (foundFragment) { return foundFragment; } // If no match was found return the next fragment after fragPrevious, or null return fragNext; } /** * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions. * @param {*} candidate - The fragment to test * @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous * @returns {number} - 0 if it matches, 1 if too low, -1 if too high */ function fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, candidate) { if (bufferEnd === void 0) { bufferEnd = 0; } if (maxFragLookUpTolerance === void 0) { maxFragLookUpTolerance = 0; } // offset should be within fragment boundary - config.maxFragLookUpTolerance // this is to cope with situations like // bufferEnd = 9.991 // frag[Ø] : [0,10] // frag[1] : [10,20] // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here // frag start frag start+duration // |-----------------------------| // <---> <---> // ...--------><-----------------------------><---------.... // previous frag matching fragment next frag // return -1 return 0 return 1 // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`); // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)); if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) { return 1; } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) { // if maxFragLookUpTolerance will have negative value then don't return -1 for first element return -1; } return 0; } /** * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions. * This function tests the candidate's program date time values, as represented in Unix time * @param {*} candidate - The fragment to test * @param {number} [pdtBufferEnd = 0] - The Unix time representing the end of the current buffered range * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous * @returns {boolean} True if contiguous, false otherwise */ function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) { var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000; // endProgramDateTime can be null, default to zero var endProgramDateTime = candidate.endProgramDateTime || 0; return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd; } function findFragWithCC(fragments, cc) { return _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__["default"].search(fragments, function (candidate) { if (candidate.cc < cc) { return 1; } else if (candidate.cc > cc) { return -1; } else { return 0; } }); } /***/ }), /***/ "./src/controller/fragment-tracker.ts": /*!********************************************!*\ !*** ./src/controller/fragment-tracker.ts ***! \********************************************/ /*! exports provided: FragmentState, FragmentTracker */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FragmentState", function() { return FragmentState; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FragmentTracker", function() { return FragmentTracker; }); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts"); var FragmentState; (function (FragmentState) { FragmentState["NOT_LOADED"] = "NOT_LOADED"; FragmentState["BACKTRACKED"] = "BACKTRACKED"; FragmentState["APPENDING"] = "APPENDING"; FragmentState["PARTIAL"] = "PARTIAL"; FragmentState["OK"] = "OK"; })(FragmentState || (FragmentState = {})); var FragmentTracker = /*#__PURE__*/function () { function FragmentTracker(hls) { this.activeFragment = null; this.activeParts = null; this.fragments = Object.create(null); this.timeRanges = Object.create(null); this.bufferPadding = 0.2; this.hls = void 0; this.hls = hls; this._registerListeners(); } var _proto = FragmentTracker.prototype; _proto._registerListeners = function _registerListeners() { var hls = this.hls; hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_APPENDED, this.onBufferAppended, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_BUFFERED, this.onFragBuffered, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_LOADED, this.onFragLoaded, this); }; _proto._unregisterListeners = function _unregisterListeners() { var hls = this.hls; hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_APPENDED, this.onBufferAppended, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_BUFFERED, this.onFragBuffered, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_LOADED, this.onFragLoaded, this); }; _proto.destroy = function destroy() { this._unregisterListeners(); // @ts-ignore this.fragments = this.timeRanges = null; } /** * Return a Fragment with an appended range that matches the position and levelType. * If not found any Fragment, return null */ ; _proto.getAppendedFrag = function getAppendedFrag(position, levelType) { if (levelType === _types_loader__WEBPACK_IMPORTED_MODULE_1__["PlaylistLevelType"].MAIN) { var activeFragment = this.activeFragment, activeParts = this.activeParts; if (!activeFragment) { return null; } if (activeParts) { for (var i = activeParts.length; i--;) { var activePart = activeParts[i]; var appendedPTS = activePart ? activePart.end : activeFragment.appendedPTS; if (activePart.start <= position && appendedPTS !== undefined && position <= appendedPTS) { // 9 is a magic number. remove parts from lookup after a match but keep some short seeks back. if (i > 9) { this.activeParts = activeParts.slice(i - 9); } return activePart; } } } else if (activeFragment.start <= position && activeFragment.appendedPTS !== undefined && position <= activeFragment.appendedPTS) { return activeFragment; } } return this.getBufferedFrag(position, levelType); } /** * Return a buffered Fragment that matches the position and levelType. * A buffered Fragment is one whose loading, parsing and appending is done (completed or "partial" meaning aborted). * If not found any Fragment, return null */ ; _proto.getBufferedFrag = function getBufferedFrag(position, levelType) { var fragments = this.fragments; var keys = Object.keys(fragments); for (var i = keys.length; i--;) { var fragmentEntity = fragments[keys[i]]; if ((fragmentEntity === null || fragmentEntity === void 0 ? void 0 : fragmentEntity.body.type) === levelType && fragmentEntity.buffered) { var frag = fragmentEntity.body; if (frag.start <= position && position <= frag.end) { return frag; } } } return null; } /** * Partial fragments effected by coded frame eviction will be removed * The browser will unload parts of the buffer to free up memory for new buffer data * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable) */ ; _proto.detectEvictedFragments = function detectEvictedFragments(elementaryStream, timeRange, playlistType) { var _this = this; // Check if any flagged fragments have been unloaded Object.keys(this.fragments).forEach(function (key) { var fragmentEntity = _this.fragments[key]; if (!fragmentEntity) { return; } if (!fragmentEntity.buffered) { if (fragmentEntity.body.type === playlistType) { _this.removeFragment(fragmentEntity.body); } return; } var esData = fragmentEntity.range[elementaryStream]; if (!esData) { return; } esData.time.some(function (time) { var isNotBuffered = !_this.isTimeBuffered(time.startPTS, time.endPTS, timeRange); if (isNotBuffered) { // Unregister partial fragment as it needs to load again to be reused _this.removeFragment(fragmentEntity.body); } return isNotBuffered; }); }); } /** * Checks if the fragment passed in is loaded in the buffer properly * Partially loaded fragments will be registered as a partial fragment */ ; _proto.detectPartialFragments = function detectPartialFragments(data) { var _this2 = this; var timeRanges = this.timeRanges; var frag = data.frag, part = data.part; if (!timeRanges || frag.sn === 'initSegment') { return; } var fragKey = getFragmentKey(frag); var fragmentEntity = this.fragments[fragKey]; if (!fragmentEntity) { return; } Object.keys(timeRanges).forEach(function (elementaryStream) { var streamInfo = frag.elementaryStreams[elementaryStream]; if (!streamInfo) { return; } var timeRange = timeRanges[elementaryStream]; var partial = part !== null || streamInfo.partial === true; fragmentEntity.range[elementaryStream] = _this2.getBufferedTimes(frag, part, partial, timeRange); }); fragmentEntity.backtrack = fragmentEntity.loaded = null; if (Object.keys(fragmentEntity.range).length) { fragmentEntity.buffered = true; } else { // remove fragment if nothing was appended this.removeFragment(fragmentEntity.body); } }; _proto.fragBuffered = function fragBuffered(frag) { var fragKey = getFragmentKey(frag); var fragmentEntity = this.fragments[fragKey]; if (fragmentEntity) { fragmentEntity.backtrack = fragmentEntity.loaded = null; fragmentEntity.buffered = true; } }; _proto.getBufferedTimes = function getBufferedTimes(fragment, part, partial, timeRange) { var buffered = { time: [], partial: partial }; var startPTS = part ? part.start : fragment.start; var endPTS = part ? part.end : fragment.end; var minEndPTS = fragment.minEndPTS || endPTS; var maxStartPTS = fragment.maxStartPTS || startPTS; for (var i = 0; i < timeRange.length; i++) { var startTime = timeRange.start(i) - this.bufferPadding; var endTime = timeRange.end(i) + this.bufferPadding; if (maxStartPTS >= startTime && minEndPTS <= endTime) { // Fragment is entirely contained in buffer // No need to check the other timeRange times since it's completely playable buffered.time.push({ startPTS: Math.max(startPTS, timeRange.start(i)), endPTS: Math.min(endPTS, timeRange.end(i)) }); break; } else if (startPTS < endTime && endPTS > startTime) { buffered.partial = true; // Check for intersection with buffer // Get playable sections of the fragment buffered.time.push({ startPTS: Math.max(startPTS, timeRange.start(i)), endPTS: Math.min(endPTS, timeRange.end(i)) }); } else if (endPTS <= startTime) { // No need to check the rest of the timeRange as it is in order break; } } return buffered; } /** * Gets the partial fragment for a certain time */ ; _proto.getPartialFragment = function getPartialFragment(time) { var bestFragment = null; var timePadding; var startTime; var endTime; var bestOverlap = 0; var bufferPadding = this.bufferPadding, fragments = this.fragments; Object.keys(fragments).forEach(function (key) { var fragmentEntity = fragments[key]; if (!fragmentEntity) { return; } if (isPartial(fragmentEntity)) { startTime = fragmentEntity.body.start - bufferPadding; endTime = fragmentEntity.body.end + bufferPadding; if (time >= startTime && time <= endTime) { // Use the fragment that has the most padding from start and end time timePadding = Math.min(time - startTime, endTime - time); if (bestOverlap <= timePadding) { bestFragment = fragmentEntity.body; bestOverlap = timePadding; } } } }); return bestFragment; }; _proto.getState = function getState(fragment) { var fragKey = getFragmentKey(fragment); var fragmentEntity = this.fragments[fragKey]; if (fragmentEntity) { if (!fragmentEntity.buffered) { if (fragmentEntity.backtrack) { return FragmentState.BACKTRACKED; } return FragmentState.APPENDING; } else if (isPartial(fragmentEntity)) { return FragmentState.PARTIAL; } else { return FragmentState.OK; } } return FragmentState.NOT_LOADED; }; _proto.backtrack = function backtrack(frag, data) { var fragKey = getFragmentKey(frag); var fragmentEntity = this.fragments[fragKey]; if (!fragmentEntity || fragmentEntity.backtrack) { return null; } var backtrack = fragmentEntity.backtrack = data ? data : fragmentEntity.loaded; fragmentEntity.loaded = null; return backtrack; }; _proto.getBacktrackData = function getBacktrackData(fragment) { var fragKey = getFragmentKey(fragment); var fragmentEntity = this.fragments[fragKey]; if (fragmentEntity) { var _backtrack$payload; var backtrack = fragmentEntity.backtrack; // If data was already sent to Worker it is detached no longer available if (backtrack !== null && backtrack !== void 0 && (_backtrack$payload = backtrack.payload) !== null && _backtrack$payload !== void 0 && _backtrack$payload.byteLength) { return backtrack; } else { this.removeFragment(fragment); } } return null; }; _proto.isTimeBuffered = function isTimeBuffered(startPTS, endPTS, timeRange) { var startTime; var endTime; for (var i = 0; i < timeRange.length; i++) { startTime = timeRange.start(i) - this.bufferPadding; endTime = timeRange.end(i) + this.bufferPadding; if (startPTS >= startTime && endPTS <= endTime) { return true; } if (endPTS <= startTime) { // No need to check the rest of the timeRange as it is in order return false; } } return false; }; _proto.onFragLoaded = function onFragLoaded(event, data) { var frag = data.frag, part = data.part; // don't track initsegment (for which sn is not a number) // don't track frags used for bitrateTest, they're irrelevant. // don't track parts for memory efficiency if (frag.sn === 'initSegment' || frag.bitrateTest || part) { return; } var fragKey = getFragmentKey(frag); this.fragments[fragKey] = { body: frag, loaded: data, backtrack: null, buffered: false, range: Object.create(null) }; }; _proto.onBufferAppended = function onBufferAppended(event, data) { var _this3 = this; var frag = data.frag, part = data.part, timeRanges = data.timeRanges; if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_1__["PlaylistLevelType"].MAIN) { this.activeFragment = frag; if (part) { var activeParts = this.activeParts; if (!activeParts) { this.activeParts = activeParts = []; } activeParts.push(part); } else { this.activeParts = null; } } // Store the latest timeRanges loaded in the buffer this.timeRanges = timeRanges; Object.keys(timeRanges).forEach(function (elementaryStream) { var timeRange = timeRanges[elementaryStream]; _this3.detectEvictedFragments(elementaryStream, timeRange); if (!part) { for (var i = 0; i < timeRange.length; i++) { frag.appendedPTS = Math.max(timeRange.end(i), frag.appendedPTS || 0); } } }); }; _proto.onFragBuffered = function onFragBuffered(event, data) { this.detectPartialFragments(data); }; _proto.hasFragment = function hasFragment(fragment) { var fragKey = getFragmentKey(fragment); return !!this.fragments[fragKey]; }; _proto.removeFragmentsInRange = function removeFragmentsInRange(start, end, playlistType) { var _this4 = this; Object.keys(this.fragments).forEach(function (key) { var fragmentEntity = _this4.fragments[key]; if (!fragmentEntity) { return; } if (fragmentEntity.buffered) { var frag = fragmentEntity.body; if (frag.type === playlistType && frag.start < end && frag.end > start) { _this4.removeFragment(frag); } } }); }; _proto.removeFragment = function removeFragment(fragment) { var fragKey = getFragmentKey(fragment); fragment.stats.loaded = 0; fragment.clearElementaryStreamInfo(); delete this.fragments[fragKey]; }; _proto.removeAllFragments = function removeAllFragments() { this.fragments = Object.create(null); this.activeFragment = null; this.activeParts = null; }; return FragmentTracker; }(); function isPartial(fragmentEntity) { var _fragmentEntity$range, _fragmentEntity$range2; return fragmentEntity.buffered && (((_fragmentEntity$range = fragmentEntity.range.video) === null || _fragmentEntity$range === void 0 ? void 0 : _fragmentEntity$range.partial) || ((_fragmentEntity$range2 = fragmentEntity.range.audio) === null || _fragmentEntity$range2 === void 0 ? void 0 : _fragmentEntity$range2.partial)); } function getFragmentKey(fragment) { return fragment.type + "_" + fragment.level + "_" + fragment.urlId + "_" + fragment.sn; } /***/ }), /***/ "./src/controller/gap-controller.ts": /*!******************************************!*\ !*** ./src/controller/gap-controller.ts ***! \******************************************/ /*! exports provided: STALL_MINIMUM_DURATION_MS, MAX_START_GAP_JUMP, SKIP_BUFFER_HOLE_STEP_SECONDS, SKIP_BUFFER_RANGE_START, default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STALL_MINIMUM_DURATION_MS", function() { return STALL_MINIMUM_DURATION_MS; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MAX_START_GAP_JUMP", function() { return MAX_START_GAP_JUMP; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SKIP_BUFFER_HOLE_STEP_SECONDS", function() { return SKIP_BUFFER_HOLE_STEP_SECONDS; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SKIP_BUFFER_RANGE_START", function() { return SKIP_BUFFER_RANGE_START; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return GapController; }); /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); var STALL_MINIMUM_DURATION_MS = 250; var MAX_START_GAP_JUMP = 2.0; var SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1; var SKIP_BUFFER_RANGE_START = 0.05; var GapController = /*#__PURE__*/function () { function GapController(config, media, fragmentTracker, hls) { this.config = void 0; this.media = void 0; this.fragmentTracker = void 0; this.hls = void 0; this.nudgeRetry = 0; this.stallReported = false; this.stalled = null; this.moved = false; this.seeking = false; this.config = config; this.media = media; this.fragmentTracker = fragmentTracker; this.hls = hls; } var _proto = GapController.prototype; _proto.destroy = function destroy() { // @ts-ignore this.hls = this.fragmentTracker = this.media = null; } /** * Checks if the playhead is stuck within a gap, and if so, attempts to free it. * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range). * * @param {number} lastCurrentTime Previously read playhead position */ ; _proto.poll = function poll(lastCurrentTime) { var config = this.config, media = this.media, stalled = this.stalled; var currentTime = media.currentTime, seeking = media.seeking; var seeked = this.seeking && !seeking; var beginSeek = !this.seeking && seeking; this.seeking = seeking; // The playhead is moving, no-op if (currentTime !== lastCurrentTime) { this.moved = true; if (stalled !== null) { // The playhead is now moving, but was previously stalled if (this.stallReported) { var _stalledDuration = self.performance.now() - stalled; _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("playback not stuck anymore @" + currentTime + ", after " + Math.round(_stalledDuration) + "ms"); this.stallReported = false; } this.stalled = null; this.nudgeRetry = 0; } return; } // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek if (beginSeek || seeked) { this.stalled = null; } // The playhead should not be moving if (media.paused || media.ended || media.playbackRate === 0 || !_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].getBuffered(media).length) { return; } var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].bufferInfo(media, currentTime, 0); var isBuffered = bufferInfo.len > 0; var nextStart = bufferInfo.nextStart || 0; // There is no playable buffer (seeked, waiting for buffer) if (!isBuffered && !nextStart) { return; } if (seeking) { // Waiting for seeking in a buffered range to complete var hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP; // Next buffered range is too far ahead to jump to while still seeking var noBufferGap = !nextStart || nextStart - currentTime > MAX_START_GAP_JUMP && !this.fragmentTracker.getPartialFragment(currentTime); if (hasEnoughBuffer || noBufferGap) { return; } // Reset moved state when seeking to a point in or before a gap this.moved = false; } // Skip start gaps if we haven't played, but the last poll detected the start of a stall // The addition poll gives the browser a chance to jump the gap for us if (!this.moved && this.stalled !== null) { var _level$details; // Jump start gaps within jump threshold var startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime; // When joining a live stream with audio tracks, account for live playlist window sliding by allowing // a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment // that begins over 1 target duration after the video start position. var level = this.hls.levels ? this.hls.levels[this.hls.currentLevel] : null; var isLive = level === null || level === void 0 ? void 0 : (_level$details = level.details) === null || _level$details === void 0 ? void 0 : _level$details.live; var maxStartGapJump = isLive ? level.details.targetduration * 2 : MAX_START_GAP_JUMP; if (startJump > 0 && startJump <= maxStartGapJump) { this._trySkipBufferHole(null); return; } } // Start tracking stall time var tnow = self.performance.now(); if (stalled === null) { this.stalled = tnow; return; } var stalledDuration = tnow - stalled; if (!seeking && stalledDuration >= STALL_MINIMUM_DURATION_MS) { // Report stalling after trying to fix this._reportStall(bufferInfo.len); } var bufferedWithHoles = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].bufferInfo(media, currentTime, config.maxBufferHole); this._tryFixBufferStall(bufferedWithHoles, stalledDuration); } /** * Detects and attempts to fix known buffer stalling issues. * @param bufferInfo - The properties of the current buffer. * @param stalledDurationMs - The amount of time Hls.js has been stalling for. * @private */ ; _proto._tryFixBufferStall = function _tryFixBufferStall(bufferInfo, stalledDurationMs) { var config = this.config, fragmentTracker = this.fragmentTracker, media = this.media; var currentTime = media.currentTime; var partial = fragmentTracker.getPartialFragment(currentTime); if (partial) { // Try to skip over the buffer hole caused by a partial fragment // This method isn't limited by the size of the gap between buffered ranges var targetTime = this._trySkipBufferHole(partial); // we return here in this case, meaning // the branch below only executes when we don't handle a partial fragment if (targetTime) { return; } } // if we haven't had to skip over a buffer hole of a partial fragment // we may just have to "nudge" the playlist as the browser decoding/rendering engine // needs to cross some sort of threshold covering all source-buffers content // to start playing properly. if (bufferInfo.len > config.maxBufferHole && stalledDurationMs > config.highBufferWatchdogPeriod * 1000) { _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Trying to nudge playhead over buffer-hole'); // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds // We only try to jump the hole if it's under the configured size // Reset stalled so to rearm watchdog timer this.stalled = null; this._tryNudgeBuffer(); } } /** * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period. * @param bufferLen - The playhead distance from the end of the current buffer segment. * @private */ ; _proto._reportStall = function _reportStall(bufferLen) { var hls = this.hls, media = this.media, stallReported = this.stallReported; if (!stallReported) { // Report stalled error once this.stallReported = true; _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("Playback stalling at @" + media.currentTime + " due to low buffer (buffer=" + bufferLen + ")"); hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_STALLED_ERROR, fatal: false, buffer: bufferLen }); } } /** * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments * @param partial - The partial fragment found at the current time (where playback is stalling). * @private */ ; _proto._trySkipBufferHole = function _trySkipBufferHole(partial) { var config = this.config, hls = this.hls, media = this.media; var currentTime = media.currentTime; var lastEndTime = 0; // Check if currentTime is between unbuffered regions of partial fragments var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].getBuffered(media); for (var i = 0; i < buffered.length; i++) { var startTime = buffered.start(i); if (currentTime + config.maxBufferHole >= lastEndTime && currentTime < startTime) { var targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, media.currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS); _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("skipping hole, adjusting currentTime from " + currentTime + " to " + targetTime); this.moved = true; this.stalled = null; media.currentTime = targetTime; if (partial) { hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_SEEK_OVER_HOLE, fatal: false, reason: "fragment loaded with buffer holes, seeking from " + currentTime + " to " + targetTime, frag: partial }); } return targetTime; } lastEndTime = buffered.end(i); } return 0; } /** * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount. * @private */ ; _proto._tryNudgeBuffer = function _tryNudgeBuffer() { var config = this.config, hls = this.hls, media = this.media; var currentTime = media.currentTime; var nudgeRetry = (this.nudgeRetry || 0) + 1; this.nudgeRetry = nudgeRetry; if (nudgeRetry < config.nudgeMaxRetry) { var targetTime = currentTime + nudgeRetry * config.nudgeOffset; // playback stalled in buffered area ... let's nudge currentTime to try to overcome this _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("Nudging 'currentTime' from " + currentTime + " to " + targetTime); media.currentTime = targetTime; hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_NUDGE_ON_STALL, fatal: false }); } else { _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].error("Playhead still not moving while enough data buffered @" + currentTime + " after " + config.nudgeMaxRetry + " nudges"); hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_STALLED_ERROR, fatal: true }); } }; return GapController; }(); /***/ }), /***/ "./src/controller/id3-track-controller.ts": /*!************************************************!*\ !*** ./src/controller/id3-track-controller.ts ***! \************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/texttrack-utils */ "./src/utils/texttrack-utils.ts"); /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts"); var MIN_CUE_DURATION = 0.25; var ID3TrackController = /*#__PURE__*/function () { function ID3TrackController(hls) { this.hls = void 0; this.id3Track = null; this.media = null; this.hls = hls; this._registerListeners(); } var _proto = ID3TrackController.prototype; _proto.destroy = function destroy() { this._unregisterListeners(); }; _proto._registerListeners = function _registerListeners() { var hls = this.hls; hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_PARSING_METADATA, this.onFragParsingMetadata, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this); }; _proto._unregisterListeners = function _unregisterListeners() { var hls = this.hls; hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_PARSING_METADATA, this.onFragParsingMetadata, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this); } // Add ID3 metatadata text track. ; _proto.onMediaAttached = function onMediaAttached(event, data) { this.media = data.media; }; _proto.onMediaDetaching = function onMediaDetaching() { if (!this.id3Track) { return; } Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["clearCurrentCues"])(this.id3Track); this.id3Track = null; this.media = null; }; _proto.getID3Track = function getID3Track(textTracks) { if (!this.media) { return; } for (var i = 0; i < textTracks.length; i++) { var textTrack = textTracks[i]; if (textTrack.kind === 'metadata' && textTrack.label === 'id3') { // send 'addtrack' when reusing the textTrack for metadata, // same as what we do for captions Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["sendAddTrackEvent"])(textTrack, this.media); return textTrack; } } return this.media.addTextTrack('metadata', 'id3'); }; _proto.onFragParsingMetadata = function onFragParsingMetadata(event, data) { if (!this.media) { return; } var fragment = data.frag; var samples = data.samples; // create track dynamically if (!this.id3Track) { this.id3Track = this.getID3Track(this.media.textTracks); this.id3Track.mode = 'hidden'; } // Attempt to recreate Safari functionality by creating // WebKitDataCue objects when available and store the decoded // ID3 data in the value property of the cue var Cue = self.WebKitDataCue || self.VTTCue || self.TextTrackCue; for (var i = 0; i < samples.length; i++) { var frames = _demux_id3__WEBPACK_IMPORTED_MODULE_2__["getID3Frames"](samples[i].data); if (frames) { var startTime = samples[i].pts; var endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.end; var timeDiff = endTime - startTime; if (timeDiff <= 0) { endTime = startTime + MIN_CUE_DURATION; } for (var j = 0; j < frames.length; j++) { var frame = frames[j]; // Safari doesn't put the timestamp frame in the TextTrack if (!_demux_id3__WEBPACK_IMPORTED_MODULE_2__["isTimeStampFrame"](frame)) { var cue = new Cue(startTime, endTime, ''); cue.value = frame; this.id3Track.addCue(cue); } } } } }; _proto.onBufferFlushing = function onBufferFlushing(event, _ref) { var startOffset = _ref.startOffset, endOffset = _ref.endOffset, type = _ref.type; if (!type || type === 'audio') { // id3 cues come from parsed audio only remove cues when audio buffer is cleared var id3Track = this.id3Track; if (id3Track) { Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["removeCuesInRange"])(id3Track, startOffset, endOffset); } } }; return ID3TrackController; }(); /* harmony default export */ __webpack_exports__["default"] = (ID3TrackController); /***/ }), /***/ "./src/controller/latency-controller.ts": /*!**********************************************!*\ !*** ./src/controller/latency-controller.ts ***! \**********************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return LatencyController; }); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var LatencyController = /*#__PURE__*/function () { function LatencyController(hls) { var _this = this; this.hls = void 0; this.config = void 0; this.media = null; this.levelDetails = null; this.currentTime = 0; this.stallCount = 0; this._latency = null; this.timeupdateHandler = function () { return _this.timeupdate(); }; this.hls = hls; this.config = hls.config; this.registerListeners(); } var _proto = LatencyController.prototype; _proto.destroy = function destroy() { this.unregisterListeners(); this.onMediaDetaching(); this.levelDetails = null; // @ts-ignore this.hls = this.timeupdateHandler = null; }; _proto.registerListeners = function registerListeners() { this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this); this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this); this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated, this); this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError, this); }; _proto.unregisterListeners = function unregisterListeners() { this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHED, this.onMediaAttached); this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching); this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading); this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated); this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError); }; _proto.onMediaAttached = function onMediaAttached(event, data) { this.media = data.media; this.media.addEventListener('timeupdate', this.timeupdateHandler); }; _proto.onMediaDetaching = function onMediaDetaching() { if (this.media) { this.media.removeEventListener('timeupdate', this.timeupdateHandler); this.media = null; } }; _proto.onManifestLoading = function onManifestLoading() { this.levelDetails = null; this._latency = null; this.stallCount = 0; }; _proto.onLevelUpdated = function onLevelUpdated(event, _ref) { var details = _ref.details; this.levelDetails = details; if (details.advanced) { this.timeupdate(); } if (!details.live && this.media) { this.media.removeEventListener('timeupdate', this.timeupdateHandler); } }; _proto.onError = function onError(event, data) { if (data.details !== _errors__WEBPACK_IMPORTED_MODULE_0__["ErrorDetails"].BUFFER_STALLED_ERROR) { return; } this.stallCount++; _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('[playback-rate-controller]: Stall detected, adjusting target latency'); }; _proto.timeupdate = function timeupdate() { var media = this.media, levelDetails = this.levelDetails; if (!media || !levelDetails) { return; } this.currentTime = media.currentTime; var latency = this.computeLatency(); if (latency === null) { return; } this._latency = latency; // Adapt playbackRate to meet target latency in low-latency mode var _this$config = this.config, lowLatencyMode = _this$config.lowLatencyMode, maxLiveSyncPlaybackRate = _this$config.maxLiveSyncPlaybackRate; if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1) { return; } var targetLatency = this.targetLatency; if (targetLatency === null) { return; } var distanceFromTarget = latency - targetLatency; // Only adjust playbackRate when within one target duration of targetLatency // and more than one second from under-buffering. // Playback further than one target duration from target can be considered DVR playback. var liveMinLatencyDuration = Math.min(this.maxLatency, targetLatency + levelDetails.targetduration); var inLiveRange = distanceFromTarget < liveMinLatencyDuration; if (levelDetails.live && inLiveRange && distanceFromTarget > 0.05 && this.forwardBufferLength > 1) { var max = Math.min(2, Math.max(1.0, maxLiveSyncPlaybackRate)); var rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled)) * 20) / 20; media.playbackRate = Math.min(max, Math.max(1, rate)); } else if (media.playbackRate !== 1 && media.playbackRate !== 0) { media.playbackRate = 1; } }; _proto.estimateLiveEdge = function estimateLiveEdge() { var levelDetails = this.levelDetails; if (levelDetails === null) { return null; } return levelDetails.edge + levelDetails.age; }; _proto.computeLatency = function computeLatency() { var liveEdge = this.estimateLiveEdge(); if (liveEdge === null) { return null; } return liveEdge - this.currentTime; }; _createClass(LatencyController, [{ key: "latency", get: function get() { return this._latency || 0; } }, { key: "maxLatency", get: function get() { var config = this.config, levelDetails = this.levelDetails; if (config.liveMaxLatencyDuration !== undefined) { return config.liveMaxLatencyDuration; } return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0; } }, { key: "targetLatency", get: function get() { var levelDetails = this.levelDetails; if (levelDetails === null) { return null; } var holdBack = levelDetails.holdBack, partHoldBack = levelDetails.partHoldBack, targetduration = levelDetails.targetduration; var _this$config2 = this.config, liveSyncDuration = _this$config2.liveSyncDuration, liveSyncDurationCount = _this$config2.liveSyncDurationCount, lowLatencyMode = _this$config2.lowLatencyMode; var userConfig = this.hls.userConfig; var targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack; if (userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) { targetLatency = liveSyncDuration !== undefined ? liveSyncDuration : liveSyncDurationCount * targetduration; } var maxLiveSyncOnStallIncrease = targetduration; var liveSyncOnStallIncrease = 1.0; return targetLatency + Math.min(this.stallCount * liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease); } }, { key: "liveSyncPosition", get: function get() { var liveEdge = this.estimateLiveEdge(); var targetLatency = this.targetLatency; var levelDetails = this.levelDetails; if (liveEdge === null || targetLatency === null || levelDetails === null) { return null; } var edge = levelDetails.edge; var syncPosition = liveEdge - targetLatency - this.edgeStalled; var min = edge - levelDetails.totalduration; var max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration); return Math.min(Math.max(min, syncPosition), max); } }, { key: "drift", get: function get() { var levelDetails = this.levelDetails; if (levelDetails === null) { return 1; } return levelDetails.drift; } }, { key: "edgeStalled", get: function get() { var levelDetails = this.levelDetails; if (levelDetails === null) { return 0; } var maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3; return Math.max(levelDetails.age - maxLevelUpdateAge, 0); } }, { key: "forwardBufferLength", get: function get() { var media = this.media, levelDetails = this.levelDetails; if (!media || !levelDetails) { return 0; } var bufferedRanges = media.buffered.length; return bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge - this.currentTime; } }]); return LatencyController; }(); /***/ }), /***/ "./src/controller/level-controller.ts": /*!********************************************!*\ !*** ./src/controller/level-controller.ts ***! \********************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return LevelController; }); /* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _utils_codecs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/codecs */ "./src/utils/codecs.ts"); /* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts"); /* harmony import */ var _base_playlist_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./base-playlist-controller */ "./src/controller/base-playlist-controller.ts"); /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts"); function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /* * Level Controller */ var chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase()); var LevelController = /*#__PURE__*/function (_BasePlaylistControll) { _inheritsLoose(LevelController, _BasePlaylistControll); function LevelController(hls) { var _this; _this = _BasePlaylistControll.call(this, hls, '[level-controller]') || this; _this._levels = []; _this._firstLevel = -1; _this._startLevel = void 0; _this.currentLevelIndex = -1; _this.manualLevelIndex = -1; _this.onParsedComplete = void 0; _this._registerListeners(); return _this; } var _proto = LevelController.prototype; _proto._registerListeners = function _registerListeners() { var hls = this.hls; hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, this.onManifestLoaded, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADED, this.onLevelLoaded, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, this.onFragLoaded, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError, this); }; _proto._unregisterListeners = function _unregisterListeners() { var hls = this.hls; hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, this.onManifestLoaded, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADED, this.onLevelLoaded, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, this.onFragLoaded, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError, this); }; _proto.destroy = function destroy() { this._unregisterListeners(); this.manualLevelIndex = -1; this._levels.length = 0; _BasePlaylistControll.prototype.destroy.call(this); }; _proto.startLoad = function startLoad() { var levels = this._levels; // clean up live level details to force reload them, and reset load errors levels.forEach(function (level) { level.loadError = 0; }); _BasePlaylistControll.prototype.startLoad.call(this); }; _proto.onManifestLoaded = function onManifestLoaded(event, data) { var levels = []; var audioTracks = []; var subtitleTracks = []; var bitrateStart; var levelSet = {}; var levelFromSet; var resolutionFound = false; var videoCodecFound = false; var audioCodecFound = false; // regroup redundant levels together data.levels.forEach(function (levelParsed) { var attributes = levelParsed.attrs; resolutionFound = resolutionFound || !!(levelParsed.width && levelParsed.height); videoCodecFound = videoCodecFound || !!levelParsed.videoCodec; audioCodecFound = audioCodecFound || !!levelParsed.audioCodec; // erase audio codec info if browser does not support mp4a.40.34. // demuxer will autodetect codec and fallback to mpeg/audio if (chromeOrFirefox && levelParsed.audioCodec && levelParsed.audioCodec.indexOf('mp4a.40.34') !== -1) { levelParsed.audioCodec = undefined; } var levelKey = levelParsed.bitrate + "-" + levelParsed.attrs.RESOLUTION + "-" + levelParsed.attrs.CODECS; levelFromSet = levelSet[levelKey]; if (!levelFromSet) { levelFromSet = new _types_level__WEBPACK_IMPORTED_MODULE_0__["Level"](levelParsed); levelSet[levelKey] = levelFromSet; levels.push(levelFromSet); } else { levelFromSet.url.push(levelParsed.url); } if (attributes) { if (attributes.AUDIO) { Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["addGroupId"])(levelFromSet, 'audio', attributes.AUDIO); } if (attributes.SUBTITLES) { Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["addGroupId"])(levelFromSet, 'text', attributes.SUBTITLES); } } }); // remove audio-only level if we also have levels with video codecs or RESOLUTION signalled if ((resolutionFound || videoCodecFound) && audioCodecFound) { levels = levels.filter(function (_ref) { var videoCodec = _ref.videoCodec, width = _ref.width, height = _ref.height; return !!videoCodec || !!(width && height); }); } // only keep levels with supported audio/video codecs levels = levels.filter(function (_ref2) { var audioCodec = _ref2.audioCodec, videoCodec = _ref2.videoCodec; return (!audioCodec || Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_3__["isCodecSupportedInMp4"])(audioCodec, 'audio')) && (!videoCodec || Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_3__["isCodecSupportedInMp4"])(videoCodec, 'video')); }); if (data.audioTracks) { audioTracks = data.audioTracks.filter(function (track) { return !track.audioCodec || Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_3__["isCodecSupportedInMp4"])(track.audioCodec, 'audio'); }); // Assign ids after filtering as array indices by group-id Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["assignTrackIdsByGroup"])(audioTracks); } if (data.subtitles) { subtitleTracks = data.subtitles; Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["assignTrackIdsByGroup"])(subtitleTracks); } if (levels.length > 0) { // start bitrate is the first bitrate of the manifest bitrateStart = levels[0].bitrate; // sort level on bitrate levels.sort(function (a, b) { return a.bitrate - b.bitrate; }); this._levels = levels; // find index of first level in sorted levels for (var i = 0; i < levels.length; i++) { if (levels[i].bitrate === bitrateStart) { this._firstLevel = i; this.log("manifest loaded, " + levels.length + " level(s) found, first bitrate: " + bitrateStart); break; } } // Audio is only alternate if manifest include a URI along with the audio group tag, // and this is not an audio-only stream where levels contain audio-only var audioOnly = audioCodecFound && !videoCodecFound; var edata = { levels: levels, audioTracks: audioTracks, subtitleTracks: subtitleTracks, firstLevel: this._firstLevel, stats: data.stats, audio: audioCodecFound, video: videoCodecFound, altAudio: !audioOnly && audioTracks.some(function (t) { return !!t.url; }) }; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_PARSED, edata); // Initiate loading after all controllers have received MANIFEST_PARSED if (this.hls.config.autoStartLoad || this.hls.forceStartLoad) { this.hls.startLoad(this.hls.config.startPosition); } } else { this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_INCOMPATIBLE_CODECS_ERROR, fatal: true, url: data.url, reason: 'no level with compatible codecs found in manifest' }); } }; _proto.onError = function onError(event, data) { _BasePlaylistControll.prototype.onError.call(this, event, data); if (data.fatal) { return; } // Switch to redundant level when track fails to load var context = data.context; var level = this._levels[this.currentLevelIndex]; if (context && (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK && level.audioGroupIds && context.groupId === level.audioGroupIds[level.urlId] || context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK && level.textGroupIds && context.groupId === level.textGroupIds[level.urlId])) { this.redundantFailover(this.currentLevelIndex); return; } var levelError = false; var levelSwitch = true; var levelIndex; // try to recover not fatal errors switch (data.details) { case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].FRAG_LOAD_ERROR: case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].FRAG_LOAD_TIMEOUT: case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].KEY_LOAD_ERROR: case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].KEY_LOAD_TIMEOUT: if (data.frag) { var _level = this._levels[data.frag.level]; // Set levelIndex when we're out of fragment retries if (_level) { _level.fragmentError++; if (_level.fragmentError > this.hls.config.fragLoadingMaxRetry) { levelIndex = data.frag.level; } } else { levelIndex = data.frag.level; } } break; case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_ERROR: case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_TIMEOUT: // Do not perform level switch if an error occurred using delivery directives // Attempt to reload level without directives first if (context) { if (context.deliveryDirectives) { levelSwitch = false; } levelIndex = context.level; } levelError = true; break; case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].REMUX_ALLOC_ERROR: levelIndex = data.level; levelError = true; break; } if (levelIndex !== undefined) { this.recoverLevel(data, levelIndex, levelError, levelSwitch); } } /** * Switch to a redundant stream if any available. * If redundant stream is not available, emergency switch down if ABR mode is enabled. */ ; _proto.recoverLevel = function recoverLevel(errorEvent, levelIndex, levelError, levelSwitch) { var errorDetails = errorEvent.details; var level = this._levels[levelIndex]; level.loadError++; if (levelError) { var retrying = this.retryLoadingOrFail(errorEvent); if (retrying) { // boolean used to inform stream controller not to switch back to IDLE on non fatal error errorEvent.levelRetry = true; } else { this.currentLevelIndex = -1; return; } } if (levelSwitch) { var redundantLevels = level.url.length; // Try redundant fail-over until level.loadError reaches redundantLevels if (redundantLevels > 1 && level.loadError < redundantLevels) { errorEvent.levelRetry = true; this.redundantFailover(levelIndex); } else if (this.manualLevelIndex === -1) { // Search for available level in auto level selection mode, cycling from highest to lowest bitrate var nextLevel = levelIndex === 0 ? this._levels.length - 1 : levelIndex - 1; if (this.currentLevelIndex !== nextLevel && this._levels[nextLevel].loadError === 0) { this.warn(errorDetails + ": switch to " + nextLevel); errorEvent.levelRetry = true; this.hls.nextAutoLevel = nextLevel; } } } }; _proto.redundantFailover = function redundantFailover(levelIndex) { var level = this._levels[levelIndex]; var redundantLevels = level.url.length; if (redundantLevels > 1) { // Update the url id of all levels so that we stay on the same set of variants when level switching var newUrlId = (level.urlId + 1) % redundantLevels; this.warn("Switching to redundant URL-id " + newUrlId); this._levels.forEach(function (level) { level.urlId = newUrlId; }); this.level = levelIndex; } } // reset errors on the successful load of a fragment ; _proto.onFragLoaded = function onFragLoaded(event, _ref3) { var frag = _ref3.frag; if (frag !== undefined && frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN) { var level = this._levels[frag.level]; if (level !== undefined) { level.fragmentError = 0; level.loadError = 0; } } }; _proto.onLevelLoaded = function onLevelLoaded(event, data) { var _data$deliveryDirecti2; var level = data.level, details = data.details; var curLevel = this._levels[level]; if (!curLevel) { var _data$deliveryDirecti; this.warn("Invalid level index " + level); if ((_data$deliveryDirecti = data.deliveryDirectives) !== null && _data$deliveryDirecti !== void 0 && _data$deliveryDirecti.skip) { details.deltaUpdateFailed = true; } return; } // only process level loaded events matching with expected level if (level === this.currentLevelIndex) { // reset level load error counter on successful level loaded only if there is no issues with fragments if (curLevel.fragmentError === 0) { curLevel.loadError = 0; this.retryCount = 0; } this.playlistLoaded(level, data, curLevel.details); } else if ((_data$deliveryDirecti2 = data.deliveryDirectives) !== null && _data$deliveryDirecti2 !== void 0 && _data$deliveryDirecti2.skip) { // received a delta playlist update that cannot be merged details.deltaUpdateFailed = true; } }; _proto.onAudioTrackSwitched = function onAudioTrackSwitched(event, data) { var currentLevel = this.hls.levels[this.currentLevelIndex]; if (!currentLevel) { return; } if (currentLevel.audioGroupIds) { var urlId = -1; var audioGroupId = this.hls.audioTracks[data.id].groupId; for (var i = 0; i < currentLevel.audioGroupIds.length; i++) { if (currentLevel.audioGroupIds[i] === audioGroupId) { urlId = i; break; } } if (urlId !== currentLevel.urlId) { currentLevel.urlId = urlId; this.startLoad(); } } }; _proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) { var level = this.currentLevelIndex; var currentLevel = this._levels[level]; if (this.canLoad && currentLevel && currentLevel.url.length > 0) { var id = currentLevel.urlId; var url = currentLevel.url[id]; if (hlsUrlParameters) { try { url = hlsUrlParameters.addDirectives(url); } catch (error) { this.warn("Could not construct new URL with HLS Delivery Directives: " + error); } } this.log("Attempt loading level index " + level + (hlsUrlParameters ? ' at sn ' + hlsUrlParameters.msn + ' part ' + hlsUrlParameters.part : '') + " with URL-id " + id + " " + url); // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId); // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level); this.clearTimer(); this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADING, { url: url, level: level, id: id, deliveryDirectives: hlsUrlParameters || null }); } }; _proto.removeLevel = function removeLevel(levelIndex, urlId) { var filterLevelAndGroupByIdIndex = function filterLevelAndGroupByIdIndex(url, id) { return id !== urlId; }; var levels = this._levels.filter(function (level, index) { if (index !== levelIndex) { return true; } if (level.url.length > 1 && urlId !== undefined) { level.url = level.url.filter(filterLevelAndGroupByIdIndex); if (level.audioGroupIds) { level.audioGroupIds = level.audioGroupIds.filter(filterLevelAndGroupByIdIndex); } if (level.textGroupIds) { level.textGroupIds = level.textGroupIds.filter(filterLevelAndGroupByIdIndex); } level.urlId = 0; return true; } return false; }).map(function (level, index) { var details = level.details; if (details !== null && details !== void 0 && details.fragments) { details.fragments.forEach(function (fragment) { fragment.level = index; }); } return level; }); this._levels = levels; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVELS_UPDATED, { levels: levels }); }; _createClass(LevelController, [{ key: "levels", get: function get() { if (this._levels.length === 0) { return null; } return this._levels; } }, { key: "level", get: function get() { return this.currentLevelIndex; }, set: function set(newLevel) { var _levels$newLevel; var levels = this._levels; if (levels.length === 0) { return; } if (this.currentLevelIndex === newLevel && (_levels$newLevel = levels[newLevel]) !== null && _levels$newLevel !== void 0 && _levels$newLevel.details) { return; } // check if level idx is valid if (newLevel < 0 || newLevel >= levels.length) { // invalid level id given, trigger error var fatal = newLevel < 0; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].OTHER_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_SWITCH_ERROR, level: newLevel, fatal: fatal, reason: 'invalid level idx' }); if (fatal) { return; } newLevel = Math.min(newLevel, levels.length - 1); } // stopping live reloading timer if any this.clearTimer(); var lastLevelIndex = this.currentLevelIndex; var lastLevel = levels[lastLevelIndex]; var level = levels[newLevel]; this.log("switching to level " + newLevel + " from " + lastLevelIndex); this.currentLevelIndex = newLevel; var levelSwitchingData = _extends({}, level, { level: newLevel, maxBitrate: level.maxBitrate, uri: level.uri, urlId: level.urlId }); // @ts-ignore delete levelSwitchingData._urlId; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_SWITCHING, levelSwitchingData); // check if we need to load playlist for this level var levelDetails = level.details; if (!levelDetails || levelDetails.live) { // level not retrieved yet, or live playlist we need to (re)load it var hlsUrlParameters = this.switchParams(level.uri, lastLevel === null || lastLevel === void 0 ? void 0 : lastLevel.details); this.loadPlaylist(hlsUrlParameters); } } }, { key: "manualLevel", get: function get() { return this.manualLevelIndex; }, set: function set(newLevel) { this.manualLevelIndex = newLevel; if (this._startLevel === undefined) { this._startLevel = newLevel; } if (newLevel !== -1) { this.level = newLevel; } } }, { key: "firstLevel", get: function get() { return this._firstLevel; }, set: function set(newLevel) { this._firstLevel = newLevel; } }, { key: "startLevel", get: function get() { // hls.startLevel takes precedence over config.startLevel // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest) if (this._startLevel === undefined) { var configStartLevel = this.hls.config.startLevel; if (configStartLevel !== undefined) { return configStartLevel; } else { return this._firstLevel; } } else { return this._startLevel; } }, set: function set(newLevel) { this._startLevel = newLevel; } }, { key: "nextLoadLevel", get: function get() { if (this.manualLevelIndex !== -1) { return this.manualLevelIndex; } else { return this.hls.nextAutoLevel; } }, set: function set(nextLevel) { this.level = nextLevel; if (this.manualLevelIndex === -1) { this.hls.nextAutoLevel = nextLevel; } } }]); return LevelController; }(_base_playlist_controller__WEBPACK_IMPORTED_MODULE_5__["default"]); /***/ }), /***/ "./src/controller/level-helper.ts": /*!****************************************!*\ !*** ./src/controller/level-helper.ts ***! \****************************************/ /*! exports provided: addGroupId, assignTrackIdsByGroup, updatePTS, updateFragPTSDTS, mergeDetails, mapPartIntersection, mapFragmentIntersection, adjustSliding, addSliding, computeReloadInterval, getFragmentWithSN, getPartWith */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addGroupId", function() { return addGroupId; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "assignTrackIdsByGroup", function() { return assignTrackIdsByGroup; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updatePTS", function() { return updatePTS; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateFragPTSDTS", function() { return updateFragPTSDTS; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeDetails", function() { return mergeDetails; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapPartIntersection", function() { return mapPartIntersection; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapFragmentIntersection", function() { return mapFragmentIntersection; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "adjustSliding", function() { return adjustSliding; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addSliding", function() { return addSliding; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "computeReloadInterval", function() { return computeReloadInterval; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFragmentWithSN", function() { return getFragmentWithSN; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPartWith", function() { return getPartWith; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /** * @module LevelHelper * Providing methods dealing with playlist sliding and drift * */ function addGroupId(level, type, id) { switch (type) { case 'audio': if (!level.audioGroupIds) { level.audioGroupIds = []; } level.audioGroupIds.push(id); break; case 'text': if (!level.textGroupIds) { level.textGroupIds = []; } level.textGroupIds.push(id); break; } } function assignTrackIdsByGroup(tracks) { var groups = {}; tracks.forEach(function (track) { var groupId = track.groupId || ''; track.id = groups[groupId] = groups[groupId] || 0; groups[groupId]++; }); } function updatePTS(fragments, fromIdx, toIdx) { var fragFrom = fragments[fromIdx]; var fragTo = fragments[toIdx]; updateFromToPTS(fragFrom, fragTo); } function updateFromToPTS(fragFrom, fragTo) { var fragToPTS = fragTo.startPTS; // if we know startPTS[toIdx] if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(fragToPTS)) { // update fragment duration. // it helps to fix drifts between playlist reported duration and fragment real duration var duration = 0; var frag; if (fragTo.sn > fragFrom.sn) { duration = fragToPTS - fragFrom.start; frag = fragFrom; } else { duration = fragFrom.start - fragToPTS; frag = fragTo; } // TODO? Drift can go either way, or the playlist could be completely accurate // console.assert(duration > 0, // `duration of ${duration} computed for frag ${frag.sn}, level ${frag.level}, there should be some duration drift between playlist and fragment!`); if (frag.duration !== duration) { frag.duration = duration; } // we dont know startPTS[toIdx] } else if (fragTo.sn > fragFrom.sn) { var contiguous = fragFrom.cc === fragTo.cc; // TODO: With part-loading end/durations we need to confirm the whole fragment is loaded before using (or setting) minEndPTS if (contiguous && fragFrom.minEndPTS) { fragTo.start = fragFrom.start + (fragFrom.minEndPTS - fragFrom.start); } else { fragTo.start = fragFrom.start + fragFrom.duration; } } else { fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0); } } function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) { var parsedMediaDuration = endPTS - startPTS; if (parsedMediaDuration <= 0) { _utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('Fragment should have a positive duration', frag); endPTS = startPTS + frag.duration; endDTS = startDTS + frag.duration; } var maxStartPTS = startPTS; var minEndPTS = endPTS; var fragStartPts = frag.startPTS; var fragEndPts = frag.endPTS; if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(fragStartPts)) { // delta PTS between audio and video var deltaPTS = Math.abs(fragStartPts - startPTS); if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.deltaPTS)) { frag.deltaPTS = deltaPTS; } else { frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS); } maxStartPTS = Math.max(startPTS, fragStartPts); startPTS = Math.min(startPTS, fragStartPts); startDTS = Math.min(startDTS, frag.startDTS); minEndPTS = Math.min(endPTS, fragEndPts); endPTS = Math.max(endPTS, fragEndPts); endDTS = Math.max(endDTS, frag.endDTS); } frag.duration = endPTS - startPTS; var drift = startPTS - frag.start; frag.appendedPTS = endPTS; frag.start = frag.startPTS = startPTS; frag.maxStartPTS = maxStartPTS; frag.startDTS = startDTS; frag.endPTS = endPTS; frag.minEndPTS = minEndPTS; frag.endDTS = endDTS; var sn = frag.sn; // 'initSegment' // exit if sn out of range if (!details || sn < details.startSN || sn > details.endSN) { return 0; } var i; var fragIdx = sn - details.startSN; var fragments = details.fragments; // update frag reference in fragments array // rationale is that fragments array might not contain this frag object. // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS() // if we don't update frag, we won't be able to propagate PTS info on the playlist // resulting in invalid sliding computation fragments[fragIdx] = frag; // adjust fragment PTS/duration from seqnum-1 to frag 0 for (i = fragIdx; i > 0; i--) { updateFromToPTS(fragments[i], fragments[i - 1]); } // adjust fragment PTS/duration from seqnum to last frag for (i = fragIdx; i < fragments.length - 1; i++) { updateFromToPTS(fragments[i], fragments[i + 1]); } if (details.fragmentHint) { updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint); } details.PTSKnown = details.alignedSliding = true; return drift; } function mergeDetails(oldDetails, newDetails) { // Track the last initSegment processed. Initialize it to the last one on the timeline. var currentInitSegment = null; var oldFragments = oldDetails.fragments; for (var i = oldFragments.length - 1; i >= 0; i--) { var oldInit = oldFragments[i].initSegment; if (oldInit) { currentInitSegment = oldInit; break; } } if (oldDetails.fragmentHint) { // prevent PTS and duration from being adjusted on the next hint delete oldDetails.fragmentHint.endPTS; } // check if old/new playlists have fragments in common // loop through overlapping SN and update startPTS , cc, and duration if any found var ccOffset = 0; var PTSFrag; mapFragmentIntersection(oldDetails, newDetails, function (oldFrag, newFrag) { var _currentInitSegment; if (oldFrag.relurl) { // Do not compare CC if the old fragment has no url. This is a level.fragmentHint used by LL-HLS parts. // It maybe be off by 1 if it was created before any parts or discontinuity tags were appended to the end // of the playlist. ccOffset = oldFrag.cc - newFrag.cc; } if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(oldFrag.startPTS) && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(oldFrag.endPTS)) { newFrag.start = newFrag.startPTS = oldFrag.startPTS; newFrag.startDTS = oldFrag.startDTS; newFrag.appendedPTS = oldFrag.appendedPTS; newFrag.maxStartPTS = oldFrag.maxStartPTS; newFrag.endPTS = oldFrag.endPTS; newFrag.endDTS = oldFrag.endDTS; newFrag.minEndPTS = oldFrag.minEndPTS; newFrag.duration = oldFrag.endPTS - oldFrag.startPTS; if (newFrag.duration) { PTSFrag = newFrag; } // PTS is known when any segment has startPTS and endPTS newDetails.PTSKnown = newDetails.alignedSliding = true; } newFrag.elementaryStreams = oldFrag.elementaryStreams; newFrag.loader = oldFrag.loader; newFrag.stats = oldFrag.stats; newFrag.urlId = oldFrag.urlId; if (oldFrag.initSegment) { newFrag.initSegment = oldFrag.initSegment; currentInitSegment = oldFrag.initSegment; } else if (!newFrag.initSegment || newFrag.initSegment.relurl == ((_currentInitSegment = currentInitSegment) === null || _currentInitSegment === void 0 ? void 0 : _currentInitSegment.relurl)) { newFrag.initSegment = currentInitSegment; } }); if (newDetails.skippedSegments) { newDetails.deltaUpdateFailed = newDetails.fragments.some(function (frag) { return !frag; }); if (newDetails.deltaUpdateFailed) { _utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('[level-helper] Previous playlist missing segments skipped in delta playlist'); for (var _i = newDetails.skippedSegments; _i--;) { newDetails.fragments.shift(); } newDetails.startSN = newDetails.fragments[0].sn; newDetails.startCC = newDetails.fragments[0].cc; } } var newFragments = newDetails.fragments; if (ccOffset) { _utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('discontinuity sliding from playlist, take drift into account'); for (var _i2 = 0; _i2 < newFragments.length; _i2++) { newFragments[_i2].cc += ccOffset; } } if (newDetails.skippedSegments) { newDetails.startCC = newDetails.fragments[0].cc; } // Merge parts mapPartIntersection(oldDetails.partList, newDetails.partList, function (oldPart, newPart) { newPart.elementaryStreams = oldPart.elementaryStreams; newPart.stats = oldPart.stats; }); // if at least one fragment contains PTS info, recompute PTS information for all fragments if (PTSFrag) { updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS); } else { // ensure that delta is within oldFragments range // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61]) // in that case we also need to adjust start offset of all fragments adjustSliding(oldDetails, newDetails); } if (newFragments.length) { newDetails.totalduration = newDetails.edge - newFragments[0].start; } newDetails.driftStartTime = oldDetails.driftStartTime; newDetails.driftStart = oldDetails.driftStart; var advancedDateTime = newDetails.advancedDateTime; if (newDetails.advanced && advancedDateTime) { var edge = newDetails.edge; if (!newDetails.driftStart) { newDetails.driftStartTime = advancedDateTime; newDetails.driftStart = edge; } newDetails.driftEndTime = advancedDateTime; newDetails.driftEnd = edge; } else { newDetails.driftEndTime = oldDetails.driftEndTime; newDetails.driftEnd = oldDetails.driftEnd; newDetails.advancedDateTime = oldDetails.advancedDateTime; } } function mapPartIntersection(oldParts, newParts, intersectionFn) { if (oldParts && newParts) { var delta = 0; for (var i = 0, len = oldParts.length; i <= len; i++) { var _oldPart = oldParts[i]; var _newPart = newParts[i + delta]; if (_oldPart && _newPart && _oldPart.index === _newPart.index && _oldPart.fragment.sn === _newPart.fragment.sn) { intersectionFn(_oldPart, _newPart); } else { delta--; } } } } function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) { var skippedSegments = newDetails.skippedSegments; var start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN; var end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN; var delta = newDetails.startSN - oldDetails.startSN; var newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments; var oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments; for (var i = start; i <= end; i++) { var _oldFrag = oldFrags[delta + i]; var _newFrag = newFrags[i]; if (skippedSegments && !_newFrag && i < skippedSegments) { // Fill in skipped segments in delta playlist _newFrag = newDetails.fragments[i] = _oldFrag; } if (_oldFrag && _newFrag) { intersectionFn(_oldFrag, _newFrag); } } } function adjustSliding(oldDetails, newDetails) { var delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN; var oldFragments = oldDetails.fragments; if (delta < 0 || delta >= oldFragments.length) { return; } addSliding(newDetails, oldFragments[delta].start); } function addSliding(details, start) { if (start) { var fragments = details.fragments; for (var i = details.skippedSegments; i < fragments.length; i++) { fragments[i].start += start; } if (details.fragmentHint) { details.fragmentHint.start += start; } } } function computeReloadInterval(newDetails, stats) { var reloadInterval = 1000 * newDetails.levelTargetDuration; var reloadIntervalAfterMiss = reloadInterval / 2; var timeSinceLastModified = newDetails.age; var useLastModified = timeSinceLastModified > 0 && timeSinceLastModified < reloadInterval * 3; var roundTrip = stats.loading.end - stats.loading.start; var estimatedTimeUntilUpdate; var availabilityDelay = newDetails.availabilityDelay; // let estimate = 'average'; if (newDetails.updated === false) { if (useLastModified) { // estimate = 'miss round trip'; // We should have had a hit so try again in the time it takes to get a response, // but no less than 1/3 second. var minRetry = 333 * newDetails.misses; estimatedTimeUntilUpdate = Math.max(Math.min(reloadIntervalAfterMiss, roundTrip * 2), minRetry); newDetails.availabilityDelay = (newDetails.availabilityDelay || 0) + estimatedTimeUntilUpdate; } else { // estimate = 'miss half average'; // follow HLS Spec, If the client reloads a Playlist file and finds that it has not // changed then it MUST wait for a period of one-half the target // duration before retrying. estimatedTimeUntilUpdate = reloadIntervalAfterMiss; } } else if (useLastModified) { // estimate = 'next modified date'; // Get the closest we've been to timeSinceLastModified on update availabilityDelay = Math.min(availabilityDelay || reloadInterval / 2, timeSinceLastModified); newDetails.availabilityDelay = availabilityDelay; estimatedTimeUntilUpdate = availabilityDelay + reloadInterval - timeSinceLastModified; } else { estimatedTimeUntilUpdate = reloadInterval - roundTrip; } // console.log(`[computeReloadInterval] live reload ${newDetails.updated ? 'REFRESHED' : 'MISSED'}`, // '\n method', estimate, // '\n estimated time until update =>', estimatedTimeUntilUpdate, // '\n average target duration', reloadInterval, // '\n time since modified', timeSinceLastModified, // '\n time round trip', roundTrip, // '\n availability delay', availabilityDelay); return Math.round(estimatedTimeUntilUpdate); } function getFragmentWithSN(level, sn, fragCurrent) { if (!level || !level.details) { return null; } var levelDetails = level.details; var fragment = levelDetails.fragments[sn - levelDetails.startSN]; if (fragment) { return fragment; } fragment = levelDetails.fragmentHint; if (fragment && fragment.sn === sn) { return fragment; } if (sn < levelDetails.startSN && fragCurrent && fragCurrent.sn === sn) { return fragCurrent; } return null; } function getPartWith(level, sn, partIndex) { if (!level || !level.details) { return null; } var partList = level.details.partList; if (partList) { for (var i = partList.length; i--;) { var part = partList[i]; if (part.index === partIndex && part.fragment.sn === sn) { return part; } } } return null; } /***/ }), /***/ "./src/controller/stream-controller.ts": /*!*********************************************!*\ !*** ./src/controller/stream-controller.ts ***! \*********************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return StreamController; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base-stream-controller */ "./src/controller/base-stream-controller.ts"); /* harmony import */ var _is_supported__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../is-supported */ "./src/is-supported.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts"); /* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts"); /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts"); /* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts"); /* harmony import */ var _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../demux/transmuxer-interface */ "./src/demux/transmuxer-interface.ts"); /* harmony import */ var _types_transmuxer__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../types/transmuxer */ "./src/types/transmuxer.ts"); /* harmony import */ var _gap_controller__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./gap-controller */ "./src/controller/gap-controller.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var TICK_INTERVAL = 100; // how often to tick in ms var StreamController = /*#__PURE__*/function (_BaseStreamController) { _inheritsLoose(StreamController, _BaseStreamController); function StreamController(hls, fragmentTracker) { var _this; _this = _BaseStreamController.call(this, hls, fragmentTracker, '[stream-controller]') || this; _this.audioCodecSwap = false; _this.gapController = null; _this.level = -1; _this._forceStartLoad = false; _this.altAudio = false; _this.audioOnly = false; _this.fragPlaying = null; _this.onvplaying = null; _this.onvseeked = null; _this.fragLastKbps = 0; _this.stalled = false; _this.couldBacktrack = false; _this.audioCodecSwitch = false; _this.videoBuffer = null; _this._registerListeners(); return _this; } var _proto = StreamController.prototype; _proto._registerListeners = function _registerListeners() { var hls = this.hls; hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_LOADING, this.onManifestLoading, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_PARSED, this.onManifestParsed, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_LOADING, this.onLevelLoading, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_LOADED, this.onLevelLoaded, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, this.onError, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_CREATED, this.onBufferCreated, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_FLUSHED, this.onBufferFlushed, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVELS_UPDATED, this.onLevelsUpdated, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_BUFFERED, this.onFragBuffered, this); }; _proto._unregisterListeners = function _unregisterListeners() { var hls = this.hls; hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_LOADING, this.onManifestLoading, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_PARSED, this.onManifestParsed, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_LOADED, this.onLevelLoaded, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, this.onError, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_CREATED, this.onBufferCreated, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_FLUSHED, this.onBufferFlushed, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVELS_UPDATED, this.onLevelsUpdated, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_BUFFERED, this.onFragBuffered, this); }; _proto.onHandlerDestroying = function onHandlerDestroying() { this._unregisterListeners(); this.onMediaDetaching(); }; _proto.startLoad = function startLoad(startPosition) { if (this.levels) { var lastCurrentTime = this.lastCurrentTime, hls = this.hls; this.stopLoad(); this.setInterval(TICK_INTERVAL); this.level = -1; this.fragLoadError = 0; if (!this.startFragRequested) { // determine load level var startLevel = hls.startLevel; if (startLevel === -1) { if (hls.config.testBandwidth) { // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level startLevel = 0; this.bitrateTest = true; } else { startLevel = hls.nextAutoLevel; } } // set new level to playlist loader : this will trigger start level load // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded this.level = hls.nextLoadLevel = startLevel; this.loadedmetadata = false; } // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime if (lastCurrentTime > 0 && startPosition === -1) { this.log("Override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3)); startPosition = lastCurrentTime; } this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition; this.tick(); } else { this._forceStartLoad = true; this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].STOPPED; } }; _proto.stopLoad = function stopLoad() { this._forceStartLoad = false; _BaseStreamController.prototype.stopLoad.call(this); }; _proto.doTick = function doTick() { switch (this.state) { case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE: this.doTickIdle(); break; case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL: { var _levels$level; var levels = this.levels, level = this.level; var details = levels === null || levels === void 0 ? void 0 : (_levels$level = levels[level]) === null || _levels$level === void 0 ? void 0 : _levels$level.details; if (details && (!details.live || this.levelLastLoaded === this.level)) { if (this.waitForCdnTuneIn(details)) { break; } this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; break; } break; } case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING_WAITING_RETRY: { var _this$media; var now = self.performance.now(); var retryDate = this.retryDate; // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading if (!retryDate || now >= retryDate || (_this$media = this.media) !== null && _this$media !== void 0 && _this$media.seeking) { this.log('retryDate reached, switch back to IDLE state'); this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; } } break; default: break; } // check buffer // check/update current fragment this.onTickEnd(); }; _proto.onTickEnd = function onTickEnd() { _BaseStreamController.prototype.onTickEnd.call(this); this.checkBuffer(); this.checkFragmentChanged(); }; _proto.doTickIdle = function doTickIdle() { var _frag$decryptdata, _frag$decryptdata2; var hls = this.hls, levelLastLoaded = this.levelLastLoaded, levels = this.levels, media = this.media; var config = hls.config, level = hls.nextLoadLevel; // if start level not parsed yet OR // if video not attached AND start fragment already requested OR start frag prefetch not enabled // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment if (levelLastLoaded === null || !media && (this.startFragRequested || !config.startFragPrefetch)) { return; } // If the "main" level is audio-only but we are loading an alternate track in the same group, do not load anything if (this.altAudio && this.audioOnly) { return; } if (!levels || !levels[level]) { return; } var levelInfo = levels[level]; // if buffer length is less than maxBufLen try to load a new fragment // set next load level : this will trigger a playlist load if needed this.level = hls.nextLoadLevel = level; var levelDetails = levelInfo.details; // if level info not retrieved yet, switch state and wait for level retrieval // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist) if (!levelDetails || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL || levelDetails.live && this.levelLastLoaded !== level) { this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL; return; } var bufferInfo = this.getFwdBufferInfo(this.mediaBuffer ? this.mediaBuffer : media, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN); if (bufferInfo === null) { return; } var bufferLen = bufferInfo.len; // compute max Buffer Length that we could get from this load level, based on level bitrate. don't buffer more than 60 MB and more than 30s var maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate); // Stay idle if we are still with buffer margins if (bufferLen >= maxBufLen) { return; } if (this._streamEnded(bufferInfo, levelDetails)) { var data = {}; if (this.altAudio) { data.type = 'video'; } this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_EOS, data); this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ENDED; return; } var targetBufferTime = bufferInfo.end; var frag = this.getNextFragment(targetBufferTime, levelDetails); // Avoid backtracking after seeking or switching by loading an earlier segment in streams that could backtrack if (this.couldBacktrack && !this.fragPrevious && frag && frag.sn !== 'initSegment') { var fragIdx = frag.sn - levelDetails.startSN; if (fragIdx > 1) { frag = levelDetails.fragments[fragIdx - 1]; this.fragmentTracker.removeFragment(frag); } } // Avoid loop loading by using nextLoadPosition set for backtracking if (frag && this.fragmentTracker.getState(frag) === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].OK && this.nextLoadPosition > targetBufferTime) { // Cleanup the fragment tracker before trying to find the next unbuffered fragment var type = this.audioOnly && !this.altAudio ? _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO : _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].VIDEO; this.afterBufferFlushed(media, type, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN); frag = this.getNextFragment(this.nextLoadPosition, levelDetails); } if (!frag) { return; } if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) { frag = frag.initSegment; } // We want to load the key if we're dealing with an identity key, because we will decrypt // this content using the key we fetch. Other keys will be handled by the DRM CDM via EME. if (((_frag$decryptdata = frag.decryptdata) === null || _frag$decryptdata === void 0 ? void 0 : _frag$decryptdata.keyFormat) === 'identity' && !((_frag$decryptdata2 = frag.decryptdata) !== null && _frag$decryptdata2 !== void 0 && _frag$decryptdata2.key)) { this.loadKey(frag, levelDetails); } else { this.loadFragment(frag, levelDetails, targetBufferTime); } }; _proto.loadFragment = function loadFragment(frag, levelDetails, targetBufferTime) { var _this$media2; // Check if fragment is not loaded var fragState = this.fragmentTracker.getState(frag); this.fragCurrent = frag; // Use data from loaded backtracked fragment if available if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].BACKTRACKED) { var data = this.fragmentTracker.getBacktrackData(frag); if (data) { this._handleFragmentLoadProgress(data); this._handleFragmentLoadComplete(data); return; } else { fragState = _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].NOT_LOADED; } } if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].NOT_LOADED || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].PARTIAL) { if (frag.sn === 'initSegment') { this._loadInitSegment(frag); } else if (this.bitrateTest) { frag.bitrateTest = true; this.log("Fragment " + frag.sn + " of level " + frag.level + " is being downloaded to test bitrate and will not be buffered"); this._loadBitrateTestFrag(frag); } else { this.startFragRequested = true; _BaseStreamController.prototype.loadFragment.call(this, frag, levelDetails, targetBufferTime); } } else if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].APPENDING) { // Lower the buffer size and try again if (this.reduceMaxBufferLength(frag.duration)) { this.fragmentTracker.removeFragment(frag); } } else if (((_this$media2 = this.media) === null || _this$media2 === void 0 ? void 0 : _this$media2.buffered.length) === 0) { // Stop gap for bad tracker / buffer flush behavior this.fragmentTracker.removeAllFragments(); } }; _proto.getAppendedFrag = function getAppendedFrag(position) { var fragOrPart = this.fragmentTracker.getAppendedFrag(position, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN); if (fragOrPart && 'fragment' in fragOrPart) { return fragOrPart.fragment; } return fragOrPart; }; _proto.getBufferedFrag = function getBufferedFrag(position) { return this.fragmentTracker.getBufferedFrag(position, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN); }; _proto.followingBufferedFrag = function followingBufferedFrag(frag) { if (frag) { // try to get range of next fragment (500ms after this range) return this.getBufferedFrag(frag.end + 0.5); } return null; } /* on immediate level switch : - pause playback if playing - cancel any pending load request - and trigger a buffer flush */ ; _proto.immediateLevelSwitch = function immediateLevelSwitch() { this.abortCurrentFrag(); this.flushMainBuffer(0, Number.POSITIVE_INFINITY); } /** * try to switch ASAP without breaking video playback: * in order to ensure smooth but quick level switching, * we need to find the next flushable buffer range * we should take into account new segment fetch time */ ; _proto.nextLevelSwitch = function nextLevelSwitch() { var levels = this.levels, media = this.media; // ensure that media is defined and that metadata are available (to retrieve currentTime) if (media !== null && media !== void 0 && media.readyState) { var fetchdelay; var fragPlayingCurrent = this.getAppendedFrag(media.currentTime); if (fragPlayingCurrent && fragPlayingCurrent.start > 1) { // flush buffer preceding current fragment (flush until current fragment start offset) // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ... this.flushMainBuffer(0, fragPlayingCurrent.start - 1); } if (!media.paused && levels) { // add a safety delay of 1s var nextLevelId = this.hls.nextLoadLevel; var nextLevel = levels[nextLevelId]; var fragLastKbps = this.fragLastKbps; if (fragLastKbps && this.fragCurrent) { fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1000 * fragLastKbps) + 1; } else { fetchdelay = 0; } } else { fetchdelay = 0; } // this.log('fetchdelay:'+fetchdelay); // find buffer range that will be reached once new fragment will be fetched var bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay); if (bufferedFrag) { // we can flush buffer range following this one without stalling playback var nextBufferedFrag = this.followingBufferedFrag(bufferedFrag); if (nextBufferedFrag) { // if we are here, we can also cancel any loading/demuxing in progress, as they are useless this.abortCurrentFrag(); // start flush position is in next buffered frag. Leave some padding for non-independent segments and smoother playback. var maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start; var fragDuration = nextBufferedFrag.duration; var startPts = Math.max(bufferedFrag.end, maxStart + Math.min(Math.max(fragDuration - this.config.maxFragLookUpTolerance, fragDuration * 0.5), fragDuration * 0.75)); this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY); } } } }; _proto.abortCurrentFrag = function abortCurrentFrag() { var fragCurrent = this.fragCurrent; this.fragCurrent = null; if (fragCurrent !== null && fragCurrent !== void 0 && fragCurrent.loader) { fragCurrent.loader.abort(); } if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].KEY_LOADING) { this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; } this.nextLoadPosition = this.getLoadPosition(); }; _proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset) { _BaseStreamController.prototype.flushMainBuffer.call(this, startOffset, endOffset, this.altAudio ? 'video' : null); }; _proto.onMediaAttached = function onMediaAttached(event, data) { _BaseStreamController.prototype.onMediaAttached.call(this, event, data); var media = data.media; this.onvplaying = this.onMediaPlaying.bind(this); this.onvseeked = this.onMediaSeeked.bind(this); media.addEventListener('playing', this.onvplaying); media.addEventListener('seeked', this.onvseeked); this.gapController = new _gap_controller__WEBPACK_IMPORTED_MODULE_10__["default"](this.config, media, this.fragmentTracker, this.hls); }; _proto.onMediaDetaching = function onMediaDetaching() { var media = this.media; if (media) { media.removeEventListener('playing', this.onvplaying); media.removeEventListener('seeked', this.onvseeked); this.onvplaying = this.onvseeked = null; this.videoBuffer = null; } this.fragPlaying = null; if (this.gapController) { this.gapController.destroy(); this.gapController = null; } _BaseStreamController.prototype.onMediaDetaching.call(this); }; _proto.onMediaPlaying = function onMediaPlaying() { // tick to speed up FRAG_CHANGED triggering this.tick(); }; _proto.onMediaSeeked = function onMediaSeeked() { var media = this.media; var currentTime = media ? media.currentTime : null; if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(currentTime)) { this.log("Media seeked to " + currentTime.toFixed(3)); } // tick to speed up FRAG_CHANGED triggering this.tick(); }; _proto.onManifestLoading = function onManifestLoading() { // reset buffer on manifest loading this.log('Trigger BUFFER_RESET'); this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_RESET, undefined); this.fragmentTracker.removeAllFragments(); this.couldBacktrack = this.stalled = false; this.startPosition = this.lastCurrentTime = 0; this.fragPlaying = null; }; _proto.onManifestParsed = function onManifestParsed(event, data) { var aac = false; var heaac = false; var codec; data.levels.forEach(function (level) { // detect if we have different kind of audio codecs used amongst playlists codec = level.audioCodec; if (codec) { if (codec.indexOf('mp4a.40.2') !== -1) { aac = true; } if (codec.indexOf('mp4a.40.5') !== -1) { heaac = true; } } }); this.audioCodecSwitch = aac && heaac && !Object(_is_supported__WEBPACK_IMPORTED_MODULE_2__["changeTypeSupported"])(); if (this.audioCodecSwitch) { this.log('Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC'); } this.levels = data.levels; this.startFragRequested = false; }; _proto.onLevelLoading = function onLevelLoading(event, data) { var levels = this.levels; if (!levels || this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE) { return; } var level = levels[data.level]; if (!level.details || level.details.live && this.levelLastLoaded !== data.level || this.waitForCdnTuneIn(level.details)) { this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL; } }; _proto.onLevelLoaded = function onLevelLoaded(event, data) { var _curLevel$details; var levels = this.levels; var newLevelId = data.level; var newDetails = data.details; var duration = newDetails.totalduration; if (!levels) { this.warn("Levels were reset while loading level " + newLevelId); return; } this.log("Level " + newLevelId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "], cc [" + newDetails.startCC + ", " + newDetails.endCC + "] duration:" + duration); var fragCurrent = this.fragCurrent; if (fragCurrent && (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING_WAITING_RETRY)) { if (fragCurrent.level !== data.level && fragCurrent.loader) { this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; fragCurrent.loader.abort(); } } var curLevel = levels[newLevelId]; var sliding = 0; if (newDetails.live || (_curLevel$details = curLevel.details) !== null && _curLevel$details !== void 0 && _curLevel$details.live) { if (!newDetails.fragments[0]) { newDetails.deltaUpdateFailed = true; } if (newDetails.deltaUpdateFailed) { return; } sliding = this.alignPlaylists(newDetails, curLevel.details); } // override level info curLevel.details = newDetails; this.levelLastLoaded = newLevelId; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_UPDATED, { details: newDetails, level: newLevelId }); // only switch back to IDLE state if we were waiting for level to start downloading a new fragment if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL) { if (this.waitForCdnTuneIn(newDetails)) { // Wait for Low-Latency CDN Tune-in return; } this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; } if (!this.startFragRequested) { this.setStartPosition(newDetails, sliding); } else if (newDetails.live) { this.synchronizeToLiveEdge(newDetails); } // trigger handler right now this.tick(); }; _proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(data) { var _frag$initSegment; var frag = data.frag, part = data.part, payload = data.payload; var levels = this.levels; if (!levels) { this.warn("Levels were reset while fragment load was in progress. Fragment " + frag.sn + " of level " + frag.level + " will not be buffered"); return; } var currentLevel = levels[frag.level]; var details = currentLevel.details; if (!details) { this.warn("Dropping fragment " + frag.sn + " of level " + frag.level + " after level details were reset"); return; } var videoCodec = currentLevel.videoCodec; // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live) var accurateTimeOffset = details.PTSKnown || !details.live; var initSegmentData = (_frag$initSegment = frag.initSegment) === null || _frag$initSegment === void 0 ? void 0 : _frag$initSegment.data; var audioCodec = this._getAudioCodec(currentLevel); // transmux the MPEG-TS data to ISO-BMFF segments // this.log(`Transmuxing ${frag.sn} of [${details.startSN} ,${details.endSN}],level ${frag.level}, cc ${frag.cc}`); var transmuxer = this.transmuxer = this.transmuxer || new _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_8__["default"](this.hls, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this)); var partIndex = part ? part.index : -1; var partial = partIndex !== -1; var chunkMeta = new _types_transmuxer__WEBPACK_IMPORTED_MODULE_9__["ChunkMetadata"](frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial); var initPTS = this.initPTS[frag.cc]; transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS); }; _proto.onAudioTrackSwitching = function onAudioTrackSwitching(event, data) { // if any URL found on new audio track, it is an alternate audio track var fromAltAudio = this.altAudio; var altAudio = !!data.url; var trackId = data.id; // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered // don't do anything if we switch to alt audio: audio stream controller is handling it. // we will just have to change buffer scheduling on audioTrackSwitched if (!altAudio) { if (this.mediaBuffer !== this.media) { this.log('Switching on main audio, use media.buffered to schedule main fragment loading'); this.mediaBuffer = this.media; var fragCurrent = this.fragCurrent; // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch if (fragCurrent !== null && fragCurrent !== void 0 && fragCurrent.loader) { this.log('Switching to main audio track, cancel main fragment load'); fragCurrent.loader.abort(); } // destroy transmuxer to force init segment generation (following audio switch) this.resetTransmuxer(); // switch to IDLE state to load new fragment this.resetLoadingState(); } else if (this.audioOnly) { // Reset audio transmuxer so when switching back to main audio we're not still appending where we left off this.resetTransmuxer(); } var hls = this.hls; // If switching from alt to main audio, flush all audio and trigger track switched if (fromAltAudio) { hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' }); } hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHED, { id: trackId }); } }; _proto.onAudioTrackSwitched = function onAudioTrackSwitched(event, data) { var trackId = data.id; var altAudio = !!this.hls.audioTracks[trackId].url; if (altAudio) { var videoBuffer = this.videoBuffer; // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered if (videoBuffer && this.mediaBuffer !== videoBuffer) { this.log('Switching on alternate audio, use video.buffered to schedule main fragment loading'); this.mediaBuffer = videoBuffer; } } this.altAudio = altAudio; this.tick(); }; _proto.onBufferCreated = function onBufferCreated(event, data) { var tracks = data.tracks; var mediaTrack; var name; var alternate = false; for (var type in tracks) { var track = tracks[type]; if (track.id === 'main') { name = type; mediaTrack = track; // keep video source buffer reference if (type === 'video') { var videoTrack = tracks[type]; if (videoTrack) { this.videoBuffer = videoTrack.buffer; } } } else { alternate = true; } } if (alternate && mediaTrack) { this.log("Alternate track found, use " + name + ".buffered to schedule main fragment loading"); this.mediaBuffer = mediaTrack.buffer; } else { this.mediaBuffer = this.media; } }; _proto.onFragBuffered = function onFragBuffered(event, data) { var frag = data.frag, part = data.part; if (frag && frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN) { return; } if (this.fragContextChanged(frag)) { // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion // Avoid setting state back to IDLE, since that will interfere with a level switch this.warn("Fragment " + frag.sn + (part ? ' p: ' + part.index : '') + " of level " + frag.level + " finished buffering, but was aborted. state: " + this.state); if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSED) { this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; } return; } var stats = part ? part.stats : frag.stats; this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first)); if (frag.sn !== 'initSegment') { this.fragPrevious = frag; } this.fragBufferedComplete(frag, part); }; _proto.onError = function onError(event, data) { switch (data.details) { case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].FRAG_LOAD_ERROR: case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].FRAG_LOAD_TIMEOUT: case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].KEY_LOAD_ERROR: case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].KEY_LOAD_TIMEOUT: this.onFragmentOrKeyLoadError(_types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN, data); break; case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].LEVEL_LOAD_ERROR: case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].LEVEL_LOAD_TIMEOUT: if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ERROR) { if (data.fatal) { // if fatal error, stop processing this.warn("" + data.details); this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ERROR; } else { // in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE if (!data.levelRetry && this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL) { this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; } } } break; case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].BUFFER_FULL_ERROR: // if in appending state if (data.parent === 'main' && (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSED)) { var flushBuffer = true; var bufferedInfo = this.getFwdBufferInfo(this.media, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN); // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end // reduce max buf len if current position is buffered if (bufferedInfo && bufferedInfo.len > 0.5) { flushBuffer = !this.reduceMaxBufferLength(bufferedInfo.len); } if (flushBuffer) { // current position is not buffered, but browser is still complaining about buffer full error // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708 // in that case flush the whole buffer to recover this.warn('buffer full error also media.currentTime is not buffered, flush main'); // flush main buffer this.immediateLevelSwitch(); } this.resetLoadingState(); } break; default: break; } } // Checks the health of the buffer and attempts to resolve playback stalls. ; _proto.checkBuffer = function checkBuffer() { var media = this.media, gapController = this.gapController; if (!media || !gapController || !media.readyState) { // Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0) return; } // Check combined buffer var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(media); if (!this.loadedmetadata && buffered.length) { this.loadedmetadata = true; this.seekToStartPos(); } else { // Resolve gaps using the main buffer, whose ranges are the intersections of the A/V sourcebuffers gapController.poll(this.lastCurrentTime); } this.lastCurrentTime = media.currentTime; }; _proto.onFragLoadEmergencyAborted = function onFragLoadEmergencyAborted() { this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; // if loadedmetadata is not set, it means that we are emergency switch down on first frag // in that case, reset startFragRequested flag if (!this.loadedmetadata) { this.startFragRequested = false; this.nextLoadPosition = this.startPosition; } this.tickImmediate(); }; _proto.onBufferFlushed = function onBufferFlushed(event, _ref) { var type = _ref.type; if (type !== _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO || this.audioOnly && !this.altAudio) { var media = (type === _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media; this.afterBufferFlushed(media, type, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN); } }; _proto.onLevelsUpdated = function onLevelsUpdated(event, data) { this.levels = data.levels; }; _proto.swapAudioCodec = function swapAudioCodec() { this.audioCodecSwap = !this.audioCodecSwap; } /** * Seeks to the set startPosition if not equal to the mediaElement's current time. * @private */ ; _proto.seekToStartPos = function seekToStartPos() { var media = this.media; var currentTime = media.currentTime; var startPosition = this.startPosition; // only adjust currentTime if different from startPosition or if startPosition not buffered // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered if (startPosition >= 0 && currentTime < startPosition) { if (media.seeking) { _utils_logger__WEBPACK_IMPORTED_MODULE_12__["logger"].log("could not seek to " + startPosition + ", already seeking at " + currentTime); return; } var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(media); var bufferStart = buffered.length ? buffered.start(0) : 0; var delta = bufferStart - startPosition; if (delta > 0 && delta < this.config.maxBufferHole) { _utils_logger__WEBPACK_IMPORTED_MODULE_12__["logger"].log("adjusting start position by " + delta + " to match buffer start"); startPosition += delta; this.startPosition = startPosition; } this.log("seek to target start position " + startPosition + " from current time " + currentTime); media.currentTime = startPosition; } }; _proto._getAudioCodec = function _getAudioCodec(currentLevel) { var audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec; if (this.audioCodecSwap && audioCodec) { this.log('Swapping audio codec'); if (audioCodec.indexOf('mp4a.40.5') !== -1) { audioCodec = 'mp4a.40.2'; } else { audioCodec = 'mp4a.40.5'; } } return audioCodec; }; _proto._loadBitrateTestFrag = function _loadBitrateTestFrag(frag) { var _this2 = this; this._doFragLoad(frag).then(function (data) { var hls = _this2.hls; if (!data || hls.nextLoadLevel || _this2.fragContextChanged(frag)) { return; } _this2.fragLoadError = 0; _this2.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; _this2.startFragRequested = false; _this2.bitrateTest = false; var stats = frag.stats; // Bitrate tests fragments are neither parsed nor buffered stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now(); hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_LOADED, data); }); }; _proto._handleTransmuxComplete = function _handleTransmuxComplete(transmuxResult) { var _id3$samples; var id = 'main'; var hls = this.hls; var remuxResult = transmuxResult.remuxResult, chunkMeta = transmuxResult.chunkMeta; var context = this.getCurrentContext(chunkMeta); if (!context) { this.warn("The loading context changed while buffering fragment " + chunkMeta.sn + " of level " + chunkMeta.level + ". This chunk will not be buffered."); this.resetLiveStartWhenNotLoaded(chunkMeta.level); return; } var frag = context.frag, part = context.part, level = context.level; var video = remuxResult.video, text = remuxResult.text, id3 = remuxResult.id3, initSegment = remuxResult.initSegment; // The audio-stream-controller handles audio buffering if Hls.js is playing an alternate audio track var audio = this.altAudio ? undefined : remuxResult.audio; // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level. // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed. if (this.fragContextChanged(frag)) { return; } this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING; if (initSegment) { if (initSegment.tracks) { this._bufferInitSegment(level, initSegment.tracks, frag, chunkMeta); hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_PARSING_INIT_SEGMENT, { frag: frag, id: id, tracks: initSegment.tracks }); } // This would be nice if Number.isFinite acted as a typeguard, but it doesn't. See: https://github.com/Microsoft/TypeScript/issues/10038 var initPTS = initSegment.initPTS; var timescale = initSegment.timescale; if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(initPTS)) { this.initPTS[frag.cc] = initPTS; hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].INIT_PTS_FOUND, { frag: frag, id: id, initPTS: initPTS, timescale: timescale }); } } // Avoid buffering if backtracking this fragment if (video && remuxResult.independent !== false) { if (level.details) { var startPTS = video.startPTS, endPTS = video.endPTS, startDTS = video.startDTS, endDTS = video.endDTS; if (part) { part.elementaryStreams[video.type] = { startPTS: startPTS, endPTS: endPTS, startDTS: startDTS, endDTS: endDTS }; } else { if (video.firstKeyFrame && video.independent) { this.couldBacktrack = true; } if (video.dropped && video.independent) { // Backtrack if dropped frames create a gap after currentTime var pos = this.getLoadPosition() + this.config.maxBufferHole; if (pos < startPTS) { this.backtrack(frag); return; } // Set video stream start to fragment start so that truncated samples do not distort the timeline, and mark it partial frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true); } } frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS); this.bufferFragmentData(video, frag, part, chunkMeta); } } else if (remuxResult.independent === false) { this.backtrack(frag); return; } if (audio) { var _startPTS = audio.startPTS, _endPTS = audio.endPTS, _startDTS = audio.startDTS, _endDTS = audio.endDTS; if (part) { part.elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO] = { startPTS: _startPTS, endPTS: _endPTS, startDTS: _startDTS, endDTS: _endDTS }; } frag.setElementaryStreamInfo(_loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO, _startPTS, _endPTS, _startDTS, _endDTS); this.bufferFragmentData(audio, frag, part, chunkMeta); } if (id3 !== null && id3 !== void 0 && (_id3$samples = id3.samples) !== null && _id3$samples !== void 0 && _id3$samples.length) { var emittedID3 = { frag: frag, id: id, samples: id3.samples }; hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_PARSING_METADATA, emittedID3); } if (text) { var emittedText = { frag: frag, id: id, samples: text.samples }; hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_PARSING_USERDATA, emittedText); } }; _proto._bufferInitSegment = function _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) { var _this3 = this; if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING) { return; } this.audioOnly = !!tracks.audio && !tracks.video; // if audio track is expected to come from audio stream controller, discard any coming from main if (this.altAudio && !this.audioOnly) { delete tracks.audio; } // include levelCodec in audio and video tracks var audio = tracks.audio, video = tracks.video, audiovideo = tracks.audiovideo; if (audio) { var audioCodec = currentLevel.audioCodec; var ua = navigator.userAgent.toLowerCase(); if (this.audioCodecSwitch) { if (audioCodec) { if (audioCodec.indexOf('mp4a.40.5') !== -1) { audioCodec = 'mp4a.40.2'; } else { audioCodec = 'mp4a.40.5'; } } // In the case that AAC and HE-AAC audio codecs are signalled in manifest, // force HE-AAC, as it seems that most browsers prefers it. // don't force HE-AAC if mono stream, or in Firefox if (audio.metadata.channelCount !== 1 && ua.indexOf('firefox') === -1) { audioCodec = 'mp4a.40.5'; } } // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise if (ua.indexOf('android') !== -1 && audio.container !== 'audio/mpeg') { // Exclude mpeg audio audioCodec = 'mp4a.40.2'; this.log("Android: force audio codec to " + audioCodec); } if (currentLevel.audioCodec && currentLevel.audioCodec !== audioCodec) { this.log("Swapping manifest audio codec \"" + currentLevel.audioCodec + "\" for \"" + audioCodec + "\""); } audio.levelCodec = audioCodec; audio.id = 'main'; this.log("Init audio buffer, container:" + audio.container + ", codecs[selected/level/parsed]=[" + (audioCodec || '') + "/" + (currentLevel.audioCodec || '') + "/" + audio.codec + "]"); } if (video) { video.levelCodec = currentLevel.videoCodec; video.id = 'main'; this.log("Init video buffer, container:" + video.container + ", codecs[level/parsed]=[" + (currentLevel.videoCodec || '') + "/" + video.codec + "]"); } if (audiovideo) { this.log("Init audiovideo buffer, container:" + audiovideo.container + ", codecs[level/parsed]=[" + (currentLevel.attrs.CODECS || '') + "/" + audiovideo.codec + "]"); } this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_CODECS, tracks); // loop through tracks that are going to be provided to bufferController Object.keys(tracks).forEach(function (trackName) { var track = tracks[trackName]; var initSegment = track.initSegment; if (initSegment !== null && initSegment !== void 0 && initSegment.byteLength) { _this3.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_APPENDING, { type: trackName, data: initSegment, frag: frag, part: null, chunkMeta: chunkMeta, parent: frag.type }); } }); // trigger handler right now this.tick(); }; _proto.backtrack = function backtrack(frag) { this.couldBacktrack = true; // Causes findFragments to backtrack through fragments to find the keyframe this.resetTransmuxer(); this.flushBufferGap(frag); var data = this.fragmentTracker.backtrack(frag); this.fragPrevious = null; this.nextLoadPosition = frag.start; if (data) { this.resetFragmentLoading(frag); } else { // Change state to BACKTRACKING so that fragmentEntity.backtrack data can be added after _doFragLoad this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].BACKTRACKING; } }; _proto.checkFragmentChanged = function checkFragmentChanged() { var video = this.media; var fragPlayingCurrent = null; if (video && video.readyState > 1 && video.seeking === false) { var currentTime = video.currentTime; /* if video element is in seeked state, currentTime can only increase. (assuming that playback rate is positive ...) As sometimes currentTime jumps back to zero after a media decode error, check this, to avoid seeking back to wrong position after a media decode error */ if (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].isBuffered(video, currentTime)) { fragPlayingCurrent = this.getAppendedFrag(currentTime); } else if (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].isBuffered(video, currentTime + 0.1)) { /* ensure that FRAG_CHANGED event is triggered at startup, when first video frame is displayed and playback is paused. add a tolerance of 100ms, in case current position is not buffered, check if current pos+100ms is buffered and use that buffer range for FRAG_CHANGED event reporting */ fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1); } if (fragPlayingCurrent) { var fragPlaying = this.fragPlaying; var fragCurrentLevel = fragPlayingCurrent.level; if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel || fragPlayingCurrent.urlId !== fragPlaying.urlId) { this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_CHANGED, { frag: fragPlayingCurrent }); if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) { this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_SWITCHED, { level: fragCurrentLevel }); } this.fragPlaying = fragPlayingCurrent; } } } }; _createClass(StreamController, [{ key: "nextLevel", get: function get() { var frag = this.nextBufferedFrag; if (frag) { return frag.level; } else { return -1; } } }, { key: "currentLevel", get: function get() { var media = this.media; if (media) { var fragPlayingCurrent = this.getAppendedFrag(media.currentTime); if (fragPlayingCurrent) { return fragPlayingCurrent.level; } } return -1; } }, { key: "nextBufferedFrag", get: function get() { var media = this.media; if (media) { // first get end range of current fragment var fragPlayingCurrent = this.getAppendedFrag(media.currentTime); return this.followingBufferedFrag(fragPlayingCurrent); } else { return null; } } }, { key: "forceStartLoad", get: function get() { return this._forceStartLoad; } }]); return StreamController; }(_base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["default"]); /***/ }), /***/ "./src/controller/subtitle-stream-controller.ts": /*!******************************************************!*\ !*** ./src/controller/subtitle-stream-controller.ts ***! \******************************************************/ /*! exports provided: SubtitleStreamController */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubtitleStreamController", function() { return SubtitleStreamController; }); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts"); /* harmony import */ var _fragment_finders__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./fragment-finders */ "./src/controller/fragment-finders.ts"); /* harmony import */ var _utils_discontinuities__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/discontinuities */ "./src/utils/discontinuities.ts"); /* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts"); /* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts"); /* harmony import */ var _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./base-stream-controller */ "./src/controller/base-stream-controller.ts"); /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts"); /* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts"); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var TICK_INTERVAL = 500; // how often to tick in ms var SubtitleStreamController = /*#__PURE__*/function (_BaseStreamController) { _inheritsLoose(SubtitleStreamController, _BaseStreamController); function SubtitleStreamController(hls, fragmentTracker) { var _this; _this = _BaseStreamController.call(this, hls, fragmentTracker, '[subtitle-stream-controller]') || this; _this.levels = []; _this.currentTrackId = -1; _this.tracksBuffered = []; _this.mainDetails = null; _this._registerListeners(); return _this; } var _proto = SubtitleStreamController.prototype; _proto.onHandlerDestroying = function onHandlerDestroying() { this._unregisterListeners(); this.mainDetails = null; }; _proto._registerListeners = function _registerListeners() { var hls = this.hls; hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADED, this.onLevelLoaded, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this); }; _proto._unregisterListeners = function _unregisterListeners() { var hls = this.hls; hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADED, this.onLevelLoaded, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this); }; _proto.startLoad = function startLoad() { this.stopLoad(); this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__["State"].IDLE; this.setInterval(TICK_INTERVAL); this.tick(); }; _proto.onManifestLoading = function onManifestLoading() { this.mainDetails = null; this.fragmentTracker.removeAllFragments(); }; _proto.onLevelLoaded = function onLevelLoaded(event, data) { this.mainDetails = data.details; }; _proto.onSubtitleFragProcessed = function onSubtitleFragProcessed(event, data) { var frag = data.frag, success = data.success; this.fragPrevious = frag; this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__["State"].IDLE; if (!success) { return; } var buffered = this.tracksBuffered[this.currentTrackId]; if (!buffered) { return; } // Create/update a buffered array matching the interface used by BufferHelper.bufferedInfo // so we can re-use the logic used to detect how much has been buffered var timeRange; var fragStart = frag.start; for (var i = 0; i < buffered.length; i++) { if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) { timeRange = buffered[i]; break; } } var fragEnd = frag.start + frag.duration; if (timeRange) { timeRange.end = fragEnd; } else { timeRange = { start: fragStart, end: fragEnd }; buffered.push(timeRange); } this.fragmentTracker.fragBuffered(frag); }; _proto.onBufferFlushing = function onBufferFlushing(event, data) { var startOffset = data.startOffset, endOffset = data.endOffset; if (startOffset === 0 && endOffset !== Number.POSITIVE_INFINITY) { var currentTrackId = this.currentTrackId, levels = this.levels; if (!levels.length || !levels[currentTrackId] || !levels[currentTrackId].details) { return; } var trackDetails = levels[currentTrackId].details; var targetDuration = trackDetails.targetduration; var endOffsetSubtitles = endOffset - targetDuration; if (endOffsetSubtitles <= 0) { return; } data.endOffsetSubtitles = Math.max(0, endOffsetSubtitles); this.tracksBuffered.forEach(function (buffered) { for (var i = 0; i < buffered.length;) { if (buffered[i].end <= endOffsetSubtitles) { buffered.shift(); continue; } else if (buffered[i].start < endOffsetSubtitles) { buffered[i].start = endOffsetSubtitles; } else { break; } i++; } }); this.fragmentTracker.removeFragmentsInRange(startOffset, endOffsetSubtitles, _types_loader__WEBPACK_IMPORTED_MODULE_8__["PlaylistLevelType"].SUBTITLE); } } // If something goes wrong, proceed to next frag, if we were processing one. ; _proto.onError = function onError(event, data) { var _this$fragCurrent; var frag = data.frag; // don't handle error not related to subtitle fragment if (!frag || frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_8__["PlaylistLevelType"].SUBTITLE) { return; } if ((_this$fragCurrent = this.fragCurrent) !== null && _this$fragCurrent !== void 0 && _this$fragCurrent.loader) { this.fragCurrent.loader.abort(); } this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__["State"].IDLE; } // Got all new subtitle levels. ; _proto.onSubtitleTracksUpdated = function onSubtitleTracksUpdated(event, _ref) { var _this2 = this; var subtitleTracks = _ref.subtitleTracks; this.tracksBuffered = []; this.levels = subtitleTracks.map(function (mediaPlaylist) { return new _types_level__WEBPACK_IMPORTED_MODULE_9__["Level"](mediaPlaylist); }); this.fragmentTracker.removeAllFragments(); this.fragPrevious = null; this.levels.forEach(function (level) { _this2.tracksBuffered[level.id] = []; }); this.mediaBuffer = null; }; _proto.onSubtitleTrackSwitch = function onSubtitleTrackSwitch(event, data) { this.currentTrackId = data.id; if (!this.levels.length || this.currentTrackId === -1) { this.clearInterval(); return; } // Check if track has the necessary details to load fragments var currentTrack = this.levels[this.currentTrackId]; if (currentTrack !== null && currentTrack !== void 0 && currentTrack.details) { this.mediaBuffer = this.mediaBufferTimeRanges; this.setInterval(TICK_INTERVAL); } else { this.mediaBuffer = null; } } // Got a new set of subtitle fragments. ; _proto.onSubtitleTrackLoaded = function onSubtitleTrackLoaded(event, data) { var _track$details; var newDetails = data.details, trackId = data.id; var currentTrackId = this.currentTrackId, levels = this.levels; if (!levels.length) { return; } var track = levels[currentTrackId]; if (trackId >= levels.length || trackId !== currentTrackId || !track) { return; } this.mediaBuffer = this.mediaBufferTimeRanges; if (newDetails.live || (_track$details = track.details) !== null && _track$details !== void 0 && _track$details.live) { var mainDetails = this.mainDetails; if (newDetails.deltaUpdateFailed || !mainDetails) { return; } var mainSlidingStartFragment = mainDetails.fragments[0]; if (!track.details) { if (newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) { Object(_utils_discontinuities__WEBPACK_IMPORTED_MODULE_4__["alignPDT"])(newDetails, mainDetails); } else if (mainSlidingStartFragment) { // line up live playlist with main so that fragments in range are loaded Object(_level_helper__WEBPACK_IMPORTED_MODULE_5__["addSliding"])(newDetails, mainSlidingStartFragment.start); } } else { var sliding = this.alignPlaylists(newDetails, track.details); if (sliding === 0 && mainSlidingStartFragment) { // realign with main when there is no overlap with last refresh Object(_level_helper__WEBPACK_IMPORTED_MODULE_5__["addSliding"])(newDetails, mainSlidingStartFragment.start); } } } track.details = newDetails; this.levelLastLoaded = trackId; // trigger handler right now this.tick(); // If playlist is misaligned because of bad PDT or drift, delete details to resync with main on reload if (newDetails.live && !this.fragCurrent && this.media && this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__["State"].IDLE) { var foundFrag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_3__["findFragmentByPTS"])(null, newDetails.fragments, this.media.currentTime, 0); if (!foundFrag) { this.warn('Subtitle playlist not aligned with playback'); track.details = undefined; } } }; _proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedData) { var frag = fragLoadedData.frag, payload = fragLoadedData.payload; var decryptData = frag.decryptdata; var hls = this.hls; if (this.fragContextChanged(frag)) { return; } // check to see if the payload needs to be decrypted if (payload && payload.byteLength > 0 && decryptData && decryptData.key && decryptData.iv && decryptData.method === 'AES-128') { var startTime = performance.now(); // decrypt the subtitles this.decrypter.webCryptoDecrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer).then(function (decryptedData) { var endTime = performance.now(); hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_DECRYPTED, { frag: frag, payload: decryptedData, stats: { tstart: startTime, tdecrypt: endTime } }); }); } }; _proto.doTick = function doTick() { if (!this.media) { this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__["State"].IDLE; return; } if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__["State"].IDLE) { var _foundFrag; var currentTrackId = this.currentTrackId, levels = this.levels; if (!levels.length || !levels[currentTrackId] || !levels[currentTrackId].details) { return; } // Expand range of subs loaded by one target-duration in either direction to make up for misaligned playlists var trackDetails = levels[currentTrackId].details; var targetDuration = trackDetails.targetduration; var config = this.config, media = this.media; var bufferedInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_2__["BufferHelper"].bufferedInfo(this.mediaBufferTimeRanges, media.currentTime - targetDuration, config.maxBufferHole); var targetBufferTime = bufferedInfo.end, bufferLen = bufferedInfo.len; var maxBufLen = this.getMaxBufferLength() + targetDuration; if (bufferLen > maxBufLen) { return; } console.assert(trackDetails, 'Subtitle track details are defined on idle subtitle stream controller tick'); var fragments = trackDetails.fragments; var fragLen = fragments.length; var end = trackDetails.edge; var foundFrag; var fragPrevious = this.fragPrevious; if (targetBufferTime < end) { var maxFragLookUpTolerance = config.maxFragLookUpTolerance; if (fragPrevious && trackDetails.hasProgramDateTime) { foundFrag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_3__["findFragmentByPDT"])(fragments, fragPrevious.endProgramDateTime, maxFragLookUpTolerance); } if (!foundFrag) { foundFrag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_3__["findFragmentByPTS"])(fragPrevious, fragments, targetBufferTime, maxFragLookUpTolerance); if (!foundFrag && fragPrevious && fragPrevious.start < fragments[0].start) { foundFrag = fragments[0]; } } } else { foundFrag = fragments[fragLen - 1]; } if ((_foundFrag = foundFrag) !== null && _foundFrag !== void 0 && _foundFrag.encrypted) { _utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log("Loading key for " + foundFrag.sn); this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__["State"].KEY_LOADING; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADING, { frag: foundFrag }); } else if (foundFrag && this.fragmentTracker.getState(foundFrag) === _fragment_tracker__WEBPACK_IMPORTED_MODULE_6__["FragmentState"].NOT_LOADED) { // only load if fragment is not loaded this.loadFragment(foundFrag, trackDetails, targetBufferTime); } } }; _proto.loadFragment = function loadFragment(frag, levelDetails, targetBufferTime) { this.fragCurrent = frag; _BaseStreamController.prototype.loadFragment.call(this, frag, levelDetails, targetBufferTime); }; _createClass(SubtitleStreamController, [{ key: "mediaBufferTimeRanges", get: function get() { return this.tracksBuffered[this.currentTrackId] || []; } }]); return SubtitleStreamController; }(_base_stream_controller__WEBPACK_IMPORTED_MODULE_7__["default"]); /***/ }), /***/ "./src/controller/subtitle-track-controller.ts": /*!*****************************************************!*\ !*** ./src/controller/subtitle-track-controller.ts ***! \*****************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/texttrack-utils */ "./src/utils/texttrack-utils.ts"); /* harmony import */ var _base_playlist_controller__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base-playlist-controller */ "./src/controller/base-playlist-controller.ts"); /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts"); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var SubtitleTrackController = /*#__PURE__*/function (_BasePlaylistControll) { _inheritsLoose(SubtitleTrackController, _BasePlaylistControll); // Enable/disable subtitle display rendering function SubtitleTrackController(hls) { var _this; _this = _BasePlaylistControll.call(this, hls, '[subtitle-track-controller]') || this; _this.media = null; _this.tracks = []; _this.groupId = null; _this.tracksInGroup = []; _this.trackId = -1; _this.selectDefaultTrack = true; _this.queuedDefaultTrack = -1; _this.trackChangeListener = function () { return _this.onTextTracksChanged(); }; _this.asyncPollTrackChange = function () { return _this.pollTrackChange(0); }; _this.useTextTrackPolling = false; _this.subtitlePollingInterval = -1; _this.subtitleDisplay = true; _this.registerListeners(); return _this; } var _proto = SubtitleTrackController.prototype; _proto.destroy = function destroy() { this.unregisterListeners(); this.tracks.length = 0; this.tracksInGroup.length = 0; this.trackChangeListener = this.asyncPollTrackChange = null; _BasePlaylistControll.prototype.destroy.call(this); }; _proto.registerListeners = function registerListeners() { var hls = this.hls; hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADING, this.onLevelLoading, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_SWITCHING, this.onLevelSwitching, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this); }; _proto.unregisterListeners = function unregisterListeners() { var hls = this.hls; hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADING, this.onLevelLoading, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_SWITCHING, this.onLevelSwitching, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this); } // Listen for subtitle track change, then extract the current track ID. ; _proto.onMediaAttached = function onMediaAttached(event, data) { this.media = data.media; if (!this.media) { return; } if (this.queuedDefaultTrack > -1) { this.subtitleTrack = this.queuedDefaultTrack; this.queuedDefaultTrack = -1; } this.useTextTrackPolling = !(this.media.textTracks && 'onchange' in this.media.textTracks); if (this.useTextTrackPolling) { this.pollTrackChange(500); } else { this.media.textTracks.addEventListener('change', this.asyncPollTrackChange); } }; _proto.pollTrackChange = function pollTrackChange(timeout) { self.clearInterval(this.subtitlePollingInterval); this.subtitlePollingInterval = self.setInterval(this.trackChangeListener, timeout); }; _proto.onMediaDetaching = function onMediaDetaching() { if (!this.media) { return; } self.clearInterval(this.subtitlePollingInterval); if (!this.useTextTrackPolling) { this.media.textTracks.removeEventListener('change', this.asyncPollTrackChange); } if (this.trackId > -1) { this.queuedDefaultTrack = this.trackId; } var textTracks = filterSubtitleTracks(this.media.textTracks); // Clear loaded cues on media detachment from tracks textTracks.forEach(function (track) { Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["clearCurrentCues"])(track); }); // Disable all subtitle tracks before detachment so when reattached only tracks in that content are enabled. this.subtitleTrack = -1; this.media = null; }; _proto.onManifestLoading = function onManifestLoading() { this.tracks = []; this.groupId = null; this.tracksInGroup = []; this.trackId = -1; this.selectDefaultTrack = true; } // Fired whenever a new manifest is loaded. ; _proto.onManifestParsed = function onManifestParsed(event, data) { this.tracks = data.subtitleTracks; }; _proto.onSubtitleTrackLoaded = function onSubtitleTrackLoaded(event, data) { var id = data.id, details = data.details; var trackId = this.trackId; var currentTrack = this.tracksInGroup[trackId]; if (!currentTrack) { this.warn("Invalid subtitle track id " + id); return; } var curDetails = currentTrack.details; currentTrack.details = data.details; this.log("subtitle track " + id + " loaded [" + details.startSN + "-" + details.endSN + "]"); if (id === this.trackId) { this.retryCount = 0; this.playlistLoaded(id, data, curDetails); } }; _proto.onLevelLoading = function onLevelLoading(event, data) { this.switchLevel(data.level); }; _proto.onLevelSwitching = function onLevelSwitching(event, data) { this.switchLevel(data.level); }; _proto.switchLevel = function switchLevel(levelIndex) { var levelInfo = this.hls.levels[levelIndex]; if (!(levelInfo !== null && levelInfo !== void 0 && levelInfo.textGroupIds)) { return; } var textGroupId = levelInfo.textGroupIds[levelInfo.urlId]; if (this.groupId !== textGroupId) { var lastTrack = this.tracksInGroup ? this.tracksInGroup[this.trackId] : undefined; var subtitleTracks = this.tracks.filter(function (track) { return !textGroupId || track.groupId === textGroupId; }); this.tracksInGroup = subtitleTracks; var initialTrackId = this.findTrackId(lastTrack === null || lastTrack === void 0 ? void 0 : lastTrack.name) || this.findTrackId(); this.groupId = textGroupId; var subtitleTracksUpdated = { subtitleTracks: subtitleTracks }; this.log("Updating subtitle tracks, " + subtitleTracks.length + " track(s) found in \"" + textGroupId + "\" group-id"); this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACKS_UPDATED, subtitleTracksUpdated); if (initialTrackId !== -1) { this.setSubtitleTrack(initialTrackId, lastTrack); } } }; _proto.findTrackId = function findTrackId(name) { var textTracks = this.tracksInGroup; for (var i = 0; i < textTracks.length; i++) { var track = textTracks[i]; if (!this.selectDefaultTrack || track.default) { if (!name || name === track.name) { return track.id; } } } return -1; }; _proto.onError = function onError(event, data) { _BasePlaylistControll.prototype.onError.call(this, event, data); if (data.fatal || !data.context) { return; } if (data.context.type === _types_loader__WEBPACK_IMPORTED_MODULE_3__["PlaylistContextType"].SUBTITLE_TRACK && data.context.id === this.trackId && data.context.groupId === this.groupId) { this.retryLoadingOrFail(data); } } /** get alternate subtitle tracks list from playlist **/ ; _proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) { var currentTrack = this.tracksInGroup[this.trackId]; if (this.shouldLoadTrack(currentTrack)) { var id = currentTrack.id; var groupId = currentTrack.groupId; var url = currentTrack.url; if (hlsUrlParameters) { try { url = hlsUrlParameters.addDirectives(url); } catch (error) { this.warn("Could not construct new URL with HLS Delivery Directives: " + error); } } this.log("Loading subtitle playlist for id " + id); this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADING, { url: url, id: id, groupId: groupId, deliveryDirectives: hlsUrlParameters || null }); } } /** * Disables the old subtitleTrack and sets current mode on the next subtitleTrack. * This operates on the DOM textTracks. * A value of -1 will disable all subtitle tracks. */ ; _proto.toggleTrackModes = function toggleTrackModes(newId) { var _this2 = this; var media = this.media, subtitleDisplay = this.subtitleDisplay, trackId = this.trackId; if (!media) { return; } var textTracks = filterSubtitleTracks(media.textTracks); var groupTracks = textTracks.filter(function (track) { return track.groupId === _this2.groupId; }); if (newId === -1) { [].slice.call(textTracks).forEach(function (track) { track.mode = 'disabled'; }); } else { var oldTrack = groupTracks[trackId]; if (oldTrack) { oldTrack.mode = 'disabled'; } } var nextTrack = groupTracks[newId]; if (nextTrack) { nextTrack.mode = subtitleDisplay ? 'showing' : 'hidden'; } } /** * This method is responsible for validating the subtitle index and periodically reloading if live. * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track. */ ; _proto.setSubtitleTrack = function setSubtitleTrack(newId, lastTrack) { var _tracks$newId; var tracks = this.tracksInGroup; // setting this.subtitleTrack will trigger internal logic // if media has not been attached yet, it will fail // we keep a reference to the default track id // and we'll set subtitleTrack when onMediaAttached is triggered if (!this.media) { this.queuedDefaultTrack = newId; return; } if (this.trackId !== newId) { this.toggleTrackModes(newId); } // exit if track id as already set or invalid if (this.trackId === newId && (newId === -1 || (_tracks$newId = tracks[newId]) !== null && _tracks$newId !== void 0 && _tracks$newId.details) || newId < -1 || newId >= tracks.length) { return; } // stopping live reloading timer if any this.clearTimer(); var track = tracks[newId]; this.log("Switching to subtitle track " + newId); this.trackId = newId; if (track) { var id = track.id, _track$groupId = track.groupId, groupId = _track$groupId === void 0 ? '' : _track$groupId, name = track.name, type = track.type, url = track.url; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_SWITCH, { id: id, groupId: groupId, name: name, type: type, url: url }); var hlsUrlParameters = this.switchParams(track.url, lastTrack === null || lastTrack === void 0 ? void 0 : lastTrack.details); this.loadPlaylist(hlsUrlParameters); } else { // switch to -1 this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_SWITCH, { id: newId }); } }; _proto.onTextTracksChanged = function onTextTracksChanged() { if (!this.useTextTrackPolling) { self.clearInterval(this.subtitlePollingInterval); } // Media is undefined when switching streams via loadSource() if (!this.media || !this.hls.config.renderTextTracksNatively) { return; } var trackId = -1; var tracks = filterSubtitleTracks(this.media.textTracks); for (var id = 0; id < tracks.length; id++) { if (tracks[id].mode === 'hidden') { // Do not break in case there is a following track with showing. trackId = id; } else if (tracks[id].mode === 'showing') { trackId = id; break; } } // Setting current subtitleTrack will invoke code. if (this.subtitleTrack !== trackId) { this.subtitleTrack = trackId; } }; _createClass(SubtitleTrackController, [{ key: "subtitleTracks", get: function get() { return this.tracksInGroup; } /** get/set index of the selected subtitle track (based on index in subtitle track lists) **/ }, { key: "subtitleTrack", get: function get() { return this.trackId; }, set: function set(newId) { this.selectDefaultTrack = false; var lastTrack = this.tracksInGroup ? this.tracksInGroup[this.trackId] : undefined; this.setSubtitleTrack(newId, lastTrack); } }]); return SubtitleTrackController; }(_base_playlist_controller__WEBPACK_IMPORTED_MODULE_2__["default"]); function filterSubtitleTracks(textTrackList) { var tracks = []; for (var i = 0; i < textTrackList.length; i++) { var track = textTrackList[i]; // Edge adds a track without a label; we don't want to use it if (track.kind === 'subtitles' && track.label) { tracks.push(textTrackList[i]); } } return tracks; } /* harmony default export */ __webpack_exports__["default"] = (SubtitleTrackController); /***/ }), /***/ "./src/controller/timeline-controller.ts": /*!***********************************************!*\ !*** ./src/controller/timeline-controller.ts ***! \***********************************************/ /*! exports provided: TimelineController */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TimelineController", function() { return TimelineController; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _utils_cea_608_parser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/cea-608-parser */ "./src/utils/cea-608-parser.ts"); /* harmony import */ var _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/output-filter */ "./src/utils/output-filter.ts"); /* harmony import */ var _utils_webvtt_parser__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/webvtt-parser */ "./src/utils/webvtt-parser.ts"); /* harmony import */ var _utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/texttrack-utils */ "./src/utils/texttrack-utils.ts"); /* harmony import */ var _utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/imsc1-ttml-parser */ "./src/utils/imsc1-ttml-parser.ts"); /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); var TimelineController = /*#__PURE__*/function () { function TimelineController(hls) { this.hls = void 0; this.media = null; this.config = void 0; this.enabled = true; this.Cues = void 0; this.textTracks = []; this.tracks = []; this.initPTS = []; this.timescale = []; this.unparsedVttFrags = []; this.captionsTracks = {}; this.nonNativeCaptionsTracks = {}; this.cea608Parser1 = void 0; this.cea608Parser2 = void 0; this.lastSn = -1; this.prevCC = -1; this.vttCCs = newVTTCCs(); this.captionsProperties = void 0; this.hls = hls; this.config = hls.config; this.Cues = hls.config.cueHandler; this.captionsProperties = { textTrack1: { label: this.config.captionsTextTrack1Label, languageCode: this.config.captionsTextTrack1LanguageCode }, textTrack2: { label: this.config.captionsTextTrack2Label, languageCode: this.config.captionsTextTrack2LanguageCode }, textTrack3: { label: this.config.captionsTextTrack3Label, languageCode: this.config.captionsTextTrack3LanguageCode }, textTrack4: { label: this.config.captionsTextTrack4Label, languageCode: this.config.captionsTextTrack4LanguageCode } }; if (this.config.enableCEA708Captions) { var channel1 = new _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__["default"](this, 'textTrack1'); var channel2 = new _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__["default"](this, 'textTrack2'); var channel3 = new _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__["default"](this, 'textTrack3'); var channel4 = new _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__["default"](this, 'textTrack4'); this.cea608Parser1 = new _utils_cea_608_parser__WEBPACK_IMPORTED_MODULE_2__["default"](1, channel1, channel2); this.cea608Parser2 = new _utils_cea_608_parser__WEBPACK_IMPORTED_MODULE_2__["default"](3, channel3, channel4); } hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, this.onManifestLoaded, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADING, this.onFragLoading, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, this.onFragLoaded, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_DECRYPTED, this.onFragDecrypted, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].INIT_PTS_FOUND, this.onInitPtsFound, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this); } var _proto = TimelineController.prototype; _proto.destroy = function destroy() { var hls = this.hls; hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, this.onManifestLoaded, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADING, this.onFragLoading, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, this.onFragLoaded, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_DECRYPTED, this.onFragDecrypted, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].INIT_PTS_FOUND, this.onInitPtsFound, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this); // @ts-ignore this.hls = this.config = this.cea608Parser1 = this.cea608Parser2 = null; }; _proto.addCues = function addCues(trackName, startTime, endTime, screen, cueRanges) { // skip cues which overlap more than 50% with previously parsed time ranges var merged = false; for (var i = cueRanges.length; i--;) { var cueRange = cueRanges[i]; var overlap = intersection(cueRange[0], cueRange[1], startTime, endTime); if (overlap >= 0) { cueRange[0] = Math.min(cueRange[0], startTime); cueRange[1] = Math.max(cueRange[1], endTime); merged = true; if (overlap / (endTime - startTime) > 0.5) { return; } } } if (!merged) { cueRanges.push([startTime, endTime]); } if (this.config.renderTextTracksNatively) { var track = this.captionsTracks[trackName]; this.Cues.newCue(track, startTime, endTime, screen); } else { var cues = this.Cues.newCue(null, startTime, endTime, screen); this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].CUES_PARSED, { type: 'captions', cues: cues, track: trackName }); } } // Triggered when an initial PTS is found; used for synchronisation of WebVTT. ; _proto.onInitPtsFound = function onInitPtsFound(event, _ref) { var _this = this; var frag = _ref.frag, id = _ref.id, initPTS = _ref.initPTS, timescale = _ref.timescale; var unparsedVttFrags = this.unparsedVttFrags; if (id === 'main') { this.initPTS[frag.cc] = initPTS; this.timescale[frag.cc] = timescale; } // Due to asynchronous processing, initial PTS may arrive later than the first VTT fragments are loaded. // Parse any unparsed fragments upon receiving the initial PTS. if (unparsedVttFrags.length) { this.unparsedVttFrags = []; unparsedVttFrags.forEach(function (frag) { _this.onFragLoaded(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, frag); }); } }; _proto.getExistingTrack = function getExistingTrack(trackName) { var media = this.media; if (media) { for (var i = 0; i < media.textTracks.length; i++) { var textTrack = media.textTracks[i]; if (textTrack[trackName]) { return textTrack; } } } return null; }; _proto.createCaptionsTrack = function createCaptionsTrack(trackName) { if (this.config.renderTextTracksNatively) { this.createNativeTrack(trackName); } else { this.createNonNativeTrack(trackName); } }; _proto.createNativeTrack = function createNativeTrack(trackName) { if (this.captionsTracks[trackName]) { return; } var captionsProperties = this.captionsProperties, captionsTracks = this.captionsTracks, media = this.media; var _captionsProperties$t = captionsProperties[trackName], label = _captionsProperties$t.label, languageCode = _captionsProperties$t.languageCode; // Enable reuse of existing text track. var existingTrack = this.getExistingTrack(trackName); if (!existingTrack) { var textTrack = this.createTextTrack('captions', label, languageCode); if (textTrack) { // Set a special property on the track so we know it's managed by Hls.js textTrack[trackName] = true; captionsTracks[trackName] = textTrack; } } else { captionsTracks[trackName] = existingTrack; Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["clearCurrentCues"])(captionsTracks[trackName]); Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["sendAddTrackEvent"])(captionsTracks[trackName], media); } }; _proto.createNonNativeTrack = function createNonNativeTrack(trackName) { if (this.nonNativeCaptionsTracks[trackName]) { return; } // Create a list of a single track for the provider to consume var trackProperties = this.captionsProperties[trackName]; if (!trackProperties) { return; } var label = trackProperties.label; var track = { _id: trackName, label: label, kind: 'captions', default: trackProperties.media ? !!trackProperties.media.default : false, closedCaptions: trackProperties.media }; this.nonNativeCaptionsTracks[trackName] = track; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].NON_NATIVE_TEXT_TRACKS_FOUND, { tracks: [track] }); }; _proto.createTextTrack = function createTextTrack(kind, label, lang) { var media = this.media; if (!media) { return; } return media.addTextTrack(kind, label, lang); }; _proto.onMediaAttaching = function onMediaAttaching(event, data) { this.media = data.media; this._cleanTracks(); }; _proto.onMediaDetaching = function onMediaDetaching() { var captionsTracks = this.captionsTracks; Object.keys(captionsTracks).forEach(function (trackName) { Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["clearCurrentCues"])(captionsTracks[trackName]); delete captionsTracks[trackName]; }); this.nonNativeCaptionsTracks = {}; }; _proto.onManifestLoading = function onManifestLoading() { this.lastSn = -1; // Detect discontinuity in fragment parsing this.prevCC = -1; this.vttCCs = newVTTCCs(); // Detect discontinuity in subtitle manifests this._cleanTracks(); this.tracks = []; this.captionsTracks = {}; this.nonNativeCaptionsTracks = {}; this.textTracks = []; this.unparsedVttFrags = this.unparsedVttFrags || []; this.initPTS = []; this.timescale = []; if (this.cea608Parser1 && this.cea608Parser2) { this.cea608Parser1.reset(); this.cea608Parser2.reset(); } }; _proto._cleanTracks = function _cleanTracks() { // clear outdated subtitles var media = this.media; if (!media) { return; } var textTracks = media.textTracks; if (textTracks) { for (var i = 0; i < textTracks.length; i++) { Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["clearCurrentCues"])(textTracks[i]); } } }; _proto.onSubtitleTracksUpdated = function onSubtitleTracksUpdated(event, data) { var _this2 = this; this.textTracks = []; var tracks = data.subtitleTracks || []; var hasIMSC1 = tracks.some(function (track) { return track.textCodec === _utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["IMSC1_CODEC"]; }); if (this.config.enableWebVTT || hasIMSC1 && this.config.enableIMSC1) { var sameTracks = this.tracks && tracks && this.tracks.length === tracks.length; this.tracks = tracks || []; if (this.config.renderTextTracksNatively) { var inUseTracks = this.media ? this.media.textTracks : []; this.tracks.forEach(function (track, index) { var textTrack; if (index < inUseTracks.length) { var inUseTrack = null; for (var i = 0; i < inUseTracks.length; i++) { if (canReuseVttTextTrack(inUseTracks[i], track)) { inUseTrack = inUseTracks[i]; break; } } // Reuse tracks with the same label, but do not reuse 608/708 tracks if (inUseTrack) { textTrack = inUseTrack; } } if (textTrack) { Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["clearCurrentCues"])(textTrack); } else { textTrack = _this2.createTextTrack('subtitles', track.name, track.lang); if (textTrack) { textTrack.mode = 'disabled'; } } if (textTrack) { textTrack.groupId = track.groupId; _this2.textTracks.push(textTrack); } }); } else if (!sameTracks && this.tracks && this.tracks.length) { // Create a list of tracks for the provider to consume var tracksList = this.tracks.map(function (track) { return { label: track.name, kind: track.type.toLowerCase(), default: track.default, subtitleTrack: track }; }); this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].NON_NATIVE_TEXT_TRACKS_FOUND, { tracks: tracksList }); } } }; _proto.onManifestLoaded = function onManifestLoaded(event, data) { var _this3 = this; if (this.config.enableCEA708Captions && data.captions) { data.captions.forEach(function (captionsTrack) { var instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(captionsTrack.instreamId); if (!instreamIdMatch) { return; } var trackName = "textTrack" + instreamIdMatch[1]; var trackProperties = _this3.captionsProperties[trackName]; if (!trackProperties) { return; } trackProperties.label = captionsTrack.name; if (captionsTrack.lang) { // optional attribute trackProperties.languageCode = captionsTrack.lang; } trackProperties.media = captionsTrack; }); } }; _proto.onFragLoading = function onFragLoading(event, data) { var cea608Parser1 = this.cea608Parser1, cea608Parser2 = this.cea608Parser2, lastSn = this.lastSn; if (!this.enabled || !(cea608Parser1 && cea608Parser2)) { return; } // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack if (data.frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_7__["PlaylistLevelType"].MAIN) { var sn = data.frag.sn; if (sn !== lastSn + 1) { cea608Parser1.reset(); cea608Parser2.reset(); } this.lastSn = sn; } }; _proto.onFragLoaded = function onFragLoaded(event, data) { var frag = data.frag, payload = data.payload; var initPTS = this.initPTS, unparsedVttFrags = this.unparsedVttFrags; if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_7__["PlaylistLevelType"].SUBTITLE) { // If fragment is subtitle type, parse as WebVTT. if (payload.byteLength) { // We need an initial synchronisation PTS. Store fragments as long as none has arrived. if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(initPTS[frag.cc])) { unparsedVttFrags.push(data); if (initPTS.length) { // finish unsuccessfully, otherwise the subtitle-stream-controller could be blocked from loading new frags. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag, error: new Error('Missing initial subtitle PTS') }); } return; } var decryptData = frag.decryptdata; // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait. if (decryptData == null || decryptData.key == null || decryptData.method !== 'AES-128') { var trackPlaylistMedia = this.tracks[frag.level]; var vttCCs = this.vttCCs; if (!vttCCs[frag.cc]) { vttCCs[frag.cc] = { start: frag.start, prevCC: this.prevCC, new: true }; this.prevCC = frag.cc; } if (trackPlaylistMedia && trackPlaylistMedia.textCodec === _utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["IMSC1_CODEC"]) { this._parseIMSC1(frag, payload); } else { this._parseVTTs(frag, payload, vttCCs); } } } else { // In case there is no payload, finish unsuccessfully. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag, error: new Error('Empty subtitle payload') }); } } }; _proto._parseIMSC1 = function _parseIMSC1(frag, payload) { var _this4 = this; var hls = this.hls; Object(_utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["parseIMSC1"])(payload, this.initPTS[frag.cc], this.timescale[frag.cc], function (cues) { _this4._appendCues(cues, frag.level); hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, { success: true, frag: frag }); }, function (error) { _utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log("Failed to parse IMSC1: " + error); hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag, error: error }); }); }; _proto._parseVTTs = function _parseVTTs(frag, payload, vttCCs) { var _this5 = this; var hls = this.hls; // Parse the WebVTT file contents. Object(_utils_webvtt_parser__WEBPACK_IMPORTED_MODULE_4__["parseWebVTT"])(payload, this.initPTS[frag.cc], this.timescale[frag.cc], vttCCs, frag.cc, frag.start, function (cues) { _this5._appendCues(cues, frag.level); hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, { success: true, frag: frag }); }, function (error) { _this5._fallbackToIMSC1(frag, payload); // Something went wrong while parsing. Trigger event with success false. _utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log("Failed to parse VTT cue: " + error); hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag, error: error }); }); }; _proto._fallbackToIMSC1 = function _fallbackToIMSC1(frag, payload) { var _this6 = this; // If textCodec is unknown, try parsing as IMSC1. Set textCodec based on the result var trackPlaylistMedia = this.tracks[frag.level]; if (!trackPlaylistMedia.textCodec) { Object(_utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["parseIMSC1"])(payload, this.initPTS[frag.cc], this.timescale[frag.cc], function () { trackPlaylistMedia.textCodec = _utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["IMSC1_CODEC"]; _this6._parseIMSC1(frag, payload); }, function () { trackPlaylistMedia.textCodec = 'wvtt'; }); } }; _proto._appendCues = function _appendCues(cues, fragLevel) { var hls = this.hls; if (this.config.renderTextTracksNatively) { var textTrack = this.textTracks[fragLevel]; // WebVTTParser.parse is an async method and if the currently selected text track mode is set to "disabled" // before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null // and trying to access getCueById method of cues will throw an exception // Because we check if the mode is disabled, we can force check `cues` below. They can't be null. if (textTrack.mode === 'disabled') { return; } cues.forEach(function (cue) { return Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["addCueToTrack"])(textTrack, cue); }); } else { var currentTrack = this.tracks[fragLevel]; var track = currentTrack.default ? 'default' : 'subtitles' + fragLevel; hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].CUES_PARSED, { type: 'subtitles', cues: cues, track: track }); } }; _proto.onFragDecrypted = function onFragDecrypted(event, data) { var frag = data.frag; if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_7__["PlaylistLevelType"].SUBTITLE) { if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.initPTS[frag.cc])) { this.unparsedVttFrags.push(data); return; } this.onFragLoaded(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, data); } }; _proto.onSubtitleTracksCleared = function onSubtitleTracksCleared() { this.tracks = []; this.captionsTracks = {}; }; _proto.onFragParsingUserdata = function onFragParsingUserdata(event, data) { var cea608Parser1 = this.cea608Parser1, cea608Parser2 = this.cea608Parser2; if (!this.enabled || !(cea608Parser1 && cea608Parser2)) { return; } // If the event contains captions (found in the bytes property), push all bytes into the parser immediately // It will create the proper timestamps based on the PTS value for (var i = 0; i < data.samples.length; i++) { var ccBytes = data.samples[i].bytes; if (ccBytes) { var ccdatas = this.extractCea608Data(ccBytes); cea608Parser1.addData(data.samples[i].pts, ccdatas[0]); cea608Parser2.addData(data.samples[i].pts, ccdatas[1]); } } }; _proto.onBufferFlushing = function onBufferFlushing(event, _ref2) { var startOffset = _ref2.startOffset, endOffset = _ref2.endOffset, endOffsetSubtitles = _ref2.endOffsetSubtitles, type = _ref2.type; var media = this.media; if (!media || media.currentTime < endOffset) { return; } // Clear 608 caption cues from the captions TextTracks when the video back buffer is flushed // Forward cues are never removed because we can loose streamed 608 content from recent fragments if (!type || type === 'video') { var captionsTracks = this.captionsTracks; Object.keys(captionsTracks).forEach(function (trackName) { return Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["removeCuesInRange"])(captionsTracks[trackName], startOffset, endOffset); }); } if (this.config.renderTextTracksNatively) { // Clear VTT/IMSC1 subtitle cues from the subtitle TextTracks when the back buffer is flushed if (startOffset === 0 && endOffsetSubtitles !== undefined) { var textTracks = this.textTracks; Object.keys(textTracks).forEach(function (trackName) { return Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["removeCuesInRange"])(textTracks[trackName], startOffset, endOffsetSubtitles); }); } } }; _proto.extractCea608Data = function extractCea608Data(byteArray) { var count = byteArray[0] & 31; var position = 2; var actualCCBytes = [[], []]; for (var j = 0; j < count; j++) { var tmpByte = byteArray[position++]; var ccbyte1 = 0x7f & byteArray[position++]; var ccbyte2 = 0x7f & byteArray[position++]; var ccValid = (4 & tmpByte) !== 0; var ccType = 3 & tmpByte; if (ccbyte1 === 0 && ccbyte2 === 0) { continue; } if (ccValid) { if (ccType === 0 || ccType === 1) { actualCCBytes[ccType].push(ccbyte1); actualCCBytes[ccType].push(ccbyte2); } } } return actualCCBytes; }; return TimelineController; }(); function canReuseVttTextTrack(inUseTrack, manifestTrack) { return inUseTrack && inUseTrack.label === manifestTrack.name && !(inUseTrack.textTrack1 || inUseTrack.textTrack2); } function intersection(x1, x2, y1, y2) { return Math.min(x2, y2) - Math.max(x1, y1); } function newVTTCCs() { return { ccOffset: 0, presentationOffset: 0, 0: { start: 0, prevCC: -1, new: false } }; } /***/ }), /***/ "./src/crypt/aes-crypto.ts": /*!*********************************!*\ !*** ./src/crypt/aes-crypto.ts ***! \*********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AESCrypto; }); var AESCrypto = /*#__PURE__*/function () { function AESCrypto(subtle, iv) { this.subtle = void 0; this.aesIV = void 0; this.subtle = subtle; this.aesIV = iv; } var _proto = AESCrypto.prototype; _proto.decrypt = function decrypt(data, key) { return this.subtle.decrypt({ name: 'AES-CBC', iv: this.aesIV }, key, data); }; return AESCrypto; }(); /***/ }), /***/ "./src/crypt/aes-decryptor.ts": /*!************************************!*\ !*** ./src/crypt/aes-decryptor.ts ***! \************************************/ /*! exports provided: removePadding, default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removePadding", function() { return removePadding; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AESDecryptor; }); /* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/typed-array */ "./src/utils/typed-array.ts"); // PKCS7 function removePadding(array) { var outputBytes = array.byteLength; var paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1); if (paddingBytes) { return Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_0__["sliceUint8"])(array, 0, outputBytes - paddingBytes); } return array; } var AESDecryptor = /*#__PURE__*/function () { function AESDecryptor() { this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)]; this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)]; this.sBox = new Uint32Array(256); this.invSBox = new Uint32Array(256); this.key = new Uint32Array(0); this.ksRows = 0; this.keySize = 0; this.keySchedule = void 0; this.invKeySchedule = void 0; this.initTable(); } // Using view.getUint32() also swaps the byte order. var _proto = AESDecryptor.prototype; _proto.uint8ArrayToUint32Array_ = function uint8ArrayToUint32Array_(arrayBuffer) { var view = new DataView(arrayBuffer); var newArray = new Uint32Array(4); for (var i = 0; i < 4; i++) { newArray[i] = view.getUint32(i * 4); } return newArray; }; _proto.initTable = function initTable() { var sBox = this.sBox; var invSBox = this.invSBox; var subMix = this.subMix; var subMix0 = subMix[0]; var subMix1 = subMix[1]; var subMix2 = subMix[2]; var subMix3 = subMix[3]; var invSubMix = this.invSubMix; var invSubMix0 = invSubMix[0]; var invSubMix1 = invSubMix[1]; var invSubMix2 = invSubMix[2]; var invSubMix3 = invSubMix[3]; var d = new Uint32Array(256); var x = 0; var xi = 0; var i = 0; for (i = 0; i < 256; i++) { if (i < 128) { d[i] = i << 1; } else { d[i] = i << 1 ^ 0x11b; } } for (i = 0; i < 256; i++) { var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4; sx = sx >>> 8 ^ sx & 0xff ^ 0x63; sBox[x] = sx; invSBox[sx] = x; // Compute multiplication var x2 = d[x]; var x4 = d[x2]; var x8 = d[x4]; // Compute sub/invSub bytes, mix columns tables var t = d[sx] * 0x101 ^ sx * 0x1010100; subMix0[x] = t << 24 | t >>> 8; subMix1[x] = t << 16 | t >>> 16; subMix2[x] = t << 8 | t >>> 24; subMix3[x] = t; // Compute inv sub bytes, inv mix columns tables t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100; invSubMix0[sx] = t << 24 | t >>> 8; invSubMix1[sx] = t << 16 | t >>> 16; invSubMix2[sx] = t << 8 | t >>> 24; invSubMix3[sx] = t; // Compute next counter if (!x) { x = xi = 1; } else { x = x2 ^ d[d[d[x8 ^ x2]]]; xi ^= d[d[xi]]; } } }; _proto.expandKey = function expandKey(keyBuffer) { // convert keyBuffer to Uint32Array var key = this.uint8ArrayToUint32Array_(keyBuffer); var sameKey = true; var offset = 0; while (offset < key.length && sameKey) { sameKey = key[offset] === this.key[offset]; offset++; } if (sameKey) { return; } this.key = key; var keySize = this.keySize = key.length; if (keySize !== 4 && keySize !== 6 && keySize !== 8) { throw new Error('Invalid aes key size=' + keySize); } var ksRows = this.ksRows = (keySize + 6 + 1) * 4; var ksRow; var invKsRow; var keySchedule = this.keySchedule = new Uint32Array(ksRows); var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows); var sbox = this.sBox; var rcon = this.rcon; var invSubMix = this.invSubMix; var invSubMix0 = invSubMix[0]; var invSubMix1 = invSubMix[1]; var invSubMix2 = invSubMix[2]; var invSubMix3 = invSubMix[3]; var prev; var t; for (ksRow = 0; ksRow < ksRows; ksRow++) { if (ksRow < keySize) { prev = keySchedule[ksRow] = key[ksRow]; continue; } t = prev; if (ksRow % keySize === 0) { // Rot word t = t << 8 | t >>> 24; // Sub word t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff]; // Mix Rcon t ^= rcon[ksRow / keySize | 0] << 24; } else if (keySize > 6 && ksRow % keySize === 4) { // Sub word t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff]; } keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0; } for (invKsRow = 0; invKsRow < ksRows; invKsRow++) { ksRow = ksRows - invKsRow; if (invKsRow & 3) { t = keySchedule[ksRow]; } else { t = keySchedule[ksRow - 4]; } if (invKsRow < 4 || ksRow <= 4) { invKeySchedule[invKsRow] = t; } else { invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]]; } invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0; } } // Adding this as a method greatly improves performance. ; _proto.networkToHostOrderSwap = function networkToHostOrderSwap(word) { return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24; }; _proto.decrypt = function decrypt(inputArrayBuffer, offset, aesIV) { var nRounds = this.keySize + 6; var invKeySchedule = this.invKeySchedule; var invSBOX = this.invSBox; var invSubMix = this.invSubMix; var invSubMix0 = invSubMix[0]; var invSubMix1 = invSubMix[1]; var invSubMix2 = invSubMix[2]; var invSubMix3 = invSubMix[3]; var initVector = this.uint8ArrayToUint32Array_(aesIV); var initVector0 = initVector[0]; var initVector1 = initVector[1]; var initVector2 = initVector[2]; var initVector3 = initVector[3]; var inputInt32 = new Int32Array(inputArrayBuffer); var outputInt32 = new Int32Array(inputInt32.length); var t0, t1, t2, t3; var s0, s1, s2, s3; var inputWords0, inputWords1, inputWords2, inputWords3; var ksRow, i; var swapWord = this.networkToHostOrderSwap; while (offset < inputInt32.length) { inputWords0 = swapWord(inputInt32[offset]); inputWords1 = swapWord(inputInt32[offset + 1]); inputWords2 = swapWord(inputInt32[offset + 2]); inputWords3 = swapWord(inputInt32[offset + 3]); s0 = inputWords0 ^ invKeySchedule[0]; s1 = inputWords3 ^ invKeySchedule[1]; s2 = inputWords2 ^ invKeySchedule[2]; s3 = inputWords1 ^ invKeySchedule[3]; ksRow = 4; // Iterate through the rounds of decryption for (i = 1; i < nRounds; i++) { t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow]; t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1]; t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2]; t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3]; // Update state s0 = t0; s1 = t1; s2 = t2; s3 = t3; ksRow = ksRow + 4; } // Shift rows, sub bytes, add round key t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow]; t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1]; t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2]; t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3]; // Write outputInt32[offset] = swapWord(t0 ^ initVector0); outputInt32[offset + 1] = swapWord(t3 ^ initVector1); outputInt32[offset + 2] = swapWord(t2 ^ initVector2); outputInt32[offset + 3] = swapWord(t1 ^ initVector3); // reset initVector to last 4 unsigned int initVector0 = inputWords0; initVector1 = inputWords1; initVector2 = inputWords2; initVector3 = inputWords3; offset = offset + 4; } return outputInt32.buffer; }; return AESDecryptor; }(); /***/ }), /***/ "./src/crypt/decrypter.ts": /*!********************************!*\ !*** ./src/crypt/decrypter.ts ***! \********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Decrypter; }); /* harmony import */ var _aes_crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./aes-crypto */ "./src/crypt/aes-crypto.ts"); /* harmony import */ var _fast_aes_key__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./fast-aes-key */ "./src/crypt/fast-aes-key.ts"); /* harmony import */ var _aes_decryptor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./aes-decryptor */ "./src/crypt/aes-decryptor.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts"); /* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/typed-array */ "./src/utils/typed-array.ts"); var CHUNK_SIZE = 16; // 16 bytes, 128 bits var Decrypter = /*#__PURE__*/function () { function Decrypter(observer, config, _temp) { var _ref = _temp === void 0 ? {} : _temp, _ref$removePKCS7Paddi = _ref.removePKCS7Padding, removePKCS7Padding = _ref$removePKCS7Paddi === void 0 ? true : _ref$removePKCS7Paddi; this.logEnabled = true; this.observer = void 0; this.config = void 0; this.removePKCS7Padding = void 0; this.subtle = null; this.softwareDecrypter = null; this.key = null; this.fastAesKey = null; this.remainderData = null; this.currentIV = null; this.currentResult = null; this.observer = observer; this.config = config; this.removePKCS7Padding = removePKCS7Padding; // built in decryptor expects PKCS7 padding if (removePKCS7Padding) { try { var browserCrypto = self.crypto; if (browserCrypto) { this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle; } } catch (e) { /* no-op */ } } if (this.subtle === null) { this.config.enableSoftwareAES = true; } } var _proto = Decrypter.prototype; _proto.destroy = function destroy() { // @ts-ignore this.observer = null; }; _proto.isSync = function isSync() { return this.config.enableSoftwareAES; }; _proto.flush = function flush() { var currentResult = this.currentResult; if (!currentResult) { this.reset(); return; } var data = new Uint8Array(currentResult); this.reset(); if (this.removePKCS7Padding) { return Object(_aes_decryptor__WEBPACK_IMPORTED_MODULE_2__["removePadding"])(data); } return data; }; _proto.reset = function reset() { this.currentResult = null; this.currentIV = null; this.remainderData = null; if (this.softwareDecrypter) { this.softwareDecrypter = null; } }; _proto.decrypt = function decrypt(data, key, iv, callback) { if (this.config.enableSoftwareAES) { this.softwareDecrypt(new Uint8Array(data), key, iv); var decryptResult = this.flush(); if (decryptResult) { callback(decryptResult.buffer); } } else { this.webCryptoDecrypt(new Uint8Array(data), key, iv).then(callback); } }; _proto.softwareDecrypt = function softwareDecrypt(data, key, iv) { var currentIV = this.currentIV, currentResult = this.currentResult, remainderData = this.remainderData; this.logOnce('JS AES decrypt'); // The output is staggered during progressive parsing - the current result is cached, and emitted on the next call // This is done in order to strip PKCS7 padding, which is found at the end of each segment. We only know we've reached // the end on flush(), but by that time we have already received all bytes for the segment. // Progressive decryption does not work with WebCrypto if (remainderData) { data = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__["appendUint8Array"])(remainderData, data); this.remainderData = null; } // Byte length must be a multiple of 16 (AES-128 = 128 bit blocks = 16 bytes) var currentChunk = this.getValidChunk(data); if (!currentChunk.length) { return null; } if (currentIV) { iv = currentIV; } var softwareDecrypter = this.softwareDecrypter; if (!softwareDecrypter) { softwareDecrypter = this.softwareDecrypter = new _aes_decryptor__WEBPACK_IMPORTED_MODULE_2__["default"](); } softwareDecrypter.expandKey(key); var result = currentResult; this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv); this.currentIV = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__["sliceUint8"])(currentChunk, -16).buffer; if (!result) { return null; } return result; }; _proto.webCryptoDecrypt = function webCryptoDecrypt(data, key, iv) { var _this = this; var subtle = this.subtle; if (this.key !== key || !this.fastAesKey) { this.key = key; this.fastAesKey = new _fast_aes_key__WEBPACK_IMPORTED_MODULE_1__["default"](subtle, key); } return this.fastAesKey.expandKey().then(function (aesKey) { // decrypt using web crypto if (!subtle) { return Promise.reject(new Error('web crypto not initialized')); } var crypto = new _aes_crypto__WEBPACK_IMPORTED_MODULE_0__["default"](subtle, iv); return crypto.decrypt(data.buffer, aesKey); }).catch(function (err) { return _this.onWebCryptoError(err, data, key, iv); }); }; _proto.onWebCryptoError = function onWebCryptoError(err, data, key, iv) { _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('[decrypter.ts]: WebCrypto Error, disable WebCrypto API:', err); this.config.enableSoftwareAES = true; this.logEnabled = true; return this.softwareDecrypt(data, key, iv); }; _proto.getValidChunk = function getValidChunk(data) { var currentChunk = data; var splitPoint = data.length - data.length % CHUNK_SIZE; if (splitPoint !== data.length) { currentChunk = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__["sliceUint8"])(data, 0, splitPoint); this.remainderData = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__["sliceUint8"])(data, splitPoint); } return currentChunk; }; _proto.logOnce = function logOnce(msg) { if (!this.logEnabled) { return; } _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log("[decrypter.ts]: " + msg); this.logEnabled = false; }; return Decrypter; }(); /***/ }), /***/ "./src/crypt/fast-aes-key.ts": /*!***********************************!*\ !*** ./src/crypt/fast-aes-key.ts ***! \***********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return FastAESKey; }); var FastAESKey = /*#__PURE__*/function () { function FastAESKey(subtle, key) { this.subtle = void 0; this.key = void 0; this.subtle = subtle; this.key = key; } var _proto = FastAESKey.prototype; _proto.expandKey = function expandKey() { return this.subtle.importKey('raw', this.key, { name: 'AES-CBC' }, false, ['encrypt', 'decrypt']); }; return FastAESKey; }(); /***/ }), /***/ "./src/demux/aacdemuxer.ts": /*!*********************************!*\ !*** ./src/demux/aacdemuxer.ts ***! \*********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base-audio-demuxer */ "./src/demux/base-audio-demuxer.ts"); /* harmony import */ var _adts__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./adts */ "./src/demux/adts.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts"); function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * AAC demuxer */ var AACDemuxer = /*#__PURE__*/function (_BaseAudioDemuxer) { _inheritsLoose(AACDemuxer, _BaseAudioDemuxer); function AACDemuxer(observer, config) { var _this; _this = _BaseAudioDemuxer.call(this) || this; _this.observer = void 0; _this.config = void 0; _this.observer = observer; _this.config = config; return _this; } var _proto = AACDemuxer.prototype; _proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) { _BaseAudioDemuxer.prototype.resetInitSegment.call(this, audioCodec, videoCodec, duration); this._audioTrack = { container: 'audio/adts', type: 'audio', id: 0, pid: -1, sequenceNumber: 0, isAAC: true, samples: [], manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000, dropped: 0 }; } // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS ; AACDemuxer.probe = function probe(data) { if (!data) { return false; } // Check for the ADTS sync word // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1 // Layer bits (position 14 and 15) in header should be always 0 for ADTS // More info https://wiki.multimedia.cx/index.php?title=ADTS var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_3__["getID3Data"](data, 0) || []; var offset = id3Data.length; for (var length = data.length; offset < length; offset++) { if (_adts__WEBPACK_IMPORTED_MODULE_1__["probe"](data, offset)) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('ADTS sync word found !'); return true; } } return false; }; _proto.canParse = function canParse(data, offset) { return _adts__WEBPACK_IMPORTED_MODULE_1__["canParse"](data, offset); }; _proto.appendFrame = function appendFrame(track, data, offset) { _adts__WEBPACK_IMPORTED_MODULE_1__["initTrackConfig"](track, this.observer, data, offset, track.manifestCodec); var frame = _adts__WEBPACK_IMPORTED_MODULE_1__["appendFrame"](track, data, offset, this.initPTS, this.frameIndex); if (frame && frame.missing === 0) { return frame; } }; return AACDemuxer; }(_base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__["default"]); AACDemuxer.minProbeByteLength = 9; /* harmony default export */ __webpack_exports__["default"] = (AACDemuxer); /***/ }), /***/ "./src/demux/adts.ts": /*!***************************!*\ !*** ./src/demux/adts.ts ***! \***************************/ /*! exports provided: getAudioConfig, isHeaderPattern, getHeaderLength, getFullFrameLength, canGetFrameLength, isHeader, canParse, probe, initTrackConfig, getFrameDuration, parseFrameHeader, appendFrame */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getAudioConfig", function() { return getAudioConfig; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeaderPattern", function() { return isHeaderPattern; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getHeaderLength", function() { return getHeaderLength; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFullFrameLength", function() { return getFullFrameLength; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canGetFrameLength", function() { return canGetFrameLength; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeader", function() { return isHeader; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canParse", function() { return canParse; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "probe", function() { return probe; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initTrackConfig", function() { return initTrackConfig; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFrameDuration", function() { return getFrameDuration; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseFrameHeader", function() { return parseFrameHeader; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendFrame", function() { return appendFrame; }); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /** * ADTS parser helper * @link https://wiki.multimedia.cx/index.php?title=ADTS */ function getAudioConfig(observer, data, offset, audioCodec) { var adtsObjectType; var adtsExtensionSamplingIndex; var adtsChanelConfig; var config; var userAgent = navigator.userAgent.toLowerCase(); var manifestCodec = audioCodec; var adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; // byte 2 adtsObjectType = ((data[offset + 2] & 0xc0) >>> 6) + 1; var adtsSamplingIndex = (data[offset + 2] & 0x3c) >>> 2; if (adtsSamplingIndex > adtsSampleingRates.length - 1) { observer.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_PARSING_ERROR, fatal: true, reason: "invalid ADTS sampling index:" + adtsSamplingIndex }); return; } adtsChanelConfig = (data[offset + 2] & 0x01) << 2; // byte 3 adtsChanelConfig |= (data[offset + 3] & 0xc0) >>> 6; _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log("manifest codec:" + audioCodec + ", ADTS type:" + adtsObjectType + ", samplingIndex:" + adtsSamplingIndex); // firefox: freq less than 24kHz = AAC SBR (HE-AAC) if (/firefox/i.test(userAgent)) { if (adtsSamplingIndex >= 6) { adtsObjectType = 5; config = new Array(4); // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies // there is a factor 2 between frame sample rate and output sample rate // multiply frequency by 2 (see table below, equivalent to substract 3) adtsExtensionSamplingIndex = adtsSamplingIndex - 3; } else { adtsObjectType = 2; config = new Array(2); adtsExtensionSamplingIndex = adtsSamplingIndex; } // Android : always use AAC } else if (userAgent.indexOf('android') !== -1) { adtsObjectType = 2; config = new Array(2); adtsExtensionSamplingIndex = adtsSamplingIndex; } else { /* for other browsers (Chrome/Vivaldi/Opera ...) always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...) */ adtsObjectType = 5; config = new Array(4); // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz) if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSamplingIndex >= 6) { // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies // there is a factor 2 between frame sample rate and output sample rate // multiply frequency by 2 (see table below, equivalent to substract 3) adtsExtensionSamplingIndex = adtsSamplingIndex - 3; } else { // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio) // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo. if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && (adtsSamplingIndex >= 6 && adtsChanelConfig === 1 || /vivaldi/i.test(userAgent)) || !audioCodec && adtsChanelConfig === 1) { adtsObjectType = 2; config = new Array(2); } adtsExtensionSamplingIndex = adtsSamplingIndex; } } /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig() Audio Profile / Audio Object Type 0: Null 1: AAC Main 2: AAC LC (Low Complexity) 3: AAC SSR (Scalable Sample Rate) 4: AAC LTP (Long Term Prediction) 5: SBR (Spectral Band Replication) 6: AAC Scalable sampling freq 0: 96000 Hz 1: 88200 Hz 2: 64000 Hz 3: 48000 Hz 4: 44100 Hz 5: 32000 Hz 6: 24000 Hz 7: 22050 Hz 8: 16000 Hz 9: 12000 Hz 10: 11025 Hz 11: 8000 Hz 12: 7350 Hz 13: Reserved 14: Reserved 15: frequency is written explictly Channel Configurations These are the channel configurations: 0: Defined in AOT Specifc Config 1: 1 channel: front-center 2: 2 channels: front-left, front-right */ // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1 config[0] = adtsObjectType << 3; // samplingFrequencyIndex config[0] |= (adtsSamplingIndex & 0x0e) >> 1; config[1] |= (adtsSamplingIndex & 0x01) << 7; // channelConfiguration config[1] |= adtsChanelConfig << 3; if (adtsObjectType === 5) { // adtsExtensionSampleingIndex config[1] |= (adtsExtensionSamplingIndex & 0x0e) >> 1; config[2] = (adtsExtensionSamplingIndex & 0x01) << 7; // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ??? // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc config[2] |= 2 << 2; config[3] = 0; } return { config: config, samplerate: adtsSampleingRates[adtsSamplingIndex], channelCount: adtsChanelConfig, codec: 'mp4a.40.' + adtsObjectType, manifestCodec: manifestCodec }; } function isHeaderPattern(data, offset) { return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0; } function getHeaderLength(data, offset) { return data[offset + 1] & 0x01 ? 7 : 9; } function getFullFrameLength(data, offset) { return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xe0) >>> 5; } function canGetFrameLength(data, offset) { return offset + 5 < data.length; } function isHeader(data, offset) { // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1 // Layer bits (position 14 and 15) in header should be always 0 for ADTS // More info https://wiki.multimedia.cx/index.php?title=ADTS return offset + 1 < data.length && isHeaderPattern(data, offset); } function canParse(data, offset) { return canGetFrameLength(data, offset) && isHeaderPattern(data, offset) && getFullFrameLength(data, offset) <= data.length - offset; } function probe(data, offset) { // same as isHeader but we also check that ADTS frame follows last ADTS frame // or end of data is reached if (isHeader(data, offset)) { // ADTS header Length var headerLength = getHeaderLength(data, offset); if (offset + headerLength >= data.length) { return false; } // ADTS frame Length var frameLength = getFullFrameLength(data, offset); if (frameLength <= headerLength) { return false; } var newOffset = offset + frameLength; return newOffset === data.length || isHeader(data, newOffset); } return false; } function initTrackConfig(track, observer, data, offset, audioCodec) { if (!track.samplerate) { var config = getAudioConfig(observer, data, offset, audioCodec); if (!config) { return; } track.config = config.config; track.samplerate = config.samplerate; track.channelCount = config.channelCount; track.codec = config.codec; track.manifestCodec = config.manifestCodec; _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log("parsed codec:" + track.codec + ", rate:" + config.samplerate + ", channels:" + config.channelCount); } } function getFrameDuration(samplerate) { return 1024 * 90000 / samplerate; } function parseFrameHeader(data, offset, pts, frameIndex, frameDuration) { // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header var headerLength = getHeaderLength(data, offset); // retrieve frame size var frameLength = getFullFrameLength(data, offset); frameLength -= headerLength; if (frameLength > 0) { var stamp = pts + frameIndex * frameDuration; // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`); return { headerLength: headerLength, frameLength: frameLength, stamp: stamp }; } } function appendFrame(track, data, offset, pts, frameIndex) { var frameDuration = getFrameDuration(track.samplerate); var header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration); if (header) { var frameLength = header.frameLength, headerLength = header.headerLength, stamp = header.stamp; var length = headerLength + frameLength; var missing = Math.max(0, offset + length - data.length); // logger.log(`AAC frame ${frameIndex}, pts:${stamp} length@offset/total: ${frameLength}@${offset+headerLength}/${data.byteLength} missing: ${missing}`); var unit; if (missing) { unit = new Uint8Array(length - headerLength); unit.set(data.subarray(offset + headerLength, data.length), 0); } else { unit = data.subarray(offset + headerLength, offset + length); } var sample = { unit: unit, pts: stamp }; if (!missing) { track.samples.push(sample); } return { sample: sample, length: length, missing: missing }; } } /***/ }), /***/ "./src/demux/base-audio-demuxer.ts": /*!*****************************************!*\ !*** ./src/demux/base-audio-demuxer.ts ***! \*****************************************/ /*! exports provided: initPTSFn, default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initPTSFn", function() { return initPTSFn; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts"); /* harmony import */ var _dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./dummy-demuxed-track */ "./src/demux/dummy-demuxed-track.ts"); /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts"); /* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/typed-array */ "./src/utils/typed-array.ts"); var BaseAudioDemuxer = /*#__PURE__*/function () { function BaseAudioDemuxer() { this._audioTrack = void 0; this._id3Track = void 0; this.frameIndex = 0; this.cachedData = null; this.initPTS = null; } var _proto = BaseAudioDemuxer.prototype; _proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) { this._id3Track = { type: 'id3', id: 0, pid: -1, inputTimeScale: 90000, sequenceNumber: 0, samples: [], dropped: 0 }; }; _proto.resetTimeStamp = function resetTimeStamp() {}; _proto.resetContiguity = function resetContiguity() {}; _proto.canParse = function canParse(data, offset) { return false; }; _proto.appendFrame = function appendFrame(track, data, offset) {} // feed incoming data to the front of the parsing pipeline ; _proto.demux = function demux(data, timeOffset) { if (this.cachedData) { data = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_3__["appendUint8Array"])(this.cachedData, data); this.cachedData = null; } var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getID3Data"](data, 0); var offset = id3Data ? id3Data.length : 0; var lastDataIndex; var pts; var track = this._audioTrack; var id3Track = this._id3Track; var timestamp = id3Data ? _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getTimeStamp"](id3Data) : undefined; var length = data.length; if (this.frameIndex === 0 || this.initPTS === null) { this.initPTS = initPTSFn(timestamp, timeOffset); } // more expressive than alternative: id3Data?.length if (id3Data && id3Data.length > 0) { id3Track.samples.push({ pts: this.initPTS, dts: this.initPTS, data: id3Data }); } pts = this.initPTS; while (offset < length) { if (this.canParse(data, offset)) { var frame = this.appendFrame(track, data, offset); if (frame) { this.frameIndex++; pts = frame.sample.pts; offset += frame.length; lastDataIndex = offset; } else { offset = length; } } else if (_demux_id3__WEBPACK_IMPORTED_MODULE_1__["canParse"](data, offset)) { // after a ID3.canParse, a call to ID3.getID3Data *should* always returns some data id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getID3Data"](data, offset); id3Track.samples.push({ pts: pts, dts: pts, data: id3Data }); offset += id3Data.length; lastDataIndex = offset; } else { offset++; } if (offset === length && lastDataIndex !== length) { var partialData = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_4__["sliceUint8"])(data, lastDataIndex); if (this.cachedData) { this.cachedData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_3__["appendUint8Array"])(this.cachedData, partialData); } else { this.cachedData = partialData; } } } return { audioTrack: track, avcTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])(), id3Track: id3Track, textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])() }; }; _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) { return Promise.reject(new Error("[" + this + "] This demuxer does not support Sample-AES decryption")); }; _proto.flush = function flush(timeOffset) { // Parse cache in case of remaining frames. var cachedData = this.cachedData; if (cachedData) { this.cachedData = null; this.demux(cachedData, 0); } this.frameIndex = 0; return { audioTrack: this._audioTrack, avcTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])(), id3Track: this._id3Track, textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])() }; }; _proto.destroy = function destroy() {}; return BaseAudioDemuxer; }(); /** * Initialize PTS * <p> * use timestamp unless it is undefined, NaN or Infinity * </p> */ var initPTSFn = function initPTSFn(timestamp, timeOffset) { return Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(timestamp) ? timestamp * 90 : timeOffset * 90000; }; /* harmony default export */ __webpack_exports__["default"] = (BaseAudioDemuxer); /***/ }), /***/ "./src/demux/chunk-cache.ts": /*!**********************************!*\ !*** ./src/demux/chunk-cache.ts ***! \**********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ChunkCache; }); var ChunkCache = /*#__PURE__*/function () { function ChunkCache() { this.chunks = []; this.dataLength = 0; } var _proto = ChunkCache.prototype; _proto.push = function push(chunk) { this.chunks.push(chunk); this.dataLength += chunk.length; }; _proto.flush = function flush() { var chunks = this.chunks, dataLength = this.dataLength; var result; if (!chunks.length) { return new Uint8Array(0); } else if (chunks.length === 1) { result = chunks[0]; } else { result = concatUint8Arrays(chunks, dataLength); } this.reset(); return result; }; _proto.reset = function reset() { this.chunks.length = 0; this.dataLength = 0; }; return ChunkCache; }(); function concatUint8Arrays(chunks, dataLength) { var result = new Uint8Array(dataLength); var offset = 0; for (var i = 0; i < chunks.length; i++) { var chunk = chunks[i]; result.set(chunk, offset); offset += chunk.length; } return result; } /***/ }), /***/ "./src/demux/dummy-demuxed-track.ts": /*!******************************************!*\ !*** ./src/demux/dummy-demuxed-track.ts ***! \******************************************/ /*! exports provided: dummyTrack */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dummyTrack", function() { return dummyTrack; }); function dummyTrack() { return { type: '', id: -1, pid: -1, inputTimeScale: 90000, sequenceNumber: -1, samples: [], dropped: 0 }; } /***/ }), /***/ "./src/demux/exp-golomb.ts": /*!*********************************!*\ !*** ./src/demux/exp-golomb.ts ***! \*********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /** * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264. */ var ExpGolomb = /*#__PURE__*/function () { function ExpGolomb(data) { this.data = void 0; this.bytesAvailable = void 0; this.word = void 0; this.bitsAvailable = void 0; this.data = data; // the number of bytes left to examine in this.data this.bytesAvailable = data.byteLength; // the current word being examined this.word = 0; // :uint // the number of bits left to examine in the current word this.bitsAvailable = 0; // :uint } // ():void var _proto = ExpGolomb.prototype; _proto.loadWord = function loadWord() { var data = this.data; var bytesAvailable = this.bytesAvailable; var position = data.byteLength - bytesAvailable; var workingBytes = new Uint8Array(4); var availableBytes = Math.min(4, bytesAvailable); if (availableBytes === 0) { throw new Error('no bytes available'); } workingBytes.set(data.subarray(position, position + availableBytes)); this.word = new DataView(workingBytes.buffer).getUint32(0); // track the amount of this.data that has been processed this.bitsAvailable = availableBytes * 8; this.bytesAvailable -= availableBytes; } // (count:int):void ; _proto.skipBits = function skipBits(count) { var skipBytes; // :int if (this.bitsAvailable > count) { this.word <<= count; this.bitsAvailable -= count; } else { count -= this.bitsAvailable; skipBytes = count >> 3; count -= skipBytes >> 3; this.bytesAvailable -= skipBytes; this.loadWord(); this.word <<= count; this.bitsAvailable -= count; } } // (size:int):uint ; _proto.readBits = function readBits(size) { var bits = Math.min(this.bitsAvailable, size); // :uint var valu = this.word >>> 32 - bits; // :uint if (size > 32) { _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].error('Cannot read more than 32 bits at a time'); } this.bitsAvailable -= bits; if (this.bitsAvailable > 0) { this.word <<= bits; } else if (this.bytesAvailable > 0) { this.loadWord(); } bits = size - bits; if (bits > 0 && this.bitsAvailable) { return valu << bits | this.readBits(bits); } else { return valu; } } // ():uint ; _proto.skipLZ = function skipLZ() { var leadingZeroCount; // :uint for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) { if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) { // the first bit of working word is 1 this.word <<= leadingZeroCount; this.bitsAvailable -= leadingZeroCount; return leadingZeroCount; } } // we exhausted word and still have not found a 1 this.loadWord(); return leadingZeroCount + this.skipLZ(); } // ():void ; _proto.skipUEG = function skipUEG() { this.skipBits(1 + this.skipLZ()); } // ():void ; _proto.skipEG = function skipEG() { this.skipBits(1 + this.skipLZ()); } // ():uint ; _proto.readUEG = function readUEG() { var clz = this.skipLZ(); // :uint return this.readBits(clz + 1) - 1; } // ():int ; _proto.readEG = function readEG() { var valu = this.readUEG(); // :int if (0x01 & valu) { // the number is odd if the low order bit is set return 1 + valu >>> 1; // add 1 to make it even, and divide by 2 } else { return -1 * (valu >>> 1); // divide by two then make it negative } } // Some convenience functions // :Boolean ; _proto.readBoolean = function readBoolean() { return this.readBits(1) === 1; } // ():int ; _proto.readUByte = function readUByte() { return this.readBits(8); } // ():int ; _proto.readUShort = function readUShort() { return this.readBits(16); } // ():int ; _proto.readUInt = function readUInt() { return this.readBits(32); } /** * Advance the ExpGolomb decoder past a scaling list. The scaling * list is optionally transmitted as part of a sequence parameter * set and is not relevant to transmuxing. * @param count the number of entries in this scaling list * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1 */ ; _proto.skipScalingList = function skipScalingList(count) { var lastScale = 8; var nextScale = 8; var deltaScale; for (var j = 0; j < count; j++) { if (nextScale !== 0) { deltaScale = this.readEG(); nextScale = (lastScale + deltaScale + 256) % 256; } lastScale = nextScale === 0 ? lastScale : nextScale; } } /** * Read a sequence parameter set and return some interesting video * properties. A sequence parameter set is the H264 metadata that * describes the properties of upcoming video frames. * @param data {Uint8Array} the bytes of a sequence parameter set * @return {object} an object with configuration parsed from the * sequence parameter set, including the dimensions of the * associated video frames. */ ; _proto.readSPS = function readSPS() { var frameCropLeftOffset = 0; var frameCropRightOffset = 0; var frameCropTopOffset = 0; var frameCropBottomOffset = 0; var numRefFramesInPicOrderCntCycle; var scalingListCount; var i; var readUByte = this.readUByte.bind(this); var readBits = this.readBits.bind(this); var readUEG = this.readUEG.bind(this); var readBoolean = this.readBoolean.bind(this); var skipBits = this.skipBits.bind(this); var skipEG = this.skipEG.bind(this); var skipUEG = this.skipUEG.bind(this); var skipScalingList = this.skipScalingList.bind(this); readUByte(); var profileIdc = readUByte(); // profile_idc readBits(5); // profileCompat constraint_set[0-4]_flag, u(5) skipBits(3); // reserved_zero_3bits u(3), readUByte(); // level_idc u(8) skipUEG(); // seq_parameter_set_id // some profiles have more optional data we don't need if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) { var chromaFormatIdc = readUEG(); if (chromaFormatIdc === 3) { skipBits(1); } // separate_colour_plane_flag skipUEG(); // bit_depth_luma_minus8 skipUEG(); // bit_depth_chroma_minus8 skipBits(1); // qpprime_y_zero_transform_bypass_flag if (readBoolean()) { // seq_scaling_matrix_present_flag scalingListCount = chromaFormatIdc !== 3 ? 8 : 12; for (i = 0; i < scalingListCount; i++) { if (readBoolean()) { // seq_scaling_list_present_flag[ i ] if (i < 6) { skipScalingList(16); } else { skipScalingList(64); } } } } } skipUEG(); // log2_max_frame_num_minus4 var picOrderCntType = readUEG(); if (picOrderCntType === 0) { readUEG(); // log2_max_pic_order_cnt_lsb_minus4 } else if (picOrderCntType === 1) { skipBits(1); // delta_pic_order_always_zero_flag skipEG(); // offset_for_non_ref_pic skipEG(); // offset_for_top_to_bottom_field numRefFramesInPicOrderCntCycle = readUEG(); for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) { skipEG(); } // offset_for_ref_frame[ i ] } skipUEG(); // max_num_ref_frames skipBits(1); // gaps_in_frame_num_value_allowed_flag var picWidthInMbsMinus1 = readUEG(); var picHeightInMapUnitsMinus1 = readUEG(); var frameMbsOnlyFlag = readBits(1); if (frameMbsOnlyFlag === 0) { skipBits(1); } // mb_adaptive_frame_field_flag skipBits(1); // direct_8x8_inference_flag if (readBoolean()) { // frame_cropping_flag frameCropLeftOffset = readUEG(); frameCropRightOffset = readUEG(); frameCropTopOffset = readUEG(); frameCropBottomOffset = readUEG(); } var pixelRatio = [1, 1]; if (readBoolean()) { // vui_parameters_present_flag if (readBoolean()) { // aspect_ratio_info_present_flag var aspectRatioIdc = readUByte(); switch (aspectRatioIdc) { case 1: pixelRatio = [1, 1]; break; case 2: pixelRatio = [12, 11]; break; case 3: pixelRatio = [10, 11]; break; case 4: pixelRatio = [16, 11]; break; case 5: pixelRatio = [40, 33]; break; case 6: pixelRatio = [24, 11]; break; case 7: pixelRatio = [20, 11]; break; case 8: pixelRatio = [32, 11]; break; case 9: pixelRatio = [80, 33]; break; case 10: pixelRatio = [18, 11]; break; case 11: pixelRatio = [15, 11]; break; case 12: pixelRatio = [64, 33]; break; case 13: pixelRatio = [160, 99]; break; case 14: pixelRatio = [4, 3]; break; case 15: pixelRatio = [3, 2]; break; case 16: pixelRatio = [2, 1]; break; case 255: { pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()]; break; } } } } return { width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2), height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset), pixelRatio: pixelRatio }; }; _proto.readSliceType = function readSliceType() { // skip NALu type this.readUByte(); // discard first_mb_in_slice this.readUEG(); // return slice_type return this.readUEG(); }; return ExpGolomb; }(); /* harmony default export */ __webpack_exports__["default"] = (ExpGolomb); /***/ }), /***/ "./src/demux/id3.ts": /*!**************************!*\ !*** ./src/demux/id3.ts ***! \**************************/ /*! exports provided: isHeader, isFooter, getID3Data, canParse, getTimeStamp, isTimeStampFrame, getID3Frames, decodeFrame, utf8ArrayToStr, testables */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeader", function() { return isHeader; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFooter", function() { return isFooter; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getID3Data", function() { return getID3Data; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canParse", function() { return canParse; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getTimeStamp", function() { return getTimeStamp; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isTimeStampFrame", function() { return isTimeStampFrame; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getID3Frames", function() { return getID3Frames; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "decodeFrame", function() { return decodeFrame; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "utf8ArrayToStr", function() { return utf8ArrayToStr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "testables", function() { return testables; }); // breaking up those two types in order to clarify what is happening in the decoding path. /** * Returns true if an ID3 header can be found at offset in data * @param {Uint8Array} data - The data to search in * @param {number} offset - The offset at which to start searching * @return {boolean} - True if an ID3 header is found */ var isHeader = function isHeader(data, offset) { /* * http://id3.org/id3v2.3.0 * [0] = 'I' * [1] = 'D' * [2] = '3' * [3,4] = {Version} * [5] = {Flags} * [6-9] = {ID3 Size} * * An ID3v2 tag can be detected with the following pattern: * $49 44 33 yy yy xx zz zz zz zz * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80 */ if (offset + 10 <= data.length) { // look for 'ID3' identifier if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) { // check version is within range if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) { // check size is within range if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) { return true; } } } } return false; }; /** * Returns true if an ID3 footer can be found at offset in data * @param {Uint8Array} data - The data to search in * @param {number} offset - The offset at which to start searching * @return {boolean} - True if an ID3 footer is found */ var isFooter = function isFooter(data, offset) { /* * The footer is a copy of the header, but with a different identifier */ if (offset + 10 <= data.length) { // look for '3DI' identifier if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) { // check version is within range if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) { // check size is within range if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) { return true; } } } } return false; }; /** * Returns any adjacent ID3 tags found in data starting at offset, as one block of data * @param {Uint8Array} data - The data to search in * @param {number} offset - The offset at which to start searching * @return {Uint8Array | undefined} - The block of data containing any ID3 tags found * or *undefined* if no header is found at the starting offset */ var getID3Data = function getID3Data(data, offset) { var front = offset; var length = 0; while (isHeader(data, offset)) { // ID3 header is 10 bytes length += 10; var size = readSize(data, offset + 6); length += size; if (isFooter(data, offset + 10)) { // ID3 footer is 10 bytes length += 10; } offset += length; } if (length > 0) { return data.subarray(front, front + length); } return undefined; }; var readSize = function readSize(data, offset) { var size = 0; size = (data[offset] & 0x7f) << 21; size |= (data[offset + 1] & 0x7f) << 14; size |= (data[offset + 2] & 0x7f) << 7; size |= data[offset + 3] & 0x7f; return size; }; var canParse = function canParse(data, offset) { return isHeader(data, offset) && readSize(data, offset + 6) + 10 <= data.length - offset; }; /** * Searches for the Elementary Stream timestamp found in the ID3 data chunk * @param {Uint8Array} data - Block of data containing one or more ID3 tags * @return {number | undefined} - The timestamp */ var getTimeStamp = function getTimeStamp(data) { var frames = getID3Frames(data); for (var i = 0; i < frames.length; i++) { var frame = frames[i]; if (isTimeStampFrame(frame)) { return readTimeStamp(frame); } } return undefined; }; /** * Returns true if the ID3 frame is an Elementary Stream timestamp frame * @param {ID3 frame} frame */ var isTimeStampFrame = function isTimeStampFrame(frame) { return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp'; }; var getFrameData = function getFrameData(data) { /* Frame ID $xx xx xx xx (four characters) Size $xx xx xx xx Flags $xx xx */ var type = String.fromCharCode(data[0], data[1], data[2], data[3]); var size = readSize(data, 4); // skip frame id, size, and flags var offset = 10; return { type: type, size: size, data: data.subarray(offset, offset + size) }; }; /** * Returns an array of ID3 frames found in all the ID3 tags in the id3Data * @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags * @return {ID3.Frame[]} - Array of ID3 frame objects */ var getID3Frames = function getID3Frames(id3Data) { var offset = 0; var frames = []; while (isHeader(id3Data, offset)) { var size = readSize(id3Data, offset + 6); // skip past ID3 header offset += 10; var end = offset + size; // loop through frames in the ID3 tag while (offset + 8 < end) { var frameData = getFrameData(id3Data.subarray(offset)); var frame = decodeFrame(frameData); if (frame) { frames.push(frame); } // skip frame header and frame data offset += frameData.size + 10; } if (isFooter(id3Data, offset)) { offset += 10; } } return frames; }; var decodeFrame = function decodeFrame(frame) { if (frame.type === 'PRIV') { return decodePrivFrame(frame); } else if (frame.type[0] === 'W') { return decodeURLFrame(frame); } return decodeTextFrame(frame); }; var decodePrivFrame = function decodePrivFrame(frame) { /* Format: <text string>\0<binary data> */ if (frame.size < 2) { return undefined; } var owner = utf8ArrayToStr(frame.data, true); var privateData = new Uint8Array(frame.data.subarray(owner.length + 1)); return { key: frame.type, info: owner, data: privateData.buffer }; }; var decodeTextFrame = function decodeTextFrame(frame) { if (frame.size < 2) { return undefined; } if (frame.type === 'TXXX') { /* Format: [0] = {Text Encoding} [1-?] = {Description}\0{Value} */ var index = 1; var description = utf8ArrayToStr(frame.data.subarray(index), true); index += description.length + 1; var value = utf8ArrayToStr(frame.data.subarray(index)); return { key: frame.type, info: description, data: value }; } /* Format: [0] = {Text Encoding} [1-?] = {Value} */ var text = utf8ArrayToStr(frame.data.subarray(1)); return { key: frame.type, data: text }; }; var decodeURLFrame = function decodeURLFrame(frame) { if (frame.type === 'WXXX') { /* Format: [0] = {Text Encoding} [1-?] = {Description}\0{URL} */ if (frame.size < 2) { return undefined; } var index = 1; var description = utf8ArrayToStr(frame.data.subarray(index), true); index += description.length + 1; var value = utf8ArrayToStr(frame.data.subarray(index)); return { key: frame.type, info: description, data: value }; } /* Format: [0-?] = {URL} */ var url = utf8ArrayToStr(frame.data); return { key: frame.type, data: url }; }; var readTimeStamp = function readTimeStamp(timeStampFrame) { if (timeStampFrame.data.byteLength === 8) { var data = new Uint8Array(timeStampFrame.data); // timestamp is 33 bit expressed as a big-endian eight-octet number, // with the upper 31 bits set to zero. var pts33Bit = data[3] & 0x1; var timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7]; timestamp /= 45; if (pts33Bit) { timestamp += 47721858.84; } // 2^32 / 90 return Math.round(timestamp); } return undefined; }; // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197 // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt /* utf.js - UTF-8 <=> UTF-16 convertion * * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp> * Version: 1.0 * LastModified: Dec 25 1999 * This library is free. You can redistribute it and/or modify it. */ var utf8ArrayToStr = function utf8ArrayToStr(array, exitOnNull) { if (exitOnNull === void 0) { exitOnNull = false; } var decoder = getTextDecoder(); if (decoder) { var decoded = decoder.decode(array); if (exitOnNull) { // grab up to the first null var idx = decoded.indexOf('\0'); return idx !== -1 ? decoded.substring(0, idx) : decoded; } // remove any null characters return decoded.replace(/\0/g, ''); } var len = array.length; var c; var char2; var char3; var out = ''; var i = 0; while (i < len) { c = array[i++]; if (c === 0x00 && exitOnNull) { return out; } else if (c === 0x00 || c === 0x03) { // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it continue; } switch (c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: // 0xxxxxxx out += String.fromCharCode(c); break; case 12: case 13: // 110x xxxx 10xx xxxx char2 = array[i++]; out += String.fromCharCode((c & 0x1f) << 6 | char2 & 0x3f); break; case 14: // 1110 xxxx 10xx xxxx 10xx xxxx char2 = array[i++]; char3 = array[i++]; out += String.fromCharCode((c & 0x0f) << 12 | (char2 & 0x3f) << 6 | (char3 & 0x3f) << 0); break; default: } } return out; }; var testables = { decodeTextFrame: decodeTextFrame }; var decoder; function getTextDecoder() { if (!decoder && typeof self.TextDecoder !== 'undefined') { decoder = new self.TextDecoder('utf-8'); } return decoder; } /***/ }), /***/ "./src/demux/mp3demuxer.ts": /*!*********************************!*\ !*** ./src/demux/mp3demuxer.ts ***! \*********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base-audio-demuxer */ "./src/demux/base-audio-demuxer.ts"); /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _mpegaudio__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./mpegaudio */ "./src/demux/mpegaudio.ts"); function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * MP3 demuxer */ var MP3Demuxer = /*#__PURE__*/function (_BaseAudioDemuxer) { _inheritsLoose(MP3Demuxer, _BaseAudioDemuxer); function MP3Demuxer() { return _BaseAudioDemuxer.apply(this, arguments) || this; } var _proto = MP3Demuxer.prototype; _proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) { _BaseAudioDemuxer.prototype.resetInitSegment.call(this, audioCodec, videoCodec, duration); this._audioTrack = { container: 'audio/mpeg', type: 'audio', id: 0, pid: -1, sequenceNumber: 0, isAAC: false, samples: [], manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000, dropped: 0 }; }; MP3Demuxer.probe = function probe(data) { if (!data) { return false; } // check if data contains ID3 timestamp and MPEG sync word // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1 // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III) // More info http://www.mp3-tech.org/programmer/frame_header.html var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getID3Data"](data, 0) || []; var offset = id3Data.length; for (var length = data.length; offset < length; offset++) { if (_mpegaudio__WEBPACK_IMPORTED_MODULE_3__["probe"](data, offset)) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('MPEG Audio sync word found !'); return true; } } return false; }; _proto.canParse = function canParse(data, offset) { return _mpegaudio__WEBPACK_IMPORTED_MODULE_3__["canParse"](data, offset); }; _proto.appendFrame = function appendFrame(track, data, offset) { if (this.initPTS === null) { return; } return _mpegaudio__WEBPACK_IMPORTED_MODULE_3__["appendFrame"](track, data, offset, this.initPTS, this.frameIndex); }; return MP3Demuxer; }(_base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__["default"]); MP3Demuxer.minProbeByteLength = 4; /* harmony default export */ __webpack_exports__["default"] = (MP3Demuxer); /***/ }), /***/ "./src/demux/mp4demuxer.ts": /*!*********************************!*\ !*** ./src/demux/mp4demuxer.ts ***! \*********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts"); /* harmony import */ var _dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./dummy-demuxed-track */ "./src/demux/dummy-demuxed-track.ts"); /** * MP4 demuxer */ var MP4Demuxer = /*#__PURE__*/function () { function MP4Demuxer(observer, config) { this.remainderData = null; this.config = void 0; this.config = config; } var _proto = MP4Demuxer.prototype; _proto.resetTimeStamp = function resetTimeStamp() {}; _proto.resetInitSegment = function resetInitSegment() {}; _proto.resetContiguity = function resetContiguity() {}; MP4Demuxer.probe = function probe(data) { // ensure we find a moof box in the first 16 kB return Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["findBox"])({ data: data, start: 0, end: Math.min(data.length, 16384) }, ['moof']).length > 0; }; _proto.demux = function demux(data) { // Load all data into the avc track. The CMAF remuxer will look for the data in the samples object; the rest of the fields do not matter var avcSamples = data; var avcTrack = Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(); if (this.config.progressive) { // Split the bytestream into two ranges: one encompassing all data up until the start of the last moof, and everything else. // This is done to guarantee that we're sending valid data to MSE - when demuxing progressively, we have no guarantee // that the fetch loader gives us flush moof+mdat pairs. If we push jagged data to MSE, it will throw an exception. if (this.remainderData) { avcSamples = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["appendUint8Array"])(this.remainderData, data); } var segmentedData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["segmentValidRange"])(avcSamples); this.remainderData = segmentedData.remainder; avcTrack.samples = segmentedData.valid || new Uint8Array(); } else { avcTrack.samples = avcSamples; } return { audioTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(), avcTrack: avcTrack, id3Track: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(), textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])() }; }; _proto.flush = function flush() { var avcTrack = Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(); avcTrack.samples = this.remainderData || new Uint8Array(); this.remainderData = null; return { audioTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(), avcTrack: avcTrack, id3Track: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(), textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])() }; }; _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) { return Promise.reject(new Error('The MP4 demuxer does not support SAMPLE-AES decryption')); }; _proto.destroy = function destroy() {}; return MP4Demuxer; }(); MP4Demuxer.minProbeByteLength = 1024; /* harmony default export */ __webpack_exports__["default"] = (MP4Demuxer); /***/ }), /***/ "./src/demux/mpegaudio.ts": /*!********************************!*\ !*** ./src/demux/mpegaudio.ts ***! \********************************/ /*! exports provided: appendFrame, parseHeader, isHeaderPattern, isHeader, canParse, probe */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendFrame", function() { return appendFrame; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseHeader", function() { return parseHeader; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeaderPattern", function() { return isHeaderPattern; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeader", function() { return isHeader; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canParse", function() { return canParse; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "probe", function() { return probe; }); /** * MPEG parser helper */ var chromeVersion = null; var BitratesMap = [32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160]; var SamplingRateMap = [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000]; var SamplesCoefficients = [// MPEG 2.5 [0, // Reserved 72, // Layer3 144, // Layer2 12 // Layer1 ], // Reserved [0, // Reserved 0, // Layer3 0, // Layer2 0 // Layer1 ], // MPEG 2 [0, // Reserved 72, // Layer3 144, // Layer2 12 // Layer1 ], // MPEG 1 [0, // Reserved 144, // Layer3 144, // Layer2 12 // Layer1 ]]; var BytesInSlot = [0, // Reserved 1, // Layer3 1, // Layer2 4 // Layer1 ]; function appendFrame(track, data, offset, pts, frameIndex) { // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference if (offset + 24 > data.length) { return; } var header = parseHeader(data, offset); if (header && offset + header.frameLength <= data.length) { var frameDuration = header.samplesPerFrame * 90000 / header.sampleRate; var stamp = pts + frameIndex * frameDuration; var sample = { unit: data.subarray(offset, offset + header.frameLength), pts: stamp, dts: stamp }; track.config = []; track.channelCount = header.channelCount; track.samplerate = header.sampleRate; track.samples.push(sample); return { sample: sample, length: header.frameLength, missing: 0 }; } } function parseHeader(data, offset) { var mpegVersion = data[offset + 1] >> 3 & 3; var mpegLayer = data[offset + 1] >> 1 & 3; var bitRateIndex = data[offset + 2] >> 4 & 15; var sampleRateIndex = data[offset + 2] >> 2 & 3; if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) { var paddingBit = data[offset + 2] >> 1 & 1; var channelMode = data[offset + 3] >> 6; var columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4; var bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1000; var columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2; var sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex]; var channelCount = channelMode === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono) var sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer]; var bytesInSlot = BytesInSlot[mpegLayer]; var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot; var frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot; if (chromeVersion === null) { var userAgent = navigator.userAgent || ''; var result = userAgent.match(/Chrome\/(\d+)/i); chromeVersion = result ? parseInt(result[1]) : 0; } var needChromeFix = !!chromeVersion && chromeVersion <= 87; if (needChromeFix && mpegLayer === 2 && bitRate >= 224000 && channelMode === 0) { // Work around bug in Chromium by setting channelMode to dual-channel (01) instead of stereo (00) data[offset + 3] = data[offset + 3] | 0x80; } return { sampleRate: sampleRate, channelCount: channelCount, frameLength: frameLength, samplesPerFrame: samplesPerFrame }; } } function isHeaderPattern(data, offset) { return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00; } function isHeader(data, offset) { // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1 // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III) // More info http://www.mp3-tech.org/programmer/frame_header.html return offset + 1 < data.length && isHeaderPattern(data, offset); } function canParse(data, offset) { var headerSize = 4; return isHeaderPattern(data, offset) && headerSize <= data.length - offset; } function probe(data, offset) { // same as isHeader but we also check that MPEG frame follows last MPEG frame // or end of data is reached if (offset + 1 < data.length && isHeaderPattern(data, offset)) { // MPEG header Length var headerLength = 4; // MPEG frame Length var header = parseHeader(data, offset); var frameLength = headerLength; if (header !== null && header !== void 0 && header.frameLength) { frameLength = header.frameLength; } var newOffset = offset + frameLength; return newOffset === data.length || isHeader(data, newOffset); } return false; } /***/ }), /***/ "./src/demux/sample-aes.ts": /*!*********************************!*\ !*** ./src/demux/sample-aes.ts ***! \*********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.ts"); /* harmony import */ var _tsdemuxer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./tsdemuxer */ "./src/demux/tsdemuxer.ts"); /** * SAMPLE-AES decrypter */ var SampleAesDecrypter = /*#__PURE__*/function () { function SampleAesDecrypter(observer, config, keyData) { this.keyData = void 0; this.decrypter = void 0; this.keyData = keyData; this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_0__["default"](observer, config, { removePKCS7Padding: false }); } var _proto = SampleAesDecrypter.prototype; _proto.decryptBuffer = function decryptBuffer(encryptedData, callback) { this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer, callback); } // AAC - encrypt all full 16 bytes blocks starting from offset 16 ; _proto.decryptAacSample = function decryptAacSample(samples, sampleIndex, callback, sync) { var curUnit = samples[sampleIndex].unit; var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16); var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length); var localthis = this; this.decryptBuffer(encryptedBuffer, function (decryptedBuffer) { var decryptedData = new Uint8Array(decryptedBuffer); curUnit.set(decryptedData, 16); if (!sync) { localthis.decryptAacSamples(samples, sampleIndex + 1, callback); } }); }; _proto.decryptAacSamples = function decryptAacSamples(samples, sampleIndex, callback) { for (;; sampleIndex++) { if (sampleIndex >= samples.length) { callback(); return; } if (samples[sampleIndex].unit.length < 32) { continue; } var sync = this.decrypter.isSync(); this.decryptAacSample(samples, sampleIndex, callback, sync); if (!sync) { return; } } } // AVC - encrypt one 16 bytes block out of ten, starting from offset 32 ; _proto.getAvcEncryptedData = function getAvcEncryptedData(decodedData) { var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16; var encryptedData = new Int8Array(encryptedDataLen); var outputPos = 0; for (var inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) { encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos); } return encryptedData; }; _proto.getAvcDecryptedUnit = function getAvcDecryptedUnit(decodedData, decryptedData) { var uint8DecryptedData = new Uint8Array(decryptedData); var inputPos = 0; for (var outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) { decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos); } return decodedData; }; _proto.decryptAvcSample = function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync) { var decodedData = Object(_tsdemuxer__WEBPACK_IMPORTED_MODULE_1__["discardEPB"])(curUnit.data); var encryptedData = this.getAvcEncryptedData(decodedData); var localthis = this; this.decryptBuffer(encryptedData.buffer, function (decryptedBuffer) { curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedBuffer); if (!sync) { localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback); } }); }; _proto.decryptAvcSamples = function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) { if (samples instanceof Uint8Array) { throw new Error('Cannot decrypt samples of type Uint8Array'); } for (;; sampleIndex++, unitIndex = 0) { if (sampleIndex >= samples.length) { callback(); return; } var curUnits = samples[sampleIndex].units; for (;; unitIndex++) { if (unitIndex >= curUnits.length) { break; } var curUnit = curUnits[unitIndex]; if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) { continue; } var sync = this.decrypter.isSync(); this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync); if (!sync) { return; } } } }; return SampleAesDecrypter; }(); /* harmony default export */ __webpack_exports__["default"] = (SampleAesDecrypter); /***/ }), /***/ "./src/demux/transmuxer-interface.ts": /*!*******************************************!*\ !*** ./src/demux/transmuxer-interface.ts ***! \*******************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TransmuxerInterface; }); /* harmony import */ var webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! webworkify-webpack */ "./node_modules/webworkify-webpack/index.js"); /* harmony import */ var webworkify_webpack__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/transmuxer */ "./src/demux/transmuxer.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/mediasource-helper */ "./src/utils/mediasource-helper.ts"); /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js"); /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_6__); var MediaSource = Object(_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__["getMediaSource"])() || { isTypeSupported: function isTypeSupported() { return false; } }; var TransmuxerInterface = /*#__PURE__*/function () { function TransmuxerInterface(hls, id, onTransmuxComplete, onFlush) { var _this = this; this.hls = void 0; this.id = void 0; this.observer = void 0; this.frag = null; this.part = null; this.worker = void 0; this.onwmsg = void 0; this.transmuxer = null; this.onTransmuxComplete = void 0; this.onFlush = void 0; this.hls = hls; this.id = id; this.onTransmuxComplete = onTransmuxComplete; this.onFlush = onFlush; var config = hls.config; var forwardMessage = function forwardMessage(ev, data) { data = data || {}; data.frag = _this.frag; data.id = _this.id; hls.trigger(ev, data); }; // forward events to main thread this.observer = new eventemitter3__WEBPACK_IMPORTED_MODULE_6__["EventEmitter"](); this.observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_DECRYPTED, forwardMessage); this.observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, forwardMessage); var typeSupported = { mp4: MediaSource.isTypeSupported('video/mp4'), mpeg: MediaSource.isTypeSupported('audio/mpeg'), mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"') }; // navigator.vendor is not always available in Web Worker // refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator var vendor = navigator.vendor; if (config.enableWorker && typeof Worker !== 'undefined') { _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log('demuxing in webworker'); var worker; try { worker = this.worker = webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__(/*require.resolve*/(/*! ../demux/transmuxer-worker.ts */ "./src/demux/transmuxer-worker.ts")); this.onwmsg = this.onWorkerMessage.bind(this); worker.addEventListener('message', this.onwmsg); worker.onerror = function (event) { hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].OTHER_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].INTERNAL_EXCEPTION, fatal: true, event: 'demuxerWorker', error: new Error(event.message + " (" + event.filename + ":" + event.lineno + ")") }); }; worker.postMessage({ cmd: 'init', typeSupported: typeSupported, vendor: vendor, id: id, config: JSON.stringify(config) }); } catch (err) { _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Error in worker:', err); _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].error('Error while initializing DemuxerWorker, fallback to inline'); if (worker) { // revoke the Object URL that was used to create transmuxer worker, so as not to leak it self.URL.revokeObjectURL(worker.objectURL); } this.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["default"](this.observer, typeSupported, config, vendor, id); this.worker = null; } } else { this.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["default"](this.observer, typeSupported, config, vendor, id); } } var _proto = TransmuxerInterface.prototype; _proto.destroy = function destroy() { var w = this.worker; if (w) { w.removeEventListener('message', this.onwmsg); w.terminate(); this.worker = null; } else { var transmuxer = this.transmuxer; if (transmuxer) { transmuxer.destroy(); this.transmuxer = null; } } var observer = this.observer; if (observer) { observer.removeAllListeners(); } // @ts-ignore this.observer = null; }; _proto.push = function push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) { var _this2 = this; chunkMeta.transmuxing.start = self.performance.now(); var transmuxer = this.transmuxer, worker = this.worker; var timeOffset = part ? part.start : frag.start; var decryptdata = frag.decryptdata; var lastFrag = this.frag; var discontinuity = !(lastFrag && frag.cc === lastFrag.cc); var trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level); var snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1; var partDiff = this.part ? chunkMeta.part - this.part.index : 1; var contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && partDiff === 1); var now = self.performance.now(); if (trackSwitch || snDiff || frag.stats.parsing.start === 0) { frag.stats.parsing.start = now; } if (part && (partDiff || !contiguous)) { part.stats.parsing.start = now; } var state = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["TransmuxState"](discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset); if (!contiguous || discontinuity) { _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log("[transmuxer-interface, " + frag.type + "]: Starting new transmux session for sn: " + chunkMeta.sn + " p: " + chunkMeta.part + " level: " + chunkMeta.level + " id: " + chunkMeta.id + "\n discontinuity: " + discontinuity + "\n trackSwitch: " + trackSwitch + "\n contiguous: " + contiguous + "\n accurateTimeOffset: " + accurateTimeOffset + "\n timeOffset: " + timeOffset); var config = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["TransmuxConfig"](audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS); this.configureTransmuxer(config); } this.frag = frag; this.part = part; // Frags with sn of 'initSegment' are not transmuxed if (worker) { // post fragment payload as transferable objects for ArrayBuffer (no copy) worker.postMessage({ cmd: 'demux', data: data, decryptdata: decryptdata, chunkMeta: chunkMeta, state: state }, data instanceof ArrayBuffer ? [data] : []); } else if (transmuxer) { var _transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state); if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["isPromise"])(_transmuxResult)) { _transmuxResult.then(function (data) { _this2.handleTransmuxComplete(data); }); } else { this.handleTransmuxComplete(_transmuxResult); } } }; _proto.flush = function flush(chunkMeta) { var _this3 = this; chunkMeta.transmuxing.start = self.performance.now(); var transmuxer = this.transmuxer, worker = this.worker; if (worker) { worker.postMessage({ cmd: 'flush', chunkMeta: chunkMeta }); } else if (transmuxer) { var _transmuxResult2 = transmuxer.flush(chunkMeta); if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["isPromise"])(_transmuxResult2)) { _transmuxResult2.then(function (data) { _this3.handleFlushResult(data, chunkMeta); }); } else { this.handleFlushResult(_transmuxResult2, chunkMeta); } } }; _proto.handleFlushResult = function handleFlushResult(results, chunkMeta) { var _this4 = this; results.forEach(function (result) { _this4.handleTransmuxComplete(result); }); this.onFlush(chunkMeta); }; _proto.onWorkerMessage = function onWorkerMessage(ev) { var data = ev.data; var hls = this.hls; switch (data.event) { case 'init': { // revoke the Object URL that was used to create transmuxer worker, so as not to leak it self.URL.revokeObjectURL(this.worker.objectURL); break; } case 'transmuxComplete': { this.handleTransmuxComplete(data.data); break; } case 'flush': { this.onFlush(data.data); break; } /* falls through */ default: { data.data = data.data || {}; data.data.frag = this.frag; data.data.id = this.id; hls.trigger(data.event, data.data); break; } } }; _proto.configureTransmuxer = function configureTransmuxer(config) { var worker = this.worker, transmuxer = this.transmuxer; if (worker) { worker.postMessage({ cmd: 'configure', config: config }); } else if (transmuxer) { transmuxer.configure(config); } }; _proto.handleTransmuxComplete = function handleTransmuxComplete(result) { result.chunkMeta.transmuxing.end = self.performance.now(); this.onTransmuxComplete(result); }; return TransmuxerInterface; }(); /***/ }), /***/ "./src/demux/transmuxer-worker.ts": /*!****************************************!*\ !*** ./src/demux/transmuxer-worker.ts ***! \****************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TransmuxerWorker; }); /* harmony import */ var _demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../demux/transmuxer */ "./src/demux/transmuxer.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js"); /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_3__); function TransmuxerWorker(self) { var observer = new eventemitter3__WEBPACK_IMPORTED_MODULE_3__["EventEmitter"](); var forwardMessage = function forwardMessage(ev, data) { self.postMessage({ event: ev, data: data }); }; // forward events to main thread observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_DECRYPTED, forwardMessage); observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, forwardMessage); self.addEventListener('message', function (ev) { var data = ev.data; switch (data.cmd) { case 'init': { var config = JSON.parse(data.config); self.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__["default"](observer, data.typeSupported, config, data.vendor, data.id); Object(_utils_logger__WEBPACK_IMPORTED_MODULE_2__["enableLogs"])(config.debug); forwardMessage('init', null); break; } case 'configure': { self.transmuxer.configure(data.config); break; } case 'demux': { var transmuxResult = self.transmuxer.push(data.data, data.decryptdata, data.chunkMeta, data.state); if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__["isPromise"])(transmuxResult)) { transmuxResult.then(function (data) { emitTransmuxComplete(self, data); }); } else { emitTransmuxComplete(self, transmuxResult); } break; } case 'flush': { var id = data.chunkMeta; var _transmuxResult = self.transmuxer.flush(id); if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__["isPromise"])(_transmuxResult)) { _transmuxResult.then(function (results) { handleFlushResult(self, results, id); }); } else { handleFlushResult(self, _transmuxResult, id); } break; } default: break; } }); } function emitTransmuxComplete(self, transmuxResult) { if (isEmptyResult(transmuxResult.remuxResult)) { return; } var transferable = []; var _transmuxResult$remux = transmuxResult.remuxResult, audio = _transmuxResult$remux.audio, video = _transmuxResult$remux.video; if (audio) { addToTransferable(transferable, audio); } if (video) { addToTransferable(transferable, video); } self.postMessage({ event: 'transmuxComplete', data: transmuxResult }, transferable); } // Converts data to a transferable object https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast) // in order to minimize message passing overhead function addToTransferable(transferable, track) { if (track.data1) { transferable.push(track.data1.buffer); } if (track.data2) { transferable.push(track.data2.buffer); } } function handleFlushResult(self, results, chunkMeta) { results.forEach(function (result) { emitTransmuxComplete(self, result); }); self.postMessage({ event: 'flush', data: chunkMeta }); } function isEmptyResult(remuxResult) { return !remuxResult.audio && !remuxResult.video && !remuxResult.text && !remuxResult.id3 && !remuxResult.initSegment; } /***/ }), /***/ "./src/demux/transmuxer.ts": /*!*********************************!*\ !*** ./src/demux/transmuxer.ts ***! \*********************************/ /*! exports provided: default, isPromise, TransmuxConfig, TransmuxState */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Transmuxer; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPromise", function() { return isPromise; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransmuxConfig", function() { return TransmuxConfig; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransmuxState", function() { return TransmuxState; }); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.ts"); /* harmony import */ var _demux_aacdemuxer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/aacdemuxer */ "./src/demux/aacdemuxer.ts"); /* harmony import */ var _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../demux/mp4demuxer */ "./src/demux/mp4demuxer.ts"); /* harmony import */ var _demux_tsdemuxer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../demux/tsdemuxer */ "./src/demux/tsdemuxer.ts"); /* harmony import */ var _demux_mp3demuxer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../demux/mp3demuxer */ "./src/demux/mp3demuxer.ts"); /* harmony import */ var _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../remux/mp4-remuxer */ "./src/remux/mp4-remuxer.ts"); /* harmony import */ var _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../remux/passthrough-remuxer */ "./src/remux/passthrough-remuxer.ts"); /* harmony import */ var _chunk_cache__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./chunk-cache */ "./src/demux/chunk-cache.ts"); /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); var now; // performance.now() not available on WebWorker, at least on Safari Desktop try { now = self.performance.now.bind(self.performance); } catch (err) { _utils_logger__WEBPACK_IMPORTED_MODULE_11__["logger"].debug('Unable to use Performance API on this environment'); now = self.Date.now; } var muxConfig = [{ demux: _demux_tsdemuxer__WEBPACK_IMPORTED_MODULE_5__["default"], remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__["default"] }, { demux: _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__["default"], remux: _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__["default"] }, { demux: _demux_aacdemuxer__WEBPACK_IMPORTED_MODULE_3__["default"], remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__["default"] }, { demux: _demux_mp3demuxer__WEBPACK_IMPORTED_MODULE_6__["default"], remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__["default"] }]; var minProbeByteLength = 1024; muxConfig.forEach(function (_ref) { var demux = _ref.demux; minProbeByteLength = Math.max(minProbeByteLength, demux.minProbeByteLength); }); var Transmuxer = /*#__PURE__*/function () { function Transmuxer(observer, typeSupported, config, vendor, id) { this.observer = void 0; this.typeSupported = void 0; this.config = void 0; this.vendor = void 0; this.id = void 0; this.demuxer = void 0; this.remuxer = void 0; this.decrypter = void 0; this.probe = void 0; this.decryptionPromise = null; this.transmuxConfig = void 0; this.currentTransmuxState = void 0; this.cache = new _chunk_cache__WEBPACK_IMPORTED_MODULE_9__["default"](); this.observer = observer; this.typeSupported = typeSupported; this.config = config; this.vendor = vendor; this.id = id; } var _proto = Transmuxer.prototype; _proto.configure = function configure(transmuxConfig) { this.transmuxConfig = transmuxConfig; if (this.decrypter) { this.decrypter.reset(); } }; _proto.push = function push(data, decryptdata, chunkMeta, state) { var _this = this; var stats = chunkMeta.transmuxing; stats.executeStart = now(); var uintData = new Uint8Array(data); var cache = this.cache, config = this.config, currentTransmuxState = this.currentTransmuxState, transmuxConfig = this.transmuxConfig; if (state) { this.currentTransmuxState = state; } var keyData = getEncryptionType(uintData, decryptdata); if (keyData && keyData.method === 'AES-128') { var decrypter = this.getDecrypter(); // Software decryption is synchronous; webCrypto is not if (config.enableSoftwareAES) { // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached // data is handled in the flush() call var decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer); if (!decryptedData) { stats.executeEnd = now(); return emptyResult(chunkMeta); } uintData = new Uint8Array(decryptedData); } else { this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer).then(function (decryptedData) { // Calling push here is important; if flush() is called while this is still resolving, this ensures that // the decrypted data has been transmuxed var result = _this.push(decryptedData, null, chunkMeta); _this.decryptionPromise = null; return result; }); return this.decryptionPromise; } } var _ref2 = state || currentTransmuxState, contiguous = _ref2.contiguous, discontinuity = _ref2.discontinuity, trackSwitch = _ref2.trackSwitch, accurateTimeOffset = _ref2.accurateTimeOffset, timeOffset = _ref2.timeOffset; var audioCodec = transmuxConfig.audioCodec, videoCodec = transmuxConfig.videoCodec, defaultInitPts = transmuxConfig.defaultInitPts, duration = transmuxConfig.duration, initSegmentData = transmuxConfig.initSegmentData; // Reset muxers before probing to ensure that their state is clean, even if flushing occurs before a successful probe if (discontinuity || trackSwitch) { this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration); } if (discontinuity) { this.resetInitialTimestamp(defaultInitPts); } if (!contiguous) { this.resetContiguity(); } if (this.needsProbing(uintData, discontinuity, trackSwitch)) { if (cache.dataLength) { var cachedData = cache.flush(); uintData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_10__["appendUint8Array"])(cachedData, uintData); } this.configureTransmuxer(uintData, transmuxConfig); } var result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta); var currentState = this.currentTransmuxState; currentState.contiguous = true; currentState.discontinuity = false; currentState.trackSwitch = false; stats.executeEnd = now(); return result; } // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type) ; _proto.flush = function flush(chunkMeta) { var _this2 = this; var stats = chunkMeta.transmuxing; stats.executeStart = now(); var decrypter = this.decrypter, cache = this.cache, currentTransmuxState = this.currentTransmuxState, decryptionPromise = this.decryptionPromise; if (decryptionPromise) { // Upon resolution, the decryption promise calls push() and returns its TransmuxerResult up the stack. Therefore // only flushing is required for async decryption return decryptionPromise.then(function () { return _this2.flush(chunkMeta); }); } var transmuxResults = []; var timeOffset = currentTransmuxState.timeOffset; if (decrypter) { // The decrypter may have data cached, which needs to be demuxed. In this case we'll have two TransmuxResults // This happens in the case that we receive only 1 push call for a segment (either for non-progressive downloads, // or for progressive downloads with small segments) var decryptedData = decrypter.flush(); if (decryptedData) { // Push always returns a TransmuxerResult if decryptdata is null transmuxResults.push(this.push(decryptedData, null, chunkMeta)); } } var bytesSeen = cache.dataLength; cache.reset(); var demuxer = this.demuxer, remuxer = this.remuxer; if (!demuxer || !remuxer) { // If probing failed, and each demuxer saw enough bytes to be able to probe, then Hls.js has been given content its not able to handle if (bytesSeen >= minProbeByteLength) { this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_PARSING_ERROR, fatal: true, reason: 'no demux matching with content found' }); } stats.executeEnd = now(); return [emptyResult(chunkMeta)]; } var demuxResultOrPromise = demuxer.flush(timeOffset); if (isPromise(demuxResultOrPromise)) { // Decrypt final SAMPLE-AES samples return demuxResultOrPromise.then(function (demuxResult) { _this2.flushRemux(transmuxResults, demuxResult, chunkMeta); return transmuxResults; }); } this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta); return transmuxResults; }; _proto.flushRemux = function flushRemux(transmuxResults, demuxResult, chunkMeta) { var audioTrack = demuxResult.audioTrack, avcTrack = demuxResult.avcTrack, id3Track = demuxResult.id3Track, textTrack = demuxResult.textTrack; var _this$currentTransmux = this.currentTransmuxState, accurateTimeOffset = _this$currentTransmux.accurateTimeOffset, timeOffset = _this$currentTransmux.timeOffset; _utils_logger__WEBPACK_IMPORTED_MODULE_11__["logger"].log("[transmuxer.ts]: Flushed fragment " + chunkMeta.sn + (chunkMeta.part > -1 ? ' p: ' + chunkMeta.part : '') + " of level " + chunkMeta.level); var remuxResult = this.remuxer.remux(audioTrack, avcTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true, this.id); transmuxResults.push({ remuxResult: remuxResult, chunkMeta: chunkMeta }); chunkMeta.transmuxing.executeEnd = now(); }; _proto.resetInitialTimestamp = function resetInitialTimestamp(defaultInitPts) { var demuxer = this.demuxer, remuxer = this.remuxer; if (!demuxer || !remuxer) { return; } demuxer.resetTimeStamp(defaultInitPts); remuxer.resetTimeStamp(defaultInitPts); }; _proto.resetContiguity = function resetContiguity() { var demuxer = this.demuxer, remuxer = this.remuxer; if (!demuxer || !remuxer) { return; } demuxer.resetContiguity(); remuxer.resetNextTimestamp(); }; _proto.resetInitSegment = function resetInitSegment(initSegmentData, audioCodec, videoCodec, duration) { var demuxer = this.demuxer, remuxer = this.remuxer; if (!demuxer || !remuxer) { return; } demuxer.resetInitSegment(audioCodec, videoCodec, duration); remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec); }; _proto.destroy = function destroy() { if (this.demuxer) { this.demuxer.destroy(); this.demuxer = undefined; } if (this.remuxer) { this.remuxer.destroy(); this.remuxer = undefined; } }; _proto.transmux = function transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) { var result; if (keyData && keyData.method === 'SAMPLE-AES') { result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta); } else { result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta); } return result; }; _proto.transmuxUnencrypted = function transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) { var _demux = this.demuxer.demux(data, timeOffset, false, !this.config.progressive), audioTrack = _demux.audioTrack, avcTrack = _demux.avcTrack, id3Track = _demux.id3Track, textTrack = _demux.textTrack; var remuxResult = this.remuxer.remux(audioTrack, avcTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false, this.id); return { remuxResult: remuxResult, chunkMeta: chunkMeta }; }; _proto.transmuxSampleAes = function transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) { var _this3 = this; return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then(function (demuxResult) { var remuxResult = _this3.remuxer.remux(demuxResult.audioTrack, demuxResult.avcTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false, _this3.id); return { remuxResult: remuxResult, chunkMeta: chunkMeta }; }); }; _proto.configureTransmuxer = function configureTransmuxer(data, transmuxConfig) { var config = this.config, observer = this.observer, typeSupported = this.typeSupported, vendor = this.vendor; var audioCodec = transmuxConfig.audioCodec, defaultInitPts = transmuxConfig.defaultInitPts, duration = transmuxConfig.duration, initSegmentData = transmuxConfig.initSegmentData, videoCodec = transmuxConfig.videoCodec; // probe for content type var mux; for (var i = 0, len = muxConfig.length; i < len; i++) { if (muxConfig[i].demux.probe(data)) { mux = muxConfig[i]; break; } } if (!mux) { // If probing previous configs fail, use mp4 passthrough _utils_logger__WEBPACK_IMPORTED_MODULE_11__["logger"].warn('Failed to find demuxer by probing frag, treating as mp4 passthrough'); mux = { demux: _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__["default"], remux: _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__["default"] }; } // so let's check that current remuxer and demuxer are still valid var demuxer = this.demuxer; var remuxer = this.remuxer; var Remuxer = mux.remux; var Demuxer = mux.demux; if (!remuxer || !(remuxer instanceof Remuxer)) { this.remuxer = new Remuxer(observer, config, typeSupported, vendor); } if (!demuxer || !(demuxer instanceof Demuxer)) { this.demuxer = new Demuxer(observer, config, typeSupported); this.probe = Demuxer.probe; } // Ensure that muxers are always initialized with an initSegment this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration); this.resetInitialTimestamp(defaultInitPts); }; _proto.needsProbing = function needsProbing(data, discontinuity, trackSwitch) { // in case of continuity change, or track switch // we might switch from content type (AAC container to TS container, or TS to fmp4 for example) return !this.demuxer || !this.remuxer || discontinuity || trackSwitch; }; _proto.getDecrypter = function getDecrypter() { var decrypter = this.decrypter; if (!decrypter) { decrypter = this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_2__["default"](this.observer, this.config); } return decrypter; }; return Transmuxer; }(); function getEncryptionType(data, decryptData) { var encryptionType = null; if (data.byteLength > 0 && decryptData != null && decryptData.key != null && decryptData.iv !== null && decryptData.method != null) { encryptionType = decryptData; } return encryptionType; } var emptyResult = function emptyResult(chunkMeta) { return { remuxResult: {}, chunkMeta: chunkMeta }; }; function isPromise(p) { return 'then' in p && p.then instanceof Function; } var TransmuxConfig = function TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) { this.audioCodec = void 0; this.videoCodec = void 0; this.initSegmentData = void 0; this.duration = void 0; this.defaultInitPts = void 0; this.audioCodec = audioCodec; this.videoCodec = videoCodec; this.initSegmentData = initSegmentData; this.duration = duration; this.defaultInitPts = defaultInitPts; }; var TransmuxState = function TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset) { this.discontinuity = void 0; this.contiguous = void 0; this.accurateTimeOffset = void 0; this.trackSwitch = void 0; this.timeOffset = void 0; this.discontinuity = discontinuity; this.contiguous = contiguous; this.accurateTimeOffset = accurateTimeOffset; this.trackSwitch = trackSwitch; this.timeOffset = timeOffset; }; /***/ }), /***/ "./src/demux/tsdemuxer.ts": /*!********************************!*\ !*** ./src/demux/tsdemuxer.ts ***! \********************************/ /*! exports provided: discardEPB, default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "discardEPB", function() { return discardEPB; }); /* harmony import */ var _adts__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./adts */ "./src/demux/adts.ts"); /* harmony import */ var _mpegaudio__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./mpegaudio */ "./src/demux/mpegaudio.ts"); /* harmony import */ var _exp_golomb__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./exp-golomb */ "./src/demux/exp-golomb.ts"); /* harmony import */ var _id3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./id3 */ "./src/demux/id3.ts"); /* harmony import */ var _sample_aes__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./sample-aes */ "./src/demux/sample-aes.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /** * highly optimized TS demuxer: * parse PAT, PMT * extract PES packet from audio and video PIDs * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet * trigger the remuxer upon parsing completion * it also tries to workaround as best as it can audio codec switch (HE-AAC to AAC and vice versa), without having to restart the MediaSource. * it also controls the remuxing process : * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state. */ // We are using fixed track IDs for driving the MP4 remuxer // instead of following the TS PIDs. // There is no reason not to do this and some browsers/SourceBuffer-demuxers // may not like if there are TrackID "switches" // See https://github.com/video-dev/hls.js/issues/1331 // Here we are mapping our internal track types to constant MP4 track IDs // With MSE currently one can only have one track of each, and we are muxing // whatever video/audio rendition in them. var RemuxerTrackIdConfig = { video: 1, audio: 2, id3: 3, text: 4 }; var TSDemuxer = /*#__PURE__*/function () { function TSDemuxer(observer, config, typeSupported) { this.observer = void 0; this.config = void 0; this.typeSupported = void 0; this.sampleAes = null; this.pmtParsed = false; this.audioCodec = void 0; this.videoCodec = void 0; this._duration = 0; this.aacLastPTS = null; this._initPTS = null; this._initDTS = null; this._pmtId = -1; this._avcTrack = void 0; this._audioTrack = void 0; this._id3Track = void 0; this._txtTrack = void 0; this.aacOverFlow = null; this.avcSample = null; this.remainderData = null; this.observer = observer; this.config = config; this.typeSupported = typeSupported; } TSDemuxer.probe = function probe(data) { var syncOffset = TSDemuxer.syncOffset(data); if (syncOffset < 0) { return false; } else { if (syncOffset) { _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn("MPEG2-TS detected but first sync word found @ offset " + syncOffset + ", junk ahead ?"); } return true; } }; TSDemuxer.syncOffset = function syncOffset(data) { // scan 1000 first bytes var scanwindow = Math.min(1000, data.length - 3 * 188); var i = 0; while (i < scanwindow) { // a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47 if (data[i] === 0x47 && data[i + 188] === 0x47 && data[i + 2 * 188] === 0x47) { return i; } else { i++; } } return -1; } /** * Creates a track model internal to demuxer used to drive remuxing input * * @param type 'audio' | 'video' | 'id3' | 'text' * @param duration * @return TSDemuxer's internal track model */ ; TSDemuxer.createTrack = function createTrack(type, duration) { return { container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined, type: type, id: RemuxerTrackIdConfig[type], pid: -1, inputTimeScale: 90000, sequenceNumber: 0, samples: [], dropped: 0, duration: type === 'audio' ? duration : undefined }; } /** * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start) * Resets all internal track instances of the demuxer. */ ; var _proto = TSDemuxer.prototype; _proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) { this.pmtParsed = false; this._pmtId = -1; this._avcTrack = TSDemuxer.createTrack('video', duration); this._audioTrack = TSDemuxer.createTrack('audio', duration); this._id3Track = TSDemuxer.createTrack('id3', duration); this._txtTrack = TSDemuxer.createTrack('text', duration); this._audioTrack.isAAC = true; // flush any partial content this.aacOverFlow = null; this.aacLastPTS = null; this.avcSample = null; this.audioCodec = audioCodec; this.videoCodec = videoCodec; this._duration = duration; }; _proto.resetTimeStamp = function resetTimeStamp() {}; _proto.resetContiguity = function resetContiguity() { var _audioTrack = this._audioTrack, _avcTrack = this._avcTrack, _id3Track = this._id3Track; if (_audioTrack) { _audioTrack.pesData = null; } if (_avcTrack) { _avcTrack.pesData = null; } if (_id3Track) { _id3Track.pesData = null; } this.aacOverFlow = null; this.aacLastPTS = null; }; _proto.demux = function demux(data, timeOffset, isSampleAes, flush) { if (isSampleAes === void 0) { isSampleAes = false; } if (flush === void 0) { flush = false; } if (!isSampleAes) { this.sampleAes = null; } var pes; var avcTrack = this._avcTrack; var audioTrack = this._audioTrack; var id3Track = this._id3Track; var avcId = avcTrack.pid; var avcData = avcTrack.pesData; var audioId = audioTrack.pid; var id3Id = id3Track.pid; var audioData = audioTrack.pesData; var id3Data = id3Track.pesData; var unknownPIDs = false; var pmtParsed = this.pmtParsed; var pmtId = this._pmtId; var len = data.length; if (this.remainderData) { data = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_6__["appendUint8Array"])(this.remainderData, data); len = data.length; this.remainderData = null; } if (len < 188 && !flush) { this.remainderData = data; return { audioTrack: audioTrack, avcTrack: avcTrack, id3Track: id3Track, textTrack: this._txtTrack }; } var syncOffset = Math.max(0, TSDemuxer.syncOffset(data)); len -= (len + syncOffset) % 188; if (len < data.byteLength && !flush) { this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len); } // loop through TS packets for (var start = syncOffset; start < len; start += 188) { if (data[start] === 0x47) { var stt = !!(data[start + 1] & 0x40); // pid is a 13-bit field starting at the last bit of TS[1] var pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2]; var atf = (data[start + 3] & 0x30) >> 4; // if an adaption field is present, its length is specified by the fifth byte of the TS packet header. var offset = void 0; if (atf > 1) { offset = start + 5 + data[start + 4]; // continue if there is only adaptation field if (offset === start + 188) { continue; } } else { offset = start + 4; } switch (pid) { case avcId: if (stt) { if (avcData && (pes = parsePES(avcData))) { this.parseAVCPES(pes, false); } avcData = { data: [], size: 0 }; } if (avcData) { avcData.data.push(data.subarray(offset, start + 188)); avcData.size += start + 188 - offset; } break; case audioId: if (stt) { if (audioData && (pes = parsePES(audioData))) { if (audioTrack.isAAC) { this.parseAACPES(pes); } else { this.parseMPEGPES(pes); } } audioData = { data: [], size: 0 }; } if (audioData) { audioData.data.push(data.subarray(offset, start + 188)); audioData.size += start + 188 - offset; } break; case id3Id: if (stt) { if (id3Data && (pes = parsePES(id3Data))) { this.parseID3PES(pes); } id3Data = { data: [], size: 0 }; } if (id3Data) { id3Data.data.push(data.subarray(offset, start + 188)); id3Data.size += start + 188 - offset; } break; case 0: if (stt) { offset += data[offset] + 1; } pmtId = this._pmtId = parsePAT(data, offset); break; case pmtId: { if (stt) { offset += data[offset] + 1; } var parsedPIDs = parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true, isSampleAes); // only update track id if track PID found while parsing PMT // this is to avoid resetting the PID to -1 in case // track PID transiently disappears from the stream // this could happen in case of transient missing audio samples for example // NOTE this is only the PID of the track as found in TS, // but we are not using this for MP4 track IDs. avcId = parsedPIDs.avc; if (avcId > 0) { avcTrack.pid = avcId; } audioId = parsedPIDs.audio; if (audioId > 0) { audioTrack.pid = audioId; audioTrack.isAAC = parsedPIDs.isAAC; } id3Id = parsedPIDs.id3; if (id3Id > 0) { id3Track.pid = id3Id; } if (unknownPIDs && !pmtParsed) { _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('reparse from beginning'); unknownPIDs = false; // we set it to -188, the += 188 in the for loop will reset start to 0 start = syncOffset - 188; } pmtParsed = this.pmtParsed = true; break; } case 17: case 0x1fff: break; default: unknownPIDs = true; break; } } else { this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorDetails"].FRAG_PARSING_ERROR, fatal: false, reason: 'TS packet did not start with 0x47' }); } } avcTrack.pesData = avcData; audioTrack.pesData = audioData; id3Track.pesData = id3Data; var demuxResult = { audioTrack: audioTrack, avcTrack: avcTrack, id3Track: id3Track, textTrack: this._txtTrack }; if (flush) { this.extractRemainingSamples(demuxResult); } return demuxResult; }; _proto.flush = function flush() { var remainderData = this.remainderData; this.remainderData = null; var result; if (remainderData) { result = this.demux(remainderData, -1, false, true); } else { result = { audioTrack: this._audioTrack, avcTrack: this._avcTrack, textTrack: this._txtTrack, id3Track: this._id3Track }; } this.extractRemainingSamples(result); if (this.sampleAes) { return this.decrypt(result, this.sampleAes); } return result; }; _proto.extractRemainingSamples = function extractRemainingSamples(demuxResult) { var audioTrack = demuxResult.audioTrack, avcTrack = demuxResult.avcTrack, id3Track = demuxResult.id3Track; var avcData = avcTrack.pesData; var audioData = audioTrack.pesData; var id3Data = id3Track.pesData; // try to parse last PES packets var pes; if (avcData && (pes = parsePES(avcData))) { this.parseAVCPES(pes, true); avcTrack.pesData = null; } else { // either avcData null or PES truncated, keep it for next frag parsing avcTrack.pesData = avcData; } if (audioData && (pes = parsePES(audioData))) { if (audioTrack.isAAC) { this.parseAACPES(pes); } else { this.parseMPEGPES(pes); } audioTrack.pesData = null; } else { if (audioData !== null && audioData !== void 0 && audioData.size) { _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('last AAC PES packet truncated,might overlap between fragments'); } // either audioData null or PES truncated, keep it for next frag parsing audioTrack.pesData = audioData; } if (id3Data && (pes = parsePES(id3Data))) { this.parseID3PES(pes); id3Track.pesData = null; } else { // either id3Data null or PES truncated, keep it for next frag parsing id3Track.pesData = id3Data; } }; _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) { var demuxResult = this.demux(data, timeOffset, true, !this.config.progressive); var sampleAes = this.sampleAes = new _sample_aes__WEBPACK_IMPORTED_MODULE_4__["default"](this.observer, this.config, keyData); return this.decrypt(demuxResult, sampleAes); }; _proto.decrypt = function decrypt(demuxResult, sampleAes) { return new Promise(function (resolve) { var audioTrack = demuxResult.audioTrack, avcTrack = demuxResult.avcTrack; if (audioTrack.samples && audioTrack.isAAC) { sampleAes.decryptAacSamples(audioTrack.samples, 0, function () { if (avcTrack.samples) { sampleAes.decryptAvcSamples(avcTrack.samples, 0, 0, function () { resolve(demuxResult); }); } else { resolve(demuxResult); } }); } else if (avcTrack.samples) { sampleAes.decryptAvcSamples(avcTrack.samples, 0, 0, function () { resolve(demuxResult); }); } }); }; _proto.destroy = function destroy() { this._initPTS = this._initDTS = null; this._duration = 0; }; _proto.parseAVCPES = function parseAVCPES(pes, last) { var _this = this; var track = this._avcTrack; var units = this.parseAVCNALu(pes.data); var debug = false; var avcSample = this.avcSample; var push; var spsfound = false; // free pes.data to save up some memory pes.data = null; // if new NAL units found and last sample still there, let's push ... // this helps parsing streams with missing AUD (only do this if AUD never found) if (avcSample && units.length && !track.audFound) { pushAccessUnit(avcSample, track); avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, ''); } units.forEach(function (unit) { switch (unit.type) { // NDR case 1: { push = true; if (!avcSample) { avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, ''); } if (debug) { avcSample.debug += 'NDR '; } avcSample.frame = true; var data = unit.data; // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...) if (spsfound && data.length > 4) { // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR var sliceType = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__["default"](data).readSliceType(); // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples. // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice. // I slice: A slice that is not an SI slice that is decoded using intra prediction only. // if (sliceType === 2 || sliceType === 7) { if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) { avcSample.key = true; } } break; // IDR } case 5: push = true; // handle PES not starting with AUD if (!avcSample) { avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, ''); } if (debug) { avcSample.debug += 'IDR '; } avcSample.key = true; avcSample.frame = true; break; // SEI case 6: { push = true; if (debug && avcSample) { avcSample.debug += 'SEI '; } var expGolombDecoder = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__["default"](discardEPB(unit.data)); // skip frameType expGolombDecoder.readUByte(); var payloadType = 0; var payloadSize = 0; var endOfCaptions = false; var b = 0; while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) { payloadType = 0; do { b = expGolombDecoder.readUByte(); payloadType += b; } while (b === 0xff); // Parse payload size. payloadSize = 0; do { b = expGolombDecoder.readUByte(); payloadSize += b; } while (b === 0xff); // TODO: there can be more than one payload in an SEI packet... // TODO: need to read type and size in a while loop to get them all if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) { endOfCaptions = true; var countryCode = expGolombDecoder.readUByte(); if (countryCode === 181) { var providerCode = expGolombDecoder.readUShort(); if (providerCode === 49) { var userStructure = expGolombDecoder.readUInt(); if (userStructure === 0x47413934) { var userDataType = expGolombDecoder.readUByte(); // Raw CEA-608 bytes wrapped in CEA-708 packet if (userDataType === 3) { var firstByte = expGolombDecoder.readUByte(); var secondByte = expGolombDecoder.readUByte(); var totalCCs = 31 & firstByte; var byteArray = [firstByte, secondByte]; for (var i = 0; i < totalCCs; i++) { // 3 bytes per CC byteArray.push(expGolombDecoder.readUByte()); byteArray.push(expGolombDecoder.readUByte()); byteArray.push(expGolombDecoder.readUByte()); } insertSampleInOrder(_this._txtTrack.samples, { type: 3, pts: pes.pts, bytes: byteArray }); } } } } } else if (payloadType === 5 && expGolombDecoder.bytesAvailable !== 0) { endOfCaptions = true; if (payloadSize > 16) { var uuidStrArray = []; for (var _i = 0; _i < 16; _i++) { uuidStrArray.push(expGolombDecoder.readUByte().toString(16)); if (_i === 3 || _i === 5 || _i === 7 || _i === 9) { uuidStrArray.push('-'); } } var length = payloadSize - 16; var userDataPayloadBytes = new Uint8Array(length); for (var _i2 = 0; _i2 < length; _i2++) { userDataPayloadBytes[_i2] = expGolombDecoder.readUByte(); } insertSampleInOrder(_this._txtTrack.samples, { pts: pes.pts, payloadType: payloadType, uuid: uuidStrArray.join(''), userData: Object(_id3__WEBPACK_IMPORTED_MODULE_3__["utf8ArrayToStr"])(userDataPayloadBytes), userDataBytes: userDataPayloadBytes }); } } else if (payloadSize < expGolombDecoder.bytesAvailable) { for (var _i3 = 0; _i3 < payloadSize; _i3++) { expGolombDecoder.readUByte(); } } } break; // SPS } case 7: push = true; spsfound = true; if (debug && avcSample) { avcSample.debug += 'SPS '; } if (!track.sps) { var _expGolombDecoder = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__["default"](unit.data); var config = _expGolombDecoder.readSPS(); track.width = config.width; track.height = config.height; track.pixelRatio = config.pixelRatio; // TODO: `track.sps` is defined as a `number[]`, but we're setting it to a `Uint8Array[]`. track.sps = [unit.data]; track.duration = _this._duration; var codecarray = unit.data.subarray(1, 4); var codecstring = 'avc1.'; for (var _i4 = 0; _i4 < 3; _i4++) { var h = codecarray[_i4].toString(16); if (h.length < 2) { h = '0' + h; } codecstring += h; } track.codec = codecstring; } break; // PPS case 8: push = true; if (debug && avcSample) { avcSample.debug += 'PPS '; } if (!track.pps) { // TODO: `track.pss` is defined as a `number[]`, but we're setting it to a `Uint8Array[]`. track.pps = [unit.data]; } break; // AUD case 9: push = false; track.audFound = true; if (avcSample) { pushAccessUnit(avcSample, track); } avcSample = _this.avcSample = createAVCSample(false, pes.pts, pes.dts, debug ? 'AUD ' : ''); break; // Filler Data case 12: push = false; break; default: push = false; if (avcSample) { avcSample.debug += 'unknown NAL ' + unit.type + ' '; } break; } if (avcSample && push) { var _units = avcSample.units; _units.push(unit); } }); // if last PES packet, push samples if (last && avcSample) { pushAccessUnit(avcSample, track); this.avcSample = null; } }; _proto.getLastNalUnit = function getLastNalUnit() { var _avcSample; var avcSample = this.avcSample; var lastUnit; // try to fallback to previous sample if current one is empty if (!avcSample || avcSample.units.length === 0) { var samples = this._avcTrack.samples; avcSample = samples[samples.length - 1]; } if ((_avcSample = avcSample) !== null && _avcSample !== void 0 && _avcSample.units) { var units = avcSample.units; lastUnit = units[units.length - 1]; } return lastUnit; }; _proto.parseAVCNALu = function parseAVCNALu(array) { var len = array.byteLength; var track = this._avcTrack; var state = track.naluState || 0; var lastState = state; var units = []; var i = 0; var value; var overflow; var unitType; var lastUnitStart = -1; var lastUnitType = 0; // logger.log('PES:' + Hex.hexDump(array)); if (state === -1) { // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet lastUnitStart = 0; // NALu type is value read from offset 0 lastUnitType = array[0] & 0x1f; state = 0; i = 1; } while (i < len) { value = array[i++]; // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case if (!state) { state = value ? 0 : 1; continue; } if (state === 1) { state = value ? 0 : 2; continue; } // here we have state either equal to 2 or 3 if (!value) { state = 3; } else if (value === 1) { if (lastUnitStart >= 0) { var unit = { data: array.subarray(lastUnitStart, i - state - 1), type: lastUnitType }; // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength); units.push(unit); } else { // lastUnitStart is undefined => this is the first start code found in this PES packet // first check if start code delimiter is overlapping between 2 PES packets, // ie it started in last packet (lastState not zero) // and ended at the beginning of this PES packet (i <= 4 - lastState) var lastUnit = this.getLastNalUnit(); if (lastUnit) { if (lastState && i <= 4 - lastState) { // start delimiter overlapping between PES packets // strip start delimiter bytes from the end of last NAL unit // check if lastUnit had a state different from zero if (lastUnit.state) { // strip last bytes lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState); } } // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit. overflow = i - state - 1; if (overflow > 0) { // logger.log('first NALU found with overflow:' + overflow); var tmp = new Uint8Array(lastUnit.data.byteLength + overflow); tmp.set(lastUnit.data, 0); tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength); lastUnit.data = tmp; } } } // check if we can read unit type if (i < len) { unitType = array[i] & 0x1f; // logger.log('find NALU @ offset:' + i + ',type:' + unitType); lastUnitStart = i; lastUnitType = unitType; state = 0; } else { // not enough byte to read unit type. let's read it on next PES parsing state = -1; } } else { state = 0; } } if (lastUnitStart >= 0 && state >= 0) { var _unit = { data: array.subarray(lastUnitStart, len), type: lastUnitType, state: state }; units.push(_unit); // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state); } // no NALu found if (units.length === 0) { // append pes.data to previous NAL unit var _lastUnit = this.getLastNalUnit(); if (_lastUnit) { var _tmp = new Uint8Array(_lastUnit.data.byteLength + array.byteLength); _tmp.set(_lastUnit.data, 0); _tmp.set(array, _lastUnit.data.byteLength); _lastUnit.data = _tmp; } } track.naluState = state; return units; }; _proto.parseAACPES = function parseAACPES(pes) { var startOffset = 0; var track = this._audioTrack; var aacOverFlow = this.aacOverFlow; var data = pes.data; if (aacOverFlow) { this.aacOverFlow = null; var sampleLength = aacOverFlow.sample.unit.byteLength; var frameMissingBytes = Math.min(aacOverFlow.missing, sampleLength); var frameOverflowBytes = sampleLength - frameMissingBytes; aacOverFlow.sample.unit.set(data.subarray(0, frameMissingBytes), frameOverflowBytes); track.samples.push(aacOverFlow.sample); // logger.log(`AAC: append overflowing ${frameOverflowBytes} bytes to beginning of new PES`); startOffset = aacOverFlow.missing; } // look for ADTS header (0xFFFx) var offset; var len; for (offset = startOffset, len = data.length; offset < len - 1; offset++) { if (_adts__WEBPACK_IMPORTED_MODULE_0__["isHeader"](data, offset)) { break; } } // if ADTS header does not start straight from the beginning of the PES payload, raise an error if (offset !== startOffset) { var reason; var fatal; if (offset < len - 1) { reason = "AAC PES did not start with ADTS header,offset:" + offset; fatal = false; } else { reason = 'no ADTS header found in AAC PES'; fatal = true; } _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn("parsing error:" + reason); this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorDetails"].FRAG_PARSING_ERROR, fatal: fatal, reason: reason }); if (fatal) { return; } } _adts__WEBPACK_IMPORTED_MODULE_0__["initTrackConfig"](track, this.observer, data, offset, this.audioCodec); var pts; if (pes.pts !== undefined) { pts = pes.pts; } else if (aacOverFlow) { // if last AAC frame is overflowing, we should ensure timestamps are contiguous: // first sample PTS should be equal to last sample PTS + frameDuration var frameDuration = _adts__WEBPACK_IMPORTED_MODULE_0__["getFrameDuration"](track.samplerate); pts = aacOverFlow.sample.pts + frameDuration; } else { _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('[tsdemuxer]: AAC PES unknown PTS'); return; } // scan for aac samples var frameIndex = 0; while (offset < len) { if (_adts__WEBPACK_IMPORTED_MODULE_0__["isHeader"](data, offset)) { if (offset + 5 < len) { var frame = _adts__WEBPACK_IMPORTED_MODULE_0__["appendFrame"](track, data, offset, pts, frameIndex); if (frame) { if (frame.missing) { this.aacOverFlow = frame; } else { offset += frame.length; frameIndex++; continue; } } } // We are at an ADTS header, but do not have enough data for a frame // Remaining data will be added to aacOverFlow break; } else { // nothing found, keep looking offset++; } } }; _proto.parseMPEGPES = function parseMPEGPES(pes) { var data = pes.data; var length = data.length; var frameIndex = 0; var offset = 0; var pts = pes.pts; if (pts === undefined) { _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('[tsdemuxer]: MPEG PES unknown PTS'); return; } while (offset < length) { if (_mpegaudio__WEBPACK_IMPORTED_MODULE_1__["isHeader"](data, offset)) { var frame = _mpegaudio__WEBPACK_IMPORTED_MODULE_1__["appendFrame"](this._audioTrack, data, offset, pts, frameIndex); if (frame) { offset += frame.length; frameIndex++; } else { // logger.log('Unable to parse Mpeg audio frame'); break; } } else { // nothing found, keep looking offset++; } } }; _proto.parseID3PES = function parseID3PES(pes) { if (pes.pts === undefined) { _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('[tsdemuxer]: ID3 PES unknown PTS'); return; } this._id3Track.samples.push(pes); }; return TSDemuxer; }(); TSDemuxer.minProbeByteLength = 188; function createAVCSample(key, pts, dts, debug) { return { key: key, frame: false, pts: pts, dts: dts, units: [], debug: debug, length: 0 }; } function parsePAT(data, offset) { // skip the PSI header and parse the first PMT entry return (data[offset + 10] & 0x1f) << 8 | data[offset + 11]; // logger.log('PMT PID:' + this._pmtId); } function parsePMT(data, offset, mpegSupported, isSampleAes) { var result = { audio: -1, avc: -1, id3: -1, isAAC: true }; var sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2]; var tableEnd = offset + 3 + sectionLength - 4; // to determine where the table is, we have to figure out how // long the program info descriptors are var programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11]; // advance the offset to the first entry in the mapping table offset += 12 + programInfoLength; while (offset < tableEnd) { var pid = (data[offset + 1] & 0x1f) << 8 | data[offset + 2]; switch (data[offset]) { case 0xcf: // SAMPLE-AES AAC if (!isSampleAes) { _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream'); break; } /* falls through */ case 0x0f: // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio) // logger.log('AAC PID:' + pid); if (result.audio === -1) { result.audio = pid; } break; // Packetized metadata (ID3) case 0x15: // logger.log('ID3 PID:' + pid); if (result.id3 === -1) { result.id3 = pid; } break; case 0xdb: // SAMPLE-AES AVC if (!isSampleAes) { _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('H.264 with AES-128-CBC slice encryption found in unencrypted stream'); break; } /* falls through */ case 0x1b: // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video) // logger.log('AVC PID:' + pid); if (result.avc === -1) { result.avc = pid; } break; // ISO/IEC 11172-3 (MPEG-1 audio) // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio) case 0x03: case 0x04: // logger.log('MPEG PID:' + pid); if (!mpegSupported) { _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('MPEG audio found, not supported in this browser'); } else if (result.audio === -1) { result.audio = pid; result.isAAC = false; } break; case 0x24: _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('Unsupported HEVC stream type found'); break; default: // logger.log('unknown stream type:' + data[offset]); break; } // move to the next table entry // skip past the elementary stream descriptors, if present offset += ((data[offset + 3] & 0x0f) << 8 | data[offset + 4]) + 5; } return result; } function parsePES(stream) { var i = 0; var frag; var pesLen; var pesHdrLen; var pesPts; var pesDts; var data = stream.data; // safety check if (!stream || stream.size === 0) { return null; } // we might need up to 19 bytes to read PES header // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes // usually only one merge is needed (and this is rare ...) while (data[0].length < 19 && data.length > 1) { var newData = new Uint8Array(data[0].length + data[1].length); newData.set(data[0]); newData.set(data[1], data[0].length); data[0] = newData; data.splice(1, 1); } // retrieve PTS/DTS from first fragment frag = data[0]; var pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2]; if (pesPrefix === 1) { pesLen = (frag[4] << 8) + frag[5]; // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated // minus 6 : PES header size if (pesLen && pesLen > stream.size - 6) { return null; } var pesFlags = frag[7]; if (pesFlags & 0xc0) { /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html as PTS / DTS is 33 bit we cannot use bitwise operator in JS, as Bitwise operators treat their operands as a sequence of 32 bits */ pesPts = (frag[9] & 0x0e) * 536870912 + // 1 << 29 (frag[10] & 0xff) * 4194304 + // 1 << 22 (frag[11] & 0xfe) * 16384 + // 1 << 14 (frag[12] & 0xff) * 128 + // 1 << 7 (frag[13] & 0xfe) / 2; if (pesFlags & 0x40) { pesDts = (frag[14] & 0x0e) * 536870912 + // 1 << 29 (frag[15] & 0xff) * 4194304 + // 1 << 22 (frag[16] & 0xfe) * 16384 + // 1 << 14 (frag[17] & 0xff) * 128 + // 1 << 7 (frag[18] & 0xfe) / 2; if (pesPts - pesDts > 60 * 90000) { _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn(Math.round((pesPts - pesDts) / 90000) + "s delta between PTS and DTS, align them"); pesPts = pesDts; } } else { pesDts = pesPts; } } pesHdrLen = frag[8]; // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension var payloadStartOffset = pesHdrLen + 9; if (stream.size <= payloadStartOffset) { return null; } stream.size -= payloadStartOffset; // reassemble PES packet var pesData = new Uint8Array(stream.size); for (var j = 0, dataLen = data.length; j < dataLen; j++) { frag = data[j]; var len = frag.byteLength; if (payloadStartOffset) { if (payloadStartOffset > len) { // trim full frag if PES header bigger than frag payloadStartOffset -= len; continue; } else { // trim partial frag if PES header smaller than frag frag = frag.subarray(payloadStartOffset); len -= payloadStartOffset; payloadStartOffset = 0; } } pesData.set(frag, i); i += len; } if (pesLen) { // payload size : remove PES header + PES extension pesLen -= pesHdrLen + 3; } return { data: pesData, pts: pesPts, dts: pesDts, len: pesLen }; } return null; } function pushAccessUnit(avcSample, avcTrack) { if (avcSample.units.length && avcSample.frame) { // if sample does not have PTS/DTS, patch with last sample PTS/DTS if (avcSample.pts === undefined) { var samples = avcTrack.samples; var nbSamples = samples.length; if (nbSamples) { var lastSample = samples[nbSamples - 1]; avcSample.pts = lastSample.pts; avcSample.dts = lastSample.dts; } else { // dropping samples, no timestamp found avcTrack.dropped++; return; } } avcTrack.samples.push(avcSample); } if (avcSample.debug.length) { _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug); } } function insertSampleInOrder(arr, data) { var len = arr.length; if (len > 0) { if (data.pts >= arr[len - 1].pts) { arr.push(data); } else { for (var pos = len - 1; pos >= 0; pos--) { if (data.pts < arr[pos].pts) { arr.splice(pos, 0, data); break; } } } } else { arr.push(data); } } /** * remove Emulation Prevention bytes from a RBSP */ function discardEPB(data) { var length = data.byteLength; var EPBPositions = []; var i = 1; // Find all `Emulation Prevention Bytes` while (i < length - 2) { if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) { EPBPositions.push(i + 2); i += 2; } else { i++; } } // If no Emulation Prevention Bytes were found just return the original // array if (EPBPositions.length === 0) { return data; } // Create a new array to hold the NAL unit data var newLength = length - EPBPositions.length; var newData = new Uint8Array(newLength); var sourceIndex = 0; for (i = 0; i < newLength; sourceIndex++, i++) { if (sourceIndex === EPBPositions[0]) { // Skip this byte sourceIndex++; // Remove this position index EPBPositions.shift(); } newData[i] = data[sourceIndex]; } return newData; } /* harmony default export */ __webpack_exports__["default"] = (TSDemuxer); /***/ }), /***/ "./src/errors.ts": /*!***********************!*\ !*** ./src/errors.ts ***! \***********************/ /*! exports provided: ErrorTypes, ErrorDetails */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorTypes", function() { return ErrorTypes; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorDetails", function() { return ErrorDetails; }); var ErrorTypes; /** * @enum {ErrorDetails} * @typedef {string} ErrorDetail */ (function (ErrorTypes) { ErrorTypes["NETWORK_ERROR"] = "networkError"; ErrorTypes["MEDIA_ERROR"] = "mediaError"; ErrorTypes["KEY_SYSTEM_ERROR"] = "keySystemError"; ErrorTypes["MUX_ERROR"] = "muxError"; ErrorTypes["OTHER_ERROR"] = "otherError"; })(ErrorTypes || (ErrorTypes = {})); var ErrorDetails; (function (ErrorDetails) { ErrorDetails["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys"; ErrorDetails["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess"; ErrorDetails["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession"; ErrorDetails["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed"; ErrorDetails["KEY_SYSTEM_NO_INIT_DATA"] = "keySystemNoInitData"; ErrorDetails["MANIFEST_LOAD_ERROR"] = "manifestLoadError"; ErrorDetails["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut"; ErrorDetails["MANIFEST_PARSING_ERROR"] = "manifestParsingError"; ErrorDetails["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError"; ErrorDetails["LEVEL_EMPTY_ERROR"] = "levelEmptyError"; ErrorDetails["LEVEL_LOAD_ERROR"] = "levelLoadError"; ErrorDetails["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut"; ErrorDetails["LEVEL_SWITCH_ERROR"] = "levelSwitchError"; ErrorDetails["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError"; ErrorDetails["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut"; ErrorDetails["SUBTITLE_LOAD_ERROR"] = "subtitleTrackLoadError"; ErrorDetails["SUBTITLE_TRACK_LOAD_TIMEOUT"] = "subtitleTrackLoadTimeOut"; ErrorDetails["FRAG_LOAD_ERROR"] = "fragLoadError"; ErrorDetails["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut"; ErrorDetails["FRAG_DECRYPT_ERROR"] = "fragDecryptError"; ErrorDetails["FRAG_PARSING_ERROR"] = "fragParsingError"; ErrorDetails["REMUX_ALLOC_ERROR"] = "remuxAllocError"; ErrorDetails["KEY_LOAD_ERROR"] = "keyLoadError"; ErrorDetails["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut"; ErrorDetails["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError"; ErrorDetails["BUFFER_INCOMPATIBLE_CODECS_ERROR"] = "bufferIncompatibleCodecsError"; ErrorDetails["BUFFER_APPEND_ERROR"] = "bufferAppendError"; ErrorDetails["BUFFER_APPENDING_ERROR"] = "bufferAppendingError"; ErrorDetails["BUFFER_STALLED_ERROR"] = "bufferStalledError"; ErrorDetails["BUFFER_FULL_ERROR"] = "bufferFullError"; ErrorDetails["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole"; ErrorDetails["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall"; ErrorDetails["INTERNAL_EXCEPTION"] = "internalException"; ErrorDetails["INTERNAL_ABORTED"] = "aborted"; ErrorDetails["UNKNOWN"] = "unknown"; })(ErrorDetails || (ErrorDetails = {})); /***/ }), /***/ "./src/events.ts": /*!***********************!*\ !*** ./src/events.ts ***! \***********************/ /*! exports provided: Events */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Events", function() { return Events; }); /** * @readonly * @enum {string} */ var Events; (function (Events) { Events["MEDIA_ATTACHING"] = "hlsMediaAttaching"; Events["MEDIA_ATTACHED"] = "hlsMediaAttached"; Events["MEDIA_DETACHING"] = "hlsMediaDetaching"; Events["MEDIA_DETACHED"] = "hlsMediaDetached"; Events["BUFFER_RESET"] = "hlsBufferReset"; Events["BUFFER_CODECS"] = "hlsBufferCodecs"; Events["BUFFER_CREATED"] = "hlsBufferCreated"; Events["BUFFER_APPENDING"] = "hlsBufferAppending"; Events["BUFFER_APPENDED"] = "hlsBufferAppended"; Events["BUFFER_EOS"] = "hlsBufferEos"; Events["BUFFER_FLUSHING"] = "hlsBufferFlushing"; Events["BUFFER_FLUSHED"] = "hlsBufferFlushed"; Events["MANIFEST_LOADING"] = "hlsManifestLoading"; Events["MANIFEST_LOADED"] = "hlsManifestLoaded"; Events["MANIFEST_PARSED"] = "hlsManifestParsed"; Events["LEVEL_SWITCHING"] = "hlsLevelSwitching"; Events["LEVEL_SWITCHED"] = "hlsLevelSwitched"; Events["LEVEL_LOADING"] = "hlsLevelLoading"; Events["LEVEL_LOADED"] = "hlsLevelLoaded"; Events["LEVEL_UPDATED"] = "hlsLevelUpdated"; Events["LEVEL_PTS_UPDATED"] = "hlsLevelPtsUpdated"; Events["LEVELS_UPDATED"] = "hlsLevelsUpdated"; Events["AUDIO_TRACKS_UPDATED"] = "hlsAudioTracksUpdated"; Events["AUDIO_TRACK_SWITCHING"] = "hlsAudioTrackSwitching"; Events["AUDIO_TRACK_SWITCHED"] = "hlsAudioTrackSwitched"; Events["AUDIO_TRACK_LOADING"] = "hlsAudioTrackLoading"; Events["AUDIO_TRACK_LOADED"] = "hlsAudioTrackLoaded"; Events["SUBTITLE_TRACKS_UPDATED"] = "hlsSubtitleTracksUpdated"; Events["SUBTITLE_TRACKS_CLEARED"] = "hlsSubtitleTracksCleared"; Events["SUBTITLE_TRACK_SWITCH"] = "hlsSubtitleTrackSwitch"; Events["SUBTITLE_TRACK_LOADING"] = "hlsSubtitleTrackLoading"; Events["SUBTITLE_TRACK_LOADED"] = "hlsSubtitleTrackLoaded"; Events["SUBTITLE_FRAG_PROCESSED"] = "hlsSubtitleFragProcessed"; Events["CUES_PARSED"] = "hlsCuesParsed"; Events["NON_NATIVE_TEXT_TRACKS_FOUND"] = "hlsNonNativeTextTracksFound"; Events["INIT_PTS_FOUND"] = "hlsInitPtsFound"; Events["FRAG_LOADING"] = "hlsFragLoading"; Events["FRAG_LOAD_EMERGENCY_ABORTED"] = "hlsFragLoadEmergencyAborted"; Events["FRAG_LOADED"] = "hlsFragLoaded"; Events["FRAG_DECRYPTED"] = "hlsFragDecrypted"; Events["FRAG_PARSING_INIT_SEGMENT"] = "hlsFragParsingInitSegment"; Events["FRAG_PARSING_USERDATA"] = "hlsFragParsingUserdata"; Events["FRAG_PARSING_METADATA"] = "hlsFragParsingMetadata"; Events["FRAG_PARSED"] = "hlsFragParsed"; Events["FRAG_BUFFERED"] = "hlsFragBuffered"; Events["FRAG_CHANGED"] = "hlsFragChanged"; Events["FPS_DROP"] = "hlsFpsDrop"; Events["FPS_DROP_LEVEL_CAPPING"] = "hlsFpsDropLevelCapping"; Events["ERROR"] = "hlsError"; Events["DESTROYING"] = "hlsDestroying"; Events["KEY_LOADING"] = "hlsKeyLoading"; Events["KEY_LOADED"] = "hlsKeyLoaded"; Events["LIVE_BACK_BUFFER_REACHED"] = "hlsLiveBackBufferReached"; Events["BACK_BUFFER_REACHED"] = "hlsBackBufferReached"; })(Events || (Events = {})); /***/ }), /***/ "./src/hls.ts": /*!********************!*\ !*** ./src/hls.ts ***! \********************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Hls; }); /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js"); /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _loader_playlist_loader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./loader/playlist-loader */ "./src/loader/playlist-loader.ts"); /* harmony import */ var _loader_key_loader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./loader/key-loader */ "./src/loader/key-loader.ts"); /* harmony import */ var _controller_id3_track_controller__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./controller/id3-track-controller */ "./src/controller/id3-track-controller.ts"); /* harmony import */ var _controller_latency_controller__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./controller/latency-controller */ "./src/controller/latency-controller.ts"); /* harmony import */ var _controller_level_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./controller/level-controller */ "./src/controller/level-controller.ts"); /* harmony import */ var _controller_fragment_tracker__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./controller/fragment-tracker */ "./src/controller/fragment-tracker.ts"); /* harmony import */ var _controller_stream_controller__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./controller/stream-controller */ "./src/controller/stream-controller.ts"); /* harmony import */ var _is_supported__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./is-supported */ "./src/is-supported.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./config */ "./src/config.ts"); /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js"); /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_11__); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./events */ "./src/events.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./errors */ "./src/errors.ts"); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } /** * @module Hls * @class * @constructor */ var Hls = /*#__PURE__*/function () { Hls.isSupported = function isSupported() { return Object(_is_supported__WEBPACK_IMPORTED_MODULE_8__["isSupported"])(); }; /** * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`. * * @constructs Hls * @param {HlsConfig} config */ function Hls(userConfig) { if (userConfig === void 0) { userConfig = {}; } this.config = void 0; this.userConfig = void 0; this.coreComponents = void 0; this.networkControllers = void 0; this._emitter = new eventemitter3__WEBPACK_IMPORTED_MODULE_11__["EventEmitter"](); this._autoLevelCapping = void 0; this.abrController = void 0; this.bufferController = void 0; this.capLevelController = void 0; this.latencyController = void 0; this.levelController = void 0; this.streamController = void 0; this.audioTrackController = void 0; this.subtitleTrackController = void 0; this.emeController = void 0; this._media = null; this.url = null; var config = this.config = Object(_config__WEBPACK_IMPORTED_MODULE_10__["mergeConfig"])(Hls.DefaultConfig, userConfig); this.userConfig = userConfig; Object(_utils_logger__WEBPACK_IMPORTED_MODULE_9__["enableLogs"])(config.debug); this._autoLevelCapping = -1; if (config.progressive) { Object(_config__WEBPACK_IMPORTED_MODULE_10__["enableStreamingMode"])(config); } // core controllers and network loaders var ConfigAbrController = config.abrController, ConfigBufferController = config.bufferController, ConfigCapLevelController = config.capLevelController, ConfigFpsController = config.fpsController; var abrController = this.abrController = new ConfigAbrController(this); var bufferController = this.bufferController = new ConfigBufferController(this); var capLevelController = this.capLevelController = new ConfigCapLevelController(this); var fpsController = new ConfigFpsController(this); var playListLoader = new _loader_playlist_loader__WEBPACK_IMPORTED_MODULE_1__["default"](this); var keyLoader = new _loader_key_loader__WEBPACK_IMPORTED_MODULE_2__["default"](this); var id3TrackController = new _controller_id3_track_controller__WEBPACK_IMPORTED_MODULE_3__["default"](this); // network controllers var levelController = this.levelController = new _controller_level_controller__WEBPACK_IMPORTED_MODULE_5__["default"](this); // FragmentTracker must be defined before StreamController because the order of event handling is important var fragmentTracker = new _controller_fragment_tracker__WEBPACK_IMPORTED_MODULE_6__["FragmentTracker"](this); var streamController = this.streamController = new _controller_stream_controller__WEBPACK_IMPORTED_MODULE_7__["default"](this, fragmentTracker); // Cap level controller uses streamController to flush the buffer capLevelController.setStreamController(streamController); // fpsController uses streamController to switch when frames are being dropped fpsController.setStreamController(streamController); var networkControllers = [levelController, streamController]; this.networkControllers = networkControllers; var coreComponents = [playListLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker]; this.audioTrackController = this.createController(config.audioTrackController, null, networkControllers); this.createController(config.audioStreamController, fragmentTracker, networkControllers); // subtitleTrackController must be defined before because the order of event handling is important this.subtitleTrackController = this.createController(config.subtitleTrackController, null, networkControllers); this.createController(config.subtitleStreamController, fragmentTracker, networkControllers); this.createController(config.timelineController, null, coreComponents); this.emeController = this.createController(config.emeController, null, coreComponents); this.latencyController = this.createController(_controller_latency_controller__WEBPACK_IMPORTED_MODULE_4__["default"], null, coreComponents); this.coreComponents = coreComponents; } var _proto = Hls.prototype; _proto.createController = function createController(ControllerClass, fragmentTracker, components) { if (ControllerClass) { var controllerInstance = fragmentTracker ? new ControllerClass(this, fragmentTracker) : new ControllerClass(this); if (components) { components.push(controllerInstance); } return controllerInstance; } return null; } // Delegate the EventEmitter through the public API of Hls.js ; _proto.on = function on(event, listener, context) { if (context === void 0) { context = this; } this._emitter.on(event, listener, context); }; _proto.once = function once(event, listener, context) { if (context === void 0) { context = this; } this._emitter.once(event, listener, context); }; _proto.removeAllListeners = function removeAllListeners(event) { this._emitter.removeAllListeners(event); }; _proto.off = function off(event, listener, context, once) { if (context === void 0) { context = this; } this._emitter.off(event, listener, context, once); }; _proto.listeners = function listeners(event) { return this._emitter.listeners(event); }; _proto.emit = function emit(event, name, eventObject) { return this._emitter.emit(event, name, eventObject); }; _proto.trigger = function trigger(event, eventObject) { if (this.config.debug) { return this.emit(event, event, eventObject); } else { try { return this.emit(event, event, eventObject); } catch (e) { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].error('An internal error happened while handling event ' + event + '. Error message: "' + e.message + '". Here is a stacktrace:', e); this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorTypes"].OTHER_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].INTERNAL_EXCEPTION, fatal: false, event: event, error: e }); } } return false; }; _proto.listenerCount = function listenerCount(event) { return this._emitter.listenerCount(event); } /** * Dispose of the instance */ ; _proto.destroy = function destroy() { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('destroy'); this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].DESTROYING, undefined); this.detachMedia(); this.removeAllListeners(); this._autoLevelCapping = -1; this.url = null; this.networkControllers.forEach(function (component) { return component.destroy(); }); this.networkControllers.length = 0; this.coreComponents.forEach(function (component) { return component.destroy(); }); this.coreComponents.length = 0; } /** * Attaches Hls.js to a media element * @param {HTMLMediaElement} media */ ; _proto.attachMedia = function attachMedia(media) { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('attachMedia'); this._media = media; this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].MEDIA_ATTACHING, { media: media }); } /** * Detach Hls.js from the media */ ; _proto.detachMedia = function detachMedia() { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('detachMedia'); this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].MEDIA_DETACHING, undefined); this._media = null; } /** * Set the source URL. Can be relative or absolute. * @param {string} url */ ; _proto.loadSource = function loadSource(url) { this.stopLoad(); var media = this.media; var loadedSource = this.url; var loadingSource = this.url = url_toolkit__WEBPACK_IMPORTED_MODULE_0__["buildAbsoluteURL"](self.location.href, url, { alwaysNormalize: true }); _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("loadSource:" + loadingSource); if (media && loadedSource && loadedSource !== loadingSource && this.bufferController.hasSourceTypes()) { this.detachMedia(); this.attachMedia(media); } // when attaching to a source URL, trigger a playlist load this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].MANIFEST_LOADING, { url: url }); } /** * Start loading data from the stream source. * Depending on default config, client starts loading automatically when a source is set. * * @param {number} startPosition Set the start position to stream from * @default -1 None (from earliest point) */ ; _proto.startLoad = function startLoad(startPosition) { if (startPosition === void 0) { startPosition = -1; } _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("startLoad(" + startPosition + ")"); this.networkControllers.forEach(function (controller) { controller.startLoad(startPosition); }); } /** * Stop loading of any stream data. */ ; _proto.stopLoad = function stopLoad() { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('stopLoad'); this.networkControllers.forEach(function (controller) { controller.stopLoad(); }); } /** * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1) */ ; _proto.swapAudioCodec = function swapAudioCodec() { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('swapAudioCodec'); this.streamController.swapAudioCodec(); } /** * When the media-element fails, this allows to detach and then re-attach it * as one call (convenience method). * * Automatic recovery of media-errors by this process is configurable. */ ; _proto.recoverMediaError = function recoverMediaError() { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('recoverMediaError'); var media = this._media; this.detachMedia(); if (media) { this.attachMedia(media); } }; _proto.removeLevel = function removeLevel(levelIndex, urlId) { if (urlId === void 0) { urlId = 0; } this.levelController.removeLevel(levelIndex, urlId); } /** * @type {Level[]} */ ; _createClass(Hls, [{ key: "levels", get: function get() { var levels = this.levelController.levels; return levels ? levels : []; } /** * Index of quality level currently played * @type {number} */ }, { key: "currentLevel", get: function get() { return this.streamController.currentLevel; } /** * Set quality level index immediately . * This will flush the current buffer to replace the quality asap. * That means playback will interrupt at least shortly to re-buffer and re-sync eventually. * @type {number} -1 for automatic level selection */ , set: function set(newLevel) { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set currentLevel:" + newLevel); this.loadLevel = newLevel; this.abrController.clearTimer(); this.streamController.immediateLevelSwitch(); } /** * Index of next quality level loaded as scheduled by stream controller. * @type {number} */ }, { key: "nextLevel", get: function get() { return this.streamController.nextLevel; } /** * Set quality level index for next loaded data. * This will switch the video quality asap, without interrupting playback. * May abort current loading of data, and flush parts of buffer (outside currently played fragment region). * @type {number} -1 for automatic level selection */ , set: function set(newLevel) { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set nextLevel:" + newLevel); this.levelController.manualLevel = newLevel; this.streamController.nextLevelSwitch(); } /** * Return the quality level of the currently or last (of none is loaded currently) segment * @type {number} */ }, { key: "loadLevel", get: function get() { return this.levelController.level; } /** * Set quality level index for next loaded data in a conservative way. * This will switch the quality without flushing, but interrupt current loading. * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer. * @type {number} newLevel -1 for automatic level selection */ , set: function set(newLevel) { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set loadLevel:" + newLevel); this.levelController.manualLevel = newLevel; } /** * get next quality level loaded * @type {number} */ }, { key: "nextLoadLevel", get: function get() { return this.levelController.nextLoadLevel; } /** * Set quality level of next loaded segment in a fully "non-destructive" way. * Same as `loadLevel` but will wait for next switch (until current loading is done). * @type {number} level */ , set: function set(level) { this.levelController.nextLoadLevel = level; } /** * Return "first level": like a default level, if not set, * falls back to index of first level referenced in manifest * @type {number} */ }, { key: "firstLevel", get: function get() { return Math.max(this.levelController.firstLevel, this.minAutoLevel); } /** * Sets "first-level", see getter. * @type {number} */ , set: function set(newLevel) { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set firstLevel:" + newLevel); this.levelController.firstLevel = newLevel; } /** * Return start level (level of first fragment that will be played back) * if not overrided by user, first level appearing in manifest will be used as start level * if -1 : automatic start level selection, playback will start from level matching download bandwidth * (determined from download of first segment) * @type {number} */ }, { key: "startLevel", get: function get() { return this.levelController.startLevel; } /** * set start level (level of first fragment that will be played back) * if not overrided by user, first level appearing in manifest will be used as start level * if -1 : automatic start level selection, playback will start from level matching download bandwidth * (determined from download of first segment) * @type {number} newLevel */ , set: function set(newLevel) { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set startLevel:" + newLevel); // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel if (newLevel !== -1) { newLevel = Math.max(newLevel, this.minAutoLevel); } this.levelController.startLevel = newLevel; } /** * Get the current setting for capLevelToPlayerSize * * @type {boolean} */ }, { key: "capLevelToPlayerSize", get: function get() { return this.config.capLevelToPlayerSize; } /** * set dynamically set capLevelToPlayerSize against (`CapLevelController`) * * @type {boolean} */ , set: function set(shouldStartCapping) { var newCapLevelToPlayerSize = !!shouldStartCapping; if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) { if (newCapLevelToPlayerSize) { this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size. } else { this.capLevelController.stopCapping(); this.autoLevelCapping = -1; this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap. } this.config.capLevelToPlayerSize = newCapLevelToPlayerSize; } } /** * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`) * @type {number} */ }, { key: "autoLevelCapping", get: function get() { return this._autoLevelCapping; } /** * get bandwidth estimate * @type {number} */ , set: /** * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`) * @type {number} */ function set(newLevel) { if (this._autoLevelCapping !== newLevel) { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set autoLevelCapping:" + newLevel); this._autoLevelCapping = newLevel; } } /** * True when automatic level selection enabled * @type {boolean} */ }, { key: "bandwidthEstimate", get: function get() { var bwEstimator = this.abrController.bwEstimator; if (!bwEstimator) { return NaN; } return bwEstimator.getEstimate(); } }, { key: "autoLevelEnabled", get: function get() { return this.levelController.manualLevel === -1; } /** * Level set manually (if any) * @type {number} */ }, { key: "manualLevel", get: function get() { return this.levelController.manualLevel; } /** * min level selectable in auto mode according to config.minAutoBitrate * @type {number} */ }, { key: "minAutoLevel", get: function get() { var levels = this.levels, minAutoBitrate = this.config.minAutoBitrate; if (!levels) return 0; var len = levels.length; for (var i = 0; i < len; i++) { if (levels[i].maxBitrate > minAutoBitrate) { return i; } } return 0; } /** * max level selectable in auto mode according to autoLevelCapping * @type {number} */ }, { key: "maxAutoLevel", get: function get() { var levels = this.levels, autoLevelCapping = this.autoLevelCapping; var maxAutoLevel; if (autoLevelCapping === -1 && levels && levels.length) { maxAutoLevel = levels.length - 1; } else { maxAutoLevel = autoLevelCapping; } return maxAutoLevel; } /** * next automatically selected quality level * @type {number} */ }, { key: "nextAutoLevel", get: function get() { // ensure next auto level is between min and max auto level return Math.min(Math.max(this.abrController.nextAutoLevel, this.minAutoLevel), this.maxAutoLevel); } /** * this setter is used to force next auto level. * this is useful to force a switch down in auto mode: * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example) * forced value is valid for one fragment. upon succesful frag loading at forced level, * this value will be resetted to -1 by ABR controller. * @type {number} */ , set: function set(nextLevel) { this.abrController.nextAutoLevel = Math.max(this.minAutoLevel, nextLevel); } /** * @type {AudioTrack[]} */ }, { key: "audioTracks", get: function get() { var audioTrackController = this.audioTrackController; return audioTrackController ? audioTrackController.audioTracks : []; } /** * index of the selected audio track (index in audio track lists) * @type {number} */ }, { key: "audioTrack", get: function get() { var audioTrackController = this.audioTrackController; return audioTrackController ? audioTrackController.audioTrack : -1; } /** * selects an audio track, based on its index in audio track lists * @type {number} */ , set: function set(audioTrackId) { var audioTrackController = this.audioTrackController; if (audioTrackController) { audioTrackController.audioTrack = audioTrackId; } } /** * get alternate subtitle tracks list from playlist * @type {MediaPlaylist[]} */ }, { key: "subtitleTracks", get: function get() { var subtitleTrackController = this.subtitleTrackController; return subtitleTrackController ? subtitleTrackController.subtitleTracks : []; } /** * index of the selected subtitle track (index in subtitle track lists) * @type {number} */ }, { key: "subtitleTrack", get: function get() { var subtitleTrackController = this.subtitleTrackController; return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1; }, set: /** * select an subtitle track, based on its index in subtitle track lists * @type {number} */ function set(subtitleTrackId) { var subtitleTrackController = this.subtitleTrackController; if (subtitleTrackController) { subtitleTrackController.subtitleTrack = subtitleTrackId; } } /** * @type {boolean} */ }, { key: "media", get: function get() { return this._media; } }, { key: "subtitleDisplay", get: function get() { var subtitleTrackController = this.subtitleTrackController; return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false; } /** * Enable/disable subtitle display rendering * @type {boolean} */ , set: function set(value) { var subtitleTrackController = this.subtitleTrackController; if (subtitleTrackController) { subtitleTrackController.subtitleDisplay = value; } } /** * get mode for Low-Latency HLS loading * @type {boolean} */ }, { key: "lowLatencyMode", get: function get() { return this.config.lowLatencyMode; } /** * Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK. * @type {boolean} */ , set: function set(mode) { this.config.lowLatencyMode = mode; } /** * position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```) * @type {number} */ }, { key: "liveSyncPosition", get: function get() { return this.latencyController.liveSyncPosition; } /** * estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced) * returns 0 before first playlist is loaded * @type {number} */ }, { key: "latency", get: function get() { return this.latencyController.latency; } /** * maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition``` * configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration``` * returns 0 before first playlist is loaded * @type {number} */ }, { key: "maxLatency", get: function get() { return this.latencyController.maxLatency; } /** * target distance from the edge as calculated by the latency controller * @type {number} */ }, { key: "targetLatency", get: function get() { return this.latencyController.targetLatency; } /** * the rate at which the edge of the current live playlist is advancing or 1 if there is none * @type {number} */ }, { key: "drift", get: function get() { return this.latencyController.drift; } /** * set to true when startLoad is called before MANIFEST_PARSED event * @type {boolean} */ }, { key: "forceStartLoad", get: function get() { return this.streamController.forceStartLoad; } }], [{ key: "version", get: function get() { return "1.0.8-0.canary.7809"; } }, { key: "Events", get: function get() { return _events__WEBPACK_IMPORTED_MODULE_12__["Events"]; } }, { key: "ErrorTypes", get: function get() { return _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorTypes"]; } }, { key: "ErrorDetails", get: function get() { return _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"]; } }, { key: "DefaultConfig", get: function get() { if (!Hls.defaultConfig) { return _config__WEBPACK_IMPORTED_MODULE_10__["hlsDefaultConfig"]; } return Hls.defaultConfig; } /** * @type {HlsConfig} */ , set: function set(defaultConfig) { Hls.defaultConfig = defaultConfig; } }]); return Hls; }(); Hls.defaultConfig = void 0; /***/ }), /***/ "./src/is-supported.ts": /*!*****************************!*\ !*** ./src/is-supported.ts ***! \*****************************/ /*! exports provided: isSupported, changeTypeSupported */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isSupported", function() { return isSupported; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "changeTypeSupported", function() { return changeTypeSupported; }); /* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/mediasource-helper */ "./src/utils/mediasource-helper.ts"); function getSourceBuffer() { return self.SourceBuffer || self.WebKitSourceBuffer; } function isSupported() { var mediaSource = Object(_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_0__["getMediaSource"])(); if (!mediaSource) { return false; } var sourceBuffer = getSourceBuffer(); var isTypeSupported = mediaSource && typeof mediaSource.isTypeSupported === 'function' && mediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'); // if SourceBuffer is exposed ensure its API is valid // safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible var sourceBufferValidAPI = !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function'; return !!isTypeSupported && !!sourceBufferValidAPI; } function changeTypeSupported() { var _sourceBuffer$prototy; var sourceBuffer = getSourceBuffer(); return typeof (sourceBuffer === null || sourceBuffer === void 0 ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) === null || _sourceBuffer$prototy === void 0 ? void 0 : _sourceBuffer$prototy.changeType) === 'function'; } /***/ }), /***/ "./src/loader/fragment-loader.ts": /*!***************************************!*\ !*** ./src/loader/fragment-loader.ts ***! \***************************************/ /*! exports provided: default, LoadError */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return FragmentLoader; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoadError", function() { return LoadError; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var MIN_CHUNK_SIZE = Math.pow(2, 17); // 128kb var FragmentLoader = /*#__PURE__*/function () { function FragmentLoader(config) { this.config = void 0; this.loader = null; this.partLoadTimeout = -1; this.config = config; } var _proto = FragmentLoader.prototype; _proto.destroy = function destroy() { if (this.loader) { this.loader.destroy(); this.loader = null; } }; _proto.abort = function abort() { if (this.loader) { // Abort the loader for current fragment. Only one may load at any given time this.loader.abort(); } }; _proto.load = function load(frag, _onProgress) { var _this = this; var url = frag.url; if (!url) { return Promise.reject(new LoadError({ type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_ERROR, fatal: false, frag: frag, networkDetails: null }, "Fragment does not have a " + (url ? 'part list' : 'url'))); } this.abort(); var config = this.config; var FragmentILoader = config.fLoader; var DefaultILoader = config.loader; return new Promise(function (resolve, reject) { if (_this.loader) { _this.loader.destroy(); } var loader = _this.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config); var loaderContext = createLoaderContext(frag); var loaderConfig = { timeout: config.fragLoadingTimeOut, maxRetry: 0, retryDelay: 0, maxRetryDelay: config.fragLoadingMaxRetryTimeout, highWaterMark: MIN_CHUNK_SIZE }; // Assign frag stats to the loader's stats reference frag.stats = loader.stats; loader.load(loaderContext, loaderConfig, { onSuccess: function onSuccess(response, stats, context, networkDetails) { _this.resetLoader(frag, loader); resolve({ frag: frag, part: null, payload: response.data, networkDetails: networkDetails }); }, onError: function onError(response, context, networkDetails) { _this.resetLoader(frag, loader); reject(new LoadError({ type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_ERROR, fatal: false, frag: frag, response: response, networkDetails: networkDetails })); }, onAbort: function onAbort(stats, context, networkDetails) { _this.resetLoader(frag, loader); reject(new LoadError({ type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].INTERNAL_ABORTED, fatal: false, frag: frag, networkDetails: networkDetails })); }, onTimeout: function onTimeout(response, context, networkDetails) { _this.resetLoader(frag, loader); reject(new LoadError({ type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_TIMEOUT, fatal: false, frag: frag, networkDetails: networkDetails })); }, onProgress: function onProgress(stats, context, data, networkDetails) { if (_onProgress) { _onProgress({ frag: frag, part: null, payload: data, networkDetails: networkDetails }); } } }); }); }; _proto.loadPart = function loadPart(frag, part, onProgress) { var _this2 = this; this.abort(); var config = this.config; var FragmentILoader = config.fLoader; var DefaultILoader = config.loader; return new Promise(function (resolve, reject) { if (_this2.loader) { _this2.loader.destroy(); } var loader = _this2.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config); var loaderContext = createLoaderContext(frag, part); var loaderConfig = { timeout: config.fragLoadingTimeOut, maxRetry: 0, retryDelay: 0, maxRetryDelay: config.fragLoadingMaxRetryTimeout, highWaterMark: MIN_CHUNK_SIZE }; // Assign part stats to the loader's stats reference part.stats = loader.stats; loader.load(loaderContext, loaderConfig, { onSuccess: function onSuccess(response, stats, context, networkDetails) { _this2.resetLoader(frag, loader); _this2.updateStatsFromPart(frag, part); var partLoadedData = { frag: frag, part: part, payload: response.data, networkDetails: networkDetails }; onProgress(partLoadedData); resolve(partLoadedData); }, onError: function onError(response, context, networkDetails) { _this2.resetLoader(frag, loader); reject(new LoadError({ type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_ERROR, fatal: false, frag: frag, part: part, response: response, networkDetails: networkDetails })); }, onAbort: function onAbort(stats, context, networkDetails) { frag.stats.aborted = part.stats.aborted; _this2.resetLoader(frag, loader); reject(new LoadError({ type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].INTERNAL_ABORTED, fatal: false, frag: frag, part: part, networkDetails: networkDetails })); }, onTimeout: function onTimeout(response, context, networkDetails) { _this2.resetLoader(frag, loader); reject(new LoadError({ type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_TIMEOUT, fatal: false, frag: frag, part: part, networkDetails: networkDetails })); } }); }); }; _proto.updateStatsFromPart = function updateStatsFromPart(frag, part) { var fragStats = frag.stats; var partStats = part.stats; var partTotal = partStats.total; fragStats.loaded += partStats.loaded; if (partTotal) { var estTotalParts = Math.round(frag.duration / part.duration); var estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts); var estRemainingParts = estTotalParts - estLoadedParts; var estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts); fragStats.total = fragStats.loaded + estRemainingBytes; } else { fragStats.total = Math.max(fragStats.loaded, fragStats.total); } var fragLoading = fragStats.loading; var partLoading = partStats.loading; if (fragLoading.start) { // add to fragment loader latency fragLoading.first += partLoading.first - partLoading.start; } else { fragLoading.start = partLoading.start; fragLoading.first = partLoading.first; } fragLoading.end = partLoading.end; }; _proto.resetLoader = function resetLoader(frag, loader) { frag.loader = null; if (this.loader === loader) { self.clearTimeout(this.partLoadTimeout); this.loader = null; } loader.destroy(); }; return FragmentLoader; }(); function createLoaderContext(frag, part) { if (part === void 0) { part = null; } var segment = part || frag; var loaderContext = { frag: frag, part: part, responseType: 'arraybuffer', url: segment.url, rangeStart: 0, rangeEnd: 0 }; var start = segment.byteRangeStartOffset; var end = segment.byteRangeEndOffset; if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(start) && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(end)) { loaderContext.rangeStart = start; loaderContext.rangeEnd = end; } return loaderContext; } var LoadError = /*#__PURE__*/function (_Error) { _inheritsLoose(LoadError, _Error); function LoadError(data) { var _this3; for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { params[_key - 1] = arguments[_key]; } _this3 = _Error.call.apply(_Error, [this].concat(params)) || this; _this3.data = void 0; _this3.data = data; return _this3; } return LoadError; }( /*#__PURE__*/_wrapNativeSuper(Error)); /***/ }), /***/ "./src/loader/fragment.ts": /*!********************************!*\ !*** ./src/loader/fragment.ts ***! \********************************/ /*! exports provided: ElementaryStreamTypes, BaseSegment, Fragment, Part */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ElementaryStreamTypes", function() { return ElementaryStreamTypes; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BaseSegment", function() { return BaseSegment; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Fragment", function() { return Fragment; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Part", function() { return Part; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js"); /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_1__); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _level_key__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./level-key */ "./src/loader/level-key.ts"); /* harmony import */ var _load_stats__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./load-stats */ "./src/loader/load-stats.ts"); function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var ElementaryStreamTypes; (function (ElementaryStreamTypes) { ElementaryStreamTypes["AUDIO"] = "audio"; ElementaryStreamTypes["VIDEO"] = "video"; ElementaryStreamTypes["AUDIOVIDEO"] = "audiovideo"; })(ElementaryStreamTypes || (ElementaryStreamTypes = {})); var BaseSegment = /*#__PURE__*/function () { // baseurl is the URL to the playlist // relurl is the portion of the URL that comes from inside the playlist. // Holds the types of data this fragment supports function BaseSegment(baseurl) { var _this$elementaryStrea; this._byteRange = null; this._url = null; this.baseurl = void 0; this.relurl = void 0; this.elementaryStreams = (_this$elementaryStrea = {}, _this$elementaryStrea[ElementaryStreamTypes.AUDIO] = null, _this$elementaryStrea[ElementaryStreamTypes.VIDEO] = null, _this$elementaryStrea[ElementaryStreamTypes.AUDIOVIDEO] = null, _this$elementaryStrea); this.baseurl = baseurl; } // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array var _proto = BaseSegment.prototype; _proto.setByteRange = function setByteRange(value, previous) { var params = value.split('@', 2); var byteRange = []; if (params.length === 1) { byteRange[0] = previous ? previous.byteRangeEndOffset : 0; } else { byteRange[0] = parseInt(params[1]); } byteRange[1] = parseInt(params[0]) + byteRange[0]; this._byteRange = byteRange; }; _createClass(BaseSegment, [{ key: "byteRange", get: function get() { if (!this._byteRange) { return []; } return this._byteRange; } }, { key: "byteRangeStartOffset", get: function get() { return this.byteRange[0]; } }, { key: "byteRangeEndOffset", get: function get() { return this.byteRange[1]; } }, { key: "url", get: function get() { if (!this._url && this.baseurl && this.relurl) { this._url = Object(url_toolkit__WEBPACK_IMPORTED_MODULE_1__["buildAbsoluteURL"])(this.baseurl, this.relurl, { alwaysNormalize: true }); } return this._url || ''; }, set: function set(value) { this._url = value; } }]); return BaseSegment; }(); var Fragment = /*#__PURE__*/function (_BaseSegment) { _inheritsLoose(Fragment, _BaseSegment); // EXTINF has to be present for a m38 to be considered valid // sn notates the sequence number for a segment, and if set to a string can be 'initSegment' // levelkey is the EXT-X-KEY that applies to this segment for decryption // core difference from the private field _decryptdata is the lack of the initialized IV // _decryptdata will set the IV for this segment based on the segment number in the fragment // A string representing the fragment type // A reference to the loader. Set while the fragment is loading, and removed afterwards. Used to abort fragment loading // The level/track index to which the fragment belongs // The continuity counter of the fragment // The starting Presentation Time Stamp (PTS) of the fragment. Set after transmux complete. // The ending Presentation Time Stamp (PTS) of the fragment. Set after transmux complete. // The latest Presentation Time Stamp (PTS) appended to the buffer. // The starting Decode Time Stamp (DTS) of the fragment. Set after transmux complete. // The ending Decode Time Stamp (DTS) of the fragment. Set after transmux complete. // The start time of the fragment, as listed in the manifest. Updated after transmux complete. // Set by `updateFragPTSDTS` in level-helper // The maximum starting Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete. // The minimum ending Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete. // Load/parse timing information // A flag indicating whether the segment was downloaded in order to test bitrate, and was not buffered // #EXTINF segment title // The Media Initialization Section for this segment function Fragment(type, baseurl) { var _this; _this = _BaseSegment.call(this, baseurl) || this; _this._decryptdata = null; _this.rawProgramDateTime = null; _this.programDateTime = null; _this.tagList = []; _this.duration = 0; _this.sn = 0; _this.levelkey = void 0; _this.type = void 0; _this.loader = null; _this.level = -1; _this.cc = 0; _this.startPTS = void 0; _this.endPTS = void 0; _this.appendedPTS = void 0; _this.startDTS = void 0; _this.endDTS = void 0; _this.start = 0; _this.deltaPTS = void 0; _this.maxStartPTS = void 0; _this.minEndPTS = void 0; _this.stats = new _load_stats__WEBPACK_IMPORTED_MODULE_4__["LoadStats"](); _this.urlId = 0; _this.data = void 0; _this.bitrateTest = false; _this.title = null; _this.initSegment = null; _this.type = type; return _this; } var _proto2 = Fragment.prototype; /** * Utility method for parseLevelPlaylist to create an initialization vector for a given segment * @param {number} segmentNumber - segment number to generate IV with * @returns {Uint8Array} */ _proto2.createInitializationVector = function createInitializationVector(segmentNumber) { var uint8View = new Uint8Array(16); for (var i = 12; i < 16; i++) { uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff; } return uint8View; } /** * Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data * @param levelkey - a playlist's encryption info * @param segmentNumber - the fragment's segment number * @returns {LevelKey} - an object to be applied as a fragment's decryptdata */ ; _proto2.setDecryptDataFromLevelKey = function setDecryptDataFromLevelKey(levelkey, segmentNumber) { var decryptdata = levelkey; if ((levelkey === null || levelkey === void 0 ? void 0 : levelkey.method) === 'AES-128' && levelkey.uri && !levelkey.iv) { decryptdata = _level_key__WEBPACK_IMPORTED_MODULE_3__["LevelKey"].fromURI(levelkey.uri); decryptdata.method = levelkey.method; decryptdata.iv = this.createInitializationVector(segmentNumber); decryptdata.keyFormat = 'identity'; } return decryptdata; }; _proto2.setElementaryStreamInfo = function setElementaryStreamInfo(type, startPTS, endPTS, startDTS, endDTS, partial) { if (partial === void 0) { partial = false; } var elementaryStreams = this.elementaryStreams; var info = elementaryStreams[type]; if (!info) { elementaryStreams[type] = { startPTS: startPTS, endPTS: endPTS, startDTS: startDTS, endDTS: endDTS, partial: partial }; return; } info.startPTS = Math.min(info.startPTS, startPTS); info.endPTS = Math.max(info.endPTS, endPTS); info.startDTS = Math.min(info.startDTS, startDTS); info.endDTS = Math.max(info.endDTS, endDTS); }; _proto2.clearElementaryStreamInfo = function clearElementaryStreamInfo() { var elementaryStreams = this.elementaryStreams; elementaryStreams[ElementaryStreamTypes.AUDIO] = null; elementaryStreams[ElementaryStreamTypes.VIDEO] = null; elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null; }; _createClass(Fragment, [{ key: "decryptdata", get: function get() { if (!this.levelkey && !this._decryptdata) { return null; } if (!this._decryptdata && this.levelkey) { var sn = this.sn; if (typeof sn !== 'number') { // We are fetching decryption data for a initialization segment // If the segment was encrypted with AES-128 // It must have an IV defined. We cannot substitute the Segment Number in. if (this.levelkey && this.levelkey.method === 'AES-128' && !this.levelkey.iv) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("missing IV for initialization segment with method=\"" + this.levelkey.method + "\" - compliance issue"); } /* Be converted to a Number. 'initSegment' will become NaN. NaN, which when converted through ToInt32() -> +0. --- Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation. */ sn = 0; } this._decryptdata = this.setDecryptDataFromLevelKey(this.levelkey, sn); } return this._decryptdata; } }, { key: "end", get: function get() { return this.start + this.duration; } }, { key: "endProgramDateTime", get: function get() { if (this.programDateTime === null) { return null; } if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.programDateTime)) { return null; } var duration = !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.duration) ? 0 : this.duration; return this.programDateTime + duration * 1000; } }, { key: "encrypted", get: function get() { var _this$decryptdata; // At the m3u8-parser level we need to add support for manifest signalled keyformats // when we want the fragment to start reporting that it is encrypted. // Currently, keyFormat will only be set for identity keys if ((_this$decryptdata = this.decryptdata) !== null && _this$decryptdata !== void 0 && _this$decryptdata.keyFormat && this.decryptdata.uri) { return true; } return false; } }]); return Fragment; }(BaseSegment); var Part = /*#__PURE__*/function (_BaseSegment2) { _inheritsLoose(Part, _BaseSegment2); function Part(partAttrs, frag, baseurl, index, previous) { var _this2; _this2 = _BaseSegment2.call(this, baseurl) || this; _this2.fragOffset = 0; _this2.duration = 0; _this2.gap = false; _this2.independent = false; _this2.relurl = void 0; _this2.fragment = void 0; _this2.index = void 0; _this2.stats = new _load_stats__WEBPACK_IMPORTED_MODULE_4__["LoadStats"](); _this2.duration = partAttrs.decimalFloatingPoint('DURATION'); _this2.gap = partAttrs.bool('GAP'); _this2.independent = partAttrs.bool('INDEPENDENT'); _this2.relurl = partAttrs.enumeratedString('URI'); _this2.fragment = frag; _this2.index = index; var byteRange = partAttrs.enumeratedString('BYTERANGE'); if (byteRange) { _this2.setByteRange(byteRange, previous); } if (previous) { _this2.fragOffset = previous.fragOffset + previous.duration; } return _this2; } _createClass(Part, [{ key: "start", get: function get() { return this.fragment.start + this.fragOffset; } }, { key: "end", get: function get() { return this.start + this.duration; } }, { key: "loaded", get: function get() { var elementaryStreams = this.elementaryStreams; return !!(elementaryStreams.audio || elementaryStreams.video || elementaryStreams.audiovideo); } }]); return Part; }(BaseSegment); /***/ }), /***/ "./src/loader/key-loader.ts": /*!**********************************!*\ !*** ./src/loader/key-loader.ts ***! \**********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return KeyLoader; }); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* * Decrypt key Loader */ var KeyLoader = /*#__PURE__*/function () { function KeyLoader(hls) { this.hls = void 0; this.loaders = {}; this.decryptkey = null; this.decrypturl = null; this.hls = hls; this._registerListeners(); } var _proto = KeyLoader.prototype; _proto._registerListeners = function _registerListeners() { this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADING, this.onKeyLoading, this); }; _proto._unregisterListeners = function _unregisterListeners() { this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADING, this.onKeyLoading); }; _proto.destroy = function destroy() { this._unregisterListeners(); for (var loaderName in this.loaders) { var loader = this.loaders[loaderName]; if (loader) { loader.destroy(); } } this.loaders = {}; }; _proto.onKeyLoading = function onKeyLoading(event, data) { var frag = data.frag; var type = frag.type; var loader = this.loaders[type]; if (!frag.decryptdata) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('Missing decryption data on fragment in onKeyLoading'); return; } // Load the key if the uri is different from previous one, or if the decrypt key has not yet been retrieved var uri = frag.decryptdata.uri; if (uri !== this.decrypturl || this.decryptkey === null) { var config = this.hls.config; if (loader) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("abort previous key loader for type:" + type); loader.abort(); } if (!uri) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('key uri is falsy'); return; } var Loader = config.loader; var fragLoader = frag.loader = this.loaders[type] = new Loader(config); this.decrypturl = uri; this.decryptkey = null; var loaderContext = { url: uri, frag: frag, responseType: 'arraybuffer' }; // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times, // key-loader will trigger an error and rely on stream-controller to handle retry logic. // this will also align retry logic with fragment-loader var loaderConfig = { timeout: config.fragLoadingTimeOut, maxRetry: 0, retryDelay: config.fragLoadingRetryDelay, maxRetryDelay: config.fragLoadingMaxRetryTimeout, highWaterMark: 0 }; var loaderCallbacks = { onSuccess: this.loadsuccess.bind(this), onError: this.loaderror.bind(this), onTimeout: this.loadtimeout.bind(this) }; fragLoader.load(loaderContext, loaderConfig, loaderCallbacks); } else if (this.decryptkey) { // Return the key if it's already been loaded frag.decryptdata.key = this.decryptkey; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADED, { frag: frag }); } }; _proto.loadsuccess = function loadsuccess(response, stats, context) { var frag = context.frag; if (!frag.decryptdata) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('after key load, decryptdata unset'); return; } this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data); // detach fragment loader on load success frag.loader = null; delete this.loaders[frag.type]; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADED, { frag: frag }); }; _proto.loaderror = function loaderror(response, context) { var frag = context.frag; var loader = frag.loader; if (loader) { loader.abort(); } delete this.loaders[frag.type]; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_LOAD_ERROR, fatal: false, frag: frag, response: response }); }; _proto.loadtimeout = function loadtimeout(stats, context) { var frag = context.frag; var loader = frag.loader; if (loader) { loader.abort(); } delete this.loaders[frag.type]; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_LOAD_TIMEOUT, fatal: false, frag: frag }); }; return KeyLoader; }(); /***/ }), /***/ "./src/loader/level-details.ts": /*!*************************************!*\ !*** ./src/loader/level-details.ts ***! \*************************************/ /*! exports provided: LevelDetails */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LevelDetails", function() { return LevelDetails; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var DEFAULT_TARGET_DURATION = 10; var LevelDetails = /*#__PURE__*/function () { // Manifest reload synchronization function LevelDetails(baseUrl) { this.PTSKnown = false; this.alignedSliding = false; this.averagetargetduration = void 0; this.endCC = 0; this.endSN = 0; this.fragments = void 0; this.fragmentHint = void 0; this.partList = null; this.live = true; this.ageHeader = 0; this.advancedDateTime = void 0; this.updated = true; this.advanced = true; this.availabilityDelay = void 0; this.misses = 0; this.needSidxRanges = false; this.startCC = 0; this.startSN = 0; this.startTimeOffset = null; this.targetduration = 0; this.totalduration = 0; this.type = null; this.url = void 0; this.m3u8 = ''; this.version = null; this.canBlockReload = false; this.canSkipUntil = 0; this.canSkipDateRanges = false; this.skippedSegments = 0; this.recentlyRemovedDateranges = void 0; this.partHoldBack = 0; this.holdBack = 0; this.partTarget = 0; this.preloadHint = void 0; this.renditionReports = void 0; this.tuneInGoal = 0; this.deltaUpdateFailed = void 0; this.driftStartTime = 0; this.driftEndTime = 0; this.driftStart = 0; this.driftEnd = 0; this.fragments = []; this.url = baseUrl; } var _proto = LevelDetails.prototype; _proto.reloaded = function reloaded(previous) { if (!previous) { this.advanced = true; this.updated = true; return; } var partSnDiff = this.lastPartSn - previous.lastPartSn; var partIndexDiff = this.lastPartIndex - previous.lastPartIndex; this.updated = this.endSN !== previous.endSN || !!partIndexDiff || !!partSnDiff; this.advanced = this.endSN > previous.endSN || partSnDiff > 0 || partSnDiff === 0 && partIndexDiff > 0; if (this.updated || this.advanced) { this.misses = Math.floor(previous.misses * 0.6); } else { this.misses = previous.misses + 1; } this.availabilityDelay = previous.availabilityDelay; }; _createClass(LevelDetails, [{ key: "hasProgramDateTime", get: function get() { if (this.fragments.length) { return Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.fragments[this.fragments.length - 1].programDateTime); } return false; } }, { key: "levelTargetDuration", get: function get() { return this.averagetargetduration || this.targetduration || DEFAULT_TARGET_DURATION; } }, { key: "drift", get: function get() { var runTime = this.driftEndTime - this.driftStartTime; if (runTime > 0) { var runDuration = this.driftEnd - this.driftStart; return runDuration * 1000 / runTime; } return 1; } }, { key: "edge", get: function get() { return this.partEnd || this.fragmentEnd; } }, { key: "partEnd", get: function get() { var _this$partList; if ((_this$partList = this.partList) !== null && _this$partList !== void 0 && _this$partList.length) { return this.partList[this.partList.length - 1].end; } return this.fragmentEnd; } }, { key: "fragmentEnd", get: function get() { var _this$fragments; if ((_this$fragments = this.fragments) !== null && _this$fragments !== void 0 && _this$fragments.length) { return this.fragments[this.fragments.length - 1].end; } return 0; } }, { key: "age", get: function get() { if (this.advancedDateTime) { return Math.max(Date.now() - this.advancedDateTime, 0) / 1000; } return 0; } }, { key: "lastPartIndex", get: function get() { var _this$partList2; if ((_this$partList2 = this.partList) !== null && _this$partList2 !== void 0 && _this$partList2.length) { return this.partList[this.partList.length - 1].index; } return -1; } }, { key: "lastPartSn", get: function get() { var _this$partList3; if ((_this$partList3 = this.partList) !== null && _this$partList3 !== void 0 && _this$partList3.length) { return this.partList[this.partList.length - 1].fragment.sn; } return this.endSN; } }]); return LevelDetails; }(); /***/ }), /***/ "./src/loader/level-key.ts": /*!*********************************!*\ !*** ./src/loader/level-key.ts ***! \*********************************/ /*! exports provided: LevelKey */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LevelKey", function() { return LevelKey; }); /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js"); /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_0__); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var LevelKey = /*#__PURE__*/function () { LevelKey.fromURL = function fromURL(baseUrl, relativeUrl) { return new LevelKey(baseUrl, relativeUrl); }; LevelKey.fromURI = function fromURI(uri) { return new LevelKey(uri); }; function LevelKey(absoluteOrBaseURI, relativeURL) { this._uri = null; this.method = null; this.keyFormat = null; this.keyFormatVersions = null; this.keyID = null; this.key = null; this.iv = null; if (relativeURL) { this._uri = Object(url_toolkit__WEBPACK_IMPORTED_MODULE_0__["buildAbsoluteURL"])(absoluteOrBaseURI, relativeURL, { alwaysNormalize: true }); } else { this._uri = absoluteOrBaseURI; } } _createClass(LevelKey, [{ key: "uri", get: function get() { return this._uri; } }]); return LevelKey; }(); /***/ }), /***/ "./src/loader/load-stats.ts": /*!**********************************!*\ !*** ./src/loader/load-stats.ts ***! \**********************************/ /*! exports provided: LoadStats */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoadStats", function() { return LoadStats; }); var LoadStats = function LoadStats() { this.aborted = false; this.loaded = 0; this.retry = 0; this.total = 0; this.chunkCount = 0; this.bwEstimate = 0; this.loading = { start: 0, first: 0, end: 0 }; this.parsing = { start: 0, end: 0 }; this.buffering = { start: 0, first: 0, end: 0 }; }; /***/ }), /***/ "./src/loader/m3u8-parser.ts": /*!***********************************!*\ !*** ./src/loader/m3u8-parser.ts ***! \***********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return M3U8Parser; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js"); /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_1__); /* harmony import */ var _fragment__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./fragment */ "./src/loader/fragment.ts"); /* harmony import */ var _level_details__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./level-details */ "./src/loader/level-details.ts"); /* harmony import */ var _level_key__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./level-key */ "./src/loader/level-key.ts"); /* harmony import */ var _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/attr-list */ "./src/utils/attr-list.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _utils_codecs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/codecs */ "./src/utils/codecs.ts"); // https://regex101.com is your friend var MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-SESSION-DATA:([^\r\n]*)[\r\n]+/g; var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g; var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title /(?!#) *(\S[\S ]*)/.source, // segment URI, group 3 => the URI (note newline is not eaten) /#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y) /#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec /#.*/.source // All other non-segment oriented tags will match with all groups empty ].join('|'), 'g'); var LEVEL_PLAYLIST_REGEX_SLOW = new RegExp([/#(EXTM3U)/.source, /#EXT-X-(PLAYLIST-TYPE):(.+)/.source, /#EXT-X-(MEDIA-SEQUENCE): *(\d+)/.source, /#EXT-X-(SKIP):(.+)/.source, /#EXT-X-(TARGETDURATION): *(\d+)/.source, /#EXT-X-(KEY):(.+)/.source, /#EXT-X-(START):(.+)/.source, /#EXT-X-(ENDLIST)/.source, /#EXT-X-(DISCONTINUITY-SEQ)UENCE: *(\d+)/.source, /#EXT-X-(DIS)CONTINUITY/.source, /#EXT-X-(VERSION):(\d+)/.source, /#EXT-X-(MAP):(.+)/.source, /#EXT-X-(SERVER-CONTROL):(.+)/.source, /#EXT-X-(PART-INF):(.+)/.source, /#EXT-X-(GAP)/.source, /#EXT-X-(BITRATE):\s*(\d+)/.source, /#EXT-X-(PART):(.+)/.source, /#EXT-X-(PRELOAD-HINT):(.+)/.source, /#EXT-X-(RENDITION-REPORT):(.+)/.source, /(#)([^:]*):(.*)/.source, /(#)(.*)(?:.*)\r?\n?/.source].join('|')); var MP4_REGEX_SUFFIX = /\.(mp4|m4s|m4v|m4a)$/i; function isMP4Url(url) { var _URLToolkit$parseURL$, _URLToolkit$parseURL; return MP4_REGEX_SUFFIX.test((_URLToolkit$parseURL$ = (_URLToolkit$parseURL = url_toolkit__WEBPACK_IMPORTED_MODULE_1__["parseURL"](url)) === null || _URLToolkit$parseURL === void 0 ? void 0 : _URLToolkit$parseURL.path) != null ? _URLToolkit$parseURL$ : ''); } var M3U8Parser = /*#__PURE__*/function () { function M3U8Parser() {} M3U8Parser.findGroup = function findGroup(groups, mediaGroupId) { for (var i = 0; i < groups.length; i++) { var group = groups[i]; if (group.id === mediaGroupId) { return group; } } }; M3U8Parser.convertAVC1ToAVCOTI = function convertAVC1ToAVCOTI(codec) { // Convert avc1 codec string from RFC-4281 to RFC-6381 for MediaSource.isTypeSupported var avcdata = codec.split('.'); if (avcdata.length > 2) { var result = avcdata.shift() + '.'; result += parseInt(avcdata.shift()).toString(16); result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4); return result; } return codec; }; M3U8Parser.resolve = function resolve(url, baseUrl) { return url_toolkit__WEBPACK_IMPORTED_MODULE_1__["buildAbsoluteURL"](baseUrl, url, { alwaysNormalize: true }); }; M3U8Parser.parseMasterPlaylist = function parseMasterPlaylist(string, baseurl) { var levels = []; var sessionData = {}; var hasSessionData = false; MASTER_PLAYLIST_REGEX.lastIndex = 0; var result; while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) { if (result[1]) { // '#EXT-X-STREAM-INF' is found, parse level tag in group 1 var attrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](result[1]); var level = { attrs: attrs, bitrate: attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH'), name: attrs.NAME, url: M3U8Parser.resolve(result[2], baseurl) }; var resolution = attrs.decimalResolution('RESOLUTION'); if (resolution) { level.width = resolution.width; level.height = resolution.height; } setCodecs((attrs.CODECS || '').split(/[ ,]+/).filter(function (c) { return c; }), level); if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) { level.videoCodec = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec); } levels.push(level); } else if (result[3]) { // '#EXT-X-SESSION-DATA' is found, parse session data in group 3 var sessionAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](result[3]); if (sessionAttrs['DATA-ID']) { hasSessionData = true; sessionData[sessionAttrs['DATA-ID']] = sessionAttrs; } } } return { levels: levels, sessionData: hasSessionData ? sessionData : null }; }; M3U8Parser.parseMasterPlaylistMedia = function parseMasterPlaylistMedia(string, baseurl, type, groups) { if (groups === void 0) { groups = []; } var result; var medias = []; var id = 0; MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0; while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) { var attrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](result[1]); if (attrs.TYPE === type) { var media = { attrs: attrs, bitrate: 0, id: id++, groupId: attrs['GROUP-ID'], instreamId: attrs['INSTREAM-ID'], name: attrs.NAME || attrs.LANGUAGE || '', type: type, default: attrs.bool('DEFAULT'), autoselect: attrs.bool('AUTOSELECT'), forced: attrs.bool('FORCED'), lang: attrs.LANGUAGE, url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : '' }; if (groups.length) { // If there are audio or text groups signalled in the manifest, let's look for a matching codec string for this track // If we don't find the track signalled, lets use the first audio groups codec we have // Acting as a best guess var groupCodec = M3U8Parser.findGroup(groups, media.groupId) || groups[0]; assignCodec(media, groupCodec, 'audioCodec'); assignCodec(media, groupCodec, 'textCodec'); } medias.push(media); } } return medias; }; M3U8Parser.parseLevelPlaylist = function parseLevelPlaylist(string, baseurl, id, type, levelUrlId) { var level = new _level_details__WEBPACK_IMPORTED_MODULE_3__["LevelDetails"](baseurl); var fragments = level.fragments; // The most recent init segment seen (applies to all subsequent segments) var currentInitSegment = null; var currentSN = 0; var currentPart = 0; var totalduration = 0; var discontinuityCounter = 0; var prevFrag = null; var frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Fragment"](type, baseurl); var result; var i; var levelkey; var firstPdtIndex = -1; var createNextFrag = false; LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0; level.m3u8 = string; while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) { if (createNextFrag) { createNextFrag = false; frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Fragment"](type, baseurl); // setup the next fragment for part loading frag.start = totalduration; frag.sn = currentSN; frag.cc = discontinuityCounter; frag.level = id; if (currentInitSegment) { frag.initSegment = currentInitSegment; frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime; } } var duration = result[1]; if (duration) { // INF frag.duration = parseFloat(duration); // avoid sliced strings https://github.com/video-dev/hls.js/issues/939 var title = (' ' + result[2]).slice(1); frag.title = title || null; frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]); } else if (result[3]) { // url if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.duration)) { frag.start = totalduration; if (levelkey) { frag.levelkey = levelkey; } frag.sn = currentSN; frag.level = id; frag.cc = discontinuityCounter; frag.urlId = levelUrlId; fragments.push(frag); // avoid sliced strings https://github.com/video-dev/hls.js/issues/939 frag.relurl = (' ' + result[3]).slice(1); assignProgramDateTime(frag, prevFrag); prevFrag = frag; totalduration += frag.duration; currentSN++; currentPart = 0; createNextFrag = true; } } else if (result[4]) { // X-BYTERANGE var data = (' ' + result[4]).slice(1); if (prevFrag) { frag.setByteRange(data, prevFrag); } else { frag.setByteRange(data); } } else if (result[5]) { // PROGRAM-DATE-TIME // avoid sliced strings https://github.com/video-dev/hls.js/issues/939 frag.rawProgramDateTime = (' ' + result[5]).slice(1); frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]); if (firstPdtIndex === -1) { firstPdtIndex = fragments.length; } } else { result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW); if (!result) { _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn('No matches on slow regex match for level playlist!'); continue; } for (i = 1; i < result.length; i++) { if (typeof result[i] !== 'undefined') { break; } } // avoid sliced strings https://github.com/video-dev/hls.js/issues/939 var tag = (' ' + result[i]).slice(1); var value1 = (' ' + result[i + 1]).slice(1); var value2 = result[i + 2] ? (' ' + result[i + 2]).slice(1) : ''; switch (tag) { case 'PLAYLIST-TYPE': level.type = value1.toUpperCase(); break; case 'MEDIA-SEQUENCE': currentSN = level.startSN = parseInt(value1); break; case 'SKIP': { var skipAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1); var skippedSegments = skipAttrs.decimalInteger('SKIPPED-SEGMENTS'); if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(skippedSegments)) { level.skippedSegments = skippedSegments; // This will result in fragments[] containing undefined values, which we will fill in with `mergeDetails` for (var _i = skippedSegments; _i--;) { fragments.unshift(null); } currentSN += skippedSegments; } var recentlyRemovedDateranges = skipAttrs.enumeratedString('RECENTLY-REMOVED-DATERANGES'); if (recentlyRemovedDateranges) { level.recentlyRemovedDateranges = recentlyRemovedDateranges.split('\t'); } break; } case 'TARGETDURATION': level.targetduration = parseFloat(value1); break; case 'VERSION': level.version = parseInt(value1); break; case 'EXTM3U': break; case 'ENDLIST': level.live = false; break; case '#': if (value1 || value2) { frag.tagList.push(value2 ? [value1, value2] : [value1]); } break; case 'DIS': discontinuityCounter++; /* falls through */ case 'GAP': frag.tagList.push([tag]); break; case 'BITRATE': frag.tagList.push([tag, value1]); break; case 'DISCONTINUITY-SEQ': discontinuityCounter = parseInt(value1); break; case 'KEY': { var _keyAttrs$enumeratedS; // https://tools.ietf.org/html/rfc8216#section-4.3.2.4 var keyAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1); var decryptmethod = keyAttrs.enumeratedString('METHOD'); var decrypturi = keyAttrs.URI; var decryptiv = keyAttrs.hexadecimalInteger('IV'); var decryptkeyformatversions = keyAttrs.enumeratedString('KEYFORMATVERSIONS'); var decryptkeyid = keyAttrs.enumeratedString('KEYID'); // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of "identity". var decryptkeyformat = (_keyAttrs$enumeratedS = keyAttrs.enumeratedString('KEYFORMAT')) != null ? _keyAttrs$enumeratedS : 'identity'; var unsupportedKnownKeyformatsInManifest = ['com.apple.streamingkeydelivery', 'com.microsoft.playready', 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed', // widevine (v2) 'com.widevine' // earlier widevine (v1) ]; if (unsupportedKnownKeyformatsInManifest.indexOf(decryptkeyformat) > -1) { _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn("Keyformat " + decryptkeyformat + " is not supported from the manifest"); continue; } else if (decryptkeyformat !== 'identity') { // We are supposed to skip keys we don't understand. // As we currently only officially support identity keys // from the manifest we shouldn't save any other key. continue; } // TODO: multiple keys can be defined on a fragment, and we need to support this // for clients that support both playready and widevine if (decryptmethod) { // TODO: need to determine if the level key is actually a relative URL // if it isn't, then we should instead construct the LevelKey using fromURI. levelkey = _level_key__WEBPACK_IMPORTED_MODULE_4__["LevelKey"].fromURL(baseurl, decrypturi); if (decrypturi && ['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].indexOf(decryptmethod) >= 0) { levelkey.method = decryptmethod; levelkey.keyFormat = decryptkeyformat; if (decryptkeyid) { levelkey.keyID = decryptkeyid; } if (decryptkeyformatversions) { levelkey.keyFormatVersions = decryptkeyformatversions; } // Initialization Vector (IV) levelkey.iv = decryptiv; } } break; } case 'START': { var startAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1); var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET'); // TIME-OFFSET can be 0 if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(startTimeOffset)) { level.startTimeOffset = startTimeOffset; } break; } case 'MAP': { var mapAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1); frag.relurl = mapAttrs.URI; if (mapAttrs.BYTERANGE) { frag.setByteRange(mapAttrs.BYTERANGE); } frag.level = id; frag.sn = 'initSegment'; if (levelkey) { frag.levelkey = levelkey; } frag.initSegment = null; currentInitSegment = frag; createNextFrag = true; break; } case 'SERVER-CONTROL': { var serverControlAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1); level.canBlockReload = serverControlAttrs.bool('CAN-BLOCK-RELOAD'); level.canSkipUntil = serverControlAttrs.optionalFloat('CAN-SKIP-UNTIL', 0); level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool('CAN-SKIP-DATERANGES'); level.partHoldBack = serverControlAttrs.optionalFloat('PART-HOLD-BACK', 0); level.holdBack = serverControlAttrs.optionalFloat('HOLD-BACK', 0); break; } case 'PART-INF': { var partInfAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1); level.partTarget = partInfAttrs.decimalFloatingPoint('PART-TARGET'); break; } case 'PART': { var partList = level.partList; if (!partList) { partList = level.partList = []; } var previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : undefined; var index = currentPart++; var part = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Part"](new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1), frag, baseurl, index, previousFragmentPart); partList.push(part); frag.duration += part.duration; break; } case 'PRELOAD-HINT': { var preloadHintAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1); level.preloadHint = preloadHintAttrs; break; } case 'RENDITION-REPORT': { var renditionReportAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1); level.renditionReports = level.renditionReports || []; level.renditionReports.push(renditionReportAttrs); break; } default: _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn("line parsed but not handled: " + result); break; } } } if (prevFrag && !prevFrag.relurl) { fragments.pop(); totalduration -= prevFrag.duration; if (level.partList) { level.fragmentHint = prevFrag; } } else if (level.partList) { assignProgramDateTime(frag, prevFrag); frag.cc = discontinuityCounter; level.fragmentHint = frag; } var fragmentLength = fragments.length; var firstFragment = fragments[0]; var lastFragment = fragments[fragmentLength - 1]; totalduration += level.skippedSegments * level.targetduration; if (totalduration > 0 && fragmentLength && lastFragment) { level.averagetargetduration = totalduration / fragmentLength; var lastSn = lastFragment.sn; level.endSN = lastSn !== 'initSegment' ? lastSn : 0; if (firstFragment) { level.startCC = firstFragment.cc; if (!firstFragment.initSegment) { // this is a bit lurky but HLS really has no other way to tell us // if the fragments are TS or MP4, except if we download them :/ // but this is to be able to handle SIDX. if (level.fragments.every(function (frag) { return frag.relurl && isMP4Url(frag.relurl); })) { _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX'); frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Fragment"](type, baseurl); frag.relurl = lastFragment.relurl; frag.level = id; frag.sn = 'initSegment'; firstFragment.initSegment = frag; level.needSidxRanges = true; } } } } else { level.endSN = 0; level.startCC = 0; } if (level.fragmentHint) { totalduration += level.fragmentHint.duration; } level.totalduration = totalduration; level.endCC = discontinuityCounter; /** * Backfill any missing PDT values * "If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after * one or more Media Segment URIs, the client SHOULD extrapolate * backward from that tag (using EXTINF durations and/or media * timestamps) to associate dates with those segments." * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs * computed. */ if (firstPdtIndex > 0) { backfillProgramDateTimes(fragments, firstPdtIndex); } return level; }; return M3U8Parser; }(); function setCodecs(codecs, level) { ['video', 'audio', 'text'].forEach(function (type) { var filtered = codecs.filter(function (codec) { return Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_7__["isCodecType"])(codec, type); }); if (filtered.length) { var preferred = filtered.filter(function (codec) { return codec.lastIndexOf('avc1', 0) === 0 || codec.lastIndexOf('mp4a', 0) === 0; }); level[type + "Codec"] = preferred.length > 0 ? preferred[0] : filtered[0]; // remove from list codecs = codecs.filter(function (codec) { return filtered.indexOf(codec) === -1; }); } }); level.unknownCodecs = codecs; } function assignCodec(media, groupItem, codecProperty) { var codecValue = groupItem[codecProperty]; if (codecValue) { media[codecProperty] = codecValue; } } function backfillProgramDateTimes(fragments, firstPdtIndex) { var fragPrev = fragments[firstPdtIndex]; for (var i = firstPdtIndex; i--;) { var frag = fragments[i]; // Exit on delta-playlist skipped segments if (!frag) { return; } frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000; fragPrev = frag; } } function assignProgramDateTime(frag, prevFrag) { if (frag.rawProgramDateTime) { frag.programDateTime = Date.parse(frag.rawProgramDateTime); } else if (prevFrag !== null && prevFrag !== void 0 && prevFrag.programDateTime) { frag.programDateTime = prevFrag.endProgramDateTime; } if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.programDateTime)) { frag.programDateTime = null; frag.rawProgramDateTime = null; } } /***/ }), /***/ "./src/loader/playlist-loader.ts": /*!***************************************!*\ !*** ./src/loader/playlist-loader.ts ***! \***************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts"); /* harmony import */ var _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./m3u8-parser */ "./src/loader/m3u8-parser.ts"); /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts"); /* harmony import */ var _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/attr-list */ "./src/utils/attr-list.ts"); /** * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models. * * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks. * * Uses loader(s) set in config to do actual internal loading of resource tasks. * * @module * */ function mapContextToLevelType(context) { var type = context.type; switch (type) { case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK: return _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO; case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK: return _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].SUBTITLE; default: return _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN; } } function getResponseUrl(response, context) { var url = response.url; // responseURL not supported on some browsers (it is used to detect URL redirection) // data-uri mode also not supported (but no need to detect redirection) if (url === undefined || url.indexOf('data:') === 0) { // fallback to initial URL url = context.url; } return url; } var PlaylistLoader = /*#__PURE__*/function () { function PlaylistLoader(hls) { this.hls = void 0; this.loaders = Object.create(null); this.hls = hls; this.registerListeners(); } var _proto = PlaylistLoader.prototype; _proto.registerListeners = function registerListeners() { var hls = this.hls; hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADING, this.onLevelLoading, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this); }; _proto.unregisterListeners = function unregisterListeners() { var hls = this.hls; hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADING, this.onLevelLoading, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this); } /** * Returns defaults or configured loader-type overloads (pLoader and loader config params) */ ; _proto.createInternalLoader = function createInternalLoader(context) { var config = this.hls.config; var PLoader = config.pLoader; var Loader = config.loader; var InternalLoader = PLoader || Loader; var loader = new InternalLoader(config); context.loader = loader; this.loaders[context.type] = loader; return loader; }; _proto.getInternalLoader = function getInternalLoader(context) { return this.loaders[context.type]; }; _proto.resetInternalLoader = function resetInternalLoader(contextType) { if (this.loaders[contextType]) { delete this.loaders[contextType]; } } /** * Call `destroy` on all internal loader instances mapped (one per context type) */ ; _proto.destroyInternalLoaders = function destroyInternalLoaders() { for (var contextType in this.loaders) { var loader = this.loaders[contextType]; if (loader) { loader.destroy(); } this.resetInternalLoader(contextType); } }; _proto.destroy = function destroy() { this.unregisterListeners(); this.destroyInternalLoaders(); }; _proto.onManifestLoading = function onManifestLoading(event, data) { var url = data.url; this.load({ id: null, groupId: null, level: 0, responseType: 'text', type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST, url: url, deliveryDirectives: null }); }; _proto.onLevelLoading = function onLevelLoading(event, data) { var id = data.id, level = data.level, url = data.url, deliveryDirectives = data.deliveryDirectives; this.load({ id: id, groupId: null, level: level, responseType: 'text', type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL, url: url, deliveryDirectives: deliveryDirectives }); }; _proto.onAudioTrackLoading = function onAudioTrackLoading(event, data) { var id = data.id, groupId = data.groupId, url = data.url, deliveryDirectives = data.deliveryDirectives; this.load({ id: id, groupId: groupId, level: null, responseType: 'text', type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK, url: url, deliveryDirectives: deliveryDirectives }); }; _proto.onSubtitleTrackLoading = function onSubtitleTrackLoading(event, data) { var id = data.id, groupId = data.groupId, url = data.url, deliveryDirectives = data.deliveryDirectives; this.load({ id: id, groupId: groupId, level: null, responseType: 'text', type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK, url: url, deliveryDirectives: deliveryDirectives }); }; _proto.load = function load(context) { var _context$deliveryDire; var config = this.hls.config; // logger.debug(`[playlist-loader]: Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`); // Check if a loader for this context already exists var loader = this.getInternalLoader(context); if (loader) { var loaderContext = loader.context; if (loaderContext && loaderContext.url === context.url) { // same URL can't overlap _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].trace('[playlist-loader]: playlist request ongoing'); return; } _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log("[playlist-loader]: aborting previous loader for type: " + context.type); loader.abort(); } var maxRetry; var timeout; var retryDelay; var maxRetryDelay; // apply different configs for retries depending on // context (manifest, level, audio/subs playlist) switch (context.type) { case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST: maxRetry = config.manifestLoadingMaxRetry; timeout = config.manifestLoadingTimeOut; retryDelay = config.manifestLoadingRetryDelay; maxRetryDelay = config.manifestLoadingMaxRetryTimeout; break; case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL: case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK: case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK: // Manage retries in Level/Track Controller maxRetry = 0; timeout = config.levelLoadingTimeOut; break; default: maxRetry = config.levelLoadingMaxRetry; timeout = config.levelLoadingTimeOut; retryDelay = config.levelLoadingRetryDelay; maxRetryDelay = config.levelLoadingMaxRetryTimeout; break; } loader = this.createInternalLoader(context); // Override level/track timeout for LL-HLS requests // (the default of 10000ms is counter productive to blocking playlist reload requests) if ((_context$deliveryDire = context.deliveryDirectives) !== null && _context$deliveryDire !== void 0 && _context$deliveryDire.part) { var levelDetails; if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL && context.level !== null) { levelDetails = this.hls.levels[context.level].details; } else if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK && context.id !== null) { levelDetails = this.hls.audioTracks[context.id].details; } else if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK && context.id !== null) { levelDetails = this.hls.subtitleTracks[context.id].details; } if (levelDetails) { var partTarget = levelDetails.partTarget; var targetDuration = levelDetails.targetduration; if (partTarget && targetDuration) { timeout = Math.min(Math.max(partTarget * 3, targetDuration * 0.8) * 1000, timeout); } } } var loaderConfig = { timeout: timeout, maxRetry: maxRetry, retryDelay: retryDelay, maxRetryDelay: maxRetryDelay, highWaterMark: 0 }; var loaderCallbacks = { onSuccess: this.loadsuccess.bind(this), onError: this.loaderror.bind(this), onTimeout: this.loadtimeout.bind(this) }; // logger.debug(`[playlist-loader]: Calling internal loader delegate for URL: ${context.url}`); loader.load(context, loaderConfig, loaderCallbacks); }; _proto.loadsuccess = function loadsuccess(response, stats, context, networkDetails) { if (networkDetails === void 0) { networkDetails = null; } if (context.isSidxRequest) { this.handleSidxRequest(response, context); this.handlePlaylistLoaded(response, stats, context, networkDetails); return; } this.resetInternalLoader(context.type); var string = response.data; // Validate if it is an M3U8 at all if (string.indexOf('#EXTM3U') !== 0) { this.handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails); return; } stats.parsing.start = performance.now(); // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present) if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) { this.handleTrackOrLevelPlaylist(response, stats, context, networkDetails); } else { this.handleMasterPlaylist(response, stats, context, networkDetails); } }; _proto.loaderror = function loaderror(response, context, networkDetails) { if (networkDetails === void 0) { networkDetails = null; } this.handleNetworkError(context, networkDetails, false, response); }; _proto.loadtimeout = function loadtimeout(stats, context, networkDetails) { if (networkDetails === void 0) { networkDetails = null; } this.handleNetworkError(context, networkDetails, true); }; _proto.handleMasterPlaylist = function handleMasterPlaylist(response, stats, context, networkDetails) { var hls = this.hls; var string = response.data; var url = getResponseUrl(response, context); var _M3U8Parser$parseMast = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylist(string, url), levels = _M3U8Parser$parseMast.levels, sessionData = _M3U8Parser$parseMast.sessionData; if (!levels.length) { this.handleManifestParsingError(response, context, 'no level found in manifest', networkDetails); return; } // multi level playlist, parse level info var audioGroups = levels.map(function (level) { return { id: level.attrs.AUDIO, audioCodec: level.audioCodec }; }); var subtitleGroups = levels.map(function (level) { return { id: level.attrs.SUBTITLES, textCodec: level.textCodec }; }); var audioTracks = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups); var subtitles = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylistMedia(string, url, 'SUBTITLES', subtitleGroups); var captions = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylistMedia(string, url, 'CLOSED-CAPTIONS'); if (audioTracks.length) { // check if we have found an audio track embedded in main playlist (audio track without URI attribute) var embeddedAudioFound = audioTracks.some(function (audioTrack) { return !audioTrack.url; }); // if no embedded audio track defined, but audio codec signaled in quality level, // we need to signal this main audio track this could happen with playlists with // alt audio rendition in which quality levels (main) // contains both audio+video. but with mixed audio track not signaled if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) { _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log('[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one'); audioTracks.unshift({ type: 'main', name: 'main', default: false, autoselect: false, forced: false, id: -1, attrs: new _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__["AttrList"]({}), bitrate: 0, url: '' }); } } hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, { levels: levels, audioTracks: audioTracks, subtitles: subtitles, captions: captions, url: url, stats: stats, networkDetails: networkDetails, sessionData: sessionData }); }; _proto.handleTrackOrLevelPlaylist = function handleTrackOrLevelPlaylist(response, stats, context, networkDetails) { var hls = this.hls; var id = context.id, level = context.level, type = context.type; var url = getResponseUrl(response, context); var levelUrlId = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(id) ? id : 0; var levelId = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(level) ? level : levelUrlId; var levelType = mapContextToLevelType(context); var levelDetails = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId); if (!levelDetails.fragments.length) { hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].NETWORK_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_EMPTY_ERROR, fatal: false, url: url, reason: 'no fragments found in level', level: typeof context.level === 'number' ? context.level : undefined }); return; } // We have done our first request (Manifest-type) and receive // not a master playlist but a chunk-list (track/level) // We fire the manifest-loaded event anyway with the parsed level-details // by creating a single-level structure for it. if (type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST) { var singleLevel = { attrs: new _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__["AttrList"]({}), bitrate: 0, details: levelDetails, name: '', url: url }; hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, { levels: [singleLevel], audioTracks: [], url: url, stats: stats, networkDetails: networkDetails, sessionData: null }); } // save parsing time stats.parsing.end = performance.now(); // in case we need SIDX ranges // return early after calling load for // the SIDX box. if (levelDetails.needSidxRanges) { var _levelDetails$fragmen; var sidxUrl = (_levelDetails$fragmen = levelDetails.fragments[0].initSegment) === null || _levelDetails$fragmen === void 0 ? void 0 : _levelDetails$fragmen.url; this.load({ url: sidxUrl, isSidxRequest: true, type: type, level: level, levelDetails: levelDetails, id: id, groupId: null, rangeStart: 0, rangeEnd: 2048, responseType: 'arraybuffer', deliveryDirectives: null }); return; } // extend the context with the new levelDetails property context.levelDetails = levelDetails; this.handlePlaylistLoaded(response, stats, context, networkDetails); }; _proto.handleSidxRequest = function handleSidxRequest(response, context) { var sidxInfo = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__["parseSegmentIndex"])(new Uint8Array(response.data)); // if provided fragment does not contain sidx, early return if (!sidxInfo) { return; } var sidxReferences = sidxInfo.references; var levelDetails = context.levelDetails; sidxReferences.forEach(function (segmentRef, index) { var segRefInfo = segmentRef.info; var frag = levelDetails.fragments[index]; if (frag.byteRange.length === 0) { frag.setByteRange(String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start)); } if (frag.initSegment) { frag.initSegment.setByteRange(String(sidxInfo.moovEndOffset) + '@0'); } }); }; _proto.handleManifestParsingError = function handleManifestParsingError(response, context, reason, networkDetails) { this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].NETWORK_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_PARSING_ERROR, fatal: context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST, url: response.url, reason: reason, response: response, context: context, networkDetails: networkDetails }); }; _proto.handleNetworkError = function handleNetworkError(context, networkDetails, timeout, response) { if (timeout === void 0) { timeout = false; } _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("[playlist-loader]: A network " + (timeout ? 'timeout' : 'error') + " occurred while loading " + context.type + " level: " + context.level + " id: " + context.id + " group-id: \"" + context.groupId + "\""); var details = _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].UNKNOWN; var fatal = false; var loader = this.getInternalLoader(context); switch (context.type) { case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST: details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_LOAD_ERROR; fatal = true; break; case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL: details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_ERROR; fatal = false; break; case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK: details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].AUDIO_TRACK_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR; fatal = false; break; case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK: details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].SUBTITLE_TRACK_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].SUBTITLE_LOAD_ERROR; fatal = false; break; } if (loader) { this.resetInternalLoader(context.type); } var errorData = { type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].NETWORK_ERROR, details: details, fatal: fatal, url: context.url, loader: loader, context: context, networkDetails: networkDetails }; if (response) { errorData.response = response; } this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, errorData); }; _proto.handlePlaylistLoaded = function handlePlaylistLoaded(response, stats, context, networkDetails) { var type = context.type, level = context.level, id = context.id, groupId = context.groupId, loader = context.loader, levelDetails = context.levelDetails, deliveryDirectives = context.deliveryDirectives; if (!(levelDetails !== null && levelDetails !== void 0 && levelDetails.targetduration)) { this.handleManifestParsingError(response, context, 'invalid target duration', networkDetails); return; } if (!loader) { return; } if (levelDetails.live) { if (loader.getCacheAge) { levelDetails.ageHeader = loader.getCacheAge() || 0; } if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) { levelDetails.ageHeader = 0; } } switch (type) { case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST: case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL: this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADED, { details: levelDetails, level: level || 0, id: id || 0, stats: stats, networkDetails: networkDetails, deliveryDirectives: deliveryDirectives }); break; case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK: this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_LOADED, { details: levelDetails, id: id || 0, groupId: groupId || '', stats: stats, networkDetails: networkDetails, deliveryDirectives: deliveryDirectives }); break; case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK: this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACK_LOADED, { details: levelDetails, id: id || 0, groupId: groupId || '', stats: stats, networkDetails: networkDetails, deliveryDirectives: deliveryDirectives }); break; } }; return PlaylistLoader; }(); /* harmony default export */ __webpack_exports__["default"] = (PlaylistLoader); /***/ }), /***/ "./src/polyfills/number.ts": /*!*********************************!*\ !*** ./src/polyfills/number.ts ***! \*********************************/ /*! exports provided: isFiniteNumber, MAX_SAFE_INTEGER */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFiniteNumber", function() { return isFiniteNumber; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MAX_SAFE_INTEGER", function() { return MAX_SAFE_INTEGER; }); var isFiniteNumber = Number.isFinite || function (value) { return typeof value === 'number' && isFinite(value); }; var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; /***/ }), /***/ "./src/remux/aac-helper.ts": /*!*********************************!*\ !*** ./src/remux/aac-helper.ts ***! \*********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * AAC helper */ var AAC = /*#__PURE__*/function () { function AAC() {} AAC.getSilentFrame = function getSilentFrame(codec, channelCount) { switch (codec) { case 'mp4a.40.2': if (channelCount === 1) { return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]); } else if (channelCount === 2) { return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]); } else if (channelCount === 3) { return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]); } else if (channelCount === 4) { return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]); } else if (channelCount === 5) { return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]); } else if (channelCount === 6) { return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2, 0x00, 0x20, 0x08, 0xe0]); } break; // handle HE-AAC below (mp4a.40.5 / mp4a.40.29) default: if (channelCount === 1) { // ffmpeg -y -f lavfi -i "aevalsrc=0:d=0.05" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x4e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x1c, 0x6, 0xf1, 0xc1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]); } else if (channelCount === 2) { // ffmpeg -y -f lavfi -i "aevalsrc=0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]); } else if (channelCount === 3) { // ffmpeg -y -f lavfi -i "aevalsrc=0|0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]); } break; } return undefined; }; return AAC; }(); /* harmony default export */ __webpack_exports__["default"] = (AAC); /***/ }), /***/ "./src/remux/mp4-generator.ts": /*!************************************!*\ !*** ./src/remux/mp4-generator.ts ***! \************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * Generate MP4 Box */ var UINT32_MAX = Math.pow(2, 32) - 1; var MP4 = /*#__PURE__*/function () { function MP4() {} MP4.init = function init() { MP4.types = { avc1: [], // codingname avcC: [], btrt: [], dinf: [], dref: [], esds: [], ftyp: [], hdlr: [], mdat: [], mdhd: [], mdia: [], mfhd: [], minf: [], moof: [], moov: [], mp4a: [], '.mp3': [], mvex: [], mvhd: [], pasp: [], sdtp: [], stbl: [], stco: [], stsc: [], stsd: [], stsz: [], stts: [], tfdt: [], tfhd: [], traf: [], trak: [], trun: [], trex: [], tkhd: [], vmhd: [], smhd: [] }; var i; for (i in MP4.types) { if (MP4.types.hasOwnProperty(i)) { MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)]; } } var videoHdlr = new Uint8Array([0x00, // version 0 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x00, // pre_defined 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide' 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler' ]); var audioHdlr = new Uint8Array([0x00, // version 0 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x00, // pre_defined 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun' 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler' ]); MP4.HDLR_TYPES = { video: videoHdlr, audio: audioHdlr }; var dref = new Uint8Array([0x00, // version 0 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x01, // entry_count 0x00, 0x00, 0x00, 0x0c, // entry_size 0x75, 0x72, 0x6c, 0x20, // 'url' type 0x00, // version 0 0x00, 0x00, 0x01 // entry_flags ]); var stco = new Uint8Array([0x00, // version 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x00 // entry_count ]); MP4.STTS = MP4.STSC = MP4.STCO = stco; MP4.STSZ = new Uint8Array([0x00, // version 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x00, // sample_size 0x00, 0x00, 0x00, 0x00 // sample_count ]); MP4.VMHD = new Uint8Array([0x00, // version 0x00, 0x00, 0x01, // flags 0x00, 0x00, // graphicsmode 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor ]); MP4.SMHD = new Uint8Array([0x00, // version 0x00, 0x00, 0x00, // flags 0x00, 0x00, // balance 0x00, 0x00 // reserved ]); MP4.STSD = new Uint8Array([0x00, // version 0 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x01]); // entry_count var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1 var minorVersion = new Uint8Array([0, 0, 0, 1]); MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand); MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref)); }; MP4.box = function box(type) { var size = 8; for (var _len = arguments.length, payload = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { payload[_key - 1] = arguments[_key]; } var i = payload.length; var len = i; // calculate the total size we need to allocate while (i--) { size += payload[i].byteLength; } var result = new Uint8Array(size); result[0] = size >> 24 & 0xff; result[1] = size >> 16 & 0xff; result[2] = size >> 8 & 0xff; result[3] = size & 0xff; result.set(type, 4); // copy the payload into the result for (i = 0, size = 8; i < len; i++) { // copy payload[i] array @ offset size result.set(payload[i], size); size += payload[i].byteLength; } return result; }; MP4.hdlr = function hdlr(type) { return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]); }; MP4.mdat = function mdat(data) { return MP4.box(MP4.types.mdat, data); }; MP4.mdhd = function mdhd(timescale, duration) { duration *= timescale; var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)); var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1)); return MP4.box(MP4.types.mdhd, new Uint8Array([0x01, // version 1 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff, // timescale upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x55, 0xc4, // 'und' language (undetermined) 0x00, 0x00])); }; MP4.mdia = function mdia(track) { return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track)); }; MP4.mfhd = function mfhd(sequenceNumber) { return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags sequenceNumber >> 24, sequenceNumber >> 16 & 0xff, sequenceNumber >> 8 & 0xff, sequenceNumber & 0xff // sequence_number ])); }; MP4.minf = function minf(track) { if (track.type === 'audio') { return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track)); } else { return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track)); } }; MP4.moof = function moof(sn, baseMediaDecodeTime, track) { return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime)); } /** * @param tracks... (optional) {array} the tracks associated with this movie */ ; MP4.moov = function moov(tracks) { var i = tracks.length; var boxes = []; while (i--) { boxes[i] = MP4.trak(tracks[i]); } return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks))); }; MP4.mvex = function mvex(tracks) { var i = tracks.length; var boxes = []; while (i--) { boxes[i] = MP4.trex(tracks[i]); } return MP4.box.apply(null, [MP4.types.mvex].concat(boxes)); }; MP4.mvhd = function mvhd(timescale, duration) { duration *= timescale; var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)); var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1)); var bytes = new Uint8Array([0x01, // version 1 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff, // timescale upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x01, 0x00, 0x00, // 1.0 rate 0x01, 0x00, // 1.0 volume 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined 0xff, 0xff, 0xff, 0xff // next_track_ID ]); return MP4.box(MP4.types.mvhd, bytes); }; MP4.sdtp = function sdtp(track) { var samples = track.samples || []; var bytes = new Uint8Array(4 + samples.length); var i; var flags; // leave the full box header (4 bytes) all zero // write the sample table for (i = 0; i < samples.length; i++) { flags = samples[i].flags; bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy; } return MP4.box(MP4.types.sdtp, bytes); }; MP4.stbl = function stbl(track) { return MP4.box(MP4.types.stbl, MP4.stsd(track), MP4.box(MP4.types.stts, MP4.STTS), MP4.box(MP4.types.stsc, MP4.STSC), MP4.box(MP4.types.stsz, MP4.STSZ), MP4.box(MP4.types.stco, MP4.STCO)); }; MP4.avc1 = function avc1(track) { var sps = []; var pps = []; var i; var data; var len; // assemble the SPSs for (i = 0; i < track.sps.length; i++) { data = track.sps[i]; len = data.byteLength; sps.push(len >>> 8 & 0xff); sps.push(len & 0xff); // SPS sps = sps.concat(Array.prototype.slice.call(data)); } // assemble the PPSs for (i = 0; i < track.pps.length; i++) { data = track.pps[i]; len = data.byteLength; pps.push(len >>> 8 & 0xff); pps.push(len & 0xff); pps = pps.concat(Array.prototype.slice.call(data)); } var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01, // version sps[3], // profile sps[4], // profile compat sps[5], // level 0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes 0xe0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets ].concat(sps).concat([track.pps.length // numOfPictureParameterSets ]).concat(pps))); // "PPS" var width = track.width; var height = track.height; var hSpacing = track.pixelRatio[0]; var vSpacing = track.pixelRatio[1]; return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, // reserved 0x00, 0x01, // data_reference_index 0x00, 0x00, // pre_defined 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined width >> 8 & 0xff, width & 0xff, // width height >> 8 & 0xff, height & 0xff, // height 0x00, 0x48, 0x00, 0x00, // horizresolution 0x00, 0x48, 0x00, 0x00, // vertresolution 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x01, // frame_count 0x12, 0x64, 0x61, 0x69, 0x6c, // dailymotion/hls.js 0x79, 0x6d, 0x6f, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x68, 0x6c, 0x73, 0x2e, 0x6a, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname 0x00, 0x18, // depth = 24 0x11, 0x11]), // pre_defined = -1 avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate 0x00, 0x2d, 0xc6, 0xc0])), // avgBitrate MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24, // hSpacing hSpacing >> 16 & 0xff, hSpacing >> 8 & 0xff, hSpacing & 0xff, vSpacing >> 24, // vSpacing vSpacing >> 16 & 0xff, vSpacing >> 8 & 0xff, vSpacing & 0xff]))); }; MP4.esds = function esds(track) { var configlen = track.config.length; return new Uint8Array([0x00, // version 0 0x00, 0x00, 0x00, // flags 0x03, // descriptor_type 0x17 + configlen, // length 0x00, 0x01, // es_id 0x00, // stream_priority 0x04, // descriptor_type 0x0f + configlen, // length 0x40, // codec : mpeg4_audio 0x15, // stream_type 0x00, 0x00, 0x00, // buffer_size 0x00, 0x00, 0x00, 0x00, // maxBitrate 0x00, 0x00, 0x00, 0x00, // avgBitrate 0x05 // descriptor_type ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor }; MP4.mp4a = function mp4a(track) { var samplerate = track.samplerate; return MP4.box(MP4.types.mp4a, new Uint8Array([0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, // reserved 0x00, 0x01, // data_reference_index 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved 0x00, track.channelCount, // channelcount 0x00, 0x10, // sampleSize:16bits 0x00, 0x00, 0x00, 0x00, // reserved2 samplerate >> 8 & 0xff, samplerate & 0xff, // 0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track))); }; MP4.mp3 = function mp3(track) { var samplerate = track.samplerate; return MP4.box(MP4.types['.mp3'], new Uint8Array([0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, // reserved 0x00, 0x01, // data_reference_index 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved 0x00, track.channelCount, // channelcount 0x00, 0x10, // sampleSize:16bits 0x00, 0x00, 0x00, 0x00, // reserved2 samplerate >> 8 & 0xff, samplerate & 0xff, // 0x00, 0x00])); }; MP4.stsd = function stsd(track) { if (track.type === 'audio') { if (!track.isAAC && track.codec === 'mp3') { return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track)); } return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track)); } else { return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track)); } }; MP4.tkhd = function tkhd(track) { var id = track.id; var duration = track.duration * track.timescale; var width = track.width; var height = track.height; var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)); var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1)); return MP4.box(MP4.types.tkhd, new Uint8Array([0x01, // version 1 0x00, 0x00, 0x07, // flags 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time id >> 24 & 0xff, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff, // track_ID 0x00, 0x00, 0x00, 0x00, // reserved upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, // layer 0x00, 0x00, // alternate_group 0x00, 0x00, // non-audio track volume 0x00, 0x00, // reserved 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix width >> 8 & 0xff, width & 0xff, 0x00, 0x00, // width height >> 8 & 0xff, height & 0xff, 0x00, 0x00 // height ])); }; MP4.traf = function traf(track, baseMediaDecodeTime) { var sampleDependencyTable = MP4.sdtp(track); var id = track.id; var upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1)); var lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1)); return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00, // version 0 0x00, 0x00, 0x00, // flags id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff // track_ID ])), MP4.box(MP4.types.tfdt, new Uint8Array([0x01, // version 1 0x00, 0x00, 0x00, // flags upperWordBaseMediaDecodeTime >> 24, upperWordBaseMediaDecodeTime >> 16 & 0xff, upperWordBaseMediaDecodeTime >> 8 & 0xff, upperWordBaseMediaDecodeTime & 0xff, lowerWordBaseMediaDecodeTime >> 24, lowerWordBaseMediaDecodeTime >> 16 & 0xff, lowerWordBaseMediaDecodeTime >> 8 & 0xff, lowerWordBaseMediaDecodeTime & 0xff])), MP4.trun(track, sampleDependencyTable.length + 16 + // tfhd 20 + // tfdt 8 + // traf header 16 + // mfhd 8 + // moof header 8), // mdat header sampleDependencyTable); } /** * Generate a track box. * @param track {object} a track definition * @return {Uint8Array} the track box */ ; MP4.trak = function trak(track) { track.duration = track.duration || 0xffffffff; return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track)); }; MP4.trex = function trex(track) { var id = track.id; return MP4.box(MP4.types.trex, new Uint8Array([0x00, // version 0 0x00, 0x00, 0x00, // flags id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff, // track_ID 0x00, 0x00, 0x00, 0x01, // default_sample_description_index 0x00, 0x00, 0x00, 0x00, // default_sample_duration 0x00, 0x00, 0x00, 0x00, // default_sample_size 0x00, 0x01, 0x00, 0x01 // default_sample_flags ])); }; MP4.trun = function trun(track, offset) { var samples = track.samples || []; var len = samples.length; var arraylen = 12 + 16 * len; var array = new Uint8Array(arraylen); var i; var sample; var duration; var size; var flags; var cts; offset += 8 + arraylen; array.set([0x00, // version 0 0x00, 0x0f, 0x01, // flags len >>> 24 & 0xff, len >>> 16 & 0xff, len >>> 8 & 0xff, len & 0xff, // sample_count offset >>> 24 & 0xff, offset >>> 16 & 0xff, offset >>> 8 & 0xff, offset & 0xff // data_offset ], 0); for (i = 0; i < len; i++) { sample = samples[i]; duration = sample.duration; size = sample.size; flags = sample.flags; cts = sample.cts; array.set([duration >>> 24 & 0xff, duration >>> 16 & 0xff, duration >>> 8 & 0xff, duration & 0xff, // sample_duration size >>> 24 & 0xff, size >>> 16 & 0xff, size >>> 8 & 0xff, size & 0xff, // sample_size flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xf0 << 8, flags.degradPrio & 0x0f, // sample_flags cts >>> 24 & 0xff, cts >>> 16 & 0xff, cts >>> 8 & 0xff, cts & 0xff // sample_composition_time_offset ], 12 + 16 * i); } return MP4.box(MP4.types.trun, array); }; MP4.initSegment = function initSegment(tracks) { if (!MP4.types) { MP4.init(); } var movie = MP4.moov(tracks); var result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength); result.set(MP4.FTYP); result.set(movie, MP4.FTYP.byteLength); return result; }; return MP4; }(); MP4.types = void 0; MP4.HDLR_TYPES = void 0; MP4.STTS = void 0; MP4.STSC = void 0; MP4.STCO = void 0; MP4.STSZ = void 0; MP4.VMHD = void 0; MP4.SMHD = void 0; MP4.STSD = void 0; MP4.FTYP = void 0; MP4.DINF = void 0; /* harmony default export */ __webpack_exports__["default"] = (MP4); /***/ }), /***/ "./src/remux/mp4-remuxer.ts": /*!**********************************!*\ !*** ./src/remux/mp4-remuxer.ts ***! \**********************************/ /*! exports provided: default, normalizePts */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return MP4Remuxer; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "normalizePts", function() { return normalizePts; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _aac_helper__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./aac-helper */ "./src/remux/aac-helper.ts"); /* harmony import */ var _mp4_generator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./mp4-generator */ "./src/remux/mp4-generator.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts"); /* harmony import */ var _utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/timescale-conversion */ "./src/utils/timescale-conversion.ts"); function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } var MAX_SILENT_FRAME_DURATION = 10 * 1000; // 10 seconds var AAC_SAMPLES_PER_FRAME = 1024; var MPEG_AUDIO_SAMPLE_PER_FRAME = 1152; var chromeVersion = null; var safariWebkitVersion = null; var requiresPositiveDts = false; var MP4Remuxer = /*#__PURE__*/function () { function MP4Remuxer(observer, config, typeSupported, vendor) { if (vendor === void 0) { vendor = ''; } this.observer = void 0; this.config = void 0; this.typeSupported = void 0; this.ISGenerated = false; this._initPTS = void 0; this._initDTS = void 0; this.nextAvcDts = null; this.nextAudioPts = null; this.isAudioContiguous = false; this.isVideoContiguous = false; this.observer = observer; this.config = config; this.typeSupported = typeSupported; this.ISGenerated = false; if (chromeVersion === null) { var userAgent = navigator.userAgent || ''; var result = userAgent.match(/Chrome\/(\d+)/i); chromeVersion = result ? parseInt(result[1]) : 0; } if (safariWebkitVersion === null) { var _result = navigator.userAgent.match(/Safari\/(\d+)/i); safariWebkitVersion = _result ? parseInt(_result[1]) : 0; } requiresPositiveDts = !!chromeVersion && chromeVersion < 75 || !!safariWebkitVersion && safariWebkitVersion < 600; } var _proto = MP4Remuxer.prototype; _proto.destroy = function destroy() {}; _proto.resetTimeStamp = function resetTimeStamp(defaultTimeStamp) { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: initPTS & initDTS reset'); this._initPTS = this._initDTS = defaultTimeStamp; }; _proto.resetNextTimestamp = function resetNextTimestamp() { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: reset next timestamp'); this.isVideoContiguous = false; this.isAudioContiguous = false; }; _proto.resetInitSegment = function resetInitSegment() { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: ISGenerated flag reset'); this.ISGenerated = false; }; _proto.getVideoStartPts = function getVideoStartPts(videoSamples) { var rolloverDetected = false; var startPTS = videoSamples.reduce(function (minPTS, sample) { var delta = sample.pts - minPTS; if (delta < -4294967296) { // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation rolloverDetected = true; return normalizePts(minPTS, sample.pts); } else if (delta > 0) { return minPTS; } else { return sample.pts; } }, videoSamples[0].pts); if (rolloverDetected) { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].debug('PTS rollover detected'); } return startPTS; }; _proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush, playlistType) { var video; var audio; var initSegment; var text; var id3; var independent; var audioTimeOffset = timeOffset; var videoTimeOffset = timeOffset; // If we're remuxing audio and video progressively, wait until we've received enough samples for each track before proceeding. // This is done to synchronize the audio and video streams. We know if the current segment will have samples if the "pid" // parameter is greater than -1. The pid is set when the PMT is parsed, which contains the tracks list. // However, if the initSegment has already been generated, or we've reached the end of a segment (flush), // then we can remux one track without waiting for the other. var hasAudio = audioTrack.pid > -1; var hasVideo = videoTrack.pid > -1; var length = videoTrack.samples.length; var enoughAudioSamples = audioTrack.samples.length > 0; var enoughVideoSamples = length > 1; var canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush; if (canRemuxAvc) { if (!this.ISGenerated) { initSegment = this.generateIS(audioTrack, videoTrack, timeOffset); } var isVideoContiguous = this.isVideoContiguous; var firstKeyFrameIndex = -1; if (enoughVideoSamples) { firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples); if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) { independent = true; if (firstKeyFrameIndex > 0) { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("[mp4-remuxer]: Dropped " + firstKeyFrameIndex + " out of " + length + " video samples due to a missing keyframe"); var startPTS = this.getVideoStartPts(videoTrack.samples); videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex); videoTrack.dropped += firstKeyFrameIndex; videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / (videoTrack.timescale || 90000); } else if (firstKeyFrameIndex === -1) { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("[mp4-remuxer]: No keyframe found out of " + length + " video samples"); independent = false; } } } if (this.ISGenerated) { if (enoughAudioSamples && enoughVideoSamples) { // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS) // if first audio DTS is not aligned with first video DTS then we need to take that into account // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small // drift between audio and video streams var _startPTS = this.getVideoStartPts(videoTrack.samples); var tsDelta = normalizePts(audioTrack.samples[0].pts, _startPTS) - _startPTS; var audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale; audioTimeOffset += Math.max(0, audiovideoTimestampDelta); videoTimeOffset += Math.max(0, -audiovideoTimestampDelta); } // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is calculated in remuxAudio. if (enoughAudioSamples) { // if initSegment was generated without audio samples, regenerate it again if (!audioTrack.samplerate) { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn('[mp4-remuxer]: regenerate InitSegment as audio detected'); initSegment = this.generateIS(audioTrack, videoTrack, timeOffset); } audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO ? videoTimeOffset : undefined); if (enoughVideoSamples) { var audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0; // if initSegment was generated without video samples, regenerate it again if (!videoTrack.inputTimeScale) { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn('[mp4-remuxer]: regenerate InitSegment as video detected'); initSegment = this.generateIS(audioTrack, videoTrack, timeOffset); } video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength); } } else if (enoughVideoSamples) { video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0); } if (video) { video.firstKeyFrame = firstKeyFrameIndex; video.independent = firstKeyFrameIndex !== -1; } } } // Allow ID3 and text to remux, even if more audio/video samples are required if (this.ISGenerated) { if (id3Track.samples.length) { id3 = this.remuxID3(id3Track, timeOffset); } if (textTrack.samples.length) { text = this.remuxText(textTrack, timeOffset); } } return { audio: audio, video: video, initSegment: initSegment, independent: independent, text: text, id3: id3 }; }; _proto.generateIS = function generateIS(audioTrack, videoTrack, timeOffset) { var audioSamples = audioTrack.samples; var videoSamples = videoTrack.samples; var typeSupported = this.typeSupported; var tracks = {}; var computePTSDTS = !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this._initPTS); var container = 'audio/mp4'; var initPTS; var initDTS; var timescale; if (computePTSDTS) { initPTS = initDTS = Infinity; } if (audioTrack.config && audioSamples.length) { // let's use audio sampling rate as MP4 time scale. // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC) // using audio sampling rate here helps having an integer MP4 frame duration // this avoids potential rounding issue and AV sync issue audioTrack.timescale = audioTrack.samplerate; if (!audioTrack.isAAC) { if (typeSupported.mpeg) { // Chrome and Safari container = 'audio/mpeg'; audioTrack.codec = ''; } else if (typeSupported.mp3) { // Firefox audioTrack.codec = 'mp3'; } } tracks.audio = { id: 'audio', container: container, codec: audioTrack.codec, initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array(0) : _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].initSegment([audioTrack]), metadata: { channelCount: audioTrack.channelCount } }; if (computePTSDTS) { timescale = audioTrack.inputTimeScale; // remember first PTS of this demuxing context. for audio, PTS = DTS initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * timeOffset); } } if (videoTrack.sps && videoTrack.pps && videoSamples.length) { // let's use input time scale as MP4 video timescale // we use input time scale straight away to avoid rounding issues on frame duration / cts computation videoTrack.timescale = videoTrack.inputTimeScale; tracks.video = { id: 'main', container: 'video/mp4', codec: videoTrack.codec, initSegment: _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].initSegment([videoTrack]), metadata: { width: videoTrack.width, height: videoTrack.height } }; if (computePTSDTS) { timescale = videoTrack.inputTimeScale; var startPTS = this.getVideoStartPts(videoSamples); var startOffset = Math.round(timescale * timeOffset); initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset); initPTS = Math.min(initPTS, startPTS - startOffset); } } if (Object.keys(tracks).length) { this.ISGenerated = true; if (computePTSDTS) { this._initPTS = initPTS; this._initDTS = initDTS; } return { tracks: tracks, initPTS: initPTS, timescale: timescale }; } }; _proto.remuxVideo = function remuxVideo(track, timeOffset, contiguous, audioTrackLength) { var timeScale = track.inputTimeScale; var inputSamples = track.samples; var outputSamples = []; var nbSamples = inputSamples.length; var initPTS = this._initPTS; var nextAvcDts = this.nextAvcDts; var offset = 8; var mp4SampleDuration; var firstDTS; var lastDTS; var minPTS = Number.POSITIVE_INFINITY; var maxPTS = Number.NEGATIVE_INFINITY; var ptsDtsShift = 0; var sortSamples = false; // if parsed fragment is contiguous with last one, let's use last DTS value as reference if (!contiguous || nextAvcDts === null) { var pts = timeOffset * timeScale; var cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts); // if not contiguous, let's use target timeOffset nextAvcDts = pts - cts; } // PTS is coded on 33bits, and can loop from -2^32 to 2^32 // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value for (var i = 0; i < nbSamples; i++) { var sample = inputSamples[i]; sample.pts = normalizePts(sample.pts - initPTS, nextAvcDts); sample.dts = normalizePts(sample.dts - initPTS, nextAvcDts); if (sample.dts > sample.pts) { var PTS_DTS_SHIFT_TOLERANCE_90KHZ = 90000 * 0.2; ptsDtsShift = Math.max(Math.min(ptsDtsShift, sample.pts - sample.dts), -1 * PTS_DTS_SHIFT_TOLERANCE_90KHZ); } if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) { sortSamples = true; } } // sort video samples by DTS then PTS then demux id order if (sortSamples) { inputSamples.sort(function (a, b) { var deltadts = a.dts - b.dts; var deltapts = a.pts - b.pts; return deltadts || deltapts; }); } // Get first/last DTS firstDTS = inputSamples[0].dts; lastDTS = inputSamples[inputSamples.length - 1].dts; // on Safari let's signal the same sample duration for all samples // sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS // set this constant duration as being the avg delta between consecutive DTS. var averageSampleDuration = Math.round((lastDTS - firstDTS) / (nbSamples - 1)); // handle broken streams with PTS < DTS, tolerance up 0.2 seconds if (ptsDtsShift < 0) { if (ptsDtsShift < averageSampleDuration * -2) { // Fix for "CNN special report, with CC" in test-streams (including Safari browser) // With large PTS < DTS errors such as this, we want to correct CTS while maintaining increasing DTS values _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("PTS < DTS detected in video samples, offsetting DTS from PTS by " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(-averageSampleDuration, true) + " ms"); var lastDts = ptsDtsShift; for (var _i = 0; _i < nbSamples; _i++) { inputSamples[_i].dts = lastDts = Math.max(lastDts, inputSamples[_i].pts - averageSampleDuration); inputSamples[_i].pts = Math.max(lastDts, inputSamples[_i].pts); } } else { // Fix for "Custom IV with bad PTS DTS" in test-streams // With smaller PTS < DTS errors we can simply move all DTS back. This increases CTS without causing buffer gaps or decode errors in Safari _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("PTS < DTS detected in video samples, shifting DTS by " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(ptsDtsShift, true) + " ms to overcome this issue"); for (var _i2 = 0; _i2 < nbSamples; _i2++) { inputSamples[_i2].dts = inputSamples[_i2].dts + ptsDtsShift; } } firstDTS = inputSamples[0].dts; } // if fragment are contiguous, detect hole/overlapping between fragments if (contiguous) { // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole) var delta = firstDTS - nextAvcDts; var foundHole = delta > averageSampleDuration; var foundOverlap = delta < -1; if (foundHole || foundOverlap) { if (foundHole) { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("AVC: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(delta, true) + " ms (" + delta + "dts) hole between fragments detected, filling it"); } else { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("AVC: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(-delta, true) + " ms (" + delta + "dts) overlapping between fragments detected"); } firstDTS = nextAvcDts; var firstPTS = inputSamples[0].pts - delta; inputSamples[0].dts = firstDTS; inputSamples[0].pts = firstPTS; _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log("Video: First PTS/DTS adjusted: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(firstPTS, true) + "/" + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(firstDTS, true) + ", delta: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(delta, true) + " ms"); } } if (requiresPositiveDts) { firstDTS = Math.max(0, firstDTS); } var nbNalu = 0; var naluLen = 0; for (var _i3 = 0; _i3 < nbSamples; _i3++) { // compute total/avc sample length and nb of NAL units var _sample = inputSamples[_i3]; var units = _sample.units; var nbUnits = units.length; var sampleLen = 0; for (var j = 0; j < nbUnits; j++) { sampleLen += units[j].data.length; } naluLen += sampleLen; nbNalu += nbUnits; _sample.length = sampleLen; // normalize PTS/DTS // ensure sample monotonic DTS _sample.dts = Math.max(_sample.dts, firstDTS); // ensure that computed value is greater or equal than sample DTS _sample.pts = Math.max(_sample.pts, _sample.dts, 0); minPTS = Math.min(_sample.pts, minPTS); maxPTS = Math.max(_sample.pts, maxPTS); } lastDTS = inputSamples[nbSamples - 1].dts; /* concatenate the video data and construct the mdat in place (need 8 more bytes to fill length and mpdat type) */ var mdatSize = naluLen + 4 * nbNalu + 8; var mdat; try { mdat = new Uint8Array(mdatSize); } catch (err) { this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].MUX_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: "fail allocating video mdat " + mdatSize }); return; } var view = new DataView(mdat.buffer); view.setUint32(0, mdatSize); mdat.set(_mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].types.mdat, 4); for (var _i4 = 0; _i4 < nbSamples; _i4++) { var avcSample = inputSamples[_i4]; var avcSampleUnits = avcSample.units; var mp4SampleLength = 0; // convert NALU bitstream to MP4 format (prepend NALU with size field) for (var _j = 0, _nbUnits = avcSampleUnits.length; _j < _nbUnits; _j++) { var unit = avcSampleUnits[_j]; var unitData = unit.data; var unitDataLen = unit.data.byteLength; view.setUint32(offset, unitDataLen); offset += 4; mdat.set(unitData, offset); offset += unitDataLen; mp4SampleLength += 4 + unitDataLen; } // expected sample duration is the Decoding Timestamp diff of consecutive samples if (_i4 < nbSamples - 1) { mp4SampleDuration = inputSamples[_i4 + 1].dts - avcSample.dts; } else { var config = this.config; var lastFrameDuration = avcSample.dts - inputSamples[_i4 > 0 ? _i4 - 1 : _i4].dts; if (config.stretchShortVideoTrack && this.nextAudioPts !== null) { // In some cases, a segment's audio track duration may exceed the video track duration. // Since we've already remuxed audio, and we know how long the audio track is, we look to // see if the delta to the next segment is longer than maxBufferHole. // If so, playback would potentially get stuck, so we artificially inflate // the duration of the last frame to minimize any potential gap between segments. var gapTolerance = Math.floor(config.maxBufferHole * timeScale); var deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts; if (deltaToFrameEnd > gapTolerance) { // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video // frame overlap. maxBufferHole should be >> lastFrameDuration anyway. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration; if (mp4SampleDuration < 0) { mp4SampleDuration = lastFrameDuration; } _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log("[mp4-remuxer]: It is approximately " + deltaToFrameEnd / 90 + " ms to the next segment; using duration " + mp4SampleDuration / 90 + " ms for the last video frame."); } else { mp4SampleDuration = lastFrameDuration; } } else { mp4SampleDuration = lastFrameDuration; } } var compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts); outputSamples.push(new Mp4Sample(avcSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset)); } if (outputSamples.length && chromeVersion && chromeVersion < 70) { // Chrome workaround, mark first sample as being a Random Access Point (keyframe) to avoid sourcebuffer append issue // https://code.google.com/p/chromium/issues/detail?id=229412 var flags = outputSamples[0].flags; flags.dependsOn = 2; flags.isNonSync = 0; } console.assert(mp4SampleDuration !== undefined, 'mp4SampleDuration must be computed'); // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale) this.nextAvcDts = nextAvcDts = lastDTS + mp4SampleDuration; this.isVideoContiguous = true; var moof = _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].moof(track.sequenceNumber++, firstDTS, _extends({}, track, { samples: outputSamples })); var type = 'video'; var data = { data1: moof, data2: mdat, startPTS: minPTS / timeScale, endPTS: (maxPTS + mp4SampleDuration) / timeScale, startDTS: firstDTS / timeScale, endDTS: nextAvcDts / timeScale, type: type, hasAudio: false, hasVideo: true, nb: outputSamples.length, dropped: track.dropped }; track.samples = []; track.dropped = 0; console.assert(mdat.length, 'MDAT length must not be zero'); return data; }; _proto.remuxAudio = function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) { var inputTimeScale = track.inputTimeScale; var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale; var scaleFactor = inputTimeScale / mp4timeScale; var mp4SampleDuration = track.isAAC ? AAC_SAMPLES_PER_FRAME : MPEG_AUDIO_SAMPLE_PER_FRAME; var inputSampleDuration = mp4SampleDuration * scaleFactor; var initPTS = this._initPTS; var rawMPEG = !track.isAAC && this.typeSupported.mpeg; var outputSamples = []; var inputSamples = track.samples; var offset = rawMPEG ? 0 : 8; var nextAudioPts = this.nextAudioPts || -1; // window.audioSamples ? window.audioSamples.push(inputSamples.map(s => s.pts)) : (window.audioSamples = [inputSamples.map(s => s.pts)]); // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs), // for sake of clarity: // consecutive fragments are frags with // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR // - less than 20 audio frames distance // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1) // this helps ensuring audio continuity // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame var timeOffsetMpegTS = timeOffset * inputTimeScale; this.isAudioContiguous = contiguous = contiguous || inputSamples.length && nextAudioPts > 0 && (accurateTimeOffset && Math.abs(timeOffsetMpegTS - nextAudioPts) < 9000 || Math.abs(normalizePts(inputSamples[0].pts - initPTS, timeOffsetMpegTS) - nextAudioPts) < 20 * inputSampleDuration); // compute normalized PTS inputSamples.forEach(function (sample) { sample.pts = normalizePts(sample.pts - initPTS, timeOffsetMpegTS); }); if (!contiguous || nextAudioPts < 0) { // filter out sample with negative PTS that are not playable anyway // if we don't remove these negative samples, they will shift all audio samples forward. // leading to audio overlap between current / next fragment inputSamples = inputSamples.filter(function (sample) { return sample.pts >= 0; }); // in case all samples have negative PTS, and have been filtered out, return now if (!inputSamples.length) { return; } if (videoTimeOffset === 0) { // Set the start to 0 to match video so that start gaps larger than inputSampleDuration are filled with silence nextAudioPts = 0; } else if (accurateTimeOffset) { // When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS nextAudioPts = Math.max(0, timeOffsetMpegTS); } else { // if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS nextAudioPts = inputSamples[0].pts; } } // If the audio track is missing samples, the frames seem to get "left-shifted" within the // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment. // In an effort to prevent this from happening, we inject frames here where there are gaps. // When possible, we inject a silent frame; when that's not possible, we duplicate the last // frame. if (track.isAAC) { var alignedWithVideo = videoTimeOffset !== undefined; var maxAudioFramesDrift = this.config.maxAudioFramesDrift; for (var i = 0, nextPts = nextAudioPts; i < inputSamples.length; i++) { // First, let's see how far off this frame is from where we expect it to be var sample = inputSamples[i]; var pts = sample.pts; var delta = pts - nextPts; var duration = Math.abs(1000 * delta / inputTimeScale); // When remuxing with video, if we're overlapping by more than a duration, drop this sample to stay in sync if (delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo) { if (i === 0) { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("Audio frame @ " + (pts / inputTimeScale).toFixed(3) + "s overlaps nextAudioPts by " + Math.round(1000 * delta / inputTimeScale) + " ms."); this.nextAudioPts = nextAudioPts = nextPts = pts; } } // eslint-disable-line brace-style // Insert missing frames if: // 1: We're more than maxAudioFramesDrift frame away // 2: Not more than MAX_SILENT_FRAME_DURATION away // 3: currentTime (aka nextPtsNorm) is not 0 // 4: remuxing with video (videoTimeOffset !== undefined) else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && alignedWithVideo) { var missing = Math.round(delta / inputSampleDuration); // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from // later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration. nextPts = pts - missing * inputSampleDuration; if (nextPts < 0) { missing--; nextPts += inputSampleDuration; } if (i === 0) { this.nextAudioPts = nextAudioPts = nextPts; } _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("[mp4-remuxer]: Injecting " + missing + " audio frame @ " + (nextPts / inputTimeScale).toFixed(3) + "s due to " + Math.round(1000 * delta / inputTimeScale) + " ms gap."); for (var j = 0; j < missing; j++) { var newStamp = Math.max(nextPts, 0); var fillFrame = _aac_helper__WEBPACK_IMPORTED_MODULE_1__["default"].getSilentFrame(track.manifestCodec || track.codec, track.channelCount); if (!fillFrame) { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead.'); fillFrame = sample.unit.subarray(); } inputSamples.splice(i, 0, { unit: fillFrame, pts: newStamp }); nextPts += inputSampleDuration; i++; } } sample.pts = nextPts; nextPts += inputSampleDuration; } } var firstPTS = null; var lastPTS = null; var mdat; var mdatSize = 0; var sampleLength = inputSamples.length; while (sampleLength--) { mdatSize += inputSamples[sampleLength].unit.byteLength; } for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) { var audioSample = inputSamples[_j2]; var unit = audioSample.unit; var _pts = audioSample.pts; if (lastPTS !== null) { // If we have more than one sample, set the duration of the sample to the "real" duration; the PTS diff with // the previous sample var prevSample = outputSamples[_j2 - 1]; prevSample.duration = Math.round((_pts - lastPTS) / scaleFactor); } else { if (contiguous && track.isAAC) { // set PTS/DTS to expected PTS/DTS _pts = nextAudioPts; } // remember first PTS of our audioSamples firstPTS = _pts; if (mdatSize > 0) { /* concatenate the audio data and construct the mdat in place (need 8 more bytes to fill length and mdat type) */ mdatSize += offset; try { mdat = new Uint8Array(mdatSize); } catch (err) { this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].MUX_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: "fail allocating audio mdat " + mdatSize }); return; } if (!rawMPEG) { var view = new DataView(mdat.buffer); view.setUint32(0, mdatSize); mdat.set(_mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].types.mdat, 4); } } else { // no audio samples return; } } mdat.set(unit, offset); var unitLen = unit.byteLength; offset += unitLen; // Default the sample's duration to the computed mp4SampleDuration, which will either be 1024 for AAC or 1152 for MPEG // In the case that we have 1 sample, this will be the duration. If we have more than one sample, the duration // becomes the PTS diff with the previous sample outputSamples.push(new Mp4Sample(true, mp4SampleDuration, unitLen, 0)); lastPTS = _pts; } // We could end up with no audio samples if all input samples were overlapping with the previously remuxed ones var nbSamples = outputSamples.length; if (!nbSamples) { return; } // The next audio sample PTS should be equal to last sample PTS + duration var lastSample = outputSamples[outputSamples.length - 1]; this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSample.duration; // Set the track samples from inputSamples to outputSamples before remuxing var moof = rawMPEG ? new Uint8Array(0) : _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].moof(track.sequenceNumber++, firstPTS / scaleFactor, _extends({}, track, { samples: outputSamples })); // Clear the track samples. This also clears the samples array in the demuxer, since the reference is shared track.samples = []; var start = firstPTS / inputTimeScale; var end = nextAudioPts / inputTimeScale; var type = 'audio'; var audioData = { data1: moof, data2: mdat, startPTS: start, endPTS: end, startDTS: start, endDTS: end, type: type, hasAudio: true, hasVideo: false, nb: nbSamples }; this.isAudioContiguous = true; console.assert(mdat.length, 'MDAT length must not be zero'); return audioData; }; _proto.remuxEmptyAudio = function remuxEmptyAudio(track, timeOffset, contiguous, videoData) { var inputTimeScale = track.inputTimeScale; var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale; var scaleFactor = inputTimeScale / mp4timeScale; var nextAudioPts = this.nextAudioPts; // sync with video's timestamp var startDTS = (nextAudioPts !== null ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS; var endDTS = videoData.endDTS * inputTimeScale + this._initDTS; // one sample's duration value var frameDuration = scaleFactor * AAC_SAMPLES_PER_FRAME; // samples count of this segment's duration var nbSamples = Math.ceil((endDTS - startDTS) / frameDuration); // silent frame var silentFrame = _aac_helper__WEBPACK_IMPORTED_MODULE_1__["default"].getSilentFrame(track.manifestCodec || track.codec, track.channelCount); _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn('[mp4-remuxer]: remux empty Audio'); // Can't remux if we can't generate a silent frame... if (!silentFrame) { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].trace('[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec'); return; } var samples = []; for (var i = 0; i < nbSamples; i++) { var stamp = startDTS + i * frameDuration; samples.push({ unit: silentFrame, pts: stamp, dts: stamp }); } track.samples = samples; return this.remuxAudio(track, timeOffset, contiguous, false); }; _proto.remuxID3 = function remuxID3(track, timeOffset) { var length = track.samples.length; if (!length) { return; } var inputTimeScale = track.inputTimeScale; var initPTS = this._initPTS; var initDTS = this._initDTS; for (var index = 0; index < length; index++) { var sample = track.samples[index]; // setting id3 pts, dts to relative time // using this._initPTS and this._initDTS to calculate relative time sample.pts = normalizePts(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale; sample.dts = normalizePts(sample.dts - initDTS, timeOffset * inputTimeScale) / inputTimeScale; } var samples = track.samples; track.samples = []; return { samples: samples }; }; _proto.remuxText = function remuxText(track, timeOffset) { var length = track.samples.length; if (!length) { return; } var inputTimeScale = track.inputTimeScale; var initPTS = this._initPTS; for (var index = 0; index < length; index++) { var sample = track.samples[index]; // setting text pts, dts to relative time // using this._initPTS and this._initDTS to calculate relative time sample.pts = normalizePts(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale; } track.samples.sort(function (a, b) { return a.pts - b.pts; }); var samples = track.samples; track.samples = []; return { samples: samples }; }; return MP4Remuxer; }(); function normalizePts(value, reference) { var offset; if (reference === null) { return value; } if (reference < value) { // - 2^33 offset = -8589934592; } else { // + 2^33 offset = 8589934592; } /* PTS is 33bit (from 0 to 2^33 -1) if diff between value and reference is bigger than half of the amplitude (2^32) then it means that PTS looping occured. fill the gap */ while (Math.abs(value - reference) > 4294967296) { value += offset; } return value; } function findKeyframeIndex(samples) { for (var i = 0; i < samples.length; i++) { if (samples[i].key) { return i; } } return -1; } var Mp4Sample = function Mp4Sample(isKeyframe, duration, size, cts) { this.size = void 0; this.duration = void 0; this.cts = void 0; this.flags = void 0; this.duration = duration; this.size = size; this.cts = cts; this.flags = new Mp4SampleFlags(isKeyframe); }; var Mp4SampleFlags = function Mp4SampleFlags(isKeyframe) { this.isLeading = 0; this.isDependedOn = 0; this.hasRedundancy = 0; this.degradPrio = 0; this.dependsOn = 1; this.isNonSync = 1; this.dependsOn = isKeyframe ? 2 : 1; this.isNonSync = isKeyframe ? 0 : 1; }; /***/ }), /***/ "./src/remux/passthrough-remuxer.ts": /*!******************************************!*\ !*** ./src/remux/passthrough-remuxer.ts ***! \******************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts"); /* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); var PassThroughRemuxer = /*#__PURE__*/function () { function PassThroughRemuxer() { this.emitInitSegment = false; this.audioCodec = void 0; this.videoCodec = void 0; this.initData = void 0; this.initPTS = void 0; this.initTracks = void 0; this.lastEndDTS = null; } var _proto = PassThroughRemuxer.prototype; _proto.destroy = function destroy() {}; _proto.resetTimeStamp = function resetTimeStamp(defaultInitPTS) { this.initPTS = defaultInitPTS; this.lastEndDTS = null; }; _proto.resetNextTimestamp = function resetNextTimestamp() { this.lastEndDTS = null; }; _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec) { this.audioCodec = audioCodec; this.videoCodec = videoCodec; this.generateInitSegment(initSegment); this.emitInitSegment = true; }; _proto.generateInitSegment = function generateInitSegment(initSegment) { var audioCodec = this.audioCodec, videoCodec = this.videoCodec; if (!initSegment || !initSegment.byteLength) { this.initTracks = undefined; this.initData = undefined; return; } var initData = this.initData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["parseInitSegment"])(initSegment); // Get codec from initSegment or fallback to default if (!audioCodec) { audioCodec = getParsedTrackCodec(initData.audio, _loader_fragment__WEBPACK_IMPORTED_MODULE_2__["ElementaryStreamTypes"].AUDIO); } if (!videoCodec) { videoCodec = getParsedTrackCodec(initData.video, _loader_fragment__WEBPACK_IMPORTED_MODULE_2__["ElementaryStreamTypes"].VIDEO); } var tracks = {}; if (initData.audio && initData.video) { tracks.audiovideo = { container: 'video/mp4', codec: audioCodec + ',' + videoCodec, initSegment: initSegment, id: 'main' }; } else if (initData.audio) { tracks.audio = { container: 'audio/mp4', codec: audioCodec, initSegment: initSegment, id: 'audio' }; } else if (initData.video) { tracks.video = { container: 'video/mp4', codec: videoCodec, initSegment: initSegment, id: 'main' }; } else { _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes.'); } this.initTracks = tracks; }; _proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset) { var initPTS = this.initPTS, lastEndDTS = this.lastEndDTS; var result = { audio: undefined, video: undefined, text: textTrack, id3: id3Track, initSegment: undefined }; // If we haven't yet set a lastEndDTS, or it was reset, set it to the provided timeOffset. We want to use the // lastEndDTS over timeOffset whenever possible; during progressive playback, the media source will not update // the media duration (which is what timeOffset is provided as) before we need to process the next chunk. if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(lastEndDTS)) { lastEndDTS = this.lastEndDTS = timeOffset || 0; } // The binary segment data is added to the videoTrack in the mp4demuxer. We don't check to see if the data is only // audio or video (or both); adding it to video was an arbitrary choice. var data = videoTrack.samples; if (!data || !data.length) { return result; } var initSegment = { initPTS: undefined, timescale: 1 }; var initData = this.initData; if (!initData || !initData.length) { this.generateInitSegment(data); initData = this.initData; } if (!initData || !initData.length) { // We can't remux if the initSegment could not be generated _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('[passthrough-remuxer.ts]: Failed to generate initSegment.'); return result; } if (this.emitInitSegment) { initSegment.tracks = this.initTracks; this.emitInitSegment = false; } if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(initPTS)) { this.initPTS = initSegment.initPTS = initPTS = computeInitPTS(initData, data, lastEndDTS); } var duration = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["getDuration"])(data, initData); var startDTS = lastEndDTS; var endDTS = duration + startDTS; Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["offsetStartDTS"])(initData, data, initPTS); if (duration > 0) { this.lastEndDTS = endDTS; } else { _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Duration parsed from mp4 should be greater than zero'); this.resetNextTimestamp(); } var hasAudio = !!initData.audio; var hasVideo = !!initData.video; var type = ''; if (hasAudio) { type += 'audio'; } if (hasVideo) { type += 'video'; } var track = { data1: data, startPTS: startDTS, startDTS: startDTS, endPTS: endDTS, endDTS: endDTS, type: type, hasAudio: hasAudio, hasVideo: hasVideo, nb: 1, dropped: 0 }; result.audio = track.type === 'audio' ? track : undefined; result.video = track.type !== 'audio' ? track : undefined; result.text = textTrack; result.id3 = id3Track; result.initSegment = initSegment; return result; }; return PassThroughRemuxer; }(); var computeInitPTS = function computeInitPTS(initData, data, timeOffset) { return Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["getStartDTS"])(initData, data) - timeOffset; }; function getParsedTrackCodec(track, type) { var parsedCodec = track === null || track === void 0 ? void 0 : track.codec; if (parsedCodec && parsedCodec.length > 4) { return parsedCodec; } // Since mp4-tools cannot parse full codec string (see 'TODO: Parse codec details'... in mp4-tools) // Provide defaults based on codec type // This allows for some playback of some fmp4 playlists without CODECS defined in manifest if (parsedCodec === 'hvc1') { return 'hvc1.1.c.L120.90'; } if (parsedCodec === 'av01') { return 'av01.0.04M.08'; } if (parsedCodec === 'avc1' || type === _loader_fragment__WEBPACK_IMPORTED_MODULE_2__["ElementaryStreamTypes"].VIDEO) { return 'avc1.42e01e'; } return 'mp4a.40.5'; } /* harmony default export */ __webpack_exports__["default"] = (PassThroughRemuxer); /***/ }), /***/ "./src/task-loop.ts": /*!**************************!*\ !*** ./src/task-loop.ts ***! \**************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TaskLoop; }); /** * Sub-class specialization of EventHandler base class. * * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop, * scheduled asynchroneously, avoiding recursive calls in the same tick. * * The task itself is implemented in `doTick`. It can be requested and called for single execution * using the `tick` method. * * It will be assured that the task execution method (`tick`) only gets called once per main loop "tick", * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly. * * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`, * and cancelled with `clearNextTick`. * * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`). * * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine. * * Further explanations: * * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks. * * When the task execution (`tick` method) is called in re-entrant way this is detected and * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further * task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo). */ var TaskLoop = /*#__PURE__*/function () { function TaskLoop() { this._boundTick = void 0; this._tickTimer = null; this._tickInterval = null; this._tickCallCount = 0; this._boundTick = this.tick.bind(this); } var _proto = TaskLoop.prototype; _proto.destroy = function destroy() { this.onHandlerDestroying(); this.onHandlerDestroyed(); }; _proto.onHandlerDestroying = function onHandlerDestroying() { // clear all timers before unregistering from event bus this.clearNextTick(); this.clearInterval(); }; _proto.onHandlerDestroyed = function onHandlerDestroyed() {} /** * @returns {boolean} */ ; _proto.hasInterval = function hasInterval() { return !!this._tickInterval; } /** * @returns {boolean} */ ; _proto.hasNextTick = function hasNextTick() { return !!this._tickTimer; } /** * @param {number} millis Interval time (ms) * @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect) */ ; _proto.setInterval = function setInterval(millis) { if (!this._tickInterval) { this._tickInterval = self.setInterval(this._boundTick, millis); return true; } return false; } /** * @returns {boolean} True when interval was cleared, false when none was set (no effect) */ ; _proto.clearInterval = function clearInterval() { if (this._tickInterval) { self.clearInterval(this._tickInterval); this._tickInterval = null; return true; } return false; } /** * @returns {boolean} True when timeout was cleared, false when none was set (no effect) */ ; _proto.clearNextTick = function clearNextTick() { if (this._tickTimer) { self.clearTimeout(this._tickTimer); this._tickTimer = null; return true; } return false; } /** * Will call the subclass doTick implementation in this main loop tick * or in the next one (via setTimeout(,0)) in case it has already been called * in this tick (in case this is a re-entrant call). */ ; _proto.tick = function tick() { this._tickCallCount++; if (this._tickCallCount === 1) { this.doTick(); // re-entrant call to tick from previous doTick call stack // -> schedule a call on the next main loop iteration to process this task processing request if (this._tickCallCount > 1) { // make sure only one timer exists at any time at max this.tickImmediate(); } this._tickCallCount = 0; } }; _proto.tickImmediate = function tickImmediate() { this.clearNextTick(); this._tickTimer = self.setTimeout(this._boundTick, 0); } /** * For subclass to implement task logic * @abstract */ ; _proto.doTick = function doTick() {}; return TaskLoop; }(); /***/ }), /***/ "./src/types/level.ts": /*!****************************!*\ !*** ./src/types/level.ts ***! \****************************/ /*! exports provided: HlsSkip, getSkipValue, HlsUrlParameters, Level */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HlsSkip", function() { return HlsSkip; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getSkipValue", function() { return getSkipValue; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HlsUrlParameters", function() { return HlsUrlParameters; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Level", function() { return Level; }); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var HlsSkip; (function (HlsSkip) { HlsSkip["No"] = ""; HlsSkip["Yes"] = "YES"; HlsSkip["v2"] = "v2"; })(HlsSkip || (HlsSkip = {})); function getSkipValue(details, msn) { var canSkipUntil = details.canSkipUntil, canSkipDateRanges = details.canSkipDateRanges, endSN = details.endSN; var snChangeGoal = msn !== undefined ? msn - endSN : 0; if (canSkipUntil && snChangeGoal < canSkipUntil) { if (canSkipDateRanges) { return HlsSkip.v2; } return HlsSkip.Yes; } return HlsSkip.No; } var HlsUrlParameters = /*#__PURE__*/function () { function HlsUrlParameters(msn, part, skip) { this.msn = void 0; this.part = void 0; this.skip = void 0; this.msn = msn; this.part = part; this.skip = skip; } var _proto = HlsUrlParameters.prototype; _proto.addDirectives = function addDirectives(uri) { var url = new self.URL(uri); if (this.msn !== undefined) { url.searchParams.set('_HLS_msn', this.msn.toString()); } if (this.part !== undefined) { url.searchParams.set('_HLS_part', this.part.toString()); } if (this.skip) { url.searchParams.set('_HLS_skip', this.skip); } return url.toString(); }; return HlsUrlParameters; }(); var Level = /*#__PURE__*/function () { function Level(data) { this.attrs = void 0; this.audioCodec = void 0; this.bitrate = void 0; this.codecSet = void 0; this.height = void 0; this.id = void 0; this.name = void 0; this.videoCodec = void 0; this.width = void 0; this.unknownCodecs = void 0; this.audioGroupIds = void 0; this.details = void 0; this.fragmentError = 0; this.loadError = 0; this.loaded = void 0; this.realBitrate = 0; this.textGroupIds = void 0; this.url = void 0; this._urlId = 0; this.url = [data.url]; this.attrs = data.attrs; this.bitrate = data.bitrate; if (data.details) { this.details = data.details; } this.id = data.id || 0; this.name = data.name; this.width = data.width || 0; this.height = data.height || 0; this.audioCodec = data.audioCodec; this.videoCodec = data.videoCodec; this.unknownCodecs = data.unknownCodecs; this.codecSet = [data.videoCodec, data.audioCodec].filter(function (c) { return c; }).join(',').replace(/\.[^.,]+/g, ''); } _createClass(Level, [{ key: "maxBitrate", get: function get() { return Math.max(this.realBitrate, this.bitrate); } }, { key: "uri", get: function get() { return this.url[this._urlId] || ''; } }, { key: "urlId", get: function get() { return this._urlId; }, set: function set(value) { var newValue = value % this.url.length; if (this._urlId !== newValue) { this.details = undefined; this._urlId = newValue; } } }]); return Level; }(); /***/ }), /***/ "./src/types/loader.ts": /*!*****************************!*\ !*** ./src/types/loader.ts ***! \*****************************/ /*! exports provided: PlaylistContextType, PlaylistLevelType */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaylistContextType", function() { return PlaylistContextType; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaylistLevelType", function() { return PlaylistLevelType; }); var PlaylistContextType; (function (PlaylistContextType) { PlaylistContextType["MANIFEST"] = "manifest"; PlaylistContextType["LEVEL"] = "level"; PlaylistContextType["AUDIO_TRACK"] = "audioTrack"; PlaylistContextType["SUBTITLE_TRACK"] = "subtitleTrack"; })(PlaylistContextType || (PlaylistContextType = {})); var PlaylistLevelType; (function (PlaylistLevelType) { PlaylistLevelType["MAIN"] = "main"; PlaylistLevelType["AUDIO"] = "audio"; PlaylistLevelType["SUBTITLE"] = "subtitle"; })(PlaylistLevelType || (PlaylistLevelType = {})); /***/ }), /***/ "./src/types/transmuxer.ts": /*!*********************************!*\ !*** ./src/types/transmuxer.ts ***! \*********************************/ /*! exports provided: ChunkMetadata */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ChunkMetadata", function() { return ChunkMetadata; }); var ChunkMetadata = function ChunkMetadata(level, sn, id, size, part, partial) { if (size === void 0) { size = 0; } if (part === void 0) { part = -1; } if (partial === void 0) { partial = false; } this.level = void 0; this.sn = void 0; this.part = void 0; this.id = void 0; this.size = void 0; this.partial = void 0; this.transmuxing = getNewPerformanceTiming(); this.buffering = { audio: getNewPerformanceTiming(), video: getNewPerformanceTiming(), audiovideo: getNewPerformanceTiming() }; this.level = level; this.sn = sn; this.id = id; this.size = size; this.part = part; this.partial = partial; }; function getNewPerformanceTiming() { return { start: 0, executeStart: 0, executeEnd: 0, end: 0 }; } /***/ }), /***/ "./src/utils/attr-list.ts": /*!********************************!*\ !*** ./src/utils/attr-list.ts ***! \********************************/ /*! exports provided: AttrList */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AttrList", function() { return AttrList; }); var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/; // eslint-disable-line no-useless-escape var ATTR_LIST_REGEX = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape // adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js var AttrList = /*#__PURE__*/function () { function AttrList(attrs) { if (typeof attrs === 'string') { attrs = AttrList.parseAttrList(attrs); } for (var attr in attrs) { if (attrs.hasOwnProperty(attr)) { this[attr] = attrs[attr]; } } } var _proto = AttrList.prototype; _proto.decimalInteger = function decimalInteger(attrName) { var intValue = parseInt(this[attrName], 10); if (intValue > Number.MAX_SAFE_INTEGER) { return Infinity; } return intValue; }; _proto.hexadecimalInteger = function hexadecimalInteger(attrName) { if (this[attrName]) { var stringValue = (this[attrName] || '0x').slice(2); stringValue = (stringValue.length & 1 ? '0' : '') + stringValue; var value = new Uint8Array(stringValue.length / 2); for (var i = 0; i < stringValue.length / 2; i++) { value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16); } return value; } else { return null; } }; _proto.hexadecimalIntegerAsNumber = function hexadecimalIntegerAsNumber(attrName) { var intValue = parseInt(this[attrName], 16); if (intValue > Number.MAX_SAFE_INTEGER) { return Infinity; } return intValue; }; _proto.decimalFloatingPoint = function decimalFloatingPoint(attrName) { return parseFloat(this[attrName]); }; _proto.optionalFloat = function optionalFloat(attrName, defaultValue) { var value = this[attrName]; return value ? parseFloat(value) : defaultValue; }; _proto.enumeratedString = function enumeratedString(attrName) { return this[attrName]; }; _proto.bool = function bool(attrName) { return this[attrName] === 'YES'; }; _proto.decimalResolution = function decimalResolution(attrName) { var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]); if (res === null) { return undefined; } return { width: parseInt(res[1], 10), height: parseInt(res[2], 10) }; }; AttrList.parseAttrList = function parseAttrList(input) { var match; var attrs = {}; var quote = '"'; ATTR_LIST_REGEX.lastIndex = 0; while ((match = ATTR_LIST_REGEX.exec(input)) !== null) { var value = match[2]; if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) { value = value.slice(1, -1); } attrs[match[1]] = value; } return attrs; }; return AttrList; }(); /***/ }), /***/ "./src/utils/binary-search.ts": /*!************************************!*\ !*** ./src/utils/binary-search.ts ***! \************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); var BinarySearch = { /** * Searches for an item in an array which matches a certain condition. * This requires the condition to only match one item in the array, * and for the array to be ordered. * * @param {Array<T>} list The array to search. * @param {BinarySearchComparison<T>} comparisonFn * Called and provided a candidate item as the first argument. * Should return: * > -1 if the item should be located at a lower index than the provided item. * > 1 if the item should be located at a higher index than the provided item. * > 0 if the item is the item you're looking for. * * @return {T | null} The object if it is found or null otherwise. */ search: function search(list, comparisonFn) { var minIndex = 0; var maxIndex = list.length - 1; var currentIndex = null; var currentElement = null; while (minIndex <= maxIndex) { currentIndex = (minIndex + maxIndex) / 2 | 0; currentElement = list[currentIndex]; var comparisonResult = comparisonFn(currentElement); if (comparisonResult > 0) { minIndex = currentIndex + 1; } else if (comparisonResult < 0) { maxIndex = currentIndex - 1; } else { return currentElement; } } return null; } }; /* harmony default export */ __webpack_exports__["default"] = (BinarySearch); /***/ }), /***/ "./src/utils/buffer-helper.ts": /*!************************************!*\ !*** ./src/utils/buffer-helper.ts ***! \************************************/ /*! exports provided: BufferHelper */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BufferHelper", function() { return BufferHelper; }); /* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./logger */ "./src/utils/logger.ts"); /** * @module BufferHelper * * Providing methods dealing with buffer length retrieval for example. * * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property. * * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered */ var noopBuffered = { length: 0, start: function start() { return 0; }, end: function end() { return 0; } }; var BufferHelper = /*#__PURE__*/function () { function BufferHelper() {} /** * Return true if `media`'s buffered include `position` * @param {Bufferable} media * @param {number} position * @returns {boolean} */ BufferHelper.isBuffered = function isBuffered(media, position) { try { if (media) { var buffered = BufferHelper.getBuffered(media); for (var i = 0; i < buffered.length; i++) { if (position >= buffered.start(i) && position <= buffered.end(i)) { return true; } } } } catch (error) {// this is to catch // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer': // This SourceBuffer has been removed from the parent media source } return false; }; BufferHelper.bufferInfo = function bufferInfo(media, pos, maxHoleDuration) { try { if (media) { var vbuffered = BufferHelper.getBuffered(media); var buffered = []; var i; for (i = 0; i < vbuffered.length; i++) { buffered.push({ start: vbuffered.start(i), end: vbuffered.end(i) }); } return this.bufferedInfo(buffered, pos, maxHoleDuration); } } catch (error) {// this is to catch // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer': // This SourceBuffer has been removed from the parent media source } return { len: 0, start: pos, end: pos, nextStart: undefined }; }; BufferHelper.bufferedInfo = function bufferedInfo(buffered, pos, maxHoleDuration) { pos = Math.max(0, pos); // sort on buffer.start/smaller end (IE does not always return sorted buffered range) buffered.sort(function (a, b) { var diff = a.start - b.start; if (diff) { return diff; } else { return b.end - a.end; } }); var buffered2 = []; if (maxHoleDuration) { // there might be some small holes between buffer time range // consider that holes smaller than maxHoleDuration are irrelevant and build another // buffer time range representations that discards those holes for (var i = 0; i < buffered.length; i++) { var buf2len = buffered2.length; if (buf2len) { var buf2end = buffered2[buf2len - 1].end; // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative) if (buffered[i].start - buf2end < maxHoleDuration) { // merge overlapping time ranges // update lastRange.end only if smaller than item.end // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end) // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15]) if (buffered[i].end > buf2end) { buffered2[buf2len - 1].end = buffered[i].end; } } else { // big hole buffered2.push(buffered[i]); } } else { // first value buffered2.push(buffered[i]); } } } else { buffered2 = buffered; } var bufferLen = 0; // bufferStartNext can possibly be undefined based on the conditional logic below var bufferStartNext; // bufferStart and bufferEnd are buffer boundaries around current video position var bufferStart = pos; var bufferEnd = pos; for (var _i = 0; _i < buffered2.length; _i++) { var start = buffered2[_i].start; var end = buffered2[_i].end; // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i)); if (pos + maxHoleDuration >= start && pos < end) { // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length bufferStart = start; bufferEnd = end; bufferLen = bufferEnd - pos; } else if (pos + maxHoleDuration < start) { bufferStartNext = start; break; } } return { len: bufferLen, start: bufferStart || 0, end: bufferEnd || 0, nextStart: bufferStartNext }; } /** * Safe method to get buffered property. * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource */ ; BufferHelper.getBuffered = function getBuffered(media) { try { return media.buffered; } catch (e) { _logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log('failed to get media.buffered', e); return noopBuffered; } }; return BufferHelper; }(); /***/ }), /***/ "./src/utils/cea-608-parser.ts": /*!*************************************!*\ !*** ./src/utils/cea-608-parser.ts ***! \*************************************/ /*! exports provided: Row, CaptionScreen, default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Row", function() { return Row; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CaptionScreen", function() { return CaptionScreen; }); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /** * * This code was ported from the dash.js project at: * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2 * * The original copyright appears below: * * The copyright in this software is being made available under the BSD License, * included below. This software may be subject to other third party and contributor * rights, including patent rights, and no such rights are granted under this license. * * Copyright (c) 2015-2016, DASH Industry Forum. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * 2. Neither the name of Dash Industry Forum nor the names of its * contributors may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes */ var specialCea608CharsCodes = { 0x2a: 0xe1, // lowercase a, acute accent 0x5c: 0xe9, // lowercase e, acute accent 0x5e: 0xed, // lowercase i, acute accent 0x5f: 0xf3, // lowercase o, acute accent 0x60: 0xfa, // lowercase u, acute accent 0x7b: 0xe7, // lowercase c with cedilla 0x7c: 0xf7, // division symbol 0x7d: 0xd1, // uppercase N tilde 0x7e: 0xf1, // lowercase n tilde 0x7f: 0x2588, // Full block // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES 0x80: 0xae, // Registered symbol (R) 0x81: 0xb0, // degree sign 0x82: 0xbd, // 1/2 symbol 0x83: 0xbf, // Inverted (open) question mark 0x84: 0x2122, // Trademark symbol (TM) 0x85: 0xa2, // Cents symbol 0x86: 0xa3, // Pounds sterling 0x87: 0x266a, // Music 8'th note 0x88: 0xe0, // lowercase a, grave accent 0x89: 0x20, // transparent space (regular) 0x8a: 0xe8, // lowercase e, grave accent 0x8b: 0xe2, // lowercase a, circumflex accent 0x8c: 0xea, // lowercase e, circumflex accent 0x8d: 0xee, // lowercase i, circumflex accent 0x8e: 0xf4, // lowercase o, circumflex accent 0x8f: 0xfb, // lowercase u, circumflex accent // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F 0x90: 0xc1, // capital letter A with acute 0x91: 0xc9, // capital letter E with acute 0x92: 0xd3, // capital letter O with acute 0x93: 0xda, // capital letter U with acute 0x94: 0xdc, // capital letter U with diaresis 0x95: 0xfc, // lowercase letter U with diaeresis 0x96: 0x2018, // opening single quote 0x97: 0xa1, // inverted exclamation mark 0x98: 0x2a, // asterisk 0x99: 0x2019, // closing single quote 0x9a: 0x2501, // box drawings heavy horizontal 0x9b: 0xa9, // copyright sign 0x9c: 0x2120, // Service mark 0x9d: 0x2022, // (round) bullet 0x9e: 0x201c, // Left double quotation mark 0x9f: 0x201d, // Right double quotation mark 0xa0: 0xc0, // uppercase A, grave accent 0xa1: 0xc2, // uppercase A, circumflex 0xa2: 0xc7, // uppercase C with cedilla 0xa3: 0xc8, // uppercase E, grave accent 0xa4: 0xca, // uppercase E, circumflex 0xa5: 0xcb, // capital letter E with diaresis 0xa6: 0xeb, // lowercase letter e with diaresis 0xa7: 0xce, // uppercase I, circumflex 0xa8: 0xcf, // uppercase I, with diaresis 0xa9: 0xef, // lowercase i, with diaresis 0xaa: 0xd4, // uppercase O, circumflex 0xab: 0xd9, // uppercase U, grave accent 0xac: 0xf9, // lowercase u, grave accent 0xad: 0xdb, // uppercase U, circumflex 0xae: 0xab, // left-pointing double angle quotation mark 0xaf: 0xbb, // right-pointing double angle quotation mark // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F 0xb0: 0xc3, // Uppercase A, tilde 0xb1: 0xe3, // Lowercase a, tilde 0xb2: 0xcd, // Uppercase I, acute accent 0xb3: 0xcc, // Uppercase I, grave accent 0xb4: 0xec, // Lowercase i, grave accent 0xb5: 0xd2, // Uppercase O, grave accent 0xb6: 0xf2, // Lowercase o, grave accent 0xb7: 0xd5, // Uppercase O, tilde 0xb8: 0xf5, // Lowercase o, tilde 0xb9: 0x7b, // Open curly brace 0xba: 0x7d, // Closing curly brace 0xbb: 0x5c, // Backslash 0xbc: 0x5e, // Caret 0xbd: 0x5f, // Underscore 0xbe: 0x7c, // Pipe (vertical line) 0xbf: 0x223c, // Tilde operator 0xc0: 0xc4, // Uppercase A, umlaut 0xc1: 0xe4, // Lowercase A, umlaut 0xc2: 0xd6, // Uppercase O, umlaut 0xc3: 0xf6, // Lowercase o, umlaut 0xc4: 0xdf, // Esszett (sharp S) 0xc5: 0xa5, // Yen symbol 0xc6: 0xa4, // Generic currency sign 0xc7: 0x2503, // Box drawings heavy vertical 0xc8: 0xc5, // Uppercase A, ring 0xc9: 0xe5, // Lowercase A, ring 0xca: 0xd8, // Uppercase O, stroke 0xcb: 0xf8, // Lowercase o, strok 0xcc: 0x250f, // Box drawings heavy down and right 0xcd: 0x2513, // Box drawings heavy down and left 0xce: 0x2517, // Box drawings heavy up and right 0xcf: 0x251b // Box drawings heavy up and left }; /** * Utils */ var getCharForByte = function getCharForByte(_byte) { var charCode = _byte; if (specialCea608CharsCodes.hasOwnProperty(_byte)) { charCode = specialCea608CharsCodes[_byte]; } return String.fromCharCode(charCode); }; var NR_ROWS = 15; var NR_COLS = 100; // Tables to look up row from PAC data var rowsLowCh1 = { 0x11: 1, 0x12: 3, 0x15: 5, 0x16: 7, 0x17: 9, 0x10: 11, 0x13: 12, 0x14: 14 }; var rowsHighCh1 = { 0x11: 2, 0x12: 4, 0x15: 6, 0x16: 8, 0x17: 10, 0x13: 13, 0x14: 15 }; var rowsLowCh2 = { 0x19: 1, 0x1a: 3, 0x1d: 5, 0x1e: 7, 0x1f: 9, 0x18: 11, 0x1b: 12, 0x1c: 14 }; var rowsHighCh2 = { 0x19: 2, 0x1a: 4, 0x1d: 6, 0x1e: 8, 0x1f: 10, 0x1b: 13, 0x1c: 15 }; var backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent']; var VerboseLevel; (function (VerboseLevel) { VerboseLevel[VerboseLevel["ERROR"] = 0] = "ERROR"; VerboseLevel[VerboseLevel["TEXT"] = 1] = "TEXT"; VerboseLevel[VerboseLevel["WARNING"] = 2] = "WARNING"; VerboseLevel[VerboseLevel["INFO"] = 2] = "INFO"; VerboseLevel[VerboseLevel["DEBUG"] = 3] = "DEBUG"; VerboseLevel[VerboseLevel["DATA"] = 3] = "DATA"; })(VerboseLevel || (VerboseLevel = {})); var CaptionsLogger = /*#__PURE__*/function () { function CaptionsLogger() { this.time = null; this.verboseLevel = VerboseLevel.ERROR; } var _proto = CaptionsLogger.prototype; _proto.log = function log(severity, msg) { if (this.verboseLevel >= severity) { _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log(this.time + " [" + severity + "] " + msg); } }; return CaptionsLogger; }(); var numArrayToHexArray = function numArrayToHexArray(numArray) { var hexArray = []; for (var j = 0; j < numArray.length; j++) { hexArray.push(numArray[j].toString(16)); } return hexArray; }; var PenState = /*#__PURE__*/function () { function PenState(foreground, underline, italics, background, flash) { this.foreground = void 0; this.underline = void 0; this.italics = void 0; this.background = void 0; this.flash = void 0; this.foreground = foreground || 'white'; this.underline = underline || false; this.italics = italics || false; this.background = background || 'black'; this.flash = flash || false; } var _proto2 = PenState.prototype; _proto2.reset = function reset() { this.foreground = 'white'; this.underline = false; this.italics = false; this.background = 'black'; this.flash = false; }; _proto2.setStyles = function setStyles(styles) { var attribs = ['foreground', 'underline', 'italics', 'background', 'flash']; for (var i = 0; i < attribs.length; i++) { var style = attribs[i]; if (styles.hasOwnProperty(style)) { this[style] = styles[style]; } } }; _proto2.isDefault = function isDefault() { return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash; }; _proto2.equals = function equals(other) { return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash; }; _proto2.copy = function copy(newPenState) { this.foreground = newPenState.foreground; this.underline = newPenState.underline; this.italics = newPenState.italics; this.background = newPenState.background; this.flash = newPenState.flash; }; _proto2.toString = function toString() { return 'color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics + ', background=' + this.background + ', flash=' + this.flash; }; return PenState; }(); /** * Unicode character with styling and background. * @constructor */ var StyledUnicodeChar = /*#__PURE__*/function () { function StyledUnicodeChar(uchar, foreground, underline, italics, background, flash) { this.uchar = void 0; this.penState = void 0; this.uchar = uchar || ' '; // unicode character this.penState = new PenState(foreground, underline, italics, background, flash); } var _proto3 = StyledUnicodeChar.prototype; _proto3.reset = function reset() { this.uchar = ' '; this.penState.reset(); }; _proto3.setChar = function setChar(uchar, newPenState) { this.uchar = uchar; this.penState.copy(newPenState); }; _proto3.setPenState = function setPenState(newPenState) { this.penState.copy(newPenState); }; _proto3.equals = function equals(other) { return this.uchar === other.uchar && this.penState.equals(other.penState); }; _proto3.copy = function copy(newChar) { this.uchar = newChar.uchar; this.penState.copy(newChar.penState); }; _proto3.isEmpty = function isEmpty() { return this.uchar === ' ' && this.penState.isDefault(); }; return StyledUnicodeChar; }(); /** * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar. * @constructor */ var Row = /*#__PURE__*/function () { function Row(logger) { this.chars = void 0; this.pos = void 0; this.currPenState = void 0; this.cueStartTime = void 0; this.logger = void 0; this.chars = []; for (var i = 0; i < NR_COLS; i++) { this.chars.push(new StyledUnicodeChar()); } this.logger = logger; this.pos = 0; this.currPenState = new PenState(); } var _proto4 = Row.prototype; _proto4.equals = function equals(other) { var equal = true; for (var i = 0; i < NR_COLS; i++) { if (!this.chars[i].equals(other.chars[i])) { equal = false; break; } } return equal; }; _proto4.copy = function copy(other) { for (var i = 0; i < NR_COLS; i++) { this.chars[i].copy(other.chars[i]); } }; _proto4.isEmpty = function isEmpty() { var empty = true; for (var i = 0; i < NR_COLS; i++) { if (!this.chars[i].isEmpty()) { empty = false; break; } } return empty; } /** * Set the cursor to a valid column. */ ; _proto4.setCursor = function setCursor(absPos) { if (this.pos !== absPos) { this.pos = absPos; } if (this.pos < 0) { this.logger.log(VerboseLevel.DEBUG, 'Negative cursor position ' + this.pos); this.pos = 0; } else if (this.pos > NR_COLS) { this.logger.log(VerboseLevel.DEBUG, 'Too large cursor position ' + this.pos); this.pos = NR_COLS; } } /** * Move the cursor relative to current position. */ ; _proto4.moveCursor = function moveCursor(relPos) { var newPos = this.pos + relPos; if (relPos > 1) { for (var i = this.pos + 1; i < newPos + 1; i++) { this.chars[i].setPenState(this.currPenState); } } this.setCursor(newPos); } /** * Backspace, move one step back and clear character. */ ; _proto4.backSpace = function backSpace() { this.moveCursor(-1); this.chars[this.pos].setChar(' ', this.currPenState); }; _proto4.insertChar = function insertChar(_byte2) { if (_byte2 >= 0x90) { // Extended char this.backSpace(); } var _char = getCharForByte(_byte2); if (this.pos >= NR_COLS) { this.logger.log(VerboseLevel.ERROR, 'Cannot insert ' + _byte2.toString(16) + ' (' + _char + ') at position ' + this.pos + '. Skipping it!'); return; } this.chars[this.pos].setChar(_char, this.currPenState); this.moveCursor(1); }; _proto4.clearFromPos = function clearFromPos(startPos) { var i; for (i = startPos; i < NR_COLS; i++) { this.chars[i].reset(); } }; _proto4.clear = function clear() { this.clearFromPos(0); this.pos = 0; this.currPenState.reset(); }; _proto4.clearToEndOfRow = function clearToEndOfRow() { this.clearFromPos(this.pos); }; _proto4.getTextString = function getTextString() { var chars = []; var empty = true; for (var i = 0; i < NR_COLS; i++) { var _char2 = this.chars[i].uchar; if (_char2 !== ' ') { empty = false; } chars.push(_char2); } if (empty) { return ''; } else { return chars.join(''); } }; _proto4.setPenStyles = function setPenStyles(styles) { this.currPenState.setStyles(styles); var currChar = this.chars[this.pos]; currChar.setPenState(this.currPenState); }; return Row; }(); /** * Keep a CEA-608 screen of 32x15 styled characters * @constructor */ var CaptionScreen = /*#__PURE__*/function () { function CaptionScreen(logger) { this.rows = void 0; this.currRow = void 0; this.nrRollUpRows = void 0; this.lastOutputScreen = void 0; this.logger = void 0; this.rows = []; for (var i = 0; i < NR_ROWS; i++) { this.rows.push(new Row(logger)); } // Note that we use zero-based numbering (0-14) this.logger = logger; this.currRow = NR_ROWS - 1; this.nrRollUpRows = null; this.lastOutputScreen = null; this.reset(); } var _proto5 = CaptionScreen.prototype; _proto5.reset = function reset() { for (var i = 0; i < NR_ROWS; i++) { this.rows[i].clear(); } this.currRow = NR_ROWS - 1; }; _proto5.equals = function equals(other) { var equal = true; for (var i = 0; i < NR_ROWS; i++) { if (!this.rows[i].equals(other.rows[i])) { equal = false; break; } } return equal; }; _proto5.copy = function copy(other) { for (var i = 0; i < NR_ROWS; i++) { this.rows[i].copy(other.rows[i]); } }; _proto5.isEmpty = function isEmpty() { var empty = true; for (var i = 0; i < NR_ROWS; i++) { if (!this.rows[i].isEmpty()) { empty = false; break; } } return empty; }; _proto5.backSpace = function backSpace() { var row = this.rows[this.currRow]; row.backSpace(); }; _proto5.clearToEndOfRow = function clearToEndOfRow() { var row = this.rows[this.currRow]; row.clearToEndOfRow(); } /** * Insert a character (without styling) in the current row. */ ; _proto5.insertChar = function insertChar(_char3) { var row = this.rows[this.currRow]; row.insertChar(_char3); }; _proto5.setPen = function setPen(styles) { var row = this.rows[this.currRow]; row.setPenStyles(styles); }; _proto5.moveCursor = function moveCursor(relPos) { var row = this.rows[this.currRow]; row.moveCursor(relPos); }; _proto5.setCursor = function setCursor(absPos) { this.logger.log(VerboseLevel.INFO, 'setCursor: ' + absPos); var row = this.rows[this.currRow]; row.setCursor(absPos); }; _proto5.setPAC = function setPAC(pacData) { this.logger.log(VerboseLevel.INFO, 'pacData = ' + JSON.stringify(pacData)); var newRow = pacData.row - 1; if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) { newRow = this.nrRollUpRows - 1; } // Make sure this only affects Roll-up Captions by checking this.nrRollUpRows if (this.nrRollUpRows && this.currRow !== newRow) { // clear all rows first for (var i = 0; i < NR_ROWS; i++) { this.rows[i].clear(); } // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location // topRowIndex - the start of rows to copy (inclusive index) var topRowIndex = this.currRow + 1 - this.nrRollUpRows; // We only copy if the last position was already shown. // We use the cueStartTime value to check this. var lastOutputScreen = this.lastOutputScreen; if (lastOutputScreen) { var prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime; var time = this.logger.time; if (prevLineTime && time !== null && prevLineTime < time) { for (var _i = 0; _i < this.nrRollUpRows; _i++) { this.rows[newRow - this.nrRollUpRows + _i + 1].copy(lastOutputScreen.rows[topRowIndex + _i]); } } } } this.currRow = newRow; var row = this.rows[this.currRow]; if (pacData.indent !== null) { var indent = pacData.indent; var prevPos = Math.max(indent - 1, 0); row.setCursor(pacData.indent); pacData.color = row.chars[prevPos].penState.foreground; } var styles = { foreground: pacData.color, underline: pacData.underline, italics: pacData.italics, background: 'black', flash: false }; this.setPen(styles); } /** * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility). */ ; _proto5.setBkgData = function setBkgData(bkgData) { this.logger.log(VerboseLevel.INFO, 'bkgData = ' + JSON.stringify(bkgData)); this.backSpace(); this.setPen(bkgData); this.insertChar(0x20); // Space }; _proto5.setRollUpRows = function setRollUpRows(nrRows) { this.nrRollUpRows = nrRows; }; _proto5.rollUp = function rollUp() { if (this.nrRollUpRows === null) { this.logger.log(VerboseLevel.DEBUG, 'roll_up but nrRollUpRows not set yet'); return; // Not properly setup } this.logger.log(VerboseLevel.TEXT, this.getDisplayText()); var topRowIndex = this.currRow + 1 - this.nrRollUpRows; var topRow = this.rows.splice(topRowIndex, 1)[0]; topRow.clear(); this.rows.splice(this.currRow, 0, topRow); this.logger.log(VerboseLevel.INFO, 'Rolling up'); // this.logger.log(VerboseLevel.TEXT, this.get_display_text()) } /** * Get all non-empty rows with as unicode text. */ ; _proto5.getDisplayText = function getDisplayText(asOneRow) { asOneRow = asOneRow || false; var displayText = []; var text = ''; var rowNr = -1; for (var i = 0; i < NR_ROWS; i++) { var rowText = this.rows[i].getTextString(); if (rowText) { rowNr = i + 1; if (asOneRow) { displayText.push('Row ' + rowNr + ": '" + rowText + "'"); } else { displayText.push(rowText.trim()); } } } if (displayText.length > 0) { if (asOneRow) { text = '[' + displayText.join(' | ') + ']'; } else { text = displayText.join('\n'); } } return text; }; _proto5.getTextAndFormat = function getTextAndFormat() { return this.rows; }; return CaptionScreen; }(); // var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT']; var Cea608Channel = /*#__PURE__*/function () { function Cea608Channel(channelNumber, outputFilter, logger) { this.chNr = void 0; this.outputFilter = void 0; this.mode = void 0; this.verbose = void 0; this.displayedMemory = void 0; this.nonDisplayedMemory = void 0; this.lastOutputScreen = void 0; this.currRollUpRow = void 0; this.writeScreen = void 0; this.cueStartTime = void 0; this.logger = void 0; this.chNr = channelNumber; this.outputFilter = outputFilter; this.mode = null; this.verbose = 0; this.displayedMemory = new CaptionScreen(logger); this.nonDisplayedMemory = new CaptionScreen(logger); this.lastOutputScreen = new CaptionScreen(logger); this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1]; this.writeScreen = this.displayedMemory; this.mode = null; this.cueStartTime = null; // Keeps track of where a cue started. this.logger = logger; } var _proto6 = Cea608Channel.prototype; _proto6.reset = function reset() { this.mode = null; this.displayedMemory.reset(); this.nonDisplayedMemory.reset(); this.lastOutputScreen.reset(); this.outputFilter.reset(); this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1]; this.writeScreen = this.displayedMemory; this.mode = null; this.cueStartTime = null; }; _proto6.getHandler = function getHandler() { return this.outputFilter; }; _proto6.setHandler = function setHandler(newHandler) { this.outputFilter = newHandler; }; _proto6.setPAC = function setPAC(pacData) { this.writeScreen.setPAC(pacData); }; _proto6.setBkgData = function setBkgData(bkgData) { this.writeScreen.setBkgData(bkgData); }; _proto6.setMode = function setMode(newMode) { if (newMode === this.mode) { return; } this.mode = newMode; this.logger.log(VerboseLevel.INFO, 'MODE=' + newMode); if (this.mode === 'MODE_POP-ON') { this.writeScreen = this.nonDisplayedMemory; } else { this.writeScreen = this.displayedMemory; this.writeScreen.reset(); } if (this.mode !== 'MODE_ROLL-UP') { this.displayedMemory.nrRollUpRows = null; this.nonDisplayedMemory.nrRollUpRows = null; } this.mode = newMode; }; _proto6.insertChars = function insertChars(chars) { for (var i = 0; i < chars.length; i++) { this.writeScreen.insertChar(chars[i]); } var screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP'; this.logger.log(VerboseLevel.INFO, screen + ': ' + this.writeScreen.getDisplayText(true)); if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') { this.logger.log(VerboseLevel.TEXT, 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true)); this.outputDataUpdate(); } }; _proto6.ccRCL = function ccRCL() { // Resume Caption Loading (switch mode to Pop On) this.logger.log(VerboseLevel.INFO, 'RCL - Resume Caption Loading'); this.setMode('MODE_POP-ON'); }; _proto6.ccBS = function ccBS() { // BackSpace this.logger.log(VerboseLevel.INFO, 'BS - BackSpace'); if (this.mode === 'MODE_TEXT') { return; } this.writeScreen.backSpace(); if (this.writeScreen === this.displayedMemory) { this.outputDataUpdate(); } }; _proto6.ccAOF = function ccAOF() {// Reserved (formerly Alarm Off) }; _proto6.ccAON = function ccAON() {// Reserved (formerly Alarm On) }; _proto6.ccDER = function ccDER() { // Delete to End of Row this.logger.log(VerboseLevel.INFO, 'DER- Delete to End of Row'); this.writeScreen.clearToEndOfRow(); this.outputDataUpdate(); }; _proto6.ccRU = function ccRU(nrRows) { // Roll-Up Captions-2,3,or 4 Rows this.logger.log(VerboseLevel.INFO, 'RU(' + nrRows + ') - Roll Up'); this.writeScreen = this.displayedMemory; this.setMode('MODE_ROLL-UP'); this.writeScreen.setRollUpRows(nrRows); }; _proto6.ccFON = function ccFON() { // Flash On this.logger.log(VerboseLevel.INFO, 'FON - Flash On'); this.writeScreen.setPen({ flash: true }); }; _proto6.ccRDC = function ccRDC() { // Resume Direct Captioning (switch mode to PaintOn) this.logger.log(VerboseLevel.INFO, 'RDC - Resume Direct Captioning'); this.setMode('MODE_PAINT-ON'); }; _proto6.ccTR = function ccTR() { // Text Restart in text mode (not supported, however) this.logger.log(VerboseLevel.INFO, 'TR'); this.setMode('MODE_TEXT'); }; _proto6.ccRTD = function ccRTD() { // Resume Text Display in Text mode (not supported, however) this.logger.log(VerboseLevel.INFO, 'RTD'); this.setMode('MODE_TEXT'); }; _proto6.ccEDM = function ccEDM() { // Erase Displayed Memory this.logger.log(VerboseLevel.INFO, 'EDM - Erase Displayed Memory'); this.displayedMemory.reset(); this.outputDataUpdate(true); }; _proto6.ccCR = function ccCR() { // Carriage Return this.logger.log(VerboseLevel.INFO, 'CR - Carriage Return'); this.writeScreen.rollUp(); this.outputDataUpdate(true); }; _proto6.ccENM = function ccENM() { // Erase Non-Displayed Memory this.logger.log(VerboseLevel.INFO, 'ENM - Erase Non-displayed Memory'); this.nonDisplayedMemory.reset(); }; _proto6.ccEOC = function ccEOC() { // End of Caption (Flip Memories) this.logger.log(VerboseLevel.INFO, 'EOC - End Of Caption'); if (this.mode === 'MODE_POP-ON') { var tmp = this.displayedMemory; this.displayedMemory = this.nonDisplayedMemory; this.nonDisplayedMemory = tmp; this.writeScreen = this.nonDisplayedMemory; this.logger.log(VerboseLevel.TEXT, 'DISP: ' + this.displayedMemory.getDisplayText()); } this.outputDataUpdate(true); }; _proto6.ccTO = function ccTO(nrCols) { // Tab Offset 1,2, or 3 columns this.logger.log(VerboseLevel.INFO, 'TO(' + nrCols + ') - Tab Offset'); this.writeScreen.moveCursor(nrCols); }; _proto6.ccMIDROW = function ccMIDROW(secondByte) { // Parse MIDROW command var styles = { flash: false }; styles.underline = secondByte % 2 === 1; styles.italics = secondByte >= 0x2e; if (!styles.italics) { var colorIndex = Math.floor(secondByte / 2) - 0x10; var colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta']; styles.foreground = colors[colorIndex]; } else { styles.foreground = 'white'; } this.logger.log(VerboseLevel.INFO, 'MIDROW: ' + JSON.stringify(styles)); this.writeScreen.setPen(styles); }; _proto6.outputDataUpdate = function outputDataUpdate(dispatch) { if (dispatch === void 0) { dispatch = false; } var time = this.logger.time; if (time === null) { return; } if (this.outputFilter) { if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) { // Start of a new cue this.cueStartTime = time; } else { if (!this.displayedMemory.equals(this.lastOutputScreen)) { this.outputFilter.newCue(this.cueStartTime, time, this.lastOutputScreen); if (dispatch && this.outputFilter.dispatchCue) { this.outputFilter.dispatchCue(); } this.cueStartTime = this.displayedMemory.isEmpty() ? null : time; } } this.lastOutputScreen.copy(this.displayedMemory); } }; _proto6.cueSplitAtTime = function cueSplitAtTime(t) { if (this.outputFilter) { if (!this.displayedMemory.isEmpty()) { if (this.outputFilter.newCue) { this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory); } this.cueStartTime = t; } } }; return Cea608Channel; }(); var Cea608Parser = /*#__PURE__*/function () { function Cea608Parser(field, out1, out2) { this.channels = void 0; this.currentChannel = 0; this.cmdHistory = void 0; this.logger = void 0; var logger = new CaptionsLogger(); this.channels = [null, new Cea608Channel(field, out1, logger), new Cea608Channel(field + 1, out2, logger)]; this.cmdHistory = createCmdHistory(); this.logger = logger; } var _proto7 = Cea608Parser.prototype; _proto7.getHandler = function getHandler(channel) { return this.channels[channel].getHandler(); }; _proto7.setHandler = function setHandler(channel, newHandler) { this.channels[channel].setHandler(newHandler); } /** * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs. */ ; _proto7.addData = function addData(time, byteList) { var cmdFound; var a; var b; var charsFound = false; this.logger.time = time; for (var i = 0; i < byteList.length; i += 2) { a = byteList[i] & 0x7f; b = byteList[i + 1] & 0x7f; if (a === 0 && b === 0) { continue; } else { this.logger.log(VerboseLevel.DATA, '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')'); } cmdFound = this.parseCmd(a, b); if (!cmdFound) { cmdFound = this.parseMidrow(a, b); } if (!cmdFound) { cmdFound = this.parsePAC(a, b); } if (!cmdFound) { cmdFound = this.parseBackgroundAttributes(a, b); } if (!cmdFound) { charsFound = this.parseChars(a, b); if (charsFound) { var currChNr = this.currentChannel; if (currChNr && currChNr > 0) { var channel = this.channels[currChNr]; channel.insertChars(charsFound); } else { this.logger.log(VerboseLevel.WARNING, 'No channel found yet. TEXT-MODE?'); } } } if (!cmdFound && !charsFound) { this.logger.log(VerboseLevel.WARNING, "Couldn't parse cleaned data " + numArrayToHexArray([a, b]) + ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]])); } } } /** * Parse Command. * @returns {Boolean} Tells if a command was found */ ; _proto7.parseCmd = function parseCmd(a, b) { var cmdHistory = this.cmdHistory; var cond1 = (a === 0x14 || a === 0x1c || a === 0x15 || a === 0x1d) && b >= 0x20 && b <= 0x2f; var cond2 = (a === 0x17 || a === 0x1f) && b >= 0x21 && b <= 0x23; if (!(cond1 || cond2)) { return false; } if (hasCmdRepeated(a, b, cmdHistory)) { setLastCmd(null, null, cmdHistory); this.logger.log(VerboseLevel.DEBUG, 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped'); return true; } var chNr = a === 0x14 || a === 0x15 || a === 0x17 ? 1 : 2; var channel = this.channels[chNr]; if (a === 0x14 || a === 0x15 || a === 0x1c || a === 0x1d) { if (b === 0x20) { channel.ccRCL(); } else if (b === 0x21) { channel.ccBS(); } else if (b === 0x22) { channel.ccAOF(); } else if (b === 0x23) { channel.ccAON(); } else if (b === 0x24) { channel.ccDER(); } else if (b === 0x25) { channel.ccRU(2); } else if (b === 0x26) { channel.ccRU(3); } else if (b === 0x27) { channel.ccRU(4); } else if (b === 0x28) { channel.ccFON(); } else if (b === 0x29) { channel.ccRDC(); } else if (b === 0x2a) { channel.ccTR(); } else if (b === 0x2b) { channel.ccRTD(); } else if (b === 0x2c) { channel.ccEDM(); } else if (b === 0x2d) { channel.ccCR(); } else if (b === 0x2e) { channel.ccENM(); } else if (b === 0x2f) { channel.ccEOC(); } } else { // a == 0x17 || a == 0x1F channel.ccTO(b - 0x20); } setLastCmd(a, b, cmdHistory); this.currentChannel = chNr; return true; } /** * Parse midrow styling command * @returns {Boolean} */ ; _proto7.parseMidrow = function parseMidrow(a, b) { var chNr = 0; if ((a === 0x11 || a === 0x19) && b >= 0x20 && b <= 0x2f) { if (a === 0x11) { chNr = 1; } else { chNr = 2; } if (chNr !== this.currentChannel) { this.logger.log(VerboseLevel.ERROR, 'Mismatch channel in midrow parsing'); return false; } var channel = this.channels[chNr]; if (!channel) { return false; } channel.ccMIDROW(b); this.logger.log(VerboseLevel.DEBUG, 'MIDROW (' + numArrayToHexArray([a, b]) + ')'); return true; } return false; } /** * Parse Preable Access Codes (Table 53). * @returns {Boolean} Tells if PAC found */ ; _proto7.parsePAC = function parsePAC(a, b) { var row; var cmdHistory = this.cmdHistory; var case1 = (a >= 0x11 && a <= 0x17 || a >= 0x19 && a <= 0x1f) && b >= 0x40 && b <= 0x7f; var case2 = (a === 0x10 || a === 0x18) && b >= 0x40 && b <= 0x5f; if (!(case1 || case2)) { return false; } if (hasCmdRepeated(a, b, cmdHistory)) { setLastCmd(null, null, cmdHistory); return true; // Repeated commands are dropped (once) } var chNr = a <= 0x17 ? 1 : 2; if (b >= 0x40 && b <= 0x5f) { row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a]; } else { // 0x60 <= b <= 0x7F row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a]; } var channel = this.channels[chNr]; if (!channel) { return false; } channel.setPAC(this.interpretPAC(row, b)); setLastCmd(a, b, cmdHistory); this.currentChannel = chNr; return true; } /** * Interpret the second byte of the pac, and return the information. * @returns {Object} pacData with style parameters. */ ; _proto7.interpretPAC = function interpretPAC(row, _byte3) { var pacIndex; var pacData = { color: null, italics: false, indent: null, underline: false, row: row }; if (_byte3 > 0x5f) { pacIndex = _byte3 - 0x60; } else { pacIndex = _byte3 - 0x40; } pacData.underline = (pacIndex & 1) === 1; if (pacIndex <= 0xd) { pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)]; } else if (pacIndex <= 0xf) { pacData.italics = true; pacData.color = 'white'; } else { pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4; } return pacData; // Note that row has zero offset. The spec uses 1. } /** * Parse characters. * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise. */ ; _proto7.parseChars = function parseChars(a, b) { var channelNr; var charCodes = null; var charCode1 = null; if (a >= 0x19) { channelNr = 2; charCode1 = a - 8; } else { channelNr = 1; charCode1 = a; } if (charCode1 >= 0x11 && charCode1 <= 0x13) { // Special character var oneCode; if (charCode1 === 0x11) { oneCode = b + 0x50; } else if (charCode1 === 0x12) { oneCode = b + 0x70; } else { oneCode = b + 0x90; } this.logger.log(VerboseLevel.INFO, "Special char '" + getCharForByte(oneCode) + "' in channel " + channelNr); charCodes = [oneCode]; } else if (a >= 0x20 && a <= 0x7f) { charCodes = b === 0 ? [a] : [a, b]; } if (charCodes) { var hexCodes = numArrayToHexArray(charCodes); this.logger.log(VerboseLevel.DEBUG, 'Char codes = ' + hexCodes.join(',')); setLastCmd(a, b, this.cmdHistory); } return charCodes; } /** * Parse extended background attributes as well as new foreground color black. * @returns {Boolean} Tells if background attributes are found */ ; _proto7.parseBackgroundAttributes = function parseBackgroundAttributes(a, b) { var case1 = (a === 0x10 || a === 0x18) && b >= 0x20 && b <= 0x2f; var case2 = (a === 0x17 || a === 0x1f) && b >= 0x2d && b <= 0x2f; if (!(case1 || case2)) { return false; } var index; var bkgData = {}; if (a === 0x10 || a === 0x18) { index = Math.floor((b - 0x20) / 2); bkgData.background = backgroundColors[index]; if (b % 2 === 1) { bkgData.background = bkgData.background + '_semi'; } } else if (b === 0x2d) { bkgData.background = 'transparent'; } else { bkgData.foreground = 'black'; if (b === 0x2f) { bkgData.underline = true; } } var chNr = a <= 0x17 ? 1 : 2; var channel = this.channels[chNr]; channel.setBkgData(bkgData); setLastCmd(a, b, this.cmdHistory); return true; } /** * Reset state of parser and its channels. */ ; _proto7.reset = function reset() { for (var i = 0; i < Object.keys(this.channels).length; i++) { var channel = this.channels[i]; if (channel) { channel.reset(); } } this.cmdHistory = createCmdHistory(); } /** * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty. */ ; _proto7.cueSplitAtTime = function cueSplitAtTime(t) { for (var i = 0; i < this.channels.length; i++) { var channel = this.channels[i]; if (channel) { channel.cueSplitAtTime(t); } } }; return Cea608Parser; }(); function setLastCmd(a, b, cmdHistory) { cmdHistory.a = a; cmdHistory.b = b; } function hasCmdRepeated(a, b, cmdHistory) { return cmdHistory.a === a && cmdHistory.b === b; } function createCmdHistory() { return { a: null, b: null }; } /* harmony default export */ __webpack_exports__["default"] = (Cea608Parser); /***/ }), /***/ "./src/utils/codecs.ts": /*!*****************************!*\ !*** ./src/utils/codecs.ts ***! \*****************************/ /*! exports provided: isCodecType, isCodecSupportedInMp4 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isCodecType", function() { return isCodecType; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isCodecSupportedInMp4", function() { return isCodecSupportedInMp4; }); // from http://mp4ra.org/codecs.html var sampleEntryCodesISO = { audio: { a3ds: true, 'ac-3': true, 'ac-4': true, alac: true, alaw: true, dra1: true, 'dts+': true, 'dts-': true, dtsc: true, dtse: true, dtsh: true, 'ec-3': true, enca: true, g719: true, g726: true, m4ae: true, mha1: true, mha2: true, mhm1: true, mhm2: true, mlpa: true, mp4a: true, 'raw ': true, Opus: true, samr: true, sawb: true, sawp: true, sevc: true, sqcp: true, ssmv: true, twos: true, ulaw: true }, video: { avc1: true, avc2: true, avc3: true, avc4: true, avcp: true, av01: true, drac: true, dvav: true, dvhe: true, encv: true, hev1: true, hvc1: true, mjp2: true, mp4v: true, mvc1: true, mvc2: true, mvc3: true, mvc4: true, resv: true, rv60: true, s263: true, svc1: true, svc2: true, 'vc-1': true, vp08: true, vp09: true }, text: { stpp: true, wvtt: true } }; function isCodecType(codec, type) { var typeCodes = sampleEntryCodesISO[type]; return !!typeCodes && typeCodes[codec.slice(0, 4)] === true; } function isCodecSupportedInMp4(codec, type) { return MediaSource.isTypeSupported((type || 'video') + "/mp4;codecs=\"" + codec + "\""); } /***/ }), /***/ "./src/utils/cues.ts": /*!***************************!*\ !*** ./src/utils/cues.ts ***! \***************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _vttparser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vttparser */ "./src/utils/vttparser.ts"); /* harmony import */ var _webvtt_parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./webvtt-parser */ "./src/utils/webvtt-parser.ts"); /* harmony import */ var _texttrack_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./texttrack-utils */ "./src/utils/texttrack-utils.ts"); var WHITESPACE_CHAR = /\s/; var Cues = { newCue: function newCue(track, startTime, endTime, captionScreen) { var result = []; var row; // the type data states this is VTTCue, but it can potentially be a TextTrackCue on old browsers var cue; var indenting; var indent; var text; var Cue = self.VTTCue || self.TextTrackCue; for (var r = 0; r < captionScreen.rows.length; r++) { row = captionScreen.rows[r]; indenting = true; indent = 0; text = ''; if (!row.isEmpty()) { for (var c = 0; c < row.chars.length; c++) { if (WHITESPACE_CHAR.test(row.chars[c].uchar) && indenting) { indent++; } else { text += row.chars[c].uchar; indenting = false; } } // To be used for cleaning-up orphaned roll-up captions row.cueStartTime = startTime; // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE if (startTime === endTime) { endTime += 0.0001; } if (indent >= 16) { indent--; } else { indent++; } var cueText = Object(_vttparser__WEBPACK_IMPORTED_MODULE_0__["fixLineBreaks"])(text.trim()); var id = Object(_webvtt_parser__WEBPACK_IMPORTED_MODULE_1__["generateCueId"])(startTime, endTime, cueText); // If this cue already exists in the track do not push it if (!track || !track.cues || !track.cues.getCueById(id)) { cue = new Cue(startTime, endTime, cueText); cue.id = id; cue.line = r + 1; cue.align = 'left'; // Clamp the position between 10 and 80 percent (CEA-608 PAC indent code) // https://dvcs.w3.org/hg/text-tracks/raw-file/default/608toVTT/608toVTT.html#positioning-in-cea-608 // Firefox throws an exception and captions break with out of bounds 0-100 values cue.position = 10 + Math.min(80, Math.floor(indent * 8 / 32) * 10); result.push(cue); } } } if (track && result.length) { // Sort bottom cues in reverse order so that they render in line order when overlapping in Chrome result.sort(function (cueA, cueB) { if (cueA.line === 'auto' || cueB.line === 'auto') { return 0; } if (cueA.line > 8 && cueB.line > 8) { return cueB.line - cueA.line; } return cueA.line - cueB.line; }); result.forEach(function (cue) { return Object(_texttrack_utils__WEBPACK_IMPORTED_MODULE_2__["addCueToTrack"])(track, cue); }); } return result; } }; /* harmony default export */ __webpack_exports__["default"] = (Cues); /***/ }), /***/ "./src/utils/discontinuities.ts": /*!**************************************!*\ !*** ./src/utils/discontinuities.ts ***! \**************************************/ /*! exports provided: findFirstFragWithCC, shouldAlignOnDiscontinuities, findDiscontinuousReferenceFrag, adjustSlidingStart, alignStream, alignPDT */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFirstFragWithCC", function() { return findFirstFragWithCC; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "shouldAlignOnDiscontinuities", function() { return shouldAlignOnDiscontinuities; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findDiscontinuousReferenceFrag", function() { return findDiscontinuousReferenceFrag; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "adjustSlidingStart", function() { return adjustSlidingStart; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alignStream", function() { return alignStream; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alignPDT", function() { return alignPDT; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./logger */ "./src/utils/logger.ts"); /* harmony import */ var _controller_level_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../controller/level-helper */ "./src/controller/level-helper.ts"); function findFirstFragWithCC(fragments, cc) { var firstFrag = null; for (var i = 0, len = fragments.length; i < len; i++) { var currentFrag = fragments[i]; if (currentFrag && currentFrag.cc === cc) { firstFrag = currentFrag; break; } } return firstFrag; } function shouldAlignOnDiscontinuities(lastFrag, lastLevel, details) { if (lastLevel.details) { if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) { return true; } } return false; } // Find the first frag in the previous level which matches the CC of the first frag of the new level function findDiscontinuousReferenceFrag(prevDetails, curDetails) { var prevFrags = prevDetails.fragments; var curFrags = curDetails.fragments; if (!curFrags.length || !prevFrags.length) { _logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log('No fragments to align'); return; } var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc); if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) { _logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log('No frag in previous level to align on'); return; } return prevStartFrag; } function adjustFragmentStart(frag, sliding) { if (frag) { var start = frag.start + sliding; frag.start = frag.startPTS = start; frag.endPTS = start + frag.duration; } } function adjustSlidingStart(sliding, details) { // Update segments var fragments = details.fragments; for (var i = 0, len = fragments.length; i < len; i++) { adjustFragmentStart(fragments[i], sliding); } // Update LL-HLS parts at the end of the playlist if (details.fragmentHint) { adjustFragmentStart(details.fragmentHint, sliding); } details.alignedSliding = true; } /** * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a * contiguous stream with the last fragments. * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time * and an extra download. * @param lastFrag * @param lastLevel * @param details */ function alignStream(lastFrag, lastLevel, details) { if (!lastLevel) { return; } alignDiscontinuities(lastFrag, details, lastLevel); if (!details.alignedSliding && lastLevel.details) { // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level. // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same // discontinuity sequence. alignPDT(details, lastLevel.details); } if (!details.alignedSliding && lastLevel.details && !details.skippedSegments) { // Try to align on sn so that we pick a better start fragment. // Do not perform this on playlists with delta updates as this is only to align levels on switch // and adjustSliding only adjusts fragments after skippedSegments. Object(_controller_level_helper__WEBPACK_IMPORTED_MODULE_2__["adjustSliding"])(lastLevel.details, details); } } /** * Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same * discontinuity sequence. * @param lastFrag - The last Fragment which shares the same discontinuity sequence * @param lastLevel - The details of the last loaded level * @param details - The details of the new level */ function alignDiscontinuities(lastFrag, details, lastLevel) { if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) { var referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details); if (referenceFrag && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(referenceFrag.start)) { _logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log("Adjusting PTS using last level due to CC increase within current level " + details.url); adjustSlidingStart(referenceFrag.start, details); } } } /** * Computes the PTS of a new level's fragments using the difference in Program Date Time from the last level. * @param details - The details of the new level * @param lastDetails - The details of the last loaded level */ function alignPDT(details, lastDetails) { // This check protects the unsafe "!" usage below for null program date time access. if (!lastDetails.fragments.length || !details.hasProgramDateTime || !lastDetails.hasProgramDateTime) { return; } // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM // and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM // then we can deduce that playlist B sliding is 1000+8 = 1008s var lastPDT = lastDetails.fragments[0].programDateTime; // hasProgramDateTime check above makes this safe. var newPDT = details.fragments[0].programDateTime; // date diff is in ms. frag.start is in seconds var sliding = (newPDT - lastPDT) / 1000 + lastDetails.fragments[0].start; if (sliding && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(sliding)) { _logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log("Adjusting PTS using programDateTime delta " + (newPDT - lastPDT) + "ms, sliding:" + sliding.toFixed(3) + " " + details.url + " "); adjustSlidingStart(sliding, details); } } /***/ }), /***/ "./src/utils/ewma-bandwidth-estimator.ts": /*!***********************************************!*\ !*** ./src/utils/ewma-bandwidth-estimator.ts ***! \***********************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _utils_ewma__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/ewma */ "./src/utils/ewma.ts"); /* * EWMA Bandwidth Estimator * - heavily inspired from shaka-player * Tracks bandwidth samples and estimates available bandwidth. * Based on the minimum of two exponentially-weighted moving averages with * different half-lives. */ var EwmaBandWidthEstimator = /*#__PURE__*/function () { function EwmaBandWidthEstimator(slow, fast, defaultEstimate) { this.defaultEstimate_ = void 0; this.minWeight_ = void 0; this.minDelayMs_ = void 0; this.slow_ = void 0; this.fast_ = void 0; this.defaultEstimate_ = defaultEstimate; this.minWeight_ = 0.001; this.minDelayMs_ = 50; this.slow_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](slow); this.fast_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](fast); } var _proto = EwmaBandWidthEstimator.prototype; _proto.update = function update(slow, fast) { var slow_ = this.slow_, fast_ = this.fast_; if (this.slow_.halfLife !== slow) { this.slow_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](slow, slow_.getEstimate(), slow_.getTotalWeight()); } if (this.fast_.halfLife !== fast) { this.fast_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](fast, fast_.getEstimate(), fast_.getTotalWeight()); } }; _proto.sample = function sample(durationMs, numBytes) { durationMs = Math.max(durationMs, this.minDelayMs_); var numBits = 8 * numBytes; // weight is duration in seconds var durationS = durationMs / 1000; // value is bandwidth in bits/s var bandwidthInBps = numBits / durationS; this.fast_.sample(durationS, bandwidthInBps); this.slow_.sample(durationS, bandwidthInBps); }; _proto.canEstimate = function canEstimate() { var fast = this.fast_; return fast && fast.getTotalWeight() >= this.minWeight_; }; _proto.getEstimate = function getEstimate() { if (this.canEstimate()) { // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate())); // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate())); // Take the minimum of these two estimates. This should have the effect of // adapting down quickly, but up more slowly. return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate()); } else { return this.defaultEstimate_; } }; _proto.destroy = function destroy() {}; return EwmaBandWidthEstimator; }(); /* harmony default export */ __webpack_exports__["default"] = (EwmaBandWidthEstimator); /***/ }), /***/ "./src/utils/ewma.ts": /*!***************************!*\ !*** ./src/utils/ewma.ts ***! \***************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* * compute an Exponential Weighted moving average * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average * - heavily inspired from shaka-player */ var EWMA = /*#__PURE__*/function () { // About half of the estimated value will be from the last |halfLife| samples by weight. function EWMA(halfLife, estimate, weight) { if (estimate === void 0) { estimate = 0; } if (weight === void 0) { weight = 0; } this.halfLife = void 0; this.alpha_ = void 0; this.estimate_ = void 0; this.totalWeight_ = void 0; this.halfLife = halfLife; // Larger values of alpha expire historical data more slowly. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0; this.estimate_ = estimate; this.totalWeight_ = weight; } var _proto = EWMA.prototype; _proto.sample = function sample(weight, value) { var adjAlpha = Math.pow(this.alpha_, weight); this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_; this.totalWeight_ += weight; }; _proto.getTotalWeight = function getTotalWeight() { return this.totalWeight_; }; _proto.getEstimate = function getEstimate() { if (this.alpha_) { var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_); if (zeroFactor) { return this.estimate_ / zeroFactor; } } return this.estimate_; }; return EWMA; }(); /* harmony default export */ __webpack_exports__["default"] = (EWMA); /***/ }), /***/ "./src/utils/fetch-loader.ts": /*!***********************************!*\ !*** ./src/utils/fetch-loader.ts ***! \***********************************/ /*! exports provided: fetchSupported, default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fetchSupported", function() { return fetchSupported; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/load-stats */ "./src/loader/load-stats.ts"); /* harmony import */ var _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/chunk-cache */ "./src/demux/chunk-cache.ts"); function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function fetchSupported() { if ( // @ts-ignore self.fetch && self.AbortController && self.ReadableStream && self.Request) { try { new self.ReadableStream({}); // eslint-disable-line no-new return true; } catch (e) { /* noop */ } } return false; } var FetchLoader = /*#__PURE__*/function () { function FetchLoader(config /* HlsConfig */ ) { this.fetchSetup = void 0; this.requestTimeout = void 0; this.request = void 0; this.response = void 0; this.controller = void 0; this.context = void 0; this.config = null; this.callbacks = null; this.stats = void 0; this.loader = null; this.fetchSetup = config.fetchSetup || getRequest; this.controller = new self.AbortController(); this.stats = new _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__["LoadStats"](); } var _proto = FetchLoader.prototype; _proto.destroy = function destroy() { this.loader = this.callbacks = null; this.abortInternal(); }; _proto.abortInternal = function abortInternal() { var response = this.response; if (!response || !response.ok) { this.stats.aborted = true; this.controller.abort(); } }; _proto.abort = function abort() { var _this$callbacks; this.abortInternal(); if ((_this$callbacks = this.callbacks) !== null && _this$callbacks !== void 0 && _this$callbacks.onAbort) { this.callbacks.onAbort(this.stats, this.context, this.response); } }; _proto.load = function load(context, config, callbacks) { var _this = this; var stats = this.stats; if (stats.loading.start) { throw new Error('Loader can only be used once.'); } stats.loading.start = self.performance.now(); var initParams = getRequestParameters(context, this.controller.signal); var onProgress = callbacks.onProgress; var isArrayBuffer = context.responseType === 'arraybuffer'; var LENGTH = isArrayBuffer ? 'byteLength' : 'length'; this.context = context; this.config = config; this.callbacks = callbacks; this.request = this.fetchSetup(context, initParams); self.clearTimeout(this.requestTimeout); this.requestTimeout = self.setTimeout(function () { _this.abortInternal(); callbacks.onTimeout(stats, context, _this.response); }, config.timeout); self.fetch(this.request).then(function (response) { _this.response = _this.loader = response; if (!response.ok) { var status = response.status, statusText = response.statusText; throw new FetchError(statusText || 'fetch, bad network response', status, response); } stats.loading.first = Math.max(self.performance.now(), stats.loading.start); stats.total = parseInt(response.headers.get('Content-Length') || '0'); if (onProgress && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(config.highWaterMark)) { return _this.loadProgressively(response, stats, context, config.highWaterMark, onProgress); } if (isArrayBuffer) { return response.arrayBuffer(); } return response.text(); }).then(function (responseData) { var response = _this.response; self.clearTimeout(_this.requestTimeout); stats.loading.end = Math.max(self.performance.now(), stats.loading.first); stats.loaded = stats.total = responseData[LENGTH]; var loaderResponse = { url: response.url, data: responseData }; if (onProgress && !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(config.highWaterMark)) { onProgress(stats, context, responseData, response); } callbacks.onSuccess(loaderResponse, stats, context, response); }).catch(function (error) { self.clearTimeout(_this.requestTimeout); if (stats.aborted) { return; } // CORS errors result in an undefined code. Set it to 0 here to align with XHR's behavior var code = error.code || 0; callbacks.onError({ code: code, text: error.message }, context, error.details); }); }; _proto.getCacheAge = function getCacheAge() { var result = null; if (this.response) { var ageHeader = this.response.headers.get('age'); result = ageHeader ? parseFloat(ageHeader) : null; } return result; }; _proto.loadProgressively = function loadProgressively(response, stats, context, highWaterMark, onProgress) { if (highWaterMark === void 0) { highWaterMark = 0; } var chunkCache = new _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_2__["default"](); var reader = response.body.getReader(); var pump = function pump() { return reader.read().then(function (data) { if (data.done) { if (chunkCache.dataLength) { onProgress(stats, context, chunkCache.flush(), response); } return Promise.resolve(new ArrayBuffer(0)); } var chunk = data.value; var len = chunk.length; stats.loaded += len; if (len < highWaterMark || chunkCache.dataLength) { // The current chunk is too small to to be emitted or the cache already has data // Push it to the cache chunkCache.push(chunk); if (chunkCache.dataLength >= highWaterMark) { // flush in order to join the typed arrays onProgress(stats, context, chunkCache.flush(), response); } } else { // If there's nothing cached already, and the chache is large enough // just emit the progress event onProgress(stats, context, chunk, response); } return pump(); }).catch(function () { /* aborted */ return Promise.reject(); }); }; return pump(); }; return FetchLoader; }(); function getRequestParameters(context, signal) { var initParams = { method: 'GET', mode: 'cors', credentials: 'same-origin', signal: signal }; if (context.rangeEnd) { initParams.headers = new self.Headers({ Range: 'bytes=' + context.rangeStart + '-' + String(context.rangeEnd - 1) }); } return initParams; } function getRequest(context, initParams) { return new self.Request(context.url, initParams); } var FetchError = /*#__PURE__*/function (_Error) { _inheritsLoose(FetchError, _Error); function FetchError(message, code, details) { var _this2; _this2 = _Error.call(this, message) || this; _this2.code = void 0; _this2.details = void 0; _this2.code = code; _this2.details = details; return _this2; } return FetchError; }( /*#__PURE__*/_wrapNativeSuper(Error)); /* harmony default export */ __webpack_exports__["default"] = (FetchLoader); /***/ }), /***/ "./src/utils/imsc1-ttml-parser.ts": /*!****************************************!*\ !*** ./src/utils/imsc1-ttml-parser.ts ***! \****************************************/ /*! exports provided: IMSC1_CODEC, parseIMSC1 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IMSC1_CODEC", function() { return IMSC1_CODEC; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseIMSC1", function() { return parseIMSC1; }); /* harmony import */ var _mp4_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./mp4-tools */ "./src/utils/mp4-tools.ts"); /* harmony import */ var _vttparser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vttparser */ "./src/utils/vttparser.ts"); /* harmony import */ var _vttcue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./vttcue */ "./src/utils/vttcue.ts"); /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts"); /* harmony import */ var _timescale_conversion__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./timescale-conversion */ "./src/utils/timescale-conversion.ts"); /* harmony import */ var _webvtt_parser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./webvtt-parser */ "./src/utils/webvtt-parser.ts"); function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } var IMSC1_CODEC = 'stpp.ttml.im1t'; // Time format: h:m:s:frames(.subframes) var HMSF_REGEX = /^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/; // Time format: hours, minutes, seconds, milliseconds, frames, ticks var TIME_UNIT_REGEX = /^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/; var textAlignToLineAlign = { left: 'start', center: 'center', right: 'end', start: 'start', end: 'end' }; function parseIMSC1(payload, initPTS, timescale, callBack, errorCallBack) { var results = Object(_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["findBox"])(new Uint8Array(payload), ['mdat']); if (results.length === 0) { errorCallBack(new Error('Could not parse IMSC1 mdat')); return; } var mdat = results[0]; var ttml = Object(_demux_id3__WEBPACK_IMPORTED_MODULE_3__["utf8ArrayToStr"])(new Uint8Array(payload, mdat.start, mdat.end - mdat.start)); var syncTime = Object(_timescale_conversion__WEBPACK_IMPORTED_MODULE_4__["toTimescaleFromScale"])(initPTS, 1, timescale); try { callBack(parseTTML(ttml, syncTime)); } catch (error) { errorCallBack(error); } } function parseTTML(ttml, syncTime) { var parser = new DOMParser(); var xmlDoc = parser.parseFromString(ttml, 'text/xml'); var tt = xmlDoc.getElementsByTagName('tt')[0]; if (!tt) { throw new Error('Invalid ttml'); } var defaultRateInfo = { frameRate: 30, subFrameRate: 1, frameRateMultiplier: 0, tickRate: 0 }; var rateInfo = Object.keys(defaultRateInfo).reduce(function (result, key) { result[key] = tt.getAttribute("ttp:" + key) || defaultRateInfo[key]; return result; }, {}); var trim = tt.getAttribute('xml:space') !== 'preserve'; var styleElements = collectionToDictionary(getElementCollection(tt, 'styling', 'style')); var regionElements = collectionToDictionary(getElementCollection(tt, 'layout', 'region')); var cueElements = getElementCollection(tt, 'body', '[begin]'); return [].map.call(cueElements, function (cueElement) { var cueText = getTextContent(cueElement, trim); if (!cueText || !cueElement.hasAttribute('begin')) { return null; } var startTime = parseTtmlTime(cueElement.getAttribute('begin'), rateInfo); var duration = parseTtmlTime(cueElement.getAttribute('dur'), rateInfo); var endTime = parseTtmlTime(cueElement.getAttribute('end'), rateInfo); if (startTime === null) { throw timestampParsingError(cueElement); } if (endTime === null) { if (duration === null) { throw timestampParsingError(cueElement); } endTime = startTime + duration; } var cue = new _vttcue__WEBPACK_IMPORTED_MODULE_2__["default"](startTime - syncTime, endTime - syncTime, cueText); cue.id = Object(_webvtt_parser__WEBPACK_IMPORTED_MODULE_5__["generateCueId"])(cue.startTime, cue.endTime, cue.text); var region = regionElements[cueElement.getAttribute('region')]; var style = styleElements[cueElement.getAttribute('style')]; // TODO: Add regions to track and cue (origin and extend) // These values are hard-coded (for now) to simulate region settings in the demo cue.position = 10; cue.size = 80; // Apply styles to cue var styles = getTtmlStyles(region, style); var textAlign = styles.textAlign; if (textAlign) { // cue.positionAlign not settable in FF~2016 var lineAlign = textAlignToLineAlign[textAlign]; if (lineAlign) { cue.lineAlign = lineAlign; } cue.align = textAlign; } _extends(cue, styles); return cue; }).filter(function (cue) { return cue !== null; }); } function getElementCollection(fromElement, parentName, childName) { var parent = fromElement.getElementsByTagName(parentName)[0]; if (parent) { return [].slice.call(parent.querySelectorAll(childName)); } return []; } function collectionToDictionary(elementsWithId) { return elementsWithId.reduce(function (dict, element) { var id = element.getAttribute('xml:id'); if (id) { dict[id] = element; } return dict; }, {}); } function getTextContent(element, trim) { return [].slice.call(element.childNodes).reduce(function (str, node, i) { var _node$childNodes; if (node.nodeName === 'br' && i) { return str + '\n'; } if ((_node$childNodes = node.childNodes) !== null && _node$childNodes !== void 0 && _node$childNodes.length) { return getTextContent(node, trim); } else if (trim) { return str + node.textContent.trim().replace(/\s+/g, ' '); } return str + node.textContent; }, ''); } function getTtmlStyles(region, style) { var ttsNs = 'http://www.w3.org/ns/ttml#styling'; var styleAttributes = ['displayAlign', 'textAlign', 'color', 'backgroundColor', 'fontSize', 'fontFamily' // 'fontWeight', // 'lineHeight', // 'wrapOption', // 'fontStyle', // 'direction', // 'writingMode' ]; return styleAttributes.reduce(function (styles, name) { var value = getAttributeNS(style, ttsNs, name) || getAttributeNS(region, ttsNs, name); if (value) { styles[name] = value; } return styles; }, {}); } function getAttributeNS(element, ns, name) { return element.hasAttributeNS(ns, name) ? element.getAttributeNS(ns, name) : null; } function timestampParsingError(node) { return new Error("Could not parse ttml timestamp " + node); } function parseTtmlTime(timeAttributeValue, rateInfo) { if (!timeAttributeValue) { return null; } var seconds = Object(_vttparser__WEBPACK_IMPORTED_MODULE_1__["parseTimeStamp"])(timeAttributeValue); if (seconds === null) { if (HMSF_REGEX.test(timeAttributeValue)) { seconds = parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo); } else if (TIME_UNIT_REGEX.test(timeAttributeValue)) { seconds = parseTimeUnits(timeAttributeValue, rateInfo); } } return seconds; } function parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo) { var m = HMSF_REGEX.exec(timeAttributeValue); var frames = (m[4] | 0) + (m[5] | 0) / rateInfo.subFrameRate; return (m[1] | 0) * 3600 + (m[2] | 0) * 60 + (m[3] | 0) + frames / rateInfo.frameRate; } function parseTimeUnits(timeAttributeValue, rateInfo) { var m = TIME_UNIT_REGEX.exec(timeAttributeValue); var value = Number(m[1]); var unit = m[2]; switch (unit) { case 'h': return value * 3600; case 'm': return value * 60; case 'ms': return value * 1000; case 'f': return value / rateInfo.frameRate; case 't': return value / rateInfo.tickRate; } return value; } /***/ }), /***/ "./src/utils/logger.ts": /*!*****************************!*\ !*** ./src/utils/logger.ts ***! \*****************************/ /*! exports provided: enableLogs, logger */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableLogs", function() { return enableLogs; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logger", function() { return logger; }); var noop = function noop() {}; var fakeLogger = { trace: noop, debug: noop, log: noop, warn: noop, info: noop, error: noop }; var exportedLogger = fakeLogger; // let lastCallTime; // function formatMsgWithTimeInfo(type, msg) { // const now = Date.now(); // const diff = lastCallTime ? '+' + (now - lastCallTime) : '0'; // lastCallTime = now; // msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )'; // return msg; // } function consolePrintFn(type) { var func = self.console[type]; if (func) { return func.bind(self.console, "[" + type + "] >"); } return noop; } function exportLoggerFunctions(debugConfig) { for (var _len = arguments.length, functions = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { functions[_key - 1] = arguments[_key]; } functions.forEach(function (type) { exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type); }); } function enableLogs(debugConfig) { // check that console is available if (self.console && debugConfig === true || typeof debugConfig === 'object') { exportLoggerFunctions(debugConfig, // Remove out from list here to hard-disable a log-level // 'trace', 'debug', 'log', 'info', 'warn', 'error'); // Some browsers don't allow to use bind on console object anyway // fallback to default if needed try { exportedLogger.log(); } catch (e) { exportedLogger = fakeLogger; } } else { exportedLogger = fakeLogger; } } var logger = exportedLogger; /***/ }), /***/ "./src/utils/mediakeys-helper.ts": /*!***************************************!*\ !*** ./src/utils/mediakeys-helper.ts ***! \***************************************/ /*! exports provided: KeySystems, requestMediaKeySystemAccess */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeySystems", function() { return KeySystems; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "requestMediaKeySystemAccess", function() { return requestMediaKeySystemAccess; }); /** * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess */ var KeySystems; (function (KeySystems) { KeySystems["WIDEVINE"] = "com.widevine.alpha"; KeySystems["PLAYREADY"] = "com.microsoft.playready"; })(KeySystems || (KeySystems = {})); var requestMediaKeySystemAccess = function () { if (typeof self !== 'undefined' && self.navigator && self.navigator.requestMediaKeySystemAccess) { return self.navigator.requestMediaKeySystemAccess.bind(self.navigator); } else { return null; } }(); /***/ }), /***/ "./src/utils/mediasource-helper.ts": /*!*****************************************!*\ !*** ./src/utils/mediasource-helper.ts ***! \*****************************************/ /*! exports provided: getMediaSource */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getMediaSource", function() { return getMediaSource; }); /** * MediaSource helper */ function getMediaSource() { return self.MediaSource || self.WebKitMediaSource; } /***/ }), /***/ "./src/utils/mp4-tools.ts": /*!********************************!*\ !*** ./src/utils/mp4-tools.ts ***! \********************************/ /*! exports provided: bin2str, readUint16, readUint32, writeUint32, findBox, parseSegmentIndex, parseInitSegment, getStartDTS, getDuration, computeRawDurationFromSamples, offsetStartDTS, segmentValidRange, appendUint8Array */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bin2str", function() { return bin2str; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "readUint16", function() { return readUint16; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "readUint32", function() { return readUint32; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "writeUint32", function() { return writeUint32; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findBox", function() { return findBox; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseSegmentIndex", function() { return parseSegmentIndex; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseInitSegment", function() { return parseInitSegment; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getStartDTS", function() { return getStartDTS; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDuration", function() { return getDuration; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "computeRawDurationFromSamples", function() { return computeRawDurationFromSamples; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "offsetStartDTS", function() { return offsetStartDTS; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "segmentValidRange", function() { return segmentValidRange; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendUint8Array", function() { return appendUint8Array; }); /* harmony import */ var _typed_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./typed-array */ "./src/utils/typed-array.ts"); /* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts"); var UINT32_MAX = Math.pow(2, 32) - 1; var push = [].push; function bin2str(data) { return String.fromCharCode.apply(null, data); } function readUint16(buffer, offset) { if ('data' in buffer) { offset += buffer.start; buffer = buffer.data; } var val = buffer[offset] << 8 | buffer[offset + 1]; return val < 0 ? 65536 + val : val; } function readUint32(buffer, offset) { if ('data' in buffer) { offset += buffer.start; buffer = buffer.data; } var val = buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3]; return val < 0 ? 4294967296 + val : val; } function writeUint32(buffer, offset, value) { if ('data' in buffer) { offset += buffer.start; buffer = buffer.data; } buffer[offset] = value >> 24; buffer[offset + 1] = value >> 16 & 0xff; buffer[offset + 2] = value >> 8 & 0xff; buffer[offset + 3] = value & 0xff; } // Find the data for a box specified by its path function findBox(input, path) { var results = []; if (!path.length) { // short-circuit the search for empty paths return results; } var data; var start; var end; if ('data' in input) { data = input.data; start = input.start; end = input.end; } else { data = input; start = 0; end = data.byteLength; } for (var i = start; i < end;) { var size = readUint32(data, i); var type = bin2str(data.subarray(i + 4, i + 8)); var endbox = size > 1 ? i + size : end; if (type === path[0]) { if (path.length === 1) { // this is the end of the path and we've found the box we were // looking for results.push({ data: data, start: i + 8, end: endbox }); } else { // recursively search for the next box along the path var subresults = findBox({ data: data, start: i + 8, end: endbox }, path.slice(1)); if (subresults.length) { push.apply(results, subresults); } } } i = endbox; } // we've finished searching all of data return results; } function parseSegmentIndex(initSegment) { var moovBox = findBox(initSegment, ['moov']); var moov = moovBox[0]; var moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data var sidxBox = findBox(initSegment, ['sidx']); if (!sidxBox || !sidxBox[0]) { return null; } var references = []; var sidx = sidxBox[0]; var version = sidx.data[0]; // set initial offset, we skip the reference ID (not needed) var index = version === 0 ? 8 : 16; var timescale = readUint32(sidx, index); index += 4; // TODO: parse earliestPresentationTime and firstOffset // usually zero in our case var earliestPresentationTime = 0; var firstOffset = 0; if (version === 0) { index += 8; } else { index += 16; } // skip reserved index += 2; var startByte = sidx.end + firstOffset; var referencesCount = readUint16(sidx, index); index += 2; for (var i = 0; i < referencesCount; i++) { var referenceIndex = index; var referenceInfo = readUint32(sidx, referenceIndex); referenceIndex += 4; var referenceSize = referenceInfo & 0x7fffffff; var referenceType = (referenceInfo & 0x80000000) >>> 31; if (referenceType === 1) { // eslint-disable-next-line no-console console.warn('SIDX has hierarchical references (not supported)'); return null; } var subsegmentDuration = readUint32(sidx, referenceIndex); referenceIndex += 4; references.push({ referenceSize: referenceSize, subsegmentDuration: subsegmentDuration, // unscaled info: { duration: subsegmentDuration / timescale, start: startByte, end: startByte + referenceSize - 1 } }); startByte += referenceSize; // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits // for |sapDelta|. referenceIndex += 4; // skip to next ref index = referenceIndex; } return { earliestPresentationTime: earliestPresentationTime, timescale: timescale, version: version, referencesCount: referencesCount, references: references, moovEndOffset: moovEndOffset }; } /** * Parses an MP4 initialization segment and extracts stream type and * timescale values for any declared tracks. Timescale values indicate the * number of clock ticks per second to assume for time-based values * elsewhere in the MP4. * * To determine the start time of an MP4, you need two pieces of * information: the timescale unit and the earliest base media decode * time. Multiple timescales can be specified within an MP4 but the * base media decode time is always expressed in the timescale from * the media header box for the track: * ``` * moov > trak > mdia > mdhd.timescale * moov > trak > mdia > hdlr * ``` * @param initSegment {Uint8Array} the bytes of the init segment * @return {InitData} a hash of track type to timescale values or null if * the init segment is malformed. */ function parseInitSegment(initSegment) { var result = []; var traks = findBox(initSegment, ['moov', 'trak']); for (var i = 0; i < traks.length; i++) { var trak = traks[i]; var tkhd = findBox(trak, ['tkhd'])[0]; if (tkhd) { var version = tkhd.data[tkhd.start]; var _index = version === 0 ? 12 : 20; var trackId = readUint32(tkhd, _index); var mdhd = findBox(trak, ['mdia', 'mdhd'])[0]; if (mdhd) { version = mdhd.data[mdhd.start]; _index = version === 0 ? 12 : 20; var timescale = readUint32(mdhd, _index); var hdlr = findBox(trak, ['mdia', 'hdlr'])[0]; if (hdlr) { var hdlrType = bin2str(hdlr.data.subarray(hdlr.start + 8, hdlr.start + 12)); var type = { soun: _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].AUDIO, vide: _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].VIDEO }[hdlrType]; if (type) { // Parse codec details var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0]; var codec = void 0; if (stsd) { codec = bin2str(stsd.data.subarray(stsd.start + 12, stsd.start + 16)); // TODO: Parse codec details to be able to build MIME type. // stsd.start += 8; // const codecBox = findBox(stsd, [codec])[0]; // if (codecBox) { // TODO: Codec parsing support for avc1, mp4a, hevc, av01... // } } result[trackId] = { timescale: timescale, type: type }; result[type] = { timescale: timescale, id: trackId, codec: codec }; } } } } } var trex = findBox(initSegment, ['moov', 'mvex', 'trex']); trex.forEach(function (trex) { var trackId = readUint32(trex, 4); var track = result[trackId]; if (track) { track.default = { duration: readUint32(trex, 12), flags: readUint32(trex, 20) }; } }); return result; } /** * Determine the base media decode start time, in seconds, for an MP4 * fragment. If multiple fragments are specified, the earliest time is * returned. * * The base media decode time can be parsed from track fragment * metadata: * ``` * moof > traf > tfdt.baseMediaDecodeTime * ``` * It requires the timescale value from the mdhd to interpret. * * @param initData {InitData} a hash of track type to timescale values * @param fmp4 {Uint8Array} the bytes of the mp4 fragment * @return {number} the earliest base media decode start time for the * fragment, in seconds */ function getStartDTS(initData, fmp4) { // we need info from two children of each track fragment box return findBox(fmp4, ['moof', 'traf']).reduce(function (result, traf) { var tfdt = findBox(traf, ['tfdt'])[0]; var version = tfdt.data[tfdt.start]; var start = findBox(traf, ['tfhd']).reduce(function (result, tfhd) { // get the track id from the tfhd var id = readUint32(tfhd, 4); var track = initData[id]; if (track) { var baseTime = readUint32(tfdt, 4); if (version === 1) { baseTime *= Math.pow(2, 32); baseTime += readUint32(tfdt, 8); } // assume a 90kHz clock if no timescale was specified var scale = track.timescale || 90e3; // convert base time to seconds var startTime = baseTime / scale; if (isFinite(startTime) && (result === null || startTime < result)) { return startTime; } } return result; }, null); if (start !== null && isFinite(start) && (result === null || start < result)) { return start; } return result; }, null) || 0; } /* For Reference: aligned(8) class TrackFragmentHeaderBox extends FullBox(‘tfhd’, 0, tf_flags){ unsigned int(32) track_ID; // all the following are optional fields unsigned int(64) base_data_offset; unsigned int(32) sample_description_index; unsigned int(32) default_sample_duration; unsigned int(32) default_sample_size; unsigned int(32) default_sample_flags } */ function getDuration(data, initData) { var rawDuration = 0; var videoDuration = 0; var audioDuration = 0; var trafs = findBox(data, ['moof', 'traf']); for (var i = 0; i < trafs.length; i++) { var traf = trafs[i]; // There is only one tfhd & trun per traf // This is true for CMAF style content, and we should perhaps check the ftyp // and only look for a single trun then, but for ISOBMFF we should check // for multiple track runs. var tfhd = findBox(traf, ['tfhd'])[0]; // get the track id from the tfhd var id = readUint32(tfhd, 4); var track = initData[id]; if (!track) { continue; } var trackDefault = track.default; var tfhdFlags = readUint32(tfhd, 0) | (trackDefault === null || trackDefault === void 0 ? void 0 : trackDefault.flags); var sampleDuration = trackDefault === null || trackDefault === void 0 ? void 0 : trackDefault.duration; if (tfhdFlags & 0x000008) { // 0x000008 indicates the presence of the default_sample_duration field if (tfhdFlags & 0x000002) { // 0x000002 indicates the presence of the sample_description_index field, which precedes default_sample_duration // If present, the default_sample_duration exists at byte offset 12 sampleDuration = readUint32(tfhd, 12); } else { // Otherwise, the duration is at byte offset 8 sampleDuration = readUint32(tfhd, 8); } } // assume a 90kHz clock if no timescale was specified var timescale = track.timescale || 90e3; var truns = findBox(traf, ['trun']); for (var j = 0; j < truns.length; j++) { if (sampleDuration) { var sampleCount = readUint32(truns[j], 4); rawDuration = sampleDuration * sampleCount; } else { rawDuration = computeRawDurationFromSamples(truns[j]); } if (track.type === _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].VIDEO) { videoDuration += rawDuration / timescale; } else if (track.type === _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].AUDIO) { audioDuration += rawDuration / timescale; } } } if (videoDuration === 0 && audioDuration === 0) { // If duration samples are not available in the traf use sidx subsegment_duration var sidx = parseSegmentIndex(data); if (sidx !== null && sidx !== void 0 && sidx.references) { return sidx.references.reduce(function (dur, ref) { return dur + ref.info.duration || 0; }, 0); } } if (videoDuration) { return videoDuration; } return audioDuration; } /* For Reference: aligned(8) class TrackRunBox extends FullBox(‘trun’, version, tr_flags) { unsigned int(32) sample_count; // the following are optional fields signed int(32) data_offset; unsigned int(32) first_sample_flags; // all fields in the following array are optional { unsigned int(32) sample_duration; unsigned int(32) sample_size; unsigned int(32) sample_flags if (version == 0) { unsigned int(32) else { signed int(32) }[ sample_count ] } */ function computeRawDurationFromSamples(trun) { var flags = readUint32(trun, 0); // Flags are at offset 0, non-optional sample_count is at offset 4. Therefore we start 8 bytes in. // Each field is an int32, which is 4 bytes var offset = 8; // data-offset-present flag if (flags & 0x000001) { offset += 4; } // first-sample-flags-present flag if (flags & 0x000004) { offset += 4; } var duration = 0; var sampleCount = readUint32(trun, 4); for (var i = 0; i < sampleCount; i++) { // sample-duration-present flag if (flags & 0x000100) { var sampleDuration = readUint32(trun, offset); duration += sampleDuration; offset += 4; } // sample-size-present flag if (flags & 0x000200) { offset += 4; } // sample-flags-present flag if (flags & 0x000400) { offset += 4; } // sample-composition-time-offsets-present flag if (flags & 0x000800) { offset += 4; } } return duration; } function offsetStartDTS(initData, fmp4, timeOffset) { findBox(fmp4, ['moof', 'traf']).forEach(function (traf) { findBox(traf, ['tfhd']).forEach(function (tfhd) { // get the track id from the tfhd var id = readUint32(tfhd, 4); var track = initData[id]; if (!track) { return; } // assume a 90kHz clock if no timescale was specified var timescale = track.timescale || 90e3; // get the base media decode time from the tfdt findBox(traf, ['tfdt']).forEach(function (tfdt) { var version = tfdt.data[tfdt.start]; var baseMediaDecodeTime = readUint32(tfdt, 4); if (version === 0) { writeUint32(tfdt, 4, baseMediaDecodeTime - timeOffset * timescale); } else { baseMediaDecodeTime *= Math.pow(2, 32); baseMediaDecodeTime += readUint32(tfdt, 8); baseMediaDecodeTime -= timeOffset * timescale; baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0); var upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1)); var lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1)); writeUint32(tfdt, 4, upper); writeUint32(tfdt, 8, lower); } }); }); }); } // TODO: Check if the last moof+mdat pair is part of the valid range function segmentValidRange(data) { var segmentedRange = { valid: null, remainder: null }; var moofs = findBox(data, ['moof']); if (!moofs) { return segmentedRange; } else if (moofs.length < 2) { segmentedRange.remainder = data; return segmentedRange; } var last = moofs[moofs.length - 1]; // Offset by 8 bytes; findBox offsets the start by as much segmentedRange.valid = Object(_typed_array__WEBPACK_IMPORTED_MODULE_0__["sliceUint8"])(data, 0, last.start - 8); segmentedRange.remainder = Object(_typed_array__WEBPACK_IMPORTED_MODULE_0__["sliceUint8"])(data, last.start - 8); return segmentedRange; } function appendUint8Array(data1, data2) { var temp = new Uint8Array(data1.length + data2.length); temp.set(data1); temp.set(data2, data1.length); return temp; } /***/ }), /***/ "./src/utils/output-filter.ts": /*!************************************!*\ !*** ./src/utils/output-filter.ts ***! \************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return OutputFilter; }); var OutputFilter = /*#__PURE__*/function () { function OutputFilter(timelineController, trackName) { this.timelineController = void 0; this.cueRanges = []; this.trackName = void 0; this.startTime = null; this.endTime = null; this.screen = null; this.timelineController = timelineController; this.trackName = trackName; } var _proto = OutputFilter.prototype; _proto.dispatchCue = function dispatchCue() { if (this.startTime === null) { return; } this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen, this.cueRanges); this.startTime = null; }; _proto.newCue = function newCue(startTime, endTime, screen) { if (this.startTime === null || this.startTime > startTime) { this.startTime = startTime; } this.endTime = endTime; this.screen = screen; this.timelineController.createCaptionsTrack(this.trackName); }; _proto.reset = function reset() { this.cueRanges = []; }; return OutputFilter; }(); /***/ }), /***/ "./src/utils/texttrack-utils.ts": /*!**************************************!*\ !*** ./src/utils/texttrack-utils.ts ***! \**************************************/ /*! exports provided: sendAddTrackEvent, addCueToTrack, clearCurrentCues, removeCuesInRange, getCuesInRange */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sendAddTrackEvent", function() { return sendAddTrackEvent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addCueToTrack", function() { return addCueToTrack; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearCurrentCues", function() { return clearCurrentCues; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeCuesInRange", function() { return removeCuesInRange; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getCuesInRange", function() { return getCuesInRange; }); /* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./logger */ "./src/utils/logger.ts"); function sendAddTrackEvent(track, videoEl) { var event; try { event = new Event('addtrack'); } catch (err) { // for IE11 event = document.createEvent('Event'); event.initEvent('addtrack', false, false); } event.track = track; videoEl.dispatchEvent(event); } function addCueToTrack(track, cue) { // Sometimes there are cue overlaps on segmented vtts so the same // cue can appear more than once in different vtt files. // This avoid showing duplicated cues with same timecode and text. var mode = track.mode; if (mode === 'disabled') { track.mode = 'hidden'; } if (track.cues && !track.cues.getCueById(cue.id)) { try { track.addCue(cue); if (!track.cues.getCueById(cue.id)) { throw new Error("addCue is failed for: " + cue); } } catch (err) { _logger__WEBPACK_IMPORTED_MODULE_0__["logger"].debug("[texttrack-utils]: " + err); var textTrackCue = new self.TextTrackCue(cue.startTime, cue.endTime, cue.text); textTrackCue.id = cue.id; track.addCue(textTrackCue); } } if (mode === 'disabled') { track.mode = mode; } } function clearCurrentCues(track) { // When track.mode is disabled, track.cues will be null. // To guarantee the removal of cues, we need to temporarily // change the mode to hidden var mode = track.mode; if (mode === 'disabled') { track.mode = 'hidden'; } if (track.cues) { for (var i = track.cues.length; i--;) { track.removeCue(track.cues[i]); } } if (mode === 'disabled') { track.mode = mode; } } function removeCuesInRange(track, start, end) { var mode = track.mode; if (mode === 'disabled') { track.mode = 'hidden'; } if (track.cues && track.cues.length > 0) { var cues = getCuesInRange(track.cues, start, end); for (var i = 0; i < cues.length; i++) { track.removeCue(cues[i]); } } if (mode === 'disabled') { track.mode = mode; } } // Find first cue starting after given time. // Modified version of binary search O(log(n)). function getFirstCueIndexAfterTime(cues, time) { // If first cue starts after time, start there if (time < cues[0].startTime) { return 0; } // If the last cue ends before time there is no overlap var len = cues.length - 1; if (time > cues[len].endTime) { return -1; } var left = 0; var right = len; while (left <= right) { var mid = Math.floor((right + left) / 2); if (time < cues[mid].startTime) { right = mid - 1; } else if (time > cues[mid].startTime && left < len) { left = mid + 1; } else { // If it's not lower or higher, it must be equal. return mid; } } // At this point, left and right have swapped. // No direct match was found, left or right element must be the closest. Check which one has the smallest diff. return cues[left].startTime - time < time - cues[right].startTime ? left : right; } function getCuesInRange(cues, start, end) { var cuesFound = []; var firstCueInRange = getFirstCueIndexAfterTime(cues, start); if (firstCueInRange > -1) { for (var i = firstCueInRange, len = cues.length; i < len; i++) { var cue = cues[i]; if (cue.startTime >= start && cue.endTime <= end) { cuesFound.push(cue); } else if (cue.startTime > end) { return cuesFound; } } } return cuesFound; } /***/ }), /***/ "./src/utils/time-ranges.ts": /*!**********************************!*\ !*** ./src/utils/time-ranges.ts ***! \**********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * TimeRanges to string helper */ var TimeRanges = { toString: function toString(r) { var log = ''; var len = r.length; for (var i = 0; i < len; i++) { log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']'; } return log; } }; /* harmony default export */ __webpack_exports__["default"] = (TimeRanges); /***/ }), /***/ "./src/utils/timescale-conversion.ts": /*!*******************************************!*\ !*** ./src/utils/timescale-conversion.ts ***! \*******************************************/ /*! exports provided: toTimescaleFromBase, toTimescaleFromScale, toMsFromMpegTsClock, toMpegTsClockFromTimescale */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toTimescaleFromBase", function() { return toTimescaleFromBase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toTimescaleFromScale", function() { return toTimescaleFromScale; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toMsFromMpegTsClock", function() { return toMsFromMpegTsClock; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toMpegTsClockFromTimescale", function() { return toMpegTsClockFromTimescale; }); var MPEG_TS_CLOCK_FREQ_HZ = 90000; function toTimescaleFromBase(value, destScale, srcBase, round) { if (srcBase === void 0) { srcBase = 1; } if (round === void 0) { round = false; } var result = value * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)` return round ? Math.round(result) : result; } function toTimescaleFromScale(value, destScale, srcScale, round) { if (srcScale === void 0) { srcScale = 1; } if (round === void 0) { round = false; } return toTimescaleFromBase(value, destScale, 1 / srcScale, round); } function toMsFromMpegTsClock(value, round) { if (round === void 0) { round = false; } return toTimescaleFromBase(value, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round); } function toMpegTsClockFromTimescale(value, srcScale) { if (srcScale === void 0) { srcScale = 1; } return toTimescaleFromBase(value, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale); } /***/ }), /***/ "./src/utils/typed-array.ts": /*!**********************************!*\ !*** ./src/utils/typed-array.ts ***! \**********************************/ /*! exports provided: sliceUint8 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sliceUint8", function() { return sliceUint8; }); function sliceUint8(array, start, end) { // @ts-expect-error This polyfills IE11 usage of Uint8Array slice. // It always exists in the TypeScript definition so fails, but it fails at runtime on IE11. return Uint8Array.prototype.slice ? array.slice(start, end) : new Uint8Array(Array.prototype.slice.call(array, start, end)); } /***/ }), /***/ "./src/utils/vttcue.ts": /*!*****************************!*\ !*** ./src/utils/vttcue.ts ***! \*****************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * Copyright 2013 vtt.js Contributors * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* harmony default export */ __webpack_exports__["default"] = ((function () { if (typeof self !== 'undefined' && self.VTTCue) { return self.VTTCue; } var AllowedDirections = ['', 'lr', 'rl']; var AllowedAlignments = ['start', 'middle', 'end', 'left', 'right']; function isAllowedValue(allowed, value) { if (typeof value !== 'string') { return false; } // necessary for assuring the generic conforms to the Array interface if (!Array.isArray(allowed)) { return false; } // reset the type so that the next narrowing works well var lcValue = value.toLowerCase(); // use the allow list to narrow the type to a specific subset of strings if (~allowed.indexOf(lcValue)) { return lcValue; } return false; } function findDirectionSetting(value) { return isAllowedValue(AllowedDirections, value); } function findAlignSetting(value) { return isAllowedValue(AllowedAlignments, value); } function extend(obj) { for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { rest[_key - 1] = arguments[_key]; } var i = 1; for (; i < arguments.length; i++) { var cobj = arguments[i]; for (var p in cobj) { obj[p] = cobj[p]; } } return obj; } function VTTCue(startTime, endTime, text) { var cue = this; var baseObj = { enumerable: true }; /** * Shim implementation specific properties. These properties are not in * the spec. */ // Lets us know when the VTTCue's data has changed in such a way that we need // to recompute its display state. This lets us compute its display state // lazily. cue.hasBeenReset = false; /** * VTTCue and TextTrackCue properties * http://dev.w3.org/html5/webvtt/#vttcue-interface */ var _id = ''; var _pauseOnExit = false; var _startTime = startTime; var _endTime = endTime; var _text = text; var _region = null; var _vertical = ''; var _snapToLines = true; var _line = 'auto'; var _lineAlign = 'start'; var _position = 50; var _positionAlign = 'middle'; var _size = 50; var _align = 'middle'; Object.defineProperty(cue, 'id', extend({}, baseObj, { get: function get() { return _id; }, set: function set(value) { _id = '' + value; } })); Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, { get: function get() { return _pauseOnExit; }, set: function set(value) { _pauseOnExit = !!value; } })); Object.defineProperty(cue, 'startTime', extend({}, baseObj, { get: function get() { return _startTime; }, set: function set(value) { if (typeof value !== 'number') { throw new TypeError('Start time must be set to a number.'); } _startTime = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, 'endTime', extend({}, baseObj, { get: function get() { return _endTime; }, set: function set(value) { if (typeof value !== 'number') { throw new TypeError('End time must be set to a number.'); } _endTime = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, 'text', extend({}, baseObj, { get: function get() { return _text; }, set: function set(value) { _text = '' + value; this.hasBeenReset = true; } })); // todo: implement VTTRegion polyfill? Object.defineProperty(cue, 'region', extend({}, baseObj, { get: function get() { return _region; }, set: function set(value) { _region = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, 'vertical', extend({}, baseObj, { get: function get() { return _vertical; }, set: function set(value) { var setting = findDirectionSetting(value); // Have to check for false because the setting an be an empty string. if (setting === false) { throw new SyntaxError('An invalid or illegal string was specified.'); } _vertical = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, { get: function get() { return _snapToLines; }, set: function set(value) { _snapToLines = !!value; this.hasBeenReset = true; } })); Object.defineProperty(cue, 'line', extend({}, baseObj, { get: function get() { return _line; }, set: function set(value) { if (typeof value !== 'number' && value !== 'auto') { throw new SyntaxError('An invalid number or illegal string was specified.'); } _line = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, { get: function get() { return _lineAlign; }, set: function set(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError('An invalid or illegal string was specified.'); } _lineAlign = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, 'position', extend({}, baseObj, { get: function get() { return _position; }, set: function set(value) { if (value < 0 || value > 100) { throw new Error('Position must be between 0 and 100.'); } _position = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, { get: function get() { return _positionAlign; }, set: function set(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError('An invalid or illegal string was specified.'); } _positionAlign = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, 'size', extend({}, baseObj, { get: function get() { return _size; }, set: function set(value) { if (value < 0 || value > 100) { throw new Error('Size must be between 0 and 100.'); } _size = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, 'align', extend({}, baseObj, { get: function get() { return _align; }, set: function set(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError('An invalid or illegal string was specified.'); } _align = setting; this.hasBeenReset = true; } })); /** * Other <track> spec defined properties */ // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state cue.displayState = undefined; } /** * VTTCue methods */ VTTCue.prototype.getCueAsHTML = function () { // Assume WebVTT.convertCueToDOMTree is on the global. var WebVTT = self.WebVTT; return WebVTT.convertCueToDOMTree(self, this.text); }; // this is a polyfill hack return VTTCue; })()); /***/ }), /***/ "./src/utils/vttparser.ts": /*!********************************!*\ !*** ./src/utils/vttparser.ts ***! \********************************/ /*! exports provided: parseTimeStamp, fixLineBreaks, VTTParser */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseTimeStamp", function() { return parseTimeStamp; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fixLineBreaks", function() { return fixLineBreaks; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VTTParser", function() { return VTTParser; }); /* harmony import */ var _vttcue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vttcue */ "./src/utils/vttcue.ts"); /* * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js */ var StringDecoder = /*#__PURE__*/function () { function StringDecoder() {} var _proto = StringDecoder.prototype; // eslint-disable-next-line @typescript-eslint/no-unused-vars _proto.decode = function decode(data, options) { if (!data) { return ''; } if (typeof data !== 'string') { throw new Error('Error - expected string data.'); } return decodeURIComponent(encodeURIComponent(data)); }; return StringDecoder; }(); // Try to parse input as a time stamp. function parseTimeStamp(input) { function computeSeconds(h, m, s, f) { return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + parseFloat(f || 0); } var m = input.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/); if (!m) { return null; } if (parseFloat(m[2]) > 59) { // Timestamp takes the form of [hours]:[minutes].[milliseconds] // First position is hours as it's over 59. return computeSeconds(m[2], m[3], 0, m[4]); } // Timestamp takes the form of [hours (optional)]:[minutes]:[seconds].[milliseconds] return computeSeconds(m[1], m[2], m[3], m[4]); } // A settings object holds key/value pairs and will ignore anything but the first // assignment to a specific key. var Settings = /*#__PURE__*/function () { function Settings() { this.values = Object.create(null); } var _proto2 = Settings.prototype; // Only accept the first assignment to any key. _proto2.set = function set(k, v) { if (!this.get(k) && v !== '') { this.values[k] = v; } } // Return the value for a key, or a default value. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with // a number of possible default values as properties where 'defaultKey' is // the key of the property that will be chosen; otherwise it's assumed to be // a single value. ; _proto2.get = function get(k, dflt, defaultKey) { if (defaultKey) { return this.has(k) ? this.values[k] : dflt[defaultKey]; } return this.has(k) ? this.values[k] : dflt; } // Check whether we have a value for a key. ; _proto2.has = function has(k) { return k in this.values; } // Accept a setting if its one of the given alternatives. ; _proto2.alt = function alt(k, v, a) { for (var n = 0; n < a.length; ++n) { if (v === a[n]) { this.set(k, v); break; } } } // Accept a setting if its a valid (signed) integer. ; _proto2.integer = function integer(k, v) { if (/^-?\d+$/.test(v)) { // integer this.set(k, parseInt(v, 10)); } } // Accept a setting if its a valid percentage. ; _proto2.percent = function percent(k, v) { if (/^([\d]{1,3})(\.[\d]*)?%$/.test(v)) { var percent = parseFloat(v); if (percent >= 0 && percent <= 100) { this.set(k, percent); return true; } } return false; }; return Settings; }(); // Helper function to parse input into groups separated by 'groupDelim', and // interpret each group as a key/value pair separated by 'keyValueDelim'. function parseOptions(input, callback, keyValueDelim, groupDelim) { var groups = groupDelim ? input.split(groupDelim) : [input]; for (var i in groups) { if (typeof groups[i] !== 'string') { continue; } var kv = groups[i].split(keyValueDelim); if (kv.length !== 2) { continue; } var _k = kv[0]; var _v = kv[1]; callback(_k, _v); } } var defaults = new _vttcue__WEBPACK_IMPORTED_MODULE_0__["default"](0, 0, ''); // 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244 // Safari doesn't yet support this change, but FF and Chrome do. var center = defaults.align === 'middle' ? 'middle' : 'center'; function parseCue(input, cue, regionList) { // Remember the original input if we need to throw an error. var oInput = input; // 4.1 WebVTT timestamp function consumeTimeStamp() { var ts = parseTimeStamp(input); if (ts === null) { throw new Error('Malformed timestamp: ' + oInput); } // Remove time stamp from input. input = input.replace(/^[^\sa-zA-Z-]+/, ''); return ts; } // 4.4.2 WebVTT cue settings function consumeCueSettings(input, cue) { var settings = new Settings(); parseOptions(input, function (k, v) { var vals; switch (k) { case 'region': // Find the last region we parsed with the same region id. for (var i = regionList.length - 1; i >= 0; i--) { if (regionList[i].id === v) { settings.set(k, regionList[i].region); break; } } break; case 'vertical': settings.alt(k, v, ['rl', 'lr']); break; case 'line': vals = v.split(','); settings.integer(k, vals[0]); if (settings.percent(k, vals[0])) { settings.set('snapToLines', false); } settings.alt(k, vals[0], ['auto']); if (vals.length === 2) { settings.alt('lineAlign', vals[1], ['start', center, 'end']); } break; case 'position': vals = v.split(','); settings.percent(k, vals[0]); if (vals.length === 2) { settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']); } break; case 'size': settings.percent(k, v); break; case 'align': settings.alt(k, v, ['start', center, 'end', 'left', 'right']); break; } }, /:/, /\s/); // Apply default values for any missing fields. cue.region = settings.get('region', null); cue.vertical = settings.get('vertical', ''); var line = settings.get('line', 'auto'); if (line === 'auto' && defaults.line === -1) { // set numeric line number for Safari line = -1; } cue.line = line; cue.lineAlign = settings.get('lineAlign', 'start'); cue.snapToLines = settings.get('snapToLines', true); cue.size = settings.get('size', 100); cue.align = settings.get('align', center); var position = settings.get('position', 'auto'); if (position === 'auto' && defaults.position === 50) { // set numeric position for Safari position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50; } cue.position = position; } function skipWhitespace() { input = input.replace(/^\s+/, ''); } // 4.1 WebVTT cue timings. skipWhitespace(); cue.startTime = consumeTimeStamp(); // (1) collect cue start time skipWhitespace(); if (input.substr(0, 3) !== '-->') { // (3) next characters must match '-->' throw new Error("Malformed time stamp (time stamps must be separated by '-->'): " + oInput); } input = input.substr(3); skipWhitespace(); cue.endTime = consumeTimeStamp(); // (5) collect cue end time // 4.1 WebVTT cue settings list. skipWhitespace(); consumeCueSettings(input, cue); } function fixLineBreaks(input) { return input.replace(/<br(?: \/)?>/gi, '\n'); } var VTTParser = /*#__PURE__*/function () { function VTTParser() { this.state = 'INITIAL'; this.buffer = ''; this.decoder = new StringDecoder(); this.regionList = []; this.cue = null; this.oncue = void 0; this.onparsingerror = void 0; this.onflush = void 0; } var _proto3 = VTTParser.prototype; _proto3.parse = function parse(data) { var _this = this; // If there is no data then we won't decode it, but will just try to parse // whatever is in buffer already. This may occur in circumstances, for // example when flush() is called. if (data) { // Try to decode the data that we received. _this.buffer += _this.decoder.decode(data, { stream: true }); } function collectNextLine() { var buffer = _this.buffer; var pos = 0; buffer = fixLineBreaks(buffer); while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') { ++pos; } var line = buffer.substr(0, pos); // Advance the buffer early in case we fail below. if (buffer[pos] === '\r') { ++pos; } if (buffer[pos] === '\n') { ++pos; } _this.buffer = buffer.substr(pos); return line; } // 3.2 WebVTT metadata header syntax function parseHeader(input) { parseOptions(input, function (k, v) {// switch (k) { // case 'region': // 3.3 WebVTT region metadata header syntax // console.log('parse region', v); // parseRegion(v); // break; // } }, /:/); } // 5.1 WebVTT file parsing. try { var line = ''; if (_this.state === 'INITIAL') { // We can't start parsing until we have the first line. if (!/\r\n|\n/.test(_this.buffer)) { return this; } line = collectNextLine(); // strip of UTF-8 BOM if any // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8 var m = line.match(/^()?WEBVTT([ \t].*)?$/); if (!m || !m[0]) { throw new Error('Malformed WebVTT signature.'); } _this.state = 'HEADER'; } var alreadyCollectedLine = false; while (_this.buffer) { // We can't parse a line until we have the full line. if (!/\r\n|\n/.test(_this.buffer)) { return this; } if (!alreadyCollectedLine) { line = collectNextLine(); } else { alreadyCollectedLine = false; } switch (_this.state) { case 'HEADER': // 13-18 - Allow a header (metadata) under the WEBVTT line. if (/:/.test(line)) { parseHeader(line); } else if (!line) { // An empty line terminates the header and starts the body (cues). _this.state = 'ID'; } continue; case 'NOTE': // Ignore NOTE blocks. if (!line) { _this.state = 'ID'; } continue; case 'ID': // Check for the start of NOTE blocks. if (/^NOTE($|[ \t])/.test(line)) { _this.state = 'NOTE'; break; } // 19-29 - Allow any number of line terminators, then initialize new cue values. if (!line) { continue; } _this.cue = new _vttcue__WEBPACK_IMPORTED_MODULE_0__["default"](0, 0, ''); _this.state = 'CUE'; // 30-39 - Check if self line contains an optional identifier or timing data. if (line.indexOf('-->') === -1) { _this.cue.id = line; continue; } // Process line as start of a cue. /* falls through */ case 'CUE': // 40 - Collect cue timings and settings. if (!_this.cue) { _this.state = 'BADCUE'; continue; } try { parseCue(line, _this.cue, _this.regionList); } catch (e) { // In case of an error ignore rest of the cue. _this.cue = null; _this.state = 'BADCUE'; continue; } _this.state = 'CUETEXT'; continue; case 'CUETEXT': { var hasSubstring = line.indexOf('-->') !== -1; // 34 - If we have an empty line then report the cue. // 35 - If we have the special substring '-->' then report the cue, // but do not collect the line as we need to process the current // one as a new cue. if (!line || hasSubstring && (alreadyCollectedLine = true)) { // We are done parsing self cue. if (_this.oncue && _this.cue) { _this.oncue(_this.cue); } _this.cue = null; _this.state = 'ID'; continue; } if (_this.cue === null) { continue; } if (_this.cue.text) { _this.cue.text += '\n'; } _this.cue.text += line; } continue; case 'BADCUE': // 54-62 - Collect and discard the remaining cue. if (!line) { _this.state = 'ID'; } } } } catch (e) { // If we are currently parsing a cue, report what we have. if (_this.state === 'CUETEXT' && _this.cue && _this.oncue) { _this.oncue(_this.cue); } _this.cue = null; // Enter BADWEBVTT state if header was not parsed correctly otherwise // another exception occurred so enter BADCUE state. _this.state = _this.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE'; } return this; }; _proto3.flush = function flush() { var _this = this; try { // Finish decoding the stream. // _this.buffer += _this.decoder.decode(); // Synthesize the end of the current cue or region. if (_this.cue || _this.state === 'HEADER') { _this.buffer += '\n\n'; _this.parse(); } // If we've flushed, parsed, and we're still on the INITIAL state then // that means we don't have enough of the stream to parse the first // line. if (_this.state === 'INITIAL' || _this.state === 'BADWEBVTT') { throw new Error('Malformed WebVTT signature.'); } } catch (e) { if (_this.onparsingerror) { _this.onparsingerror(e); } } if (_this.onflush) { _this.onflush(); } return this; }; return VTTParser; }(); /***/ }), /***/ "./src/utils/webvtt-parser.ts": /*!************************************!*\ !*** ./src/utils/webvtt-parser.ts ***! \************************************/ /*! exports provided: generateCueId, parseWebVTT */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "generateCueId", function() { return generateCueId; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseWebVTT", function() { return parseWebVTT; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _vttparser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vttparser */ "./src/utils/vttparser.ts"); /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts"); /* harmony import */ var _timescale_conversion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./timescale-conversion */ "./src/utils/timescale-conversion.ts"); /* harmony import */ var _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../remux/mp4-remuxer */ "./src/remux/mp4-remuxer.ts"); var LINEBREAKS = /\r\n|\n\r|\n|\r/g; // String.prototype.startsWith is not supported in IE11 var startsWith = function startsWith(inputString, searchString, position) { if (position === void 0) { position = 0; } return inputString.substr(position, searchString.length) === searchString; }; var cueString2millis = function cueString2millis(timeString) { var ts = parseInt(timeString.substr(-3)); var secs = parseInt(timeString.substr(-6, 2)); var mins = parseInt(timeString.substr(-9, 2)); var hours = timeString.length > 9 ? parseInt(timeString.substr(0, timeString.indexOf(':'))) : 0; if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(ts) || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(secs) || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mins) || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(hours)) { throw Error("Malformed X-TIMESTAMP-MAP: Local:" + timeString); } ts += 1000 * secs; ts += 60 * 1000 * mins; ts += 60 * 60 * 1000 * hours; return ts; }; // From https://github.com/darkskyapp/string-hash var hash = function hash(text) { var hash = 5381; var i = text.length; while (i) { hash = hash * 33 ^ text.charCodeAt(--i); } return (hash >>> 0).toString(); }; // Create a unique hash id for a cue based on start/end times and text. // This helps timeline-controller to avoid showing repeated captions. function generateCueId(startTime, endTime, text) { return hash(startTime.toString()) + hash(endTime.toString()) + hash(text); } var calculateOffset = function calculateOffset(vttCCs, cc, presentationTime) { var currCC = vttCCs[cc]; var prevCC = vttCCs[currCC.prevCC]; // This is the first discontinuity or cues have been processed since the last discontinuity // Offset = current discontinuity time if (!prevCC || !prevCC.new && currCC.new) { vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start; currCC.new = false; return; } // There have been discontinuities since cues were last parsed. // Offset = time elapsed while ((_prevCC = prevCC) !== null && _prevCC !== void 0 && _prevCC.new) { var _prevCC; vttCCs.ccOffset += currCC.start - prevCC.start; currCC.new = false; currCC = prevCC; prevCC = vttCCs[currCC.prevCC]; } vttCCs.presentationOffset = presentationTime; }; function parseWebVTT(vttByteArray, initPTS, timescale, vttCCs, cc, timeOffset, callBack, errorCallBack) { var parser = new _vttparser__WEBPACK_IMPORTED_MODULE_1__["VTTParser"](); // Convert byteArray into string, replacing any somewhat exotic linefeeds with "\n", then split on that character. // Uint8Array.prototype.reduce is not implemented in IE11 var vttLines = Object(_demux_id3__WEBPACK_IMPORTED_MODULE_2__["utf8ArrayToStr"])(new Uint8Array(vttByteArray)).trim().replace(LINEBREAKS, '\n').split('\n'); var cues = []; var initPTS90Hz = Object(_timescale_conversion__WEBPACK_IMPORTED_MODULE_3__["toMpegTsClockFromTimescale"])(initPTS, timescale); var cueTime = '00:00.000'; var timestampMapMPEGTS = 0; var timestampMapLOCAL = 0; var parsingError; var inHeader = true; var timestampMap = false; parser.oncue = function (cue) { // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline. var currCC = vttCCs[cc]; var cueOffset = vttCCs.ccOffset; // Calculate subtitle PTS offset var webVttMpegTsMapOffset = (timestampMapMPEGTS - initPTS90Hz) / 90000; // Update offsets for new discontinuities if (currCC !== null && currCC !== void 0 && currCC.new) { if (timestampMapLOCAL !== undefined) { // When local time is provided, offset = discontinuity start time - local time cueOffset = vttCCs.ccOffset = currCC.start; } else { calculateOffset(vttCCs, cc, webVttMpegTsMapOffset); } } if (webVttMpegTsMapOffset) { // If we have MPEGTS, offset = presentation time + discontinuity offset cueOffset = webVttMpegTsMapOffset - vttCCs.presentationOffset; } if (timestampMap) { var duration = cue.endTime - cue.startTime; var startTime = Object(_remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_4__["normalizePts"])((cue.startTime + cueOffset - timestampMapLOCAL) * 90000, timeOffset * 90000) / 90000; cue.startTime = startTime; cue.endTime = startTime + duration; } //trim trailing webvtt block whitespaces var text = cue.text.trim(); // Fix encoding of special characters cue.text = decodeURIComponent(encodeURIComponent(text)); // If the cue was not assigned an id from the VTT file (line above the content), create one. if (!cue.id) { cue.id = generateCueId(cue.startTime, cue.endTime, text); } if (cue.endTime > 0) { cues.push(cue); } }; parser.onparsingerror = function (error) { parsingError = error; }; parser.onflush = function () { if (parsingError) { errorCallBack(parsingError); return; } callBack(cues); }; // Go through contents line by line. vttLines.forEach(function (line) { if (inHeader) { // Look for X-TIMESTAMP-MAP in header. if (startsWith(line, 'X-TIMESTAMP-MAP=')) { // Once found, no more are allowed anyway, so stop searching. inHeader = false; timestampMap = true; // Extract LOCAL and MPEGTS. line.substr(16).split(',').forEach(function (timestamp) { if (startsWith(timestamp, 'LOCAL:')) { cueTime = timestamp.substr(6); } else if (startsWith(timestamp, 'MPEGTS:')) { timestampMapMPEGTS = parseInt(timestamp.substr(7)); } }); try { // Convert cue time to seconds timestampMapLOCAL = cueString2millis(cueTime) / 1000; } catch (error) { timestampMap = false; parsingError = error; } // Return without parsing X-TIMESTAMP-MAP line. return; } else if (line === '') { inHeader = false; } } // Parse line by default. parser.parse(line + '\n'); }); parser.flush(); } /***/ }), /***/ "./src/utils/xhr-loader.ts": /*!*********************************!*\ !*** ./src/utils/xhr-loader.ts ***! \*********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/load-stats */ "./src/loader/load-stats.ts"); var AGE_HEADER_LINE_REGEX = /^age:\s*[\d.]+\s*$/m; var XhrLoader = /*#__PURE__*/function () { function XhrLoader(config /* HlsConfig */ ) { this.xhrSetup = void 0; this.requestTimeout = void 0; this.retryTimeout = void 0; this.retryDelay = void 0; this.config = null; this.callbacks = null; this.context = void 0; this.loader = null; this.stats = void 0; this.xhrSetup = config ? config.xhrSetup : null; this.stats = new _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__["LoadStats"](); this.retryDelay = 0; } var _proto = XhrLoader.prototype; _proto.destroy = function destroy() { this.callbacks = null; this.abortInternal(); this.loader = null; this.config = null; }; _proto.abortInternal = function abortInternal() { var loader = this.loader; self.clearTimeout(this.requestTimeout); self.clearTimeout(this.retryTimeout); if (loader) { loader.onreadystatechange = null; loader.onprogress = null; if (loader.readyState !== 4) { this.stats.aborted = true; loader.abort(); } } }; _proto.abort = function abort() { var _this$callbacks; this.abortInternal(); if ((_this$callbacks = this.callbacks) !== null && _this$callbacks !== void 0 && _this$callbacks.onAbort) { this.callbacks.onAbort(this.stats, this.context, this.loader); } }; _proto.load = function load(context, config, callbacks) { if (this.stats.loading.start) { throw new Error('Loader can only be used once.'); } this.stats.loading.start = self.performance.now(); this.context = context; this.config = config; this.callbacks = callbacks; this.retryDelay = config.retryDelay; this.loadInternal(); }; _proto.loadInternal = function loadInternal() { var config = this.config, context = this.context; if (!config) { return; } var xhr = this.loader = new self.XMLHttpRequest(); var stats = this.stats; stats.loading.first = 0; stats.loaded = 0; var xhrSetup = this.xhrSetup; try { if (xhrSetup) { try { xhrSetup(xhr, context.url); } catch (e) { // fix xhrSetup: (xhr, url) => {xhr.setRequestHeader("Content-Language", "test");} // not working, as xhr.setRequestHeader expects xhr.readyState === OPEN xhr.open('GET', context.url, true); xhrSetup(xhr, context.url); } } if (!xhr.readyState) { xhr.open('GET', context.url, true); } } catch (e) { // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS this.callbacks.onError({ code: xhr.status, text: e.message }, context, xhr); return; } if (context.rangeEnd) { xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1)); } xhr.onreadystatechange = this.readystatechange.bind(this); xhr.onprogress = this.loadprogress.bind(this); xhr.responseType = context.responseType; // setup timeout before we perform request self.clearTimeout(this.requestTimeout); this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout); xhr.send(); }; _proto.readystatechange = function readystatechange() { var context = this.context, xhr = this.loader, stats = this.stats; if (!context || !xhr) { return; } var readyState = xhr.readyState; var config = this.config; // don't proceed if xhr has been aborted if (stats.aborted) { return; } // >= HEADERS_RECEIVED if (readyState >= 2) { // clear xhr timeout and rearm it if readyState less than 4 self.clearTimeout(this.requestTimeout); if (stats.loading.first === 0) { stats.loading.first = Math.max(self.performance.now(), stats.loading.start); } if (readyState === 4) { xhr.onreadystatechange = null; xhr.onprogress = null; var status = xhr.status; // http status between 200 to 299 are all successful if (status >= 200 && status < 300) { stats.loading.end = Math.max(self.performance.now(), stats.loading.first); var data; var len; if (context.responseType === 'arraybuffer') { data = xhr.response; len = data.byteLength; } else { data = xhr.responseText; len = data.length; } stats.loaded = stats.total = len; if (!this.callbacks) { return; } var onProgress = this.callbacks.onProgress; if (onProgress) { onProgress(stats, context, data, xhr); } if (!this.callbacks) { return; } var response = { url: xhr.responseURL, data: data }; this.callbacks.onSuccess(response, stats, context, xhr); } else { // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error if (stats.retry >= config.maxRetry || status >= 400 && status < 499) { _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].error(status + " while loading " + context.url); this.callbacks.onError({ code: status, text: xhr.statusText }, context, xhr); } else { // retry _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].warn(status + " while loading " + context.url + ", retrying in " + this.retryDelay + "..."); // abort and reset internal state this.abortInternal(); this.loader = null; // schedule retry self.clearTimeout(this.retryTimeout); this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay); // set exponential backoff this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay); stats.retry++; } } } else { // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet self.clearTimeout(this.requestTimeout); this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout); } } }; _proto.loadtimeout = function loadtimeout() { _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].warn("timeout while loading " + this.context.url); var callbacks = this.callbacks; if (callbacks) { this.abortInternal(); callbacks.onTimeout(this.stats, this.context, this.loader); } }; _proto.loadprogress = function loadprogress(event) { var stats = this.stats; stats.loaded = event.loaded; if (event.lengthComputable) { stats.total = event.total; } }; _proto.getCacheAge = function getCacheAge() { var result = null; if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) { var ageHeader = this.loader.getResponseHeader('age'); result = ageHeader ? parseFloat(ageHeader) : null; } return result; }; return XhrLoader; }(); /* harmony default export */ __webpack_exports__["default"] = (XhrLoader); /***/ }) /******/ })["default"]; }); //# sourceMappingURL=hls.js.map
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.ensureProps = ensureProps; var _lodash = require('lodash'); var _lodash2 = _interopRequireDefault(_lodash); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * ensure object has properties. throw * exception if not present */ function ensureProps(obj, propLs) { _lodash2.default.forEach(propLs, function (e) { if (!_lodash2.default.has(obj, e)) { throw new Error('ensureProps FAILED'); } }); return true; }
// # models var models = module.exports = { User: require('./user') }
var Project = React.createClass({displayName: "Project", render: function() { var data = this.props.data; return ( React.createElement("a", {href: data.href}, React.createElement("div", {className: "project"}, React.createElement("img", {src: data.src, alt: data.alt}), React.createElement("h4", null, data.title), React.createElement("p", null, data.description, React.createElement("br", null), data.tech) ) ) ); } }); var ProjectColumn = React.createClass({displayName: "ProjectColumn", render: function() { var projects = this.props.projects; return ( React.createElement("div", {className: this.props.classList}, projects.map(function(project) { return React.createElement(Project, {key: project.id, data: project}) }) ) ); } }); var ProjectDisplay = React.createClass({displayName: "ProjectDisplay", render: function() { return( React.createElement("div", null, React.createElement("h1", null, React.createElement("span", {className: "glyphicon glyphicon-ok"}), " Projects"), React.createElement("h2", null, React.createElement("small", null, "I currently enjoy building with Rails, PostgreSQL, ReactJS, and SCSS")), React.createElement(ProjectColumn, {classList: "col-sm-6 col-md-4 col-md-offset-2", projects: projectColumn1}), React.createElement(ProjectColumn, {classList: "col-sm-6 col-md-4", projects: projectColumn2}) ) ) } }) // make a ProjectDisplayColumn var projectColumn1 = [ { id: 1, src: 'img/transaction-mappr-screen.png', href: 'https://stark-shelf-3141.herokuapp.com', alt: "screenshot of TransactionMappr", title: "TransactionMappr", description: "Dynamically display relationships between users' locations, transaction types/totals, and date", tech: 'Rails, React, jQuery, and Sass' }, { id: 2, src: "img/hummingbird-screen.png", alt: "Screenshot of Hummingbird", title: "Hummingbird", description: "Schedule text messages for precision date/time delivery.", tech: "Rails, Ionic, Angular" } ]; var projectColumn2 = [ { id: 3, src: "img/northstar-screen.png", href: 'https://northstar-app.herokuapp.com', alt: "Screenshot of Northstar", title: "Northstar", description: "Develop a better sense of distance and direction. Instantly locate in relation to favorite landmarks.", tech: "Sinatra, Ruby, Javascript, Google Maps" }, { id: 4, src: "img/coming-soon.png", alt: "Coming Soon!", title: "Traintracks", description: "Planning and tracking tool for race training. New project.", tech: "Rails, React, Postgres, Sass" } ]; React.render( React.createElement(ProjectDisplay, null), document.getElementById('projects') ); // /* Coming Soon.
/* Databinder @version 0.7 @author Sylvain Pollet-Villard @license MIT @website http://syllab.fr/projets/web/databinder/ */ ;(function(global){ var BINDING_ATTRIBUTE = "data-bind"; var BINDING_GLOBAL = "databind"; var BINDINGS_REGEX = /(?:^|,)\s*(?:(\w+):)?\s*([\w\.\/\|\'\"\s-]+|{.+})+/g; function getTypeOf(obj) { return Object.prototype.toString.call(obj).match(/\s([a-zA-Z]+)/)[1]; } function isFunction(obj){ return getTypeOf(obj) === 'Function'; } function DatabinderError(message){ return new Error("[Databinder] "+message); } /* classList shim for IE9 */ var classListSupported = ("classList" in document.createElement("p")); function toggleClass(elm, className, bool){ if(!classListSupported){ var classes = elm.className.split(" "), i = classes.indexOf(className); if(bool && i === -1){ classes.push(className); } else if(!bool && i >= 0){ classes.splice(i, 1); } elm.className = classes.join(" ").trim(); } else { elm.classList[bool ? "add" : "remove"](className); } } function getCopyRef(obj){ var copy, type = getTypeOf(obj); if (type in global && !(obj instanceof Object)) { copy = new global[type](obj); } else { copy = obj; } if (copy instanceof Object) { for (var attr in obj) { if(obj.hasOwnProperty(attr)){ copy[attr] = obj[attr]; } } } return copy; } var DataBoundElement = Object.create({ set: function(data){ this.scope = DataScope.init(data); return this.reset(); }, reset: function(){ if(this.originalHTML !== undefined){ this.elm.innerHTML = this.originalHTML; } this.parse(); return this; }, get: function(){ var b, c, l, i; for(i=0, l=this.bindings.length; b = this.bindings[i], i<l; i++) { if((this.elm instanceof HTMLInputElement && b.attribute === "value") || (this.elm instanceof HTMLTextAreaElement && ["value","text","html"].indexOf(b.attribute) > 0)){ this.scope.lookup(b.value, this.elm).data[b.value] = this.elm.value; } } if(this.elm.children) { for(c=0, l=this.elm.children.length; c<l; c++){ var child = this.elm.children[c]; if(DataBoundElement.isPrototypeOf(child.databinding)) { child.databinding.get(); } } } return this; }, getBindings: function(){ var bindings = [], bindingAttr = this.elm.getAttribute(BINDING_ATTRIBUTE); if(bindingAttr === ""){ return [{ attribute: undefined, value: undefined }]; } if(bindingAttr !== null){ var match = BINDINGS_REGEX.exec(bindingAttr); if(match === null){ throw DatabinderError("Invalid argument for data-binding: "+bindingAttr); } while (match !== null) { bindings.push({ attribute: match[1], value: match[2] }); match = BINDINGS_REGEX.exec(bindingAttr); } } return bindings; }, parse: function(){ var binding, bindingSet, loop, innerScope = this.scope; for(var b=0, l=this.bindings.length; binding = this.bindings[b], b<l; b++){ if(binding.value === undefined){ binding.value = this.guessValue(); } else if(binding.value[0] === '{'){ bindingSet = {}; var pairs = binding.value.slice(1,-1).split(','); for(var p=0, m=pairs.length; p < m; p++){ var match = pairs[p].match(/(\w+):\s*([\w\.\/\|\s]+)/); if(match === null || match.length < 3){ throw DatabinderError("Invalid argument for binding set: "+pairs[p]); } bindingSet[match[1].trim()] = match[2].trim(); } } if(binding.attribute === undefined){ binding.attribute = this.guessAttribute(binding.value); } switch(binding.attribute){ case "text": this.bindText(this.scope.resolve(binding.value, this.elm)); innerScope = null; break; case "html": this.bindHTML(this.scope.resolve(binding.value, this.elm)); innerScope = null; break; case "with": innerScope = DataScope.init(this.scope.resolve(binding.value, this.elm), this.scope); break; case "loop": innerScope = this.bindLoop(bindingSet || { in: binding.value }); break; case "if": if(this.bindIf(binding.value, true)) return; break; case "ifnot": if(this.bindIf(binding.value, false)) return; break; case "visible": this.bindVisibility(binding.value, true); break; case "hidden": this.bindVisibility(binding.value, false); break; case "style": this.bindStyle(bindingSet || binding.value); break; case "class": this.bindClass(bindingSet || binding.value); break; case "on": this.bindEvents(bindingSet); break; case "template": this.bindTemplate(binding.value); break; default: if( ("on" + binding.attribute) in global){ var eventBinding = {}; eventBinding[binding.attribute] = binding.value; this.bindEvents(eventBinding); } else { this.bindAttribute(binding.attribute, this.scope.resolve(binding.value, this.elm)); } break; } } if(this.loop !== undefined) { this.parseLoop(innerScope); } else if(innerScope !== null){ this.parseChildren(innerScope); } }, bindText: function(value){ if(value !== undefined){ this.elm.textContent = value; } }, bindHTML: function(value){ if(value instanceof Element){ this.elm.innerHTML = ""; this.elm.appendChild(value); } else if(value !== undefined) { this.elm.innerHTML = value; } }, bindAttribute: function(attr, value){ if (value === null) { this.elm.removeAttribute(attr); } else if(value === true || value === false){ this.elm[attr] = value; } else if(value !== undefined){ this.elm.setAttribute(attr, value); } }, bindStyle: function(value){ var p, r; if(value instanceof Object){ for(p in value){ if(value.hasOwnProperty(p) && (r = this.scope.resolve(value[p], this.elm)) !== undefined ){ this.elm.style[p] = r; } } } else { value = this.scope.resolve(value, this.elm); if(value instanceof Object){ for(p in value){ if(value.hasOwnProperty(p) && value[p] !== undefined){ this.elm.style[p] = value[p]; } } } else { this.bindAttribute("style", value); } } }, bindClass: function(classList){ var className; if(classList instanceof Object){ for(className in classList){ if(classList.hasOwnProperty(className)){ var bool = this.scope.resolve(classList[className], this.elm); toggleClass(this.elm, className, bool); } } } else { classList = this.scope.resolve(classList, this.elm); if(Array.isArray(classList)){ this.elm.className = classList.join(' '); } else if(classList instanceof Object){ for(className in classList){ if(classList.hasOwnProperty(className)){ toggleClass(this.elm, className, classList[className]); } } } else { this.elm.className = classList; } } }, bindIf: function(value, bool){ if(Boolean(this.scope.resolve(value, this.elm)) !== bool){ this.elm.parentNode.removeChild(this.elm); return true; //stops parsing } return false; }, bindVisibility: function(value, bool){ this.elm.style.display = Boolean(this.scope.resolve(value, this.elm)) === bool ? "" : "none"; }, bindEvents: function(bindingSet){ var eventType, fn, dbe, root; if(bindingSet === undefined){ throw DatabinderError('"on" binding expects a binding set, instead got ' +bindingSet); } dbe = this; root = dbe.scope; while(root && root.parent){ root = root.parent; } function makeHandler(fn){ return function(event){ fn.call(dbe.scope.data, event, root.data, dbe.elm); }; } for(eventType in bindingSet){ if(bindingSet.hasOwnProperty(eventType)){ fn = this.scope.resolve(bindingSet[eventType], dbe.elm, true); if(isFunction(fn)){ var handler = makeHandler(fn); if(eventType in this.eventListeners){ this.elm.removeEventListener(eventType, this.eventListeners[eventType]); } this.eventListeners[eventType] = handler; this.elm.addEventListener(eventType, handler); } } } }, bindLoop: function(bindingSet){ if (bindingSet["in"] === undefined) { throw DatabinderError("No list specified for loop declaration: " + bindingSet); } this.loop = { list: bindingSet["in"], index: bindingSet["at"] || "loopIndex", item: bindingSet["as"] || "loopValue" }; return this.scope.lookup(bindingSet["in"], this.elm, false); }, bindTemplate: function(templateId){ var template = document.getElementById(templateId); if(template === null){ throw DatabinderError("Template not found: "+templateId); } this.elm.innerHTML = template.innerHTML; }, parseChildren: function(innerScope){ var c, children; if(DataScope.isPrototypeOf(innerScope) && this.elm.children) { children = []; for(c=0; c<this.elm.children.length; c++){ children.push(this.elm.children[c]); } for(c=0; c<children.length; c++){ if(children[c] instanceof Element){ databind(children[c]).set(innerScope); } } } }, parseLoop: function(innerScope){ var i, l, children, list; if(DataScope.isPrototypeOf(innerScope)) { children = []; for (i=0, l=this.elm.childNodes.length; i<l; i++) { children.push(this.elm.childNodes[i].cloneNode(true)); } this.elm.innerHTML = ""; //remove all child nodes list = innerScope.resolve(this.loop.list, this.elm, true); if(Array.isArray(list)){ for(i=0; i<list.length; i++){ this.parseLoopIteration(i, list[i], children, innerScope); } } else if(isFunction(list)){ for(i=0; (l = innerScope.evalFunction(list)) !== null; i++){ this.parseLoopIteration(i, l, children, innerScope); } } else if(list instanceof Object) { for(i in list){ if(list.hasOwnProperty(i)){ this.parseLoopIteration(i, list[i], children, innerScope); } } } } }, parseLoopIteration: function(key, value, children, innerScope){ var c, l, newChild; var data = getCopyRef(value); var scope = DataScope.init(data, innerScope); scope.loopItem = this.loop.item; scope.loopIndex = this.loop.index; scope.data[this.loop.index] = key; scope.data[this.loop.item] = data; for(c=0, l=children.length; c<l; c++){ newChild = children[c].cloneNode(true); this.elm.appendChild(newChild); if(newChild instanceof Element){ databind(newChild).set(scope); } } }, guessValue: function(){ var c, candidate, candidates = []; var id = this.elm.id; var name = this.elm.getAttribute("name"); var classes = this.elm.className.split(" "); candidates = candidates.concat(id).concat(name).concat(classes); for(c=0; c<candidates.length; c++){ if(candidates[c] && (candidate = this.scope.resolve(candidates[c], this.elm)) !== null){ return candidates[c]; } } throw DatabinderError("No binding value suitable for element "+this.elm.outerHTML); }, guessAttribute: function(valueName){ var value = this.scope.resolve(valueName, this.elm); var type = getTypeOf(value); switch(true){ case type==="Object": return "with"; case type==="Array": return "loop"; case value instanceof Element: return "html"; case type==="Boolean": if(getTypeOf(this.elm)==="HTMLInputElement" && "checked" in this.elm) return "checked"; if(getTypeOf(this.elm)==="HTMLOptionElement") return "selected"; return "if"; case type==="String": case type==="Number": if(getTypeOf(this.elm)==="HTMLInputElement") return "value"; if("src" in this.elm) return "src"; return "text"; default: return "text"; } } }); var DataScope = Object.create({ init: function(data, parent) { if(DataScope.isPrototypeOf(data)){ return data; } var ds = Object.create(DataScope); ds.data = data || {}; ds.parent = parent; return ds; }, //Getting a scope centered on value by name lookup: function(name, element, inner) { var value, names, i, l; var scope = this; if(name === "."){ return scope; } if (name[0] === '/') { while(scope.parent){ scope = scope.parent; } name = name.slice(1); } else if(name[0] === "."){ i = 0; while(name[++i] === '.' && scope.parent){ scope = scope.parent; } name = name.slice(i); } else { //Lookup to find a scope with a matching value value = name.split(".")[0]; while(scope.data[value] === undefined && scope.parent){ scope = scope.parent; } } names = name.split('.'); value = scope.data; i = 0; l = names.length - 1; if(inner === true){ l++; } //stops to penultimate name while (value !== undefined && i < l) { value = value[names[i++]]; if(isFunction(value)){ value = this.evalFunction(value, element); } scope = DataScope.init(value, scope); } return scope; }, evalFunction: function(value, element){ var root; if(isFunction(value)){ root = this; while(root && root.parent){ root = root.parent; } value = value.call(this.data, root.data, element); } return value; }, resolve: function(declaration, element, expectsFunction){ var f, l, p, pl, params, resolvedParams, extension, extensionName; var extensions = declaration.split("|"); var value = this.resolveParam(extensions.shift().trim(), element); if(!expectsFunction) { value = this.evalFunction(value, element); } if(extensions.length > 0){ for (f = 0, l = extensions.length; f < l; f++) { params = extensions[f].trim().split(/\s+/); extensionName = params.shift(); extension = databind.extensions[extensionName]; if(extension !== undefined && isFunction(extension)){ resolvedParams = []; for(p = 0, pl = params.length; p < pl; p++){ resolvedParams.push(this.resolveParam(params[p], element)); } value = extension.apply(value, resolvedParams); } else { throw DatabinderError("Unknown extension: " + extensionName); } } } return value; }, resolveParam: function(param, element){ if(!isNaN(param)){ return +param; //inline Number } if(param[0] === '"' || param[0] === "'"){ return param.slice(1, -1); //inline String } var scope = this.lookup(param, element, false); if(param === "."){ return scope.data; } return scope.data[param.match(/([^\/\.\s]+)\s*$/)[1]]; } }); var databind = function(selector, data){ var elm = selector instanceof Element ? selector : document.querySelector(selector); if(elm === null){ throw DatabinderError("No element matched for selector "+selector); } if(elm.databinding){ return elm.databinding; } var dbe = Object.create(DataBoundElement); dbe.eventListeners = {}; dbe.originalHTML = elm.innerHTML; dbe.elm = elm; dbe.bindings = dbe.getBindings(); elm.databinding = dbe; if(data !== undefined){ dbe.set(data); } return dbe; }; databind.extensions = {}; global[BINDING_GLOBAL] = databind; return databind; })(this);
var app_data = require('./app_data.js'); module.exports = { remove_dir : function(){ return {command: 'rm -rf ' + app_data.paths.ios + '/*'}; }, cordova_cli: function(){ return { options: { path: app_data.paths.ios }, create: { options: { command: 'create', id: app_data.app_id, name: app_data.app_name } }, add_platform: { options: { command: 'platform', action: 'add', platforms: ['ios'] } }, add_plugins: { options: { command: 'plugin', action: 'add', plugins: [ app_data.plugins.statusbar, app_data.plugins.dialogs, app_data.plugins.geolocation, app_data.plugins.inappbrowser ] } }, build: { options: { command: 'build', platforms: ['ios'] } } }; }, cordova_config: function(){ return { options: { id: app_data.app_id, version: app_data.app_version.ios, name: app_data.app_name, preferences: [ {name: 'Fullscreen', value: 'false'}, {name: 'Orientation', value: 'portrait'} ] }, dest: app_data.paths.ios + '/config.xml' }; } };
var isArray = require('lodash.isarray'); var levenshtein = require('levenshtein-dist'); /** * Remove reference 'noise' from a string * @param string a The string to remove the noise from * @return string The input string with all noise removed */ function stripNoise(a) { return a .replace(/[^a-z0-9]+/i, ' ') .replace(/ (the|a) /, ' '); } /** * Fuzzily compare strings a and b * @param string a The first string to compare * @param string b The second string to compare * @param number tolerence The tolerence when comparing using levenshtein, defaults to 10 * @return boolean True if a ≈ b */ function fuzzyStringCompare(a, b, tolerence) { if (a == b) return true; var as = stripNoise(a); as = as.toLowerCase(); if (as.length > 255) as = as.substr(0, 255); var bs = stripNoise(b); bs = bs.toLowerCase(); if (bs.length > 255) bs = bs.substr(0, 255); if (tolerence == undefined && levenshtein(as, bs) < 10) return true; if (tolerence && levenshtein(as, bs) <= tolerence) return true; } /** * Splits an author string into its component parts * @param string author The raw author string to split * @return array An array composed of lastname, initial/name */ function splitAuthor(author) { return author .split(/\s*[,\.\s]\s*/) .filter(function(i) { return !!i }) // Strip out blanks .filter(function(i) { return !/^[0-9]+(st|nd|rd|th)$/.test(i) }); // Strip out decendent numerics (e.g. '1st', '23rd') } /** * Splits a single string of multiple authors into an array * @param string str The string to split * @return array The array of extracted authors */ function splitAuthorString(str) { return str.split(/\s*;\s*/); } /** * Compare an array of authors against a second array * @param array a The first array of authors * @param array b The second array of authors * @return bolean True if a ≈ b */ function compareNames(a, b) { if (!isArray(a)) a = splitAuthorString(a); if (!isArray(b)) b = splitAuthorString(b); var aPos = 0, bPos = 0; var authorLimit = Math.min(a.length, b.length); var failed = false; while (aPos < authorLimit && bPos < authorLimit) { if (fuzzyStringCompare(a[aPos], b[bPos])) { // Direct or fuzzy matching of entire strings aPos++; bPos++; } else { var aAuth = splitAuthor(a[aPos]); var bAuth = splitAuthor(b[bPos]); var nameLimit = Math.min(aAuth.length, bAuth.length); var nameMatches = 0; for (var n = 0; n < nameLimit; n++) { if ( aAuth[n] == bAuth[n] || // Direct match aAuth[n].length == 1 && bAuth[n].substr(0, 1) || // A is initial and B is full name bAuth[n].length == 1 && aAuth[n].substr(0, 1) || (aAuth[n].length > 1 && bAuth[n].length > 1 && fuzzyStringCompare(aAuth[n], bAuth[n], 3)) ) { nameMatches++; } } if (nameMatches >= nameLimit) { aPos++; bPos++; } else { failed = true; } break; } } return !failed; } module.exports = compareNames;
HappeningsProjectEmberClient.Router.map(function () { // this.route('happening', { path: '/' }); this.resource('happening', { path: '/all'}, function() { // this.route('show', { path: '/details/:id'}); this.route('when', {path: '/'}); this.route('when', {path: '/:category'}); this.route('when', {path: '/:category/:city'}); this.route('when', {path: '/:category/:city/:range'}); }); });
/** * Created with JetBrains WebStorm. * User: a.demarchi * Date: 17/04/13 * Time: 14.09 * To change this template use File | Settings | File Templates. */ app.routers.router = Backbone.Router.extend({ routes: { '': 'index', ':lang': 'index', ':lang/login': 'login', ':lang/logout': 'logout', 'lang/:lang': 'lang', ':lang/registration': 'registration', ':lang/profile': 'profile', ':lang/password': 'password', ':lang/dashboard': 'dashboard', ':lang/report': 'report', ':lang/report/type_id/:type_id': 'report', ':lang/mapdashboard': 'mapdashboard', ':lang/mapdashboard/id/:id': 'mapdashboard_single', ':lang/credits': 'credits', ':lang/help': 'help', ':lang/project': 'project', ':lang/resend': 'resend', ':lang/activate/:id/:apikey': 'activate', '*undefined': 'error' }, /** public function **/ index: function() { /** load data from localstorage service **/ app.utils.loadTokens(); var lang = app.utils.getLanguage(); /** render navbar view **/ app.global.navbarView = new app.views.navbar(); app.global.navbarView.render(); $('#navbar_content').html(app.global.navbarView.el); /** render index view **/ app.global.indexView = new app.views.index(); app.global.indexView.render(); $('#content').html(app.global.indexView.el); /** render footer view **/ app.global.footerView = new app.views.footer(); app.global.footerView.render(); $('#footer_content').html(app.global.footerView.el); this.navigate('#!' + lang, { trigger : false }); }, /** public function **/ login: function() { /** load data from localstorage service **/ app.utils.loadTokens(); var lang = app.utils.getLanguage(); if (app.global.tokensCollection.length == 0) { /** render navbar view **/ app.global.navbarView = new app.views.navbar(); app.global.navbarView.render(); $('#navbar_content').html(app.global.navbarView.el); /** render login view **/ app.global.loginView = new app.views.login(); app.global.loginView.render(); $('#content').html(app.global.loginView.el); /** render footer view **/ app.global.footerView = new app.views.footer(); app.global.footerView.render(); $('#footer_content').html(app.global.footerView.el); this.navigate('#!' + lang + '/login', { trigger : false }); } else { this.dashboard(); } }, /** private function **/ logout: function() { /** load data from localstorage service **/ app.utils.loadTokens(); if (app.global.tokensCollection.length > 0) { app.global.tokensCollection.each(function(model) { model.destroy(); } ); } app.utils.destroyViews(); this.index(); }, /** public function **/ lang: function(lang) { /** set default language **/ app.utils.setLanguage(lang); /** reload template and language **/ app.utils.init(false); }, /** public function **/ registration: function() { /** load data from localstorage service **/ app.utils.loadTokens(); var lang = app.utils.getLanguage(); if (app.global.tokensCollection.length == 0) { /** render navbar view **/ app.global.navbarView = new app.views.navbar(); app.global.navbarView.render(); $('#navbar_content').html(app.global.navbarView.el); /** render registration view **/ app.global.registrationView = new app.views.registration(); app.global.registrationView.render(); $('#content').html(app.global.registrationView.el); /** render footer view **/ app.global.footerView = new app.views.footer(); app.global.footerView.render(); $('#footer_content').html(app.global.footerView.el); this.navigate('#!' + lang + '/registration', { trigger : false }); } else { this.dashboard(); } }, /** private function **/ dashboard: function() { /** load data from localstorage service **/ app.utils.loadTokens(); var lang = app.utils.getLanguage(); if (app.global.tokensCollection.length == 0) { this.index(); } else { /** render navbar view **/ app.global.navbarView = new app.views.navbar(); app.global.navbarView.render(); $('#navbar_content').html(app.global.navbarView.el); /** render dashboard view **/ app.global.dashboardView = new app.views.dashboard(); app.global.dashboardView.render(); $('#content').html(app.global.dashboardView.el); /** render sidebar view **/ app.global.sidebarView = new app.views.sidebar(); app.global.sidebarView.render('dashboard'); $('#sidebar_content').html(app.global.sidebarView.el); /** render footer view **/ app.global.footerView = new app.views.footer(); app.global.footerView.render(); $('#footer_content').html(app.global.footerView.el); this.navigate('#!' + lang + '/dashboard', { trigger : false }); } }, /** private function **/ profile: function() { /** load data from localstorage service **/ app.utils.loadTokens(); var lang = app.utils.getLanguage(); if (app.global.tokensCollection.length == 0) { this.index(); } else { /** render navbar view **/ app.global.navbarView = new app.views.navbar(); app.global.navbarView.render(); $('#navbar_content').html(app.global.navbarView.el); /** render profile view **/ app.global.profileView = new app.views.profile(); app.global.profileView.render(); $('#content').html(app.global.profileView.el); /** render sidebar view **/ app.global.sidebarView = new app.views.sidebar(); app.global.sidebarView.render('profile'); $('#sidebar_content').html(app.global.sidebarView.el); /** render footer view **/ app.global.footerView = new app.views.footer(); app.global.footerView.render(); $('#footer_content').html(app.global.footerView.el); this.navigate('#!' + lang + '/profile', { trigger : false }); } }, /** private function **/ report: function(lng, type_id) { /** load data from localstorage service **/ app.utils.loadTokens(); var lang = app.utils.getLanguage(); if (typeof type_id === 'undefined') { type_id = 0; } if (app.global.tokensCollection.length == 0) { this.index(); } else { /** render navbar view **/ app.global.navbarView = new app.views.navbar(); app.global.navbarView.render(); $('#navbar_content').html(app.global.navbarView.el); /** render report view **/ app.global.reportView = new app.views.report(); app.global.reportView.render(type_id); $('#content').html(app.global.reportView.el); /** render sidebar view **/ app.global.sidebarView = new app.views.sidebar(); app.global.sidebarView.render('report'); $('#sidebar_content').html(app.global.sidebarView.el); /** render footer view **/ app.global.footerView = new app.views.footer(); app.global.footerView.render(); $('#footer_content').html(app.global.footerView.el); /** set css - bugfix bootstrap and google maps**/ app.global.reportView.init_map(); this.navigate('#!' + lang + '/report', { trigger : false }); } }, /** public function **/ mapdashboard: function() { /** load data from localstorage service **/ app.utils.loadTokens(); var lang = app.utils.getLanguage(); /** render navbar view **/ app.global.navbarView = new app.views.navbar(); app.global.navbarView.render(); $('#navbar_content').html(app.global.navbarView.el); /** render mapdashboard view **/ app.global.mapdashboardView = new app.views.mapdashboard(); app.global.mapdashboardView.render(); $('#content').html(app.global.mapdashboardView.el); /** render map sidebar view **/ app.global.mapsidebarView = new app.views.mapsidebar(); app.global.mapsidebarView.render(); $('#map_sidebar_content').html(app.global.mapsidebarView.el); /** render ad view **/ var windowWidth = $(window).width(); if (windowWidth >= 800) { app.global.adlargeView = new app.views.adlarge(); app.global.adlargeView.render(); $('#ad_content').html(app.global.adlargeView.el); } else if (windowWidth < 500) { app.global.adsmallView = new app.views.adsmall(); app.global.adsmallView.render(); $('#ad_content').html(app.global.adsmallView.el); } else { app.global.admediumView = new app.views.admedium(); app.global.admediumView.render(); $('#ad_content').html(app.global.admediumView.el); } /** render footer view **/ app.global.footerView = new app.views.footer(); app.global.footerView.render(); $('#footer_content').html(app.global.footerView.el); /** set css - bugfix bootstrap and google maps **/ app.global.mapdashboardView.init_map(); app.global.mapsidebarView.init_geo(); this.navigate('#!' + lang + '/mapdashboard', { trigger : false }); }, /** public function **/ mapdashboard_single: function(lang, id) { /** load data from localstorage service **/ app.utils.loadTokens(); var lang = app.utils.getLanguage(); /** render navbar view **/ app.global.navbarView = new app.views.navbar(); app.global.navbarView.render(); $('#navbar_content').html(app.global.navbarView.el); /** render mapdashboardsingle view **/ app.global.mapdashboardsingleView = new app.views.mapdashboardsingle(); app.global.mapdashboardsingleView.render(); $('#content').html(app.global.mapdashboardsingleView.el); /** render ad view **/ var windowWidth = $(window).width(); if (windowWidth >= 800) { app.global.adlargeView = new app.views.adlarge(); app.global.adlargeView.render(); $('#ad_content').html(app.global.adlargeView.el); } else if (windowWidth < 500) { app.global.adsmallView = new app.views.adsmall(); app.global.adsmallView.render(); $('#ad_content').html(app.global.adsmallView.el); } else { app.global.admediumView = new app.views.admedium(); app.global.admediumView.render(); $('#ad_content').html(app.global.admediumView.el); } /** render footer view **/ app.global.footerView = new app.views.footer(); app.global.footerView.render(); $('#footer_content').html(app.global.footerView.el); /** set css - bugfix bootstrap and google maps **/ app.global.mapdashboardsingleView.init_map(id); this.navigate('#!' + lang + '/mapdashboard/id/' + id, { trigger : false }); }, /** public function **/ credits: function() { /** load data from localstorage service **/ app.utils.loadTokens(); var lang = app.utils.getLanguage(); /** render navbar view **/ app.global.navbarView = new app.views.navbar(); app.global.navbarView.render(); $('#navbar_content').html(app.global.navbarView.el); /** render credits view **/ app.global.creditsView = new app.views.credits(); app.global.creditsView.render(); $('#content').html(app.global.creditsView.el); /** render footer view **/ app.global.footerView = new app.views.footer(); app.global.footerView.render(); $('#footer_content').html(app.global.footerView.el); this.navigate('#!' + lang + '/credits', { trigger : false }); }, /** public function **/ help: function() { /** load data from localstorage service **/ app.utils.loadTokens(); var lang = app.utils.getLanguage(); /** render navbar view **/ app.global.navbarView = new app.views.navbar(); app.global.navbarView.render(); $('#navbar_content').html(app.global.navbarView.el); /** render help view **/ app.global.helpView = new app.views.help(); app.global.helpView.render(); $('#content').html(app.global.helpView.el); /** render footer view **/ app.global.footerView = new app.views.footer(); app.global.footerView.render(); $('#footer_content').html(app.global.footerView.el); this.navigate('#!' + lang + '/help', { trigger : false }); }, /** public function **/ project: function() { /** load data from localstorage service **/ app.utils.loadTokens(); var lang = app.utils.getLanguage(); /** render navbar view **/ app.global.navbarView = new app.views.navbar(); app.global.navbarView.render(); $('#navbar_content').html(app.global.navbarView.el); /** render documentation view **/ app.global.projectView = new app.views.project(); app.global.projectView.render(); $('#content').html(app.global.projectView.el); /** render footer view **/ app.global.footerView = new app.views.footer(); app.global.footerView.render(); $('#footer_content').html(app.global.footerView.el); this.navigate('#!' + lang + '/project', { trigger : false }); }, /** private function **/ password: function() { /** load data from localstorage service **/ app.utils.loadTokens(); var lang = app.utils.getLanguage(); if (app.global.tokensCollection.length == 0) { this.index(); } else { /** render navbar view **/ app.global.navbarView = new app.views.navbar(); app.global.navbarView.render(); $('#navbar_content').html(app.global.navbarView.el); /** render password view **/ app.global.passwordView = new app.views.password(); app.global.passwordView.render(); $('#content').html(app.global.passwordView.el); /** render sidebar view **/ app.global.sidebarView = new app.views.sidebar(); app.global.sidebarView.render('password'); $('#sidebar_content').html(app.global.sidebarView.el); /** render footer view **/ app.global.footerView = new app.views.footer(); app.global.footerView.render(); $('#footer_content').html(app.global.footerView.el); this.navigate('#!' + lang + '/password', { trigger : false }); } }, /** public function **/ resend: function() { /** load data from localstorage service **/ app.utils.loadTokens(); var lang = app.utils.getLanguage(); /** render navbar view **/ app.global.navbarView = new app.views.navbar(); app.global.navbarView.render(); $('#navbar_content').html(app.global.navbarView.el); /** render resend view **/ app.global.resendView = new app.views.resend(); app.global.resendView.render(); $('#content').html(app.global.resendView.el); /** render footer view **/ app.global.footerView = new app.views.footer(); app.global.footerView.render(); $('#footer_content').html(app.global.footerView.el); this.navigate('#!' + lang + '/resend', { trigger : false }); }, /** public function **/ activate: function(lang, id, apikey) { /** load data from localstorage service **/ app.utils.loadTokens(); var lang = app.utils.getLanguage(); /** render navbar view **/ app.global.navbarView = new app.views.navbar(); app.global.navbarView.render(); $('#navbar_content').html(app.global.navbarView.el); /** render activate view **/ app.global.activateView = new app.views.activate(); app.global.activateView.render(); $('#content').html(app.global.activateView.el); /** render footer view **/ app.global.footerView = new app.views.footer(); app.global.footerView.render(); $('#footer_content').html(app.global.footerView.el); /** activate apiKey **/ app.global.activateView.init_activate(id, apikey); this.navigate('#!' + lang + '/activate/' + id + '/' + apikey, { trigger : false }); }, /** public function **/ error: function() { /** load data from localstorage service **/ app.utils.loadTokens(); var lang = app.utils.getLanguage(); /** render navbar view **/ app.global.navbarView = new app.views.navbar(); app.global.navbarView.render(); $('#navbar_content').html(app.global.navbarView.el); /** render error view **/ app.global.errorView = new app.views.error(); app.global.errorView.render(); $('#content').html(app.global.errorView.el); /** render footer view **/ app.global.footerView = new app.views.footer(); app.global.footerView.render(); $('#footer_content').html(app.global.footerView.el); this.navigate('#!' + lang + '/error', { trigger : false }); } });
define(["require", "exports"], function (require, exports) { "use strict"; var WebGLRenderer = (function () { function WebGLRenderer() { } return WebGLRenderer; }()); exports.WebGLRenderer = WebGLRenderer; });
var matchbox = require("matchbox") var Header = matchbox.region.extend({ name: "Header", constructor: function (){ this.appBar = this.component("appBar") this.appBar.hello() this.deleage("event", "appBar", function( e, appBar ){ appBar.hello() }) this.event("click", function(){}) this.announce("roundtrip", "data", function( intent ){}) this.react("roundtrip", function( intent, cb ){ cb() }) this.relay("intent", "data") this.receive("intent", function( intent ){}) this.invoke("app.hello", "data") this.invoke("app.async", "data", function( result ){ }) } }) // ======= var header = new Header(null) var AppBar = matchbox.region.extend({ name: "app-bar", constructor: function () { this.action("click", "element:close", function (e, button) { this.relay("") }) } }) var FilterBar = matchbox.region.extend({ name: "filter-bar", constructor: function(){ this.search = this.node(":search", "search") this.orderSelect = this.node(":order", "select") this.cardList = this.node(":cards", "sortable-list") this.cards = this.node(":card") this.selects = this.node("select", "select") this.action("select", "select", function (e, button) { this.relay("") }) } }) var Select = matchbox.widget.extend({ name: "select", attribute: { open: false, value: function(){ return this.selectedOption.value } }, get: { selectedOption: function(){ return this.select(":option", {selected: true}) } }, onCreate: function () { this.label = this.node(":label") this.menu = this.node(":menu") this.options = this.nodeList(":option", "select-option") this.delegate("click", ":option", "selectOption") }, selectOption: function (option) { if (this.selectedOption == option) { return } if (this.selectedOption) { this.selectedOption.selected = false } option.selected = true this.label.textContent = option.textContent this.open = false this.dispatch("select") }, selectValue: function (value) { var option = this.select(":option", {value: value}) if (option) { this.selectOption(option) } } })
/* * Guerilla * Copyright 2015, Yahoo Inc. * Copyrights licensed under the MIT License. * * An abstraction of a task. */ var path = require('path'); var async = require('async'); var utilities = require('./utilities'); function Task (params) { this.errors = []; this.output = {}; this.params = params || {}; } Task.prototype.run = function (context, exec, callback) { var self = this; async.series([ function (cb) { self.validate(context, exec, cb); }, function (cb) { self.execute(context, exec, cb); }, function (cb) { self.verify(context, exec, cb); } ], function (error) { callback(error, self.output); }); }; function process (self, fn, args, cb) { var guard = false; function callback () { if (!guard) { guard = true; cb.apply(this, arguments); } } args.push(function (error, output) { self.addError(error); self.addOutput(output); callback((self.errors.length > 0) ? self.errors : null); }); require(path.join(__rootdir, 'tasks', self.params.type))[fn].apply(self, args); } Task.prototype.validate = function (context, exec, callback) { if (['javascript', 'bash', 'none'].indexOf(this.params.type) < 0) return callback(new Error('Invalid task type: ' + this.params.type)); var args = [this.params, context]; process(this, 'validate', args, callback); }; Task.prototype.execute = function (context, exec, callback) { var args = [this.params, context, exec]; process(this, 'execute', args, callback); }; Task.prototype.verify = function (context, exec, callback) { var p = Object.create(this.params); if (!p.verify) p.verify = {}; var args = [p, this.output, context, exec]; process(this, 'verify', args, callback); }; Task.prototype.addOutput = function (output) { if (utilities.isDictionary(output)) { for (var key in output) { if (utilities.exists(output[key])) this.output[key] = output[key]; } } }; Task.prototype.addError = function (error) { var errors = []; if (Array.isArray(error)) { error.forEach(function (e) { if (e) errors.push(e); }) } else if (error) { errors.push(error); } this.errors = this.errors.concat(errors); }; Task.prototype.toJSON = function () { var json = { params: this.params, }; if (this.output) json.output = this.output; if (this.errors) { json.errors = []; this.errors.forEach(function (error) { if (error) json.errors.push(error.stack || error.toString()); }); } return json; }; module.exports = Task;
RelationError = Error.progeny('RelationError', { init: function(m) { this.name = this.className; this.message = m; } }); var extend = require('extend'), noop = function() {}; Relation = Object.progeny('Relation', { init: function(modelClass, model) { this.modelClass = modelClass; model ? (this.model = model) : (this._query = {}); this.loaded = false; this.items = null; this.size = null; this.RSVP = { success: noop, error: noop, wasKept: false }; }, kept: function(value) { this.loaded = true; this.RSVP.wasKept = value; this.items = this.size = null; if(Array.isArray(value)) { this.items = value; } else if(isNumber(value)) { this.size = value; } makeRSVPCallback.call(this); }, then: function(success, error) { this.RSVP.success = success || noop; this.RSVP.error = error || noop; makeRSVPCallback.call(this); }, query: function() { return this._query ? extend({}, this._query) : null; }, count: function() { var that = this; var count = new Document.Count(this); this.modelClass.adapter().count(function(result) { that.loaded = true; count.kept(result); }); return count; }, find: function(options) { var that = this; this.loaded = false; if(this.model) { this.modelClass.adapter().where({_id: this.model.id}, function(value) { that.loaded = true; value = Array.isArray(value) ? that.model.class.shortToLong(value[0]) : value; that.model.kept(value); }); return this.model; } else { var Model = this.modelClass; options = Model.longToShort(options); this.modelClass.adapter().where(options, function(value) { if(Array.isArray(value)) { value = value.map(function(options) { var model = new Model({_id: null}); model.kept(Model.shortToLong(options)); return model; }); } that.kept(value); }); return this; } }, asJSON: function() { if(this.items) { return this.items.map(function(model) { return model.asJSON(); }); } else if (isNumber(this.size)) { return this.size; } return null; }, create: function(options) { var that = this; this.loaded = false; if(!this.model) throw new RelationError('Non-model creates are not supported.'); options = extend(options, { createdAt: new Date(), updatedAt: new Date() }); options = this.modelClass.longToShort(options); this.modelClass.adapter().create(options, function(value) { that.loaded = true; value = that.model.class.shortToLong(value); that.model.kept(value); }); return this.model; }, update: function(options) { var that = this; this.loaded = false; options = extend(options, { updatedAt: new Date() }); options = this.modelClass.longToShort(options); if(this.model) { this.modelClass.adapter().update({_id: this.model.id}, options, function(value) { that.loaded = true; that.model.kept(value); }); return this.model; } else { // TODO query should translate fields when the value of _query can change this.modelClass.adapter().update(this._query, options, function(value) { that.kept(value); }); return this; } } }); function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } function makeRSVPCallback() { if(this.loaded) { if(!this.RSVP.wasKept) this.RSVP.error.call(this); else this.RSVP.success.call(this, this.RSVP.wasKept); } } module.exports = Relation;
/** * Created by USER: tarso. * On DATE: 23/12/16. * By NAME: app01.js. * * Source: https://github.com/typicode/json-server */ 'use strict'; var jsonServer = require('json-server'); var server = jsonServer.create(); var router = jsonServer.router('db.json'); var middlewares = jsonServer.defaults(); server.use(middlewares); server.use(router); server.listen(3000, function () { console.log('JSON Server is running') });
define(['exports', './bindables'], function (exports, _bindables) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var ControlProperties = (function () { function ControlProperties() { _classCallCheck(this, ControlProperties); this.cache = []; this.templateProperties = []; } ControlProperties.prototype.getProperties = function getProperties(controlName) { if (this.cache[controlName]) { return this.cache[controlName]; } var options1 = this.getWidgetProperties(controlName); var options2 = _bindables.bindables[controlName]; if (!options2) { throw new Error(controlName + ' not found in generated bindables.js'); } var keys = options1.concat(options2.filter(function (item) { return options1.indexOf(item) < 0; })); this.cache[controlName] = keys; return keys; }; ControlProperties.prototype.getWidgetProperties = function getWidgetProperties(controlName) { if (jQuery.fn[controlName]) { return Object.keys(jQuery.fn[controlName].widget.prototype.options); } return []; }; ControlProperties.prototype.getTemplateProperties = function getTemplateProperties(controlName) { var properties = this.getProperties(controlName); var templates = properties.filter(function (prop) { return prop.toLowerCase().indexOf('template') >= -1; }); return templates; }; return ControlProperties; })(); exports.ControlProperties = ControlProperties; });
var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; import { Bean, BeanStub, PostConstruct, _ } from '@ag-grid-community/core'; var AggFuncService = /** @class */ (function (_super) { __extends(AggFuncService, _super); function AggFuncService() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.aggFuncsMap = {}; _this.initialised = false; return _this; } AggFuncService_1 = AggFuncService; AggFuncService.prototype.init = function () { if (this.initialised) { return; } this.initialiseWithDefaultAggregations(); this.addAggFuncs(this.gridOptionsWrapper.getAggFuncs()); }; AggFuncService.prototype.initialiseWithDefaultAggregations = function () { this.aggFuncsMap[AggFuncService_1.AGG_SUM] = aggSum; this.aggFuncsMap[AggFuncService_1.AGG_FIRST] = aggFirst; this.aggFuncsMap[AggFuncService_1.AGG_LAST] = aggLast; this.aggFuncsMap[AggFuncService_1.AGG_MIN] = aggMin; this.aggFuncsMap[AggFuncService_1.AGG_MAX] = aggMax; this.aggFuncsMap[AggFuncService_1.AGG_COUNT] = aggCount; this.aggFuncsMap[AggFuncService_1.AGG_AVG] = aggAvg; this.initialised = true; }; AggFuncService.prototype.getDefaultAggFunc = function (column) { var allKeys = this.getFuncNames(column); // use 'sum' if it's a) allowed for the column and b) still registered // (ie not removed by user) var sumInKeysList = _.includes(allKeys, AggFuncService_1.AGG_SUM); var sumInFuncs = _.exists(this.aggFuncsMap[AggFuncService_1.AGG_SUM]); if (sumInKeysList && sumInFuncs) { return AggFuncService_1.AGG_SUM; } return _.existsAndNotEmpty(allKeys) ? allKeys[0] : null; }; AggFuncService.prototype.addAggFuncs = function (aggFuncs) { _.iterateObject(aggFuncs, this.addAggFunc.bind(this)); }; AggFuncService.prototype.addAggFunc = function (key, aggFunc) { this.init(); this.aggFuncsMap[key] = aggFunc; }; AggFuncService.prototype.getAggFunc = function (name) { this.init(); return this.aggFuncsMap[name]; }; AggFuncService.prototype.getFuncNames = function (column) { var userAllowedFuncs = column.getColDef().allowedAggFuncs; return userAllowedFuncs == null ? Object.keys(this.aggFuncsMap).sort() : userAllowedFuncs; }; AggFuncService.prototype.clear = function () { this.aggFuncsMap = {}; }; var AggFuncService_1; AggFuncService.AGG_SUM = 'sum'; AggFuncService.AGG_FIRST = 'first'; AggFuncService.AGG_LAST = 'last'; AggFuncService.AGG_MIN = 'min'; AggFuncService.AGG_MAX = 'max'; AggFuncService.AGG_COUNT = 'count'; AggFuncService.AGG_AVG = 'avg'; __decorate([ PostConstruct ], AggFuncService.prototype, "init", null); AggFuncService = AggFuncService_1 = __decorate([ Bean('aggFuncService') ], AggFuncService); return AggFuncService; }(BeanStub)); export { AggFuncService }; function aggSum(params) { var values = params.values; var result = null; // the logic ensures that we never combine bigint arithmetic with numbers, but TS is hard to please // for optimum performance, we use a for loop here rather than calling any helper methods or using functional code for (var i = 0; i < values.length; i++) { var value = values[i]; if (typeof value === 'number') { if (result === null) { result = value; } else { result += typeof result === 'number' ? value : BigInt(value); } } else if (typeof value === 'bigint') { if (result === null) { result = value; } else { result = (typeof result === 'bigint' ? result : BigInt(result)) + value; } } } return result; } function aggFirst(params) { return params.values.length > 0 ? params.values[0] : null; } function aggLast(params) { return params.values.length > 0 ? _.last(params.values) : null; } function aggMin(params) { var values = params.values; var result = null; // for optimum performance, we use a for loop here rather than calling any helper methods or using functional code for (var i = 0; i < values.length; i++) { var value = values[i]; if ((typeof value === 'number' || typeof value === 'bigint') && (result === null || result > value)) { result = value; } } return result; } function aggMax(params) { var values = params.values; var result = null; // for optimum performance, we use a for loop here rather than calling any helper methods or using functional code for (var i = 0; i < values.length; i++) { var value = values[i]; if ((typeof value === 'number' || typeof value === 'bigint') && (result === null || result < value)) { result = value; } } return result; } function aggCount(params) { var values = params.values; var result = 0; // for optimum performance, we use a for loop here rather than calling any helper methods or using functional code for (var i = 0; i < values.length; i++) { var value = values[i]; // check if the value is from a group, in which case use the group's count result += value != null && typeof value.value === 'number' ? value.value : 1; } return { value: result, toString: function () { return this.value.toString(); }, // used for sorting toNumber: function () { return this.value; } }; } // the average function is tricky as the multiple levels require weighted averages // for the non-leaf node aggregations. function aggAvg(params) { var values = params.values; var sum = 0; // the logic ensures that we never combine bigint arithmetic with numbers, but TS is hard to please var count = 0; // for optimum performance, we use a for loop here rather than calling any helper methods or using functional code for (var i = 0; i < values.length; i++) { var value_1 = values[i]; var valueToAdd = null; if (typeof value_1 === 'number' || typeof value_1 === 'bigint') { valueToAdd = value_1; count++; } else if (value_1 != null && (typeof value_1.value === 'number' || typeof value_1.value === 'bigint') && typeof value_1.count === 'number') { // we are aggregating groups, so we take the aggregated values to calculated a weighted average valueToAdd = value_1.value * (typeof value_1.value === 'number' ? value_1.count : BigInt(value_1.count)); count += value_1.count; } if (typeof valueToAdd === 'number') { sum += typeof sum === 'number' ? valueToAdd : BigInt(valueToAdd); } else if (typeof valueToAdd === 'bigint') { sum = (typeof sum === 'bigint' ? sum : BigInt(sum)) + valueToAdd; } } var value = null; // avoid divide by zero error if (count > 0) { value = sum / (typeof sum === 'number' ? count : BigInt(count)); } // the result will be an object. when this cell is rendered, only the avg is shown. // however when this cell is part of another aggregation, the count is also needed // to create a weighted average for the next level. return { count: count, value: value, // the grid by default uses toString to render values for an object, so this // is a trick to get the default cellRenderer to display the avg value toString: function () { return typeof this.value === 'number' || typeof this.value === 'bigint' ? this.value.toString() : ''; }, // used for sorting toNumber: function () { return this.value; } }; }
/** * @license * PlayCanvas Engine v1.45.3 revision 895add4b6 * Copyright 2011-2021 PlayCanvas Ltd. All rights reserved. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.pcx = {})); }(this, (function (exports) { 'use strict'; function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var CpuTimer = function () { function CpuTimer(app) { this._frameIndex = 0; this._frameTimings = []; this._timings = []; this._prevTimings = []; this.unitsName = "ms"; this.decimalPlaces = 1; this.enabled = true; app.on('frameupdate', this.begin.bind(this, 'update')); app.on('framerender', this.mark.bind(this, 'render')); app.on('frameend', this.mark.bind(this, 'other')); } var _proto = CpuTimer.prototype; _proto.begin = function begin(name) { if (!this.enabled) { return; } if (this._frameIndex < this._frameTimings.length) { this._frameTimings.splice(this._frameIndex); } var tmp = this._prevTimings; this._prevTimings = this._timings; this._timings = this._frameTimings; this._frameTimings = tmp; this._frameIndex = 0; this.mark(name); }; _proto.mark = function mark(name) { if (!this.enabled) { return; } var timestamp = pc.now(); var prev; if (this._frameIndex > 0) { prev = this._frameTimings[this._frameIndex - 1]; prev[1] = timestamp - prev[1]; } else if (this._timings.length > 0) { prev = this._timings[this._timings.length - 1]; prev[1] = timestamp - prev[1]; } if (this._frameIndex >= this._frameTimings.length) { this._frameTimings.push([name, timestamp]); } else { var timing = this._frameTimings[this._frameIndex]; timing[0] = name; timing[1] = timestamp; } this._frameIndex++; }; _createClass(CpuTimer, [{ key: "timings", get: function get() { return this._timings.slice(0, -1).map(function (v) { return v[1]; }); } }]); return CpuTimer; }(); var GpuTimer = function () { function GpuTimer(app) { this._gl = app.graphicsDevice.gl; this._ext = app.graphicsDevice.extDisjointTimerQuery; this._freeQueries = []; this._frameQueries = []; this._frames = []; this._timings = []; this._prevTimings = []; this.enabled = true; this.unitsName = "ms"; this.decimalPlaces = 1; app.on('frameupdate', this.begin.bind(this, 'update')); app.on('framerender', this.mark.bind(this, 'render')); app.on('frameend', this.end.bind(this)); } var _proto = GpuTimer.prototype; _proto.loseContext = function loseContext() { this._freeQueries = []; this._frameQueries = []; this._frames = []; }; _proto.begin = function begin(name) { if (!this.enabled) { return; } if (this._frameQueries.length > 0) { this.end(); } this._checkDisjoint(); if (this._frames.length > 0) { if (this._resolveFrameTimings(this._frames[0], this._prevTimings)) { var tmp = this._prevTimings; this._prevTimings = this._timings; this._timings = tmp; this._freeQueries = this._freeQueries.concat(this._frames.splice(0, 1)[0]); } } this.mark(name); }; _proto.mark = function mark(name) { if (!this.enabled) { return; } if (this._frameQueries.length > 0) { this._gl.endQuery(this._ext.TIME_ELAPSED_EXT); } var query = this._allocateQuery(); query[0] = name; this._gl.beginQuery(this._ext.TIME_ELAPSED_EXT, query[1]); this._frameQueries.push(query); }; _proto.end = function end() { if (!this.enabled) { return; } this._gl.endQuery(this._ext.TIME_ELAPSED_EXT); this._frames.push(this._frameQueries); this._frameQueries = []; }; _proto._checkDisjoint = function _checkDisjoint() { var disjoint = this._gl.getParameter(this._ext.GPU_DISJOINT_EXT); if (disjoint) { this._freeQueries = [this._frames, [this._frameQueries], [this._freeQueries]].flat(2); this._frameQueries = []; this._frames = []; } }; _proto._allocateQuery = function _allocateQuery() { return this._freeQueries.length > 0 ? this._freeQueries.splice(-1, 1)[0] : ["", this._gl.createQuery()]; }; _proto._resolveFrameTimings = function _resolveFrameTimings(frame, timings) { if (!this._gl.getQueryParameter(frame[frame.length - 1][1], this._gl.QUERY_RESULT_AVAILABLE)) { return false; } for (var i = 0; i < frame.length; ++i) { timings[i] = [frame[i][0], this._gl.getQueryParameter(frame[i][1], this._gl.QUERY_RESULT) * 0.000001]; } return true; }; _createClass(GpuTimer, [{ key: "timings", get: function get() { return this._timings.map(function (v) { return v[1]; }); } }]); return GpuTimer; }(); var StatsTimer = function () { function StatsTimer(app, statNames, decimalPlaces, unitsName, multiplier) { this.app = app; this.values = []; this.statNames = statNames; if (this.statNames.length > 3) this.statNames.length = 3; this.unitsName = unitsName; this.decimalPlaces = decimalPlaces; this.multiplier = multiplier || 1; var self = this; function resolve(path, obj) { return path.split('.').reduce(function (prev, curr) { return prev ? prev[curr] : null; }, obj || self); } app.on('frameupdate', function (ms) { for (var i = 0; i < self.statNames.length; i++) { self.values[i] = resolve(self.statNames[i], self.app.stats) * self.multiplier; } }); } _createClass(StatsTimer, [{ key: "timings", get: function get() { return this.values; } }]); return StatsTimer; }(); var Graph = function () { function Graph(name, app, watermark, textRefreshRate, timer) { this.name = name; this.device = app.graphicsDevice; this.timer = timer; this.watermark = watermark; this.enabled = false; this.textRefreshRate = textRefreshRate; this.avgTotal = 0; this.avgTimer = 0; this.avgCount = 0; this.timingText = ""; this.texture = null; this.yOffset = 0; this.cursor = 0; this.sample = new Uint8ClampedArray(4); this.sample.set([0, 0, 0, 255]); app.on('frameupdate', this.update.bind(this)); this.counter = 0; } var _proto = Graph.prototype; _proto.loseContext = function loseContext() { if (this.timer && typeof this.timer.loseContext === 'function') { this.timer.loseContext(); } }; _proto.update = function update(ms) { var timings = this.timer.timings; var total = timings.reduce(function (a, v) { return a + v; }, 0); this.avgTotal += total; this.avgTimer += ms; this.avgCount++; if (this.avgTimer > this.textRefreshRate) { this.timingText = (this.avgTotal / this.avgCount).toFixed(this.timer.decimalPlaces); this.avgTimer = 0; this.avgTotal = 0; this.avgCount = 0; } if (this.enabled) { var value = 0; var range = 1.5 * this.watermark; for (var i = 0; i < timings.length; ++i) { value += Math.floor(timings[i] / range * 255); this.sample[i] = value; } this.sample[3] = this.watermark / range * 255; var gl = this.device.gl; this.device.bindTexture(this.texture); gl.texSubImage2D(gl.TEXTURE_2D, 0, this.cursor, this.yOffset, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, this.sample); this.cursor++; if (this.cursor === this.texture.width) { this.cursor = 0; } } }; _proto.render = function render(render2d, x, y, w, h) { render2d.quad(this.texture, x + w, y, -w, h, this.cursor, 0.5 + this.yOffset, -w, 0, this.enabled); }; return Graph; }(); var WordAtlas = function () { function WordAtlas(texture, words) { var canvas = document.createElement('canvas'); canvas.width = texture.width; canvas.height = texture.height; var context = canvas.getContext('2d', { alpha: true }); context.font = '10px "Lucida Console", Monaco, monospace'; context.textAlign = "left"; context.textBaseline = "alphabetic"; context.fillStyle = "rgb(255, 255, 255)"; var padding = 5; var x = padding; var y = padding; var placements = []; var i; for (i = 0; i < words.length; ++i) { var measurement = context.measureText(words[i]); var l = Math.ceil(-measurement.actualBoundingBoxLeft); var r = Math.ceil(measurement.actualBoundingBoxRight); var a = Math.ceil(measurement.actualBoundingBoxAscent); var d = Math.ceil(measurement.actualBoundingBoxDescent); var w = l + r; var h = a + d; if (x + w >= canvas.width) { x = padding; y += 16; } context.fillStyle = words[i].length === 1 ? "rgb(255, 255, 255)" : "rgb(150, 150, 150)"; context.fillText(words[i], x - l, y + a); placements.push({ l: l, r: r, a: a, d: d, x: x, y: y, w: w, h: h }); x += w + padding; } var wordMap = {}; words.forEach(function (w, i) { wordMap[w] = i; }); this.words = words; this.wordMap = wordMap; this.placements = placements; this.texture = texture; var source = context.getImageData(0, 0, canvas.width, canvas.height); var dest = texture.lock(); var red, alpha; for (y = 0; y < source.height; ++y) { for (x = 0; x < source.width; ++x) { var offset = (x + y * texture.width) * 4; dest[offset] = 255; dest[offset + 1] = 255; dest[offset + 2] = 255; red = source.data[(x + (source.height - 1 - y) * source.width) * 4]; alpha = source.data[(x + (source.height - 1 - y) * source.width) * 4 + 3]; dest[offset + 3] = alpha * (red > 150 ? 1 : 0.7); } } } var _proto = WordAtlas.prototype; _proto.render = function render(render2d, word, x, y) { var p = this.placements[this.wordMap[word]]; if (p) { var padding = 1; render2d.quad(this.texture, x + p.l - padding, y - p.d + padding, p.w + padding * 2, p.h + padding * 2, p.x - padding, 64 - p.y - p.h - padding, undefined, undefined, true); return p.w; } return 0; }; return WordAtlas; }(); var Render2d = function () { function Render2d(device, colors, maxQuads) { if (maxQuads === void 0) { maxQuads = 512; } var vertexShader = 'attribute vec3 vertex_position;\n' + 'attribute vec4 vertex_texCoord0;\n' + 'uniform vec4 screenAndTextureSize;\n' + 'varying vec4 uv0;\n' + 'varying float enabled;\n' + 'void main(void) {\n' + ' vec2 pos = vertex_position.xy / screenAndTextureSize.xy;\n' + ' gl_Position = vec4(pos * 2.0 - 1.0, 0.5, 1.0);\n' + ' uv0 = vec4(vertex_texCoord0.xy / screenAndTextureSize.zw, vertex_texCoord0.zw);\n' + ' enabled = vertex_position.z;\n' + '}\n'; var fragmentShader = 'varying vec4 uv0;\n' + 'varying float enabled;\n' + 'uniform vec4 clr;\n' + 'uniform vec4 col0;\n' + 'uniform vec4 col1;\n' + 'uniform vec4 col2;\n' + 'uniform vec4 watermark;\n' + 'uniform float watermarkSize;\n' + 'uniform vec4 background;\n' + 'uniform sampler2D source;\n' + 'void main (void) {\n' + ' vec4 tex = texture2D(source, uv0.xy);\n' + ' if (!(tex.rgb == vec3(1.0, 1.0, 1.0))) {\n' + ' if (enabled < 0.5)\n' + ' tex = background;\n' + ' else if (abs(uv0.w - tex.a) < watermarkSize)\n' + ' tex = watermark;\n' + ' else if (uv0.w < tex.r)\n' + ' tex = col0;\n' + ' else if (uv0.w < tex.g)\n' + ' tex = col1;\n' + ' else if (uv0.w < tex.b)\n' + ' tex = col2;\n' + ' else\n' + ' tex = background;\n' + ' }\n' + ' gl_FragColor = tex * clr;\n' + '}\n'; var format = new pc.VertexFormat(device, [{ semantic: pc.SEMANTIC_POSITION, components: 3, type: pc.TYPE_FLOAT32 }, { semantic: pc.SEMANTIC_TEXCOORD0, components: 4, type: pc.TYPE_FLOAT32 }]); var indices = new Uint16Array(maxQuads * 6); for (var i = 0; i < maxQuads; ++i) { indices[i * 6 + 0] = i * 4; indices[i * 6 + 1] = i * 4 + 1; indices[i * 6 + 2] = i * 4 + 2; indices[i * 6 + 3] = i * 4; indices[i * 6 + 4] = i * 4 + 2; indices[i * 6 + 5] = i * 4 + 3; } this.device = device; this.shader = pc.shaderChunks.createShaderFromCode(device, vertexShader, fragmentShader, "mini-stats"); this.buffer = new pc.VertexBuffer(device, format, maxQuads * 4, pc.BUFFER_STREAM); this.data = new Float32Array(this.buffer.numBytes / 4); this.indexBuffer = new pc.IndexBuffer(device, pc.INDEXFORMAT_UINT16, maxQuads * 6, pc.BUFFER_STATIC, indices); this.prims = []; this.prim = null; this.primIndex = -1; this.quads = 0; var setupColor = function (name, value) { this[name] = new Float32Array([value.r, value.g, value.b, value.a]); this[name + "Id"] = device.scope.resolve(name); }.bind(this); setupColor("col0", colors.graph0); setupColor("col1", colors.graph1); setupColor("col2", colors.graph2); setupColor("watermark", colors.watermark); setupColor("background", colors.background); this.watermarkSizeId = device.scope.resolve('watermarkSize'); this.clrId = device.scope.resolve('clr'); this.clr = new Float32Array(4); this.screenTextureSizeId = device.scope.resolve('screenAndTextureSize'); this.screenTextureSize = new Float32Array(4); } var _proto = Render2d.prototype; _proto.quad = function quad(texture, x, y, w, h, u, v, uw, uh, enabled) { var quad = this.quads++; var prim = this.prim; if (prim && prim.texture === texture) { prim.count += 6; } else { this.primIndex++; if (this.primIndex === this.prims.length) { prim = { type: pc.PRIMITIVE_TRIANGLES, indexed: true, base: quad * 6, count: 6, texture: texture }; this.prims.push(prim); } else { prim = this.prims[this.primIndex]; prim.base = quad * 6; prim.count = 6; prim.texture = texture; } this.prim = prim; } var x1 = x + w; var y1 = y + h; var u1 = u + (uw === undefined ? w : uw); var v1 = v + (uh === undefined ? h : uh); var colorize = enabled ? 1 : 0; this.data.set([x, y, colorize, u, v, 0, 0, x1, y, colorize, u1, v, 1, 0, x1, y1, colorize, u1, v1, 1, 1, x, y1, colorize, u, v1, 0, 1], 4 * 7 * quad); }; _proto.render = function render(clr, height) { var device = this.device; var buffer = this.buffer; buffer.setData(this.data.buffer); device.updateBegin(); device.setDepthTest(false); device.setDepthWrite(false); device.setCullMode(pc.CULLFACE_NONE); device.setBlending(true); device.setBlendFunctionSeparate(pc.BLENDMODE_SRC_ALPHA, pc.BLENDMODE_ONE_MINUS_SRC_ALPHA, pc.BLENDMODE_ONE, pc.BLENDMODE_ONE); device.setBlendEquationSeparate(pc.BLENDEQUATION_ADD, pc.BLENDEQUATION_ADD); device.setVertexBuffer(buffer, 0); device.setIndexBuffer(this.indexBuffer); device.setShader(this.shader); var pr = Math.min(device.maxPixelRatio, window.devicePixelRatio); this.clr.set(clr, 0); this.clrId.setValue(this.clr); this.screenTextureSize[0] = device.width / pr; this.screenTextureSize[1] = device.height / pr; this.col0Id.setValue(this.col0); this.col1Id.setValue(this.col1); this.col2Id.setValue(this.col2); this.watermarkId.setValue(this.watermark); this.backgroundId.setValue(this.background); for (var i = 0; i <= this.primIndex; ++i) { var prim = this.prims[i]; this.screenTextureSize[2] = prim.texture.width; this.screenTextureSize[3] = prim.texture.height; this.screenTextureSizeId.setValue(this.screenTextureSize); device.constantTexSource.setValue(prim.texture); this.watermarkSizeId.setValue(0.5 / height); device.draw(prim); } device.updateEnd(); this.prim = null; this.primIndex = -1; this.quads = 0; }; return Render2d; }(); var MiniStats = function () { function MiniStats(app, options) { var device = app.graphicsDevice; this._contextLostHandler = function (event) { event.preventDefault(); if (this.graphs) { for (var i = 0; i < this.graphs.length; i++) { this.graphs[i].loseContext(); } } }.bind(this); device.canvas.addEventListener("webglcontextlost", this._contextLostHandler, false); options = options || MiniStats.getDefaultOptions(); var graphs = this.initGraphs(app, device, options); var words = ["", "ms", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "."]; graphs.forEach(function (graph) { words.push(graph.name); }); if (options.stats) { options.stats.forEach(function (stat) { if (stat.unitsName) words.push(stat.unitsName); }); } words = words.filter(function (item, index) { return words.indexOf(item) >= index; }); var maxWidth = options.sizes.reduce(function (max, v) { return v.width > max ? v.width : max; }, 0); var wordAtlasData = this.initWordAtlas(device, words, maxWidth, graphs.length); var texture = wordAtlasData.texture; graphs.forEach(function (graph, i) { graph.texture = texture; graph.yOffset = i; }); this.sizes = options.sizes; this._activeSizeIndex = options.startSizeIndex; var self = this; var div = document.createElement('div'); div.style.cssText = 'position:fixed;bottom:0;left:0;background:transparent;'; document.body.appendChild(div); div.addEventListener('mouseenter', function (event) { self.opacity = 1.0; }); div.addEventListener('mouseleave', function (event) { self.opacity = 0.5; }); div.addEventListener('click', function (event) { event.preventDefault(); if (self._enabled) { self.activeSizeIndex = (self.activeSizeIndex + 1) % self.sizes.length; self.resize(self.sizes[self.activeSizeIndex].width, self.sizes[self.activeSizeIndex].height, self.sizes[self.activeSizeIndex].graphs); } }); device.on("resizecanvas", function () { self.updateDiv(); }); app.on('postrender', function () { if (self._enabled) { self.render(); } }); this.device = device; this.texture = texture; this.wordAtlas = wordAtlasData.atlas; this.render2d = new Render2d(device, options.colors); this.graphs = graphs; this.div = div; this.width = 0; this.height = 0; this.gspacing = 2; this.clr = [1, 1, 1, 0.5]; this._enabled = true; this.activeSizeIndex = this._activeSizeIndex; } MiniStats.getDefaultOptions = function getDefaultOptions() { return { sizes: [{ width: 100, height: 16, spacing: 0, graphs: false }, { width: 128, height: 32, spacing: 2, graphs: true }, { width: 256, height: 64, spacing: 2, graphs: true }], startSizeIndex: 0, textRefreshRate: 500, colors: { graph0: new pc.Color(0.7, 0.2, 0.2, 1), graph1: new pc.Color(0.2, 0.7, 0.2, 1), graph2: new pc.Color(0.2, 0.2, 0.7, 1), watermark: new pc.Color(0.4, 0.4, 0.2, 1), background: new pc.Color(0, 0, 0, 1.0) }, cpu: { enabled: true, watermark: 33 }, gpu: { enabled: true, watermark: 33 }, stats: [{ name: "Frame", stats: ["frame.ms"], decimalPlaces: 1, unitsName: "ms", watermark: 33 }, { name: "DrawCalls", stats: ["drawCalls.total"], watermark: 1000 }] }; }; var _proto = MiniStats.prototype; _proto.initWordAtlas = function initWordAtlas(device, words, maxWidth, numGraphs) { var texture = new pc.Texture(device, { name: 'mini-stats', width: pc.math.nextPowerOfTwo(maxWidth), height: 64, mipmaps: false, minFilter: pc.FILTER_NEAREST, magFilter: pc.FILTER_NEAREST }); var wordAtlas = new WordAtlas(texture, words); var dest = texture.lock(); for (var i = 0; i < texture.width * numGraphs; ++i) { dest.set([0, 0, 0, 255], i * 4); } texture.unlock(); device.setTexture(texture, 0); return { atlas: wordAtlas, texture: texture }; }; _proto.initGraphs = function initGraphs(app, device, options) { var graphs = []; if (options.cpu.enabled) { graphs.push(new Graph('CPU', app, options.cpu.watermark, options.textRefreshRate, new CpuTimer(app))); } if (options.gpu.enabled && device.extDisjointTimerQuery) { graphs.push(new Graph('GPU', app, options.gpu.watermark, options.textRefreshRate, new GpuTimer(app))); } if (options.stats) { options.stats.forEach(function (entry) { graphs.push(new Graph(entry.name, app, entry.watermark, options.textRefreshRate, new StatsTimer(app, entry.stats, entry.decimalPlaces, entry.unitsName, entry.multiplier))); }); } return graphs; }; _proto.render = function render() { var graphs = this.graphs; var wordAtlas = this.wordAtlas; var render2d = this.render2d; var width = this.width; var height = this.height; var gspacing = this.gspacing; var i, j, x, y, graph; for (i = 0; i < graphs.length; ++i) { graph = graphs[i]; y = i * (height + gspacing); graph.render(render2d, 0, y, width, height); x = 1; y += height - 13; x += wordAtlas.render(render2d, graph.name, x, y) + 10; var timingText = graph.timingText; for (j = 0; j < timingText.length; ++j) { x += wordAtlas.render(render2d, timingText[j], x, y); } if (graph.timer.unitsName) { x += 3; wordAtlas.render(render2d, graph.timer.unitsName, x, y); } } render2d.render(this.clr, height); }; _proto.resize = function resize(width, height, showGraphs) { var graphs = this.graphs; for (var i = 0; i < graphs.length; ++i) { graphs[i].enabled = showGraphs; } this.width = width; this.height = height; this.updateDiv(); }; _proto.updateDiv = function updateDiv() { var rect = this.device.canvas.getBoundingClientRect(); this.div.style.left = rect.left + "px"; this.div.style.bottom = window.innerHeight - rect.bottom + "px"; this.div.style.width = this.width + "px"; this.div.style.height = this.overallHeight + "px"; }; _createClass(MiniStats, [{ key: "activeSizeIndex", get: function get() { return this._activeSizeIndex; }, set: function set(value) { this._activeSizeIndex = value; this.gspacing = this.sizes[value].spacing; this.resize(this.sizes[value].width, this.sizes[value].height, this.sizes[value].graphs); } }, { key: "opacity", get: function get() { return this.clr[3]; }, set: function set(value) { this.clr[3] = value; } }, { key: "overallHeight", get: function get() { var graphs = this.graphs; var spacing = this.gspacing; return this.height * graphs.length + spacing * (graphs.length - 1); } }, { key: "enabled", get: function get() { return this._enabled; }, set: function set(value) { if (value !== this._enabled) { this._enabled = value; for (var i = 0; i < this.graphs.length; ++i) { this.graphs[i].enabled = value; this.graphs[i].timer.enabled = value; } } } }]); return MiniStats; }(); exports.MiniStats = MiniStats; Object.defineProperty(exports, '__esModule', { value: true }); })));
'use strict' require('babel-register')({ plugins: [ 'transform-async-to-generator' ] }) require('./errors.es7')
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ Ext.define('sisprod.view.AnnullableWorkOrder.ListAnnullableWorkOrder', { extend: 'sisprod.view.base.TabPanelGridItem', require: [ 'sisprod.view.base.TabPanelGridItem' ], alias: 'widget.listAnnullableWorkOrder', options: {}, usedInPAndP: true, entityName: '', listTitle: 'Work Orders List', messages: { headers: { idWorkOrder: 'ID', taskSchedulerEmployeeName: 'Employee', sectorName: 'Sector Name', workOrderFullNumber: 'Work Order Full Number', workRequestFullNumber: 'Work Request Full Number', workCategoryName: 'Work Category', workCategoryDetailName: 'Work Detail Category', workShopName: 'Work Shop Name', locationName: 'Location', workDescription: 'Description', equipmentName: 'Equipment Name', workOrderStatusName: 'Work Order Status Name', direct: 'Direct' } }, gridOptions: { region: 'center' }, showCheckInactive: false, initComponent: function(){ var me = this; var storeName = sisprod.getApplication().getStoreName(me.entityName); var modelName = sisprod.getApplication().getModelName('WorkOrder'); me.gridOptions = { title: me.listTitle, entityName: me.entityName, autoGenerationOptions:{ model: modelName, autoGenerateColumns: true, columnOptions: { idWorkOrder: {header: me.messages.headers.idWorkOrder}, workOrderFullNumber: {header: me.messages.headers.workOrderFullNumber, flex: 1.5}, // 'workRequest.idWorkRequest': {hideable: false}, idWorkRequest: {hideable: false}, // 'workRequest.workRequestFullNumber': {header: me.messages.headers.workRequestFullNumber, flex: 1.5}, workRequestFullNumber: {header: me.messages.headers.workRequestFullNumber, flex: 1.5}, // 'sector.idSector': {hideable: false}, idSector:{hideable: false}, // 'sector.sectorName': {header: me.messages.headers.sectorName}, sectorName: {header: me.messages.headers.sectorName}, // 'taskScheduler.idTaskScheduler': {hideable: false}, idTaskScheduler: {hideable:false}, // 'taskScheduler.employee.person.personFullName': {header: me.messages.headers.taskSchedulerEmployeeName, flex: 2}, taskSchedulerName : {header: me.messages.headers.taskSchedulerEmployeeName, flex: 2, hidden: true, hideable:false}, // 'workCategoryDetail.idWorkCategoryDetail': {hideable: false}, idWorkCategoryDetail: {hideable: false}, // 'workCategoryDetail.workCategory.workCategoryName': {header: me.messages.headers.workCategoryName, flex: 1.5}, workCategoryName: {header: me.messages.headers.workCategoryName}, // 'workCategoryDetail.workCategoryDetailName': {header: me.messages.headers.workCategoryDetailName, flex: 1.5}, workCategoryDetailName: {header: me.messages.headers.workCategoryDetailName, flex: 1.5}, idLocation: {hideable: false}, // 'location.locationName': {header: me.messages.headers.locationName}, locationName: {header: me.messages.headers.locationName}, // 'workOrderStatus.idWorkOrderStatus': {hideable: false}, workOrderDate: {hideable: false}, workOrderYear: {hideable: false}, workOrderNumber: {hideable: false}, annulledWorkOrder: {hideable: false}, scheduledStartDate: {hideable: false}, scheduledEndDate: {hideable: false}, executionStartDate: {hideable: false}, executionEndDate: {hideable: false}, manHours:{hideable: false}, machineHours: {hideable: false}, ownResources: {hideable: false}, description: {header: me.messages.headers.description, hideable: false}, comment: {hideable: false}, // 'wOOwnResources.idWOOwnResources': {hideable: false}, idWOOwnResources: {hideable: false}, // 'workShop.workShopName': {header: me.messages.headers.workShopName}, workShopName: {header: me.messages.headers.workShopName}, // 'wOOwnResources.quadrille.quadrilleName': {hideable: false}, quadrilleName : {hideable: false}, // 'workShopCoordinator.employee.person.personFullName': {hideable: false}, personFullName: {hideable: false}, // 'workRequest.workRequestSource.workRequestSourceName': {hideable: false}, workRequestSourceName: {hideable: false}, // 'wOThirdPartyResource.supplier.entity.entityName': {hideable: false}, entityName: {hideable: false}, // 'workRequest.equipment.equipmentName': {header: me.messages.headers.equipmentName}, equipmentName: {header: me.messages.headers.equipmentName}, // 'workRequest.attentionMaximumDate': {hideable: false}, attentionMaximumDate: {hideable: false}, idWorkOrderStatus: {hideable: false}, reportLink: {hidden:true ,hideable: false}, worshopCoordinatorName: {hideable: false, hidden: true}, percentageUsageResources:{hideable: false, hidden: true}, percentageAdvance:{hideable: false, hidden: true}, // 'workOrderStatus.workOrderStatusName': { // header: me.messages.headers.workOrderStatusName, // renderer: function(value, metaData, record, rowIndex, colIndex, store, view){ // metaData.style = Ext.String.format("background-color: {0};background-image: none;", // record.raw['workOrderStatus']['workOrderStatusColor']); // return Ext.util.Format.htmlEncode(Ext.util.Format.uppercase(value)); // } // }, workOrderStatusName: { header: me.messages.headers.workOrderStatusName, renderer: function(value, metaData, record, rowIndex, colIndex, store, view){ metaData.style = Ext.String.format("background-color: {0};background-image: none;", record.raw['workOrderStatus']['workOrderStatusColor']); return Ext.util.Format.htmlEncode(Ext.util.Format.uppercase(value)); } }, isDirectWorkOrder: {header: me.messages.headers.direct} } }, region: 'center', store: me.controller.getStore(storeName), baseGridOptions: false, topBarButtons: [ { xtype: 'button', text: 'Anular', iconCls: 'remove', action: 'nullify' } ] }; me.callParent(arguments); } });
typeof window !== "undefined" && (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["Hls"] = factory(); else root["Hls"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./src/hls.ts"); /******/ }) /************************************************************************/ /******/ ({ /***/ "./node_modules/eventemitter3/index.js": /*!*********************************************!*\ !*** ./node_modules/eventemitter3/index.js ***! \*********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var has = Object.prototype.hasOwnProperty , prefix = '~'; /** * Constructor to create a storage for our `EE` objects. * An `Events` instance is a plain object whose properties are event names. * * @constructor * @private */ function Events() {} // // We try to not inherit from `Object.prototype`. In some engines creating an // instance in this way is faster than calling `Object.create(null)` directly. // If `Object.create(null)` is not supported we prefix the event names with a // character to make sure that the built-in object properties are not // overridden or used as an attack vector. // if (Object.create) { Events.prototype = Object.create(null); // // This hack is needed because the `__proto__` property is still inherited in // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. // if (!new Events().__proto__) prefix = false; } /** * Representation of a single event listener. * * @param {Function} fn The listener function. * @param {*} context The context to invoke the listener with. * @param {Boolean} [once=false] Specify if the listener is a one-time listener. * @constructor * @private */ function EE(fn, context, once) { this.fn = fn; this.context = context; this.once = once || false; } /** * Add a listener for a given event. * * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} context The context to invoke the listener with. * @param {Boolean} once Specify if the listener is a one-time listener. * @returns {EventEmitter} * @private */ function addListener(emitter, event, fn, context, once) { if (typeof fn !== 'function') { throw new TypeError('The listener must be a function'); } var listener = new EE(fn, context || emitter, once) , evt = prefix ? prefix + event : event; if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); else emitter._events[evt] = [emitter._events[evt], listener]; return emitter; } /** * Clear event by name. * * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. * @param {(String|Symbol)} evt The Event name. * @private */ function clearEvent(emitter, evt) { if (--emitter._eventsCount === 0) emitter._events = new Events(); else delete emitter._events[evt]; } /** * Minimal `EventEmitter` interface that is molded against the Node.js * `EventEmitter` interface. * * @constructor * @public */ function EventEmitter() { this._events = new Events(); this._eventsCount = 0; } /** * Return an array listing the events for which the emitter has registered * listeners. * * @returns {Array} * @public */ EventEmitter.prototype.eventNames = function eventNames() { var names = [] , events , name; if (this._eventsCount === 0) return names; for (name in (events = this._events)) { if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); } if (Object.getOwnPropertySymbols) { return names.concat(Object.getOwnPropertySymbols(events)); } return names; }; /** * Return the listeners registered for a given event. * * @param {(String|Symbol)} event The event name. * @returns {Array} The registered listeners. * @public */ EventEmitter.prototype.listeners = function listeners(event) { var evt = prefix ? prefix + event : event , handlers = this._events[evt]; if (!handlers) return []; if (handlers.fn) return [handlers.fn]; for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { ee[i] = handlers[i].fn; } return ee; }; /** * Return the number of listeners listening to a given event. * * @param {(String|Symbol)} event The event name. * @returns {Number} The number of listeners. * @public */ EventEmitter.prototype.listenerCount = function listenerCount(event) { var evt = prefix ? prefix + event : event , listeners = this._events[evt]; if (!listeners) return 0; if (listeners.fn) return 1; return listeners.length; }; /** * Calls each of the listeners registered for a given event. * * @param {(String|Symbol)} event The event name. * @returns {Boolean} `true` if the event had listeners, else `false`. * @public */ EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return false; var listeners = this._events[evt] , len = arguments.length , args , i; if (listeners.fn) { if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); switch (len) { case 1: return listeners.fn.call(listeners.context), true; case 2: return listeners.fn.call(listeners.context, a1), true; case 3: return listeners.fn.call(listeners.context, a1, a2), true; case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; } for (i = 1, args = new Array(len -1); i < len; i++) { args[i - 1] = arguments[i]; } listeners.fn.apply(listeners.context, args); } else { var length = listeners.length , j; for (i = 0; i < length; i++) { if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); switch (len) { case 1: listeners[i].fn.call(listeners[i].context); break; case 2: listeners[i].fn.call(listeners[i].context, a1); break; case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; default: if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { args[j - 1] = arguments[j]; } listeners[i].fn.apply(listeners[i].context, args); } } } return true; }; /** * Add a listener for a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.on = function on(event, fn, context) { return addListener(this, event, fn, context, false); }; /** * Add a one-time listener for a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.once = function once(event, fn, context) { return addListener(this, event, fn, context, true); }; /** * Remove the listeners of a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn Only remove the listeners that match this function. * @param {*} context Only remove the listeners that have this context. * @param {Boolean} once Only remove one-time listeners. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return this; if (!fn) { clearEvent(this, evt); return this; } var listeners = this._events[evt]; if (listeners.fn) { if ( listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context) ) { clearEvent(this, evt); } } else { for (var i = 0, events = [], length = listeners.length; i < length; i++) { if ( listeners[i].fn !== fn || (once && !listeners[i].once) || (context && listeners[i].context !== context) ) { events.push(listeners[i]); } } // // Reset the array, or remove it completely if we have no more listeners. // if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; else clearEvent(this, evt); } return this; }; /** * Remove all listeners, or those of the specified event. * * @param {(String|Symbol)} [event] The event name. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { var evt; if (event) { evt = prefix ? prefix + event : event; if (this._events[evt]) clearEvent(this, evt); } else { this._events = new Events(); this._eventsCount = 0; } return this; }; // // Alias methods names because people roll like that. // EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.addListener = EventEmitter.prototype.on; // // Expose the prefix. // EventEmitter.prefixed = prefix; // // Allow `EventEmitter` to be imported as module namespace. // EventEmitter.EventEmitter = EventEmitter; // // Expose the module. // if (true) { module.exports = EventEmitter; } /***/ }), /***/ "./node_modules/url-toolkit/src/url-toolkit.js": /*!*****************************************************!*\ !*** ./node_modules/url-toolkit/src/url-toolkit.js ***! \*****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // see https://tools.ietf.org/html/rfc1808 (function (root) { var URL_REGEX = /^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#[^]*)?$/; var FIRST_SEGMENT_REGEX = /^([^\/?#]*)([^]*)$/; var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g; var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g; var URLToolkit = { // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or // // E.g // With opts.alwaysNormalize = false (default, spec compliant) // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g // With opts.alwaysNormalize = true (not spec compliant) // http://a.com/b/cd + /e/f/../g => http://a.com/e/g buildAbsoluteURL: function (baseURL, relativeURL, opts) { opts = opts || {}; // remove any remaining space and CRLF baseURL = baseURL.trim(); relativeURL = relativeURL.trim(); if (!relativeURL) { // 2a) If the embedded URL is entirely empty, it inherits the // entire base URL (i.e., is set equal to the base URL) // and we are done. if (!opts.alwaysNormalize) { return baseURL; } var basePartsForNormalise = URLToolkit.parseURL(baseURL); if (!basePartsForNormalise) { throw new Error('Error trying to parse base URL.'); } basePartsForNormalise.path = URLToolkit.normalizePath( basePartsForNormalise.path ); return URLToolkit.buildURLFromParts(basePartsForNormalise); } var relativeParts = URLToolkit.parseURL(relativeURL); if (!relativeParts) { throw new Error('Error trying to parse relative URL.'); } if (relativeParts.scheme) { // 2b) If the embedded URL starts with a scheme name, it is // interpreted as an absolute URL and we are done. if (!opts.alwaysNormalize) { return relativeURL; } relativeParts.path = URLToolkit.normalizePath(relativeParts.path); return URLToolkit.buildURLFromParts(relativeParts); } var baseParts = URLToolkit.parseURL(baseURL); if (!baseParts) { throw new Error('Error trying to parse base URL.'); } if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') { // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a' var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path); baseParts.netLoc = pathParts[1]; baseParts.path = pathParts[2]; } if (baseParts.netLoc && !baseParts.path) { baseParts.path = '/'; } var builtParts = { // 2c) Otherwise, the embedded URL inherits the scheme of // the base URL. scheme: baseParts.scheme, netLoc: relativeParts.netLoc, path: null, params: relativeParts.params, query: relativeParts.query, fragment: relativeParts.fragment, }; if (!relativeParts.netLoc) { // 3) If the embedded URL's <net_loc> is non-empty, we skip to // Step 7. Otherwise, the embedded URL inherits the <net_loc> // (if any) of the base URL. builtParts.netLoc = baseParts.netLoc; // 4) If the embedded URL path is preceded by a slash "/", the // path is not relative and we skip to Step 7. if (relativeParts.path[0] !== '/') { if (!relativeParts.path) { // 5) If the embedded URL path is empty (and not preceded by a // slash), then the embedded URL inherits the base URL path builtParts.path = baseParts.path; // 5a) if the embedded URL's <params> is non-empty, we skip to // step 7; otherwise, it inherits the <params> of the base // URL (if any) and if (!relativeParts.params) { builtParts.params = baseParts.params; // 5b) if the embedded URL's <query> is non-empty, we skip to // step 7; otherwise, it inherits the <query> of the base // URL (if any) and we skip to step 7. if (!relativeParts.query) { builtParts.query = baseParts.query; } } } else { // 6) The last segment of the base URL's path (anything // following the rightmost slash "/", or the entire path if no // slash is present) is removed and the embedded URL's path is // appended in its place. var baseURLPath = baseParts.path; var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path; builtParts.path = URLToolkit.normalizePath(newPath); } } } if (builtParts.path === null) { builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path; } return URLToolkit.buildURLFromParts(builtParts); }, parseURL: function (url) { var parts = URL_REGEX.exec(url); if (!parts) { return null; } return { scheme: parts[1] || '', netLoc: parts[2] || '', path: parts[3] || '', params: parts[4] || '', query: parts[5] || '', fragment: parts[6] || '', }; }, normalizePath: function (path) { // The following operations are // then applied, in order, to the new path: // 6a) All occurrences of "./", where "." is a complete path // segment, are removed. // 6b) If the path ends with "." as a complete path segment, // that "." is removed. path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, ''); // 6c) All occurrences of "<segment>/../", where <segment> is a // complete path segment not equal to "..", are removed. // Removal of these path segments is performed iteratively, // removing the leftmost matching pattern on each iteration, // until no matching pattern remains. // 6d) If the path ends with "<segment>/..", where <segment> is a // complete path segment not equal to "..", that // "<segment>/.." is removed. while ( path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length ) {} return path.split('').reverse().join(''); }, buildURLFromParts: function (parts) { return ( parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment ); }, }; if (true) module.exports = URLToolkit; else {} })(this); /***/ }), /***/ "./node_modules/webworkify-webpack/index.js": /*!**************************************************!*\ !*** ./node_modules/webworkify-webpack/index.js ***! \**************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { function webpackBootstrapFunc (modules) { /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.l = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/"; /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; var f = __webpack_require__(__webpack_require__.s = ENTRY_MODULE) return f.default || f // try to call default if defined to also support babel esmodule exports } var moduleNameReqExp = '[\\.|\\-|\\+|\\w|\/|@]+' var dependencyRegExp = '\\(\\s*(\/\\*.*?\\*\/)?\\s*.*?(' + moduleNameReqExp + ').*?\\)' // additional chars when output.pathinfo is true // http://stackoverflow.com/a/2593661/130442 function quoteRegExp (str) { return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&') } function isNumeric(n) { return !isNaN(1 * n); // 1 * n converts integers, integers as string ("123"), 1e3 and "1e3" to integers and strings to NaN } function getModuleDependencies (sources, module, queueName) { var retval = {} retval[queueName] = [] var fnString = module.toString() var wrapperSignature = fnString.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/) if (!wrapperSignature) return retval var webpackRequireName = wrapperSignature[1] // main bundle deps var re = new RegExp('(\\\\n|\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g') var match while ((match = re.exec(fnString))) { if (match[3] === 'dll-reference') continue retval[queueName].push(match[3]) } // dll deps re = new RegExp('\\(' + quoteRegExp(webpackRequireName) + '\\("(dll-reference\\s(' + moduleNameReqExp + '))"\\)\\)' + dependencyRegExp, 'g') while ((match = re.exec(fnString))) { if (!sources[match[2]]) { retval[queueName].push(match[1]) sources[match[2]] = __webpack_require__(match[1]).m } retval[match[2]] = retval[match[2]] || [] retval[match[2]].push(match[4]) } // convert 1e3 back to 1000 - this can be important after uglify-js converted 1000 to 1e3 var keys = Object.keys(retval); for (var i = 0; i < keys.length; i++) { for (var j = 0; j < retval[keys[i]].length; j++) { if (isNumeric(retval[keys[i]][j])) { retval[keys[i]][j] = 1 * retval[keys[i]][j]; } } } return retval } function hasValuesInQueues (queues) { var keys = Object.keys(queues) return keys.reduce(function (hasValues, key) { return hasValues || queues[key].length > 0 }, false) } function getRequiredModules (sources, moduleId) { var modulesQueue = { main: [moduleId] } var requiredModules = { main: [] } var seenModules = { main: {} } while (hasValuesInQueues(modulesQueue)) { var queues = Object.keys(modulesQueue) for (var i = 0; i < queues.length; i++) { var queueName = queues[i] var queue = modulesQueue[queueName] var moduleToCheck = queue.pop() seenModules[queueName] = seenModules[queueName] || {} if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue seenModules[queueName][moduleToCheck] = true requiredModules[queueName] = requiredModules[queueName] || [] requiredModules[queueName].push(moduleToCheck) var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName) var newModulesKeys = Object.keys(newModules) for (var j = 0; j < newModulesKeys.length; j++) { modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || [] modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]]) } } } return requiredModules } module.exports = function (moduleId, options) { options = options || {} var sources = { main: __webpack_require__.m } var requiredModules = options.all ? { main: Object.keys(sources.main) } : getRequiredModules(sources, moduleId) var src = '' Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) { var entryModule = 0 while (requiredModules[module][entryModule]) { entryModule++ } requiredModules[module].push(entryModule) sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })' src = src + 'var ' + module + ' = (' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(entryModule)) + ')({' + requiredModules[module].map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[module][id].toString() }).join(',') + '});\n' }) src = src + 'new ((' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.main.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources.main[id].toString() }).join(',') + '}))(self);' var blob = new window.Blob([src], { type: 'text/javascript' }) if (options.bare) { return blob } var URL = window.URL || window.webkitURL || window.mozURL || window.msURL var workerUrl = URL.createObjectURL(blob) var worker = new window.Worker(workerUrl) worker.objectURL = workerUrl return worker } /***/ }), /***/ "./src/config.ts": /*!***********************!*\ !*** ./src/config.ts ***! \***********************/ /*! exports provided: hlsDefaultConfig, mergeConfig, enableStreamingMode */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hlsDefaultConfig", function() { return hlsDefaultConfig; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeConfig", function() { return mergeConfig; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableStreamingMode", function() { return enableStreamingMode; }); /* harmony import */ var _controller_abr_controller__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./controller/abr-controller */ "./src/controller/abr-controller.ts"); /* harmony import */ var _controller_audio_stream_controller__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./controller/audio-stream-controller */ "./src/empty.js"); /* harmony import */ var _controller_audio_stream_controller__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_controller_audio_stream_controller__WEBPACK_IMPORTED_MODULE_1__); /* harmony import */ var _controller_buffer_controller__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./controller/buffer-controller */ "./src/controller/buffer-controller.ts"); /* harmony import */ var _controller_cap_level_controller__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./controller/cap-level-controller */ "./src/controller/cap-level-controller.ts"); /* harmony import */ var _controller_fps_controller__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./controller/fps-controller */ "./src/controller/fps-controller.ts"); /* harmony import */ var _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./utils/xhr-loader */ "./src/utils/xhr-loader.ts"); /* harmony import */ var _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./utils/fetch-loader */ "./src/utils/fetch-loader.ts"); /* harmony import */ var _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./utils/mediakeys-helper */ "./src/utils/mediakeys-helper.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./utils/logger */ "./src/utils/logger.ts"); function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } // If possible, keep hlsDefaultConfig shallow // It is cloned whenever a new Hls instance is created, by keeping the config // shallow the properties are cloned, and we don't end up manipulating the default var hlsDefaultConfig = _objectSpread(_objectSpread({ autoStartLoad: true, // used by stream-controller startPosition: -1, // used by stream-controller defaultAudioCodec: undefined, // used by stream-controller debug: false, // used by logger capLevelOnFPSDrop: false, // used by fps-controller capLevelToPlayerSize: false, // used by cap-level-controller initialLiveManifestSize: 1, // used by stream-controller maxBufferLength: 30, // used by stream-controller backBufferLength: Infinity, // used by buffer-controller maxBufferSize: 60 * 1000 * 1000, // used by stream-controller maxBufferHole: 0.1, // used by stream-controller highBufferWatchdogPeriod: 2, // used by stream-controller nudgeOffset: 0.1, // used by stream-controller nudgeMaxRetry: 3, // used by stream-controller maxFragLookUpTolerance: 0.25, // used by stream-controller liveSyncDurationCount: 3, // used by latency-controller liveMaxLatencyDurationCount: Infinity, // used by latency-controller liveSyncDuration: undefined, // used by latency-controller liveMaxLatencyDuration: undefined, // used by latency-controller maxLiveSyncPlaybackRate: 1, // used by latency-controller liveDurationInfinity: false, // used by buffer-controller liveBackBufferLength: null, // used by buffer-controller maxMaxBufferLength: 600, // used by stream-controller enableWorker: true, // used by demuxer enableSoftwareAES: true, // used by decrypter manifestLoadingTimeOut: 10000, // used by playlist-loader manifestLoadingMaxRetry: 1, // used by playlist-loader manifestLoadingRetryDelay: 1000, // used by playlist-loader manifestLoadingMaxRetryTimeout: 64000, // used by playlist-loader startLevel: undefined, // used by level-controller levelLoadingTimeOut: 10000, // used by playlist-loader levelLoadingMaxRetry: 4, // used by playlist-loader levelLoadingRetryDelay: 1000, // used by playlist-loader levelLoadingMaxRetryTimeout: 64000, // used by playlist-loader fragLoadingTimeOut: 20000, // used by fragment-loader fragLoadingMaxRetry: 6, // used by fragment-loader fragLoadingRetryDelay: 1000, // used by fragment-loader fragLoadingMaxRetryTimeout: 64000, // used by fragment-loader startFragPrefetch: false, // used by stream-controller fpsDroppedMonitoringPeriod: 5000, // used by fps-controller fpsDroppedMonitoringThreshold: 0.2, // used by fps-controller appendErrorMaxRetry: 3, // used by buffer-controller loader: _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_5__["default"], // loader: FetchLoader, fLoader: undefined, // used by fragment-loader pLoader: undefined, // used by playlist-loader xhrSetup: undefined, // used by xhr-loader licenseXhrSetup: undefined, // used by eme-controller licenseResponseCallback: undefined, // used by eme-controller abrController: _controller_abr_controller__WEBPACK_IMPORTED_MODULE_0__["default"], bufferController: _controller_buffer_controller__WEBPACK_IMPORTED_MODULE_2__["default"], capLevelController: _controller_cap_level_controller__WEBPACK_IMPORTED_MODULE_3__["default"], fpsController: _controller_fps_controller__WEBPACK_IMPORTED_MODULE_4__["default"], stretchShortVideoTrack: false, // used by mp4-remuxer maxAudioFramesDrift: 1, // used by mp4-remuxer forceKeyFrameOnDiscontinuity: true, // used by ts-demuxer abrEwmaFastLive: 3, // used by abr-controller abrEwmaSlowLive: 9, // used by abr-controller abrEwmaFastVoD: 3, // used by abr-controller abrEwmaSlowVoD: 9, // used by abr-controller abrEwmaDefaultEstimate: 5e5, // 500 kbps // used by abr-controller abrBandWidthFactor: 0.95, // used by abr-controller abrBandWidthUpFactor: 0.7, // used by abr-controller abrMaxWithRealBitrate: false, // used by abr-controller maxStarvationDelay: 4, // used by abr-controller maxLoadingDelay: 4, // used by abr-controller minAutoBitrate: 0, // used by hls emeEnabled: false, // used by eme-controller widevineLicenseUrl: undefined, // used by eme-controller drmSystemOptions: {}, // used by eme-controller requestMediaKeySystemAccessFunc: _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_7__["requestMediaKeySystemAccess"], // used by eme-controller testBandwidth: true, progressive: false, lowLatencyMode: true }, timelineConfig()), {}, { subtitleStreamController: false ? undefined : undefined, subtitleTrackController: false ? undefined : undefined, timelineController: false ? undefined : undefined, audioStreamController: false ? undefined : undefined, audioTrackController: false ? undefined : undefined, emeController: false ? undefined : undefined }); function timelineConfig() { return { cueHandler: _controller_audio_stream_controller__WEBPACK_IMPORTED_MODULE_1___default.a, // used by timeline-controller enableCEA708Captions: false, // used by timeline-controller enableWebVTT: false, // used by timeline-controller enableIMSC1: false, // used by timeline-controller captionsTextTrack1Label: 'English', // used by timeline-controller captionsTextTrack1LanguageCode: 'en', // used by timeline-controller captionsTextTrack2Label: 'Spanish', // used by timeline-controller captionsTextTrack2LanguageCode: 'es', // used by timeline-controller captionsTextTrack3Label: 'Unknown CC', // used by timeline-controller captionsTextTrack3LanguageCode: '', // used by timeline-controller captionsTextTrack4Label: 'Unknown CC', // used by timeline-controller captionsTextTrack4LanguageCode: '', // used by timeline-controller renderTextTracksNatively: true }; } function mergeConfig(defaultConfig, userConfig) { if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) { throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration"); } if (userConfig.liveMaxLatencyDurationCount !== undefined && (userConfig.liveSyncDurationCount === undefined || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) { throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"'); } if (userConfig.liveMaxLatencyDuration !== undefined && (userConfig.liveSyncDuration === undefined || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) { throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"'); } return _extends({}, defaultConfig, userConfig); } function enableStreamingMode(config) { var currentLoader = config.loader; if (currentLoader !== _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_6__["default"] && currentLoader !== _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_5__["default"]) { // If a developer has configured their own loader, respect that choice _utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log('[config]: Custom loader detected, cannot enable progressive streaming'); config.progressive = false; } else { var canStreamProgressively = Object(_utils_fetch_loader__WEBPACK_IMPORTED_MODULE_6__["fetchSupported"])(); if (canStreamProgressively) { config.loader = _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_6__["default"]; config.progressive = true; config.enableSoftwareAES = true; _utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log('[config]: Progressive streaming enabled, using FetchLoader'); } } } /***/ }), /***/ "./src/controller/abr-controller.ts": /*!******************************************!*\ !*** ./src/controller/abr-controller.ts ***! \******************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _utils_ewma_bandwidth_estimator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/ewma-bandwidth-estimator */ "./src/utils/ewma-bandwidth-estimator.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var AbrController = /*#__PURE__*/function () { function AbrController(hls) { this.hls = void 0; this.lastLoadedFragLevel = 0; this._nextAutoLevel = -1; this.timer = void 0; this.onCheck = this._abandonRulesCheck.bind(this); this.fragCurrent = null; this.partCurrent = null; this.bitrateTestDelay = 0; this.bwEstimator = void 0; this.hls = hls; var config = hls.config; this.bwEstimator = new _utils_ewma_bandwidth_estimator__WEBPACK_IMPORTED_MODULE_1__["default"](config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate); this.registerListeners(); } var _proto = AbrController.prototype; _proto.registerListeners = function registerListeners() { var hls = this.hls; hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADING, this.onFragLoading, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADED, this.onFragLoaded, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, this.onFragBuffered, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].LEVEL_LOADED, this.onLevelLoaded, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, this.onError, this); }; _proto.unregisterListeners = function unregisterListeners() { var hls = this.hls; hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADING, this.onFragLoading, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADED, this.onFragLoaded, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, this.onFragBuffered, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].LEVEL_LOADED, this.onLevelLoaded, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, this.onError, this); }; _proto.destroy = function destroy() { this.unregisterListeners(); this.clearTimer(); // @ts-ignore this.hls = this.onCheck = null; this.fragCurrent = this.partCurrent = null; }; _proto.onFragLoading = function onFragLoading(event, data) { var frag = data.frag; if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_5__["PlaylistLevelType"].MAIN) { if (!this.timer) { var _data$part; this.fragCurrent = frag; this.partCurrent = (_data$part = data.part) != null ? _data$part : null; this.timer = self.setInterval(this.onCheck, 100); } } }; _proto.onLevelLoaded = function onLevelLoaded(event, data) { var config = this.hls.config; if (data.details.live) { this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive); } else { this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD); } } /* This method monitors the download rate of the current fragment, and will downswitch if that fragment will not load quickly enough to prevent underbuffering */ ; _proto._abandonRulesCheck = function _abandonRulesCheck() { var frag = this.fragCurrent, part = this.partCurrent, hls = this.hls; var autoLevelEnabled = hls.autoLevelEnabled, config = hls.config, media = hls.media; if (!frag || !media) { return; } var stats = part ? part.stats : frag.stats; var duration = part ? part.duration : frag.duration; // If loading has been aborted and not in lowLatencyMode, stop timer and return if (stats.aborted) { _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn('frag loader destroy or aborted, disarm abandonRules'); this.clearTimer(); // reset forced auto level value so that next level will be selected this._nextAutoLevel = -1; return; } // This check only runs if we're in ABR mode and actually playing if (!autoLevelEnabled || media.paused || !media.playbackRate || !media.readyState) { return; } var requestDelay = performance.now() - stats.loading.start; var playbackRate = Math.abs(media.playbackRate); // In order to work with a stable bandwidth, only begin monitoring bandwidth after half of the fragment has been loaded if (requestDelay <= 500 * duration / playbackRate) { return; } var levels = hls.levels, minAutoLevel = hls.minAutoLevel; var level = levels[frag.level]; var expectedLen = stats.total || Math.max(stats.loaded, Math.round(duration * level.maxBitrate / 8)); var loadRate = Math.max(1, stats.bwEstimate ? stats.bwEstimate / 8 : stats.loaded * 1000 / requestDelay); // fragLoadDelay is an estimate of the time (in seconds) it will take to buffer the entire fragment var fragLoadedDelay = (expectedLen - stats.loaded) / loadRate; var pos = media.currentTime; // bufferStarvationDelay is an estimate of the amount time (in seconds) it will take to exhaust the buffer var bufferStarvationDelay = (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(media, pos, config.maxBufferHole).end - pos) / playbackRate; // Attempt an emergency downswitch only if less than 2 fragment lengths are buffered, and the time to finish loading // the current fragment is greater than the amount of buffer we have left if (bufferStarvationDelay >= 2 * duration / playbackRate || fragLoadedDelay <= bufferStarvationDelay) { return; } var fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY; var nextLoadLevel; // Iterate through lower level and try to find the largest one that avoids rebuffering for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) { // compute time to load next fragment at lower level // 0.8 : consider only 80% of current bw to be conservative // 8 = bits per byte (bps/Bps) var levelNextBitrate = levels[nextLoadLevel].maxBitrate; fragLevelNextLoadedDelay = duration * levelNextBitrate / (8 * 0.8 * loadRate); if (fragLevelNextLoadedDelay < bufferStarvationDelay) { break; } } // Only emergency switch down if it takes less time to load a new fragment at lowest level instead of continuing // to load the current one if (fragLevelNextLoadedDelay >= fragLoadedDelay) { return; } var bwEstimate = this.bwEstimator.getEstimate(); _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn("Fragment " + frag.sn + (part ? ' part ' + part.index : '') + " of level " + frag.level + " is loading too slowly and will cause an underbuffer; aborting and switching to level " + nextLoadLevel + "\n Current BW estimate: " + (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(bwEstimate) ? (bwEstimate / 1024).toFixed(3) : 'Unknown') + " Kb/s\n Estimated load time for current fragment: " + fragLoadedDelay.toFixed(3) + " s\n Estimated load time for the next fragment: " + fragLevelNextLoadedDelay.toFixed(3) + " s\n Time to underbuffer: " + bufferStarvationDelay.toFixed(3) + " s"); hls.nextLoadLevel = nextLoadLevel; this.bwEstimator.sample(requestDelay, stats.loaded); this.clearTimer(); if (frag.loader) { this.fragCurrent = this.partCurrent = null; frag.loader.abort(); } hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOAD_EMERGENCY_ABORTED, { frag: frag, part: part, stats: stats }); }; _proto.onFragLoaded = function onFragLoaded(event, _ref) { var frag = _ref.frag, part = _ref.part; if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_5__["PlaylistLevelType"].MAIN && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.sn)) { var stats = part ? part.stats : frag.stats; var duration = part ? part.duration : frag.duration; // stop monitoring bw once frag loaded this.clearTimer(); // store level id after successful fragment load this.lastLoadedFragLevel = frag.level; // reset forced auto level value so that next level will be selected this._nextAutoLevel = -1; // compute level average bitrate if (this.hls.config.abrMaxWithRealBitrate) { var level = this.hls.levels[frag.level]; var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded; var loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration; level.loaded = { bytes: loadedBytes, duration: loadedDuration }; level.realBitrate = Math.round(8 * loadedBytes / loadedDuration); } if (frag.bitrateTest) { var fragBufferedData = { stats: stats, frag: frag, part: part, id: frag.type }; this.onFragBuffered(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, fragBufferedData); frag.bitrateTest = false; } } }; _proto.onFragBuffered = function onFragBuffered(event, data) { var frag = data.frag, part = data.part; var stats = part ? part.stats : frag.stats; if (stats.aborted) { return; } // Only count non-alt-audio frags which were actually buffered in our BW calculations if (frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_5__["PlaylistLevelType"].MAIN || frag.sn === 'initSegment') { return; } // Use the difference between parsing and request instead of buffering and request to compute fragLoadingProcessing; // rationale is that buffer appending only happens once media is attached. This can happen when config.startFragPrefetch // is used. If we used buffering in that case, our BW estimate sample will be very large. var processingMs = stats.parsing.end - stats.loading.start; this.bwEstimator.sample(processingMs, stats.loaded); stats.bwEstimate = this.bwEstimator.getEstimate(); if (frag.bitrateTest) { this.bitrateTestDelay = processingMs / 1000; } else { this.bitrateTestDelay = 0; } }; _proto.onError = function onError(event, data) { // stop timer in case of frag loading error switch (data.details) { case _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].FRAG_LOAD_ERROR: case _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].FRAG_LOAD_TIMEOUT: this.clearTimer(); break; default: break; } }; _proto.clearTimer = function clearTimer() { self.clearInterval(this.timer); this.timer = undefined; } // return next auto level ; _proto.getNextABRAutoLevel = function getNextABRAutoLevel() { var fragCurrent = this.fragCurrent, partCurrent = this.partCurrent, hls = this.hls; var maxAutoLevel = hls.maxAutoLevel, config = hls.config, minAutoLevel = hls.minAutoLevel, media = hls.media; var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0; var pos = media ? media.currentTime : 0; // playbackRate is the absolute value of the playback rate; if media.playbackRate is 0, we use 1 to load as // if we're playing back at the normal rate. var playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1.0; var avgbw = this.bwEstimator ? this.bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate; // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted. var bufferStarvationDelay = (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(media, pos, config.maxBufferHole).end - pos) / playbackRate; // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all var bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor); if (bestLevel >= 0) { return bestLevel; } _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].trace((bufferStarvationDelay ? 'rebuffering expected' : 'buffer is empty') + ", finding optimal quality level"); // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering // if no matching level found, logic will return 0 var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay; var bwFactor = config.abrBandWidthFactor; var bwUpFactor = config.abrBandWidthUpFactor; if (!bufferStarvationDelay) { // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test var bitrateTestDelay = this.bitrateTestDelay; if (bitrateTestDelay) { // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value // max video loading delay used in automatic start level selection : // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level + // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` ) // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay; maxStarvationDelay = maxLoadingDelay - bitrateTestDelay; _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].trace("bitrate test took " + Math.round(1000 * bitrateTestDelay) + "ms, set first fragment max fetchDuration to " + Math.round(1000 * maxStarvationDelay) + " ms"); // don't use conservative factor on bitrate test bwFactor = bwUpFactor = 1; } } bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor); return Math.max(bestLevel, 0); }; _proto.findBestLevel = function findBestLevel(currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor) { var _level$details; var fragCurrent = this.fragCurrent, partCurrent = this.partCurrent, currentLevel = this.lastLoadedFragLevel; var levels = this.hls.levels; var level = levels[currentLevel]; var live = !!(level !== null && level !== void 0 && (_level$details = level.details) !== null && _level$details !== void 0 && _level$details.live); var currentCodecSet = level === null || level === void 0 ? void 0 : level.codecSet; var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0; for (var i = maxAutoLevel; i >= minAutoLevel; i--) { var levelInfo = levels[i]; if (!levelInfo || currentCodecSet && levelInfo.codecSet !== currentCodecSet) { continue; } var levelDetails = levelInfo.details; var avgDuration = (partCurrent ? levelDetails === null || levelDetails === void 0 ? void 0 : levelDetails.partTarget : levelDetails === null || levelDetails === void 0 ? void 0 : levelDetails.averagetargetduration) || currentFragDuration; var adjustedbw = void 0; // follow algorithm captured from stagefright : // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp // Pick the highest bandwidth stream below or equal to estimated bandwidth. // consider only 80% of the available bandwidth, but if we are switching up, // be even more conservative (70%) to avoid overestimating and immediately // switching back. if (i <= currentLevel) { adjustedbw = bwFactor * currentBw; } else { adjustedbw = bwUpFactor * currentBw; } var bitrate = levels[i].maxBitrate; var fetchDuration = bitrate * avgDuration / adjustedbw; _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: " + i + "/" + Math.round(adjustedbw) + "/" + bitrate + "/" + avgDuration + "/" + maxFetchDuration + "/" + fetchDuration); // if adjusted bw is greater than level bitrate AND if (adjustedbw > bitrate && ( // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches // we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ... // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1 !fetchDuration || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration)) { // as we are looping from highest to lowest, this will return the best achievable quality level return i; } } // not enough time budget even with quality level 0 ... rebuffering might happen return -1; }; _createClass(AbrController, [{ key: "nextAutoLevel", get: function get() { var forcedAutoLevel = this._nextAutoLevel; var bwEstimator = this.bwEstimator; // in case next auto level has been forced, and bw not available or not reliable, return forced value if (forcedAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) { return forcedAutoLevel; } // compute next level using ABR logic var nextABRAutoLevel = this.getNextABRAutoLevel(); // if forced auto level has been defined, use it to cap ABR computed quality level if (forcedAutoLevel !== -1) { nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel); } return nextABRAutoLevel; }, set: function set(nextLevel) { this._nextAutoLevel = nextLevel; } }]); return AbrController; }(); /* harmony default export */ __webpack_exports__["default"] = (AbrController); /***/ }), /***/ "./src/controller/base-playlist-controller.ts": /*!****************************************************!*\ !*** ./src/controller/base-playlist-controller.ts ***! \****************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BasePlaylistController; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts"); /* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); var BasePlaylistController = /*#__PURE__*/function () { function BasePlaylistController(hls, logPrefix) { this.hls = void 0; this.timer = -1; this.canLoad = false; this.retryCount = 0; this.log = void 0; this.warn = void 0; this.log = _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"], logPrefix + ":"); this.warn = _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"], logPrefix + ":"); this.hls = hls; } var _proto = BasePlaylistController.prototype; _proto.destroy = function destroy() { this.clearTimer(); // @ts-ignore this.hls = this.log = this.warn = null; }; _proto.onError = function onError(event, data) { if (data.fatal && data.type === _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].NETWORK_ERROR) { this.clearTimer(); } }; _proto.clearTimer = function clearTimer() { clearTimeout(this.timer); this.timer = -1; }; _proto.startLoad = function startLoad() { this.canLoad = true; this.retryCount = 0; this.loadPlaylist(); }; _proto.stopLoad = function stopLoad() { this.canLoad = false; this.clearTimer(); }; _proto.switchParams = function switchParams(playlistUri, previous) { var renditionReports = previous === null || previous === void 0 ? void 0 : previous.renditionReports; if (renditionReports) { for (var i = 0; i < renditionReports.length; i++) { var attr = renditionReports[i]; var uri = '' + attr.URI; if (uri === playlistUri.substr(-uri.length)) { var msn = parseInt(attr['LAST-MSN']); var part = parseInt(attr['LAST-PART']); if (previous && this.hls.config.lowLatencyMode) { var currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration); if (part !== undefined && currentGoal > previous.partTarget) { part += 1; } } if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(msn)) { return new _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsUrlParameters"](msn, Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(part) ? part : undefined, _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsSkip"].No); } } } } }; _proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {}; _proto.shouldLoadTrack = function shouldLoadTrack(track) { return this.canLoad && track && !!track.url && (!track.details || track.details.live); }; _proto.playlistLoaded = function playlistLoaded(index, data, previousDetails) { var _this = this; var details = data.details, stats = data.stats; // Set last updated date-time var elapsed = stats.loading.end ? Math.max(0, self.performance.now() - stats.loading.end) : 0; details.advancedDateTime = Date.now() - elapsed; // if current playlist is a live playlist, arm a timer to reload it if (details.live || previousDetails !== null && previousDetails !== void 0 && previousDetails.live) { details.reloaded(previousDetails); if (previousDetails) { this.log("live playlist " + index + " " + (details.advanced ? 'REFRESHED ' + details.lastPartSn + '-' + details.lastPartIndex : 'MISSED')); } // Merge live playlists to adjust fragment starts and fill in delta playlist skipped segments if (previousDetails && details.fragments.length > 0) { Object(_level_helper__WEBPACK_IMPORTED_MODULE_2__["mergeDetails"])(previousDetails, details); } if (!this.canLoad || !details.live) { return; } var deliveryDirectives; var msn = undefined; var part = undefined; if (details.canBlockReload && details.endSN && details.advanced) { // Load level with LL-HLS delivery directives var lowLatencyMode = this.hls.config.lowLatencyMode; var lastPartSn = details.lastPartSn; var endSn = details.endSN; var lastPartIndex = details.lastPartIndex; var hasParts = lastPartIndex !== -1; var lastPart = lastPartSn === endSn; // When low latency mode is disabled, we'll skip part requests once the last part index is found var nextSnStartIndex = lowLatencyMode ? 0 : lastPartIndex; if (hasParts) { msn = lastPart ? endSn + 1 : lastPartSn; part = lastPart ? nextSnStartIndex : lastPartIndex + 1; } else { msn = endSn + 1; } // Low-Latency CDN Tune-in: "age" header and time since load indicates we're behind by more than one part // Update directives to obtain the Playlist that has the estimated additional duration of media var lastAdvanced = details.age; var cdnAge = lastAdvanced + details.ageHeader; var currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5); if (currentGoal > 0) { if (previousDetails && currentGoal > previousDetails.tuneInGoal) { // If we attempted to get the next or latest playlist update, but currentGoal increased, // then we either can't catchup, or the "age" header cannot be trusted. this.warn("CDN Tune-in goal increased from: " + previousDetails.tuneInGoal + " to: " + currentGoal + " with playlist age: " + details.age); currentGoal = 0; } else { var segments = Math.floor(currentGoal / details.targetduration); msn += segments; if (part !== undefined) { var parts = Math.round(currentGoal % details.targetduration / details.partTarget); part += parts; } this.log("CDN Tune-in age: " + details.ageHeader + "s last advanced " + lastAdvanced.toFixed(2) + "s goal: " + currentGoal + " skip sn " + segments + " to part " + part); } details.tuneInGoal = currentGoal; } deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part); if (lowLatencyMode || !lastPart) { this.loadPlaylist(deliveryDirectives); return; } } else { deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part); } var reloadInterval = Object(_level_helper__WEBPACK_IMPORTED_MODULE_2__["computeReloadInterval"])(details, stats); if (msn !== undefined && details.canBlockReload) { reloadInterval -= details.partTarget || 1; } this.log("reload live playlist " + index + " in " + Math.round(reloadInterval) + " ms"); this.timer = self.setTimeout(function () { return _this.loadPlaylist(deliveryDirectives); }, reloadInterval); } else { this.clearTimer(); } }; _proto.getDeliveryDirectives = function getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) { var skip = Object(_types_level__WEBPACK_IMPORTED_MODULE_1__["getSkipValue"])(details, msn); if (previousDeliveryDirectives !== null && previousDeliveryDirectives !== void 0 && previousDeliveryDirectives.skip && details.deltaUpdateFailed) { msn = previousDeliveryDirectives.msn; part = previousDeliveryDirectives.part; skip = _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsSkip"].No; } return new _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsUrlParameters"](msn, part, skip); }; _proto.retryLoadingOrFail = function retryLoadingOrFail(errorEvent) { var _this2 = this; var config = this.hls.config; var retry = this.retryCount < config.levelLoadingMaxRetry; if (retry) { var _errorEvent$context; this.retryCount++; if (errorEvent.details.indexOf('LoadTimeOut') > -1 && (_errorEvent$context = errorEvent.context) !== null && _errorEvent$context !== void 0 && _errorEvent$context.deliveryDirectives) { // The LL-HLS request already timed out so retry immediately this.warn("retry playlist loading #" + this.retryCount + " after \"" + errorEvent.details + "\""); this.loadPlaylist(); } else { // exponential backoff capped to max retry timeout var delay = Math.min(Math.pow(2, this.retryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout); // Schedule level/track reload this.timer = self.setTimeout(function () { return _this2.loadPlaylist(); }, delay); this.warn("retry playlist loading #" + this.retryCount + " in " + delay + " ms after \"" + errorEvent.details + "\""); } } else { this.warn("cannot recover from error \"" + errorEvent.details + "\""); // stopping live reloading timer if any this.clearTimer(); // switch error to fatal errorEvent.fatal = true; } return retry; }; return BasePlaylistController; }(); /***/ }), /***/ "./src/controller/base-stream-controller.ts": /*!**************************************************!*\ !*** ./src/controller/base-stream-controller.ts ***! \**************************************************/ /*! exports provided: State, default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "State", function() { return State; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BaseStreamController; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _task_loop__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../task-loop */ "./src/task-loop.ts"); /* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts"); /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _types_transmuxer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../types/transmuxer */ "./src/types/transmuxer.ts"); /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts"); /* harmony import */ var _utils_discontinuities__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/discontinuities */ "./src/utils/discontinuities.ts"); /* harmony import */ var _fragment_finders__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./fragment-finders */ "./src/controller/fragment-finders.ts"); /* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts"); /* harmony import */ var _loader_fragment_loader__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../loader/fragment-loader */ "./src/loader/fragment-loader.ts"); /* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.ts"); /* harmony import */ var _utils_time_ranges__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/time-ranges */ "./src/utils/time-ranges.ts"); /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts"); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var State = { STOPPED: 'STOPPED', IDLE: 'IDLE', KEY_LOADING: 'KEY_LOADING', FRAG_LOADING: 'FRAG_LOADING', FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY', WAITING_TRACK: 'WAITING_TRACK', PARSING: 'PARSING', PARSED: 'PARSED', BACKTRACKING: 'BACKTRACKING', ENDED: 'ENDED', ERROR: 'ERROR', WAITING_INIT_PTS: 'WAITING_INIT_PTS', WAITING_LEVEL: 'WAITING_LEVEL' }; var BaseStreamController = /*#__PURE__*/function (_TaskLoop) { _inheritsLoose(BaseStreamController, _TaskLoop); function BaseStreamController(hls, fragmentTracker, logPrefix) { var _this; _this = _TaskLoop.call(this) || this; _this.hls = void 0; _this.fragPrevious = null; _this.fragCurrent = null; _this.fragmentTracker = void 0; _this.transmuxer = null; _this._state = State.STOPPED; _this.media = void 0; _this.mediaBuffer = void 0; _this.config = void 0; _this.bitrateTest = false; _this.lastCurrentTime = 0; _this.nextLoadPosition = 0; _this.startPosition = 0; _this.loadedmetadata = false; _this.fragLoadError = 0; _this.retryDate = 0; _this.levels = null; _this.fragmentLoader = void 0; _this.levelLastLoaded = null; _this.startFragRequested = false; _this.decrypter = void 0; _this.initPTS = []; _this.onvseeking = null; _this.onvended = null; _this.logPrefix = ''; _this.log = void 0; _this.warn = void 0; _this.logPrefix = logPrefix; _this.log = _utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"].log.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"], logPrefix + ":"); _this.warn = _utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"].warn.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"], logPrefix + ":"); _this.hls = hls; _this.fragmentLoader = new _loader_fragment_loader__WEBPACK_IMPORTED_MODULE_12__["default"](hls.config); _this.fragmentTracker = fragmentTracker; _this.config = hls.config; _this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_13__["default"](hls, hls.config); hls.on(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].KEY_LOADED, _this.onKeyLoaded, _assertThisInitialized(_this)); return _this; } var _proto = BaseStreamController.prototype; _proto.doTick = function doTick() { this.onTickEnd(); }; _proto.onTickEnd = function onTickEnd() {} // eslint-disable-next-line @typescript-eslint/no-unused-vars ; _proto.startLoad = function startLoad(startPosition) {}; _proto.stopLoad = function stopLoad() { this.fragmentLoader.abort(); var frag = this.fragCurrent; if (frag) { this.fragmentTracker.removeFragment(frag); } this.resetTransmuxer(); this.fragCurrent = null; this.fragPrevious = null; this.clearInterval(); this.clearNextTick(); this.state = State.STOPPED; }; _proto._streamEnded = function _streamEnded(bufferInfo, levelDetails) { var fragCurrent = this.fragCurrent, fragmentTracker = this.fragmentTracker; // we just got done loading the final fragment and there is no other buffered range after ... // rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between // so we should not switch to ENDED in that case, to be able to buffer them if (!levelDetails.live && fragCurrent && fragCurrent.sn === levelDetails.endSN && !bufferInfo.nextStart) { var fragState = fragmentTracker.getState(fragCurrent); return fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].PARTIAL || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].OK; } return false; }; _proto.onMediaAttached = function onMediaAttached(event, data) { var media = this.media = this.mediaBuffer = data.media; this.onvseeking = this.onMediaSeeking.bind(this); this.onvended = this.onMediaEnded.bind(this); media.addEventListener('seeking', this.onvseeking); media.addEventListener('ended', this.onvended); var config = this.config; if (this.levels && config.autoStartLoad && this.state === State.STOPPED) { this.startLoad(config.startPosition); } }; _proto.onMediaDetaching = function onMediaDetaching() { var media = this.media; if (media !== null && media !== void 0 && media.ended) { this.log('MSE detaching and video ended, reset startPosition'); this.startPosition = this.lastCurrentTime = 0; } // remove video listeners if (media) { media.removeEventListener('seeking', this.onvseeking); media.removeEventListener('ended', this.onvended); this.onvseeking = this.onvended = null; } this.media = this.mediaBuffer = null; this.loadedmetadata = false; this.fragmentTracker.removeAllFragments(); this.stopLoad(); }; _proto.onMediaSeeking = function onMediaSeeking() { var config = this.config, fragCurrent = this.fragCurrent, media = this.media, mediaBuffer = this.mediaBuffer, state = this.state; var currentTime = media ? media.currentTime : 0; var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(mediaBuffer || media, currentTime, config.maxBufferHole); this.log("media seeking to " + (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(currentTime) ? currentTime.toFixed(3) : currentTime) + ", state: " + state); if (state === State.ENDED) { this.resetLoadingState(); } else if (fragCurrent && !bufferInfo.len) { // check if we are seeking to a unbuffered area AND if frag loading is in progress var tolerance = config.maxFragLookUpTolerance; var fragStartOffset = fragCurrent.start - tolerance; var fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance; var pastFragment = currentTime > fragEndOffset; // check if the seek position is past current fragment, and if so abort loading if (currentTime < fragStartOffset || pastFragment) { if (pastFragment && fragCurrent.loader) { this.log('seeking outside of buffer while fragment load in progress, cancel fragment load'); fragCurrent.loader.abort(); } this.resetLoadingState(); } } if (media) { this.lastCurrentTime = currentTime; } // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target if (!this.loadedmetadata && !bufferInfo.len) { this.nextLoadPosition = this.startPosition = currentTime; } // Async tick to speed up processing this.tickImmediate(); }; _proto.onMediaEnded = function onMediaEnded() { // reset startPosition and lastCurrentTime to restart playback @ stream beginning this.startPosition = this.lastCurrentTime = 0; }; _proto.onKeyLoaded = function onKeyLoaded(event, data) { if (this.state !== State.KEY_LOADING || data.frag !== this.fragCurrent || !this.levels) { return; } this.state = State.IDLE; var levelDetails = this.levels[data.frag.level].details; if (levelDetails) { this.loadFragment(data.frag, levelDetails, data.frag.start); } }; _proto.onHandlerDestroying = function onHandlerDestroying() { this.stopLoad(); _TaskLoop.prototype.onHandlerDestroying.call(this); }; _proto.onHandlerDestroyed = function onHandlerDestroyed() { this.state = State.STOPPED; this.hls.off(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].KEY_LOADED, this.onKeyLoaded, this); if (this.fragmentLoader) { this.fragmentLoader.destroy(); } if (this.decrypter) { this.decrypter.destroy(); } this.hls = this.log = this.warn = this.decrypter = this.fragmentLoader = this.fragmentTracker = null; _TaskLoop.prototype.onHandlerDestroyed.call(this); }; _proto.loadKey = function loadKey(frag, details) { this.log("Loading key for " + frag.sn + " of [" + details.startSN + "-" + details.endSN + "], " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + " " + frag.level); this.state = State.KEY_LOADING; this.fragCurrent = frag; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].KEY_LOADING, { frag: frag }); }; _proto.loadFragment = function loadFragment(frag, levelDetails, targetBufferTime) { this._loadFragForPlayback(frag, levelDetails, targetBufferTime); }; _proto._loadFragForPlayback = function _loadFragForPlayback(frag, levelDetails, targetBufferTime) { var _this2 = this; var progressCallback = function progressCallback(data) { if (_this2.fragContextChanged(frag)) { _this2.warn("Fragment " + frag.sn + (data.part ? ' p: ' + data.part.index : '') + " of level " + frag.level + " was dropped during download."); _this2.fragmentTracker.removeFragment(frag); return; } frag.stats.chunkCount++; _this2._handleFragmentLoadProgress(data); }; this._doFragLoad(frag, levelDetails, targetBufferTime, progressCallback).then(function (data) { if (!data) { // if we're here we probably needed to backtrack or are waiting for more parts return; } _this2.fragLoadError = 0; var state = _this2.state; if (_this2.fragContextChanged(frag)) { if (state === State.FRAG_LOADING || state === State.BACKTRACKING || !_this2.fragCurrent && state === State.PARSING) { _this2.fragmentTracker.removeFragment(frag); _this2.state = State.IDLE; } return; } if ('payload' in data) { _this2.log("Loaded fragment " + frag.sn + " of level " + frag.level); _this2.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADED, data); // Tracker backtrack must be called after onFragLoaded to update the fragment entity state to BACKTRACKED // This happens after handleTransmuxComplete when the worker or progressive is disabled if (_this2.state === State.BACKTRACKING) { _this2.fragmentTracker.backtrack(frag, data); _this2.resetFragmentLoading(frag); return; } } // Pass through the whole payload; controllers not implementing progressive loading receive data from this callback _this2._handleFragmentLoadComplete(data); }).catch(function (reason) { _this2.warn(reason); _this2.resetFragmentLoading(frag); }); }; _proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset, type) { if (type === void 0) { type = null; } if (!(startOffset - endOffset)) { return; } // When alternate audio is playing, the audio-stream-controller is responsible for the audio buffer. Otherwise, // passing a null type flushes both buffers var flushScope = { startOffset: startOffset, endOffset: endOffset, type: type }; // Reset load errors on flush this.fragLoadError = 0; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].BUFFER_FLUSHING, flushScope); }; _proto._loadInitSegment = function _loadInitSegment(frag) { var _this3 = this; this._doFragLoad(frag).then(function (data) { if (!data || _this3.fragContextChanged(frag) || !_this3.levels) { throw new Error('init load aborted'); } return data; }).then(function (data) { var hls = _this3.hls; var payload = data.payload; var decryptData = frag.decryptdata; // check to see if the payload needs to be decrypted if (payload && payload.byteLength > 0 && decryptData && decryptData.key && decryptData.iv && decryptData.method === 'AES-128') { var startTime = self.performance.now(); // decrypt the subtitles return _this3.decrypter.webCryptoDecrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer).then(function (decryptedData) { var endTime = self.performance.now(); hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_DECRYPTED, { frag: frag, payload: decryptedData, stats: { tstart: startTime, tdecrypt: endTime } }); data.payload = decryptedData; return data; }); } return data; }).then(function (data) { var fragCurrent = _this3.fragCurrent, hls = _this3.hls, levels = _this3.levels; if (!levels) { throw new Error('init load aborted, missing levels'); } var details = levels[frag.level].details; console.assert(details, 'Level details are defined when init segment is loaded'); var stats = frag.stats; _this3.state = State.IDLE; _this3.fragLoadError = 0; frag.data = new Uint8Array(data.payload); stats.parsing.start = stats.buffering.start = self.performance.now(); stats.parsing.end = stats.buffering.end = self.performance.now(); // Silence FRAG_BUFFERED event if fragCurrent is null if (data.frag === fragCurrent) { hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_BUFFERED, { stats: stats, frag: fragCurrent, part: null, id: frag.type }); } _this3.tick(); }).catch(function (reason) { _this3.warn(reason); _this3.resetFragmentLoading(frag); }); }; _proto.fragContextChanged = function fragContextChanged(frag) { var fragCurrent = this.fragCurrent; return !frag || !fragCurrent || frag.level !== fragCurrent.level || frag.sn !== fragCurrent.sn || frag.urlId !== fragCurrent.urlId; }; _proto.fragBufferedComplete = function fragBufferedComplete(frag, part) { var media = this.mediaBuffer ? this.mediaBuffer : this.media; this.log("Buffered " + frag.type + " sn: " + frag.sn + (part ? ' part: ' + part.index : '') + " of " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + " " + frag.level + " " + _utils_time_ranges__WEBPACK_IMPORTED_MODULE_14__["default"].toString(_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].getBuffered(media))); this.state = State.IDLE; this.tick(); }; _proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedEndData) { var transmuxer = this.transmuxer; if (!transmuxer) { return; } var frag = fragLoadedEndData.frag, part = fragLoadedEndData.part, partsLoaded = fragLoadedEndData.partsLoaded; // If we did not load parts, or loaded all parts, we have complete (not partial) fragment data var complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some(function (fragLoaded) { return !fragLoaded; }); var chunkMeta = new _types_transmuxer__WEBPACK_IMPORTED_MODULE_7__["ChunkMetadata"](frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete); transmuxer.flush(chunkMeta); } // eslint-disable-next-line @typescript-eslint/no-unused-vars ; _proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(frag) {}; _proto._doFragLoad = function _doFragLoad(frag, details, targetBufferTime, progressCallback) { var _this4 = this; if (targetBufferTime === void 0) { targetBufferTime = null; } if (!this.levels) { throw new Error('frag load aborted, missing levels'); } targetBufferTime = Math.max(frag.start, targetBufferTime || 0); if (this.config.lowLatencyMode && details) { var partList = details.partList; if (partList && progressCallback) { if (targetBufferTime > frag.end && details.fragmentHint) { frag = details.fragmentHint; } var partIndex = this.getNextPart(partList, frag, targetBufferTime); if (partIndex > -1) { var part = partList[partIndex]; this.log("Loading part sn: " + frag.sn + " p: " + part.index + " cc: " + frag.cc + " of playlist [" + details.startSN + "-" + details.endSN + "] parts [0-" + partIndex + "-" + (partList.length - 1) + "] " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + ": " + frag.level + ", target: " + parseFloat(targetBufferTime.toFixed(3))); this.nextLoadPosition = part.start + part.duration; this.state = State.FRAG_LOADING; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADING, { frag: frag, part: partList[partIndex], targetBufferTime: targetBufferTime }); return this.doFragPartsLoad(frag, partList, partIndex, progressCallback).catch(function (error) { return _this4.handleFragLoadError(error); }); } else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) { // Fragment hint has no parts return Promise.resolve(null); } } } this.log("Loading fragment " + frag.sn + " cc: " + frag.cc + " " + (details ? 'of [' + details.startSN + '-' + details.endSN + '] ' : '') + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + ": " + frag.level + ", target: " + parseFloat(targetBufferTime.toFixed(3))); // Don't update nextLoadPosition for fragments which are not buffered if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.sn) && !this.bitrateTest) { this.nextLoadPosition = frag.start + frag.duration; } this.state = State.FRAG_LOADING; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADING, { frag: frag, targetBufferTime: targetBufferTime }); return this.fragmentLoader.load(frag, progressCallback).catch(function (error) { return _this4.handleFragLoadError(error); }); }; _proto.doFragPartsLoad = function doFragPartsLoad(frag, partList, partIndex, progressCallback) { var _this5 = this; return new Promise(function (resolve, reject) { var partsLoaded = []; var loadPartIndex = function loadPartIndex(index) { var part = partList[index]; _this5.fragmentLoader.loadPart(frag, part, progressCallback).then(function (partLoadedData) { partsLoaded[part.index] = partLoadedData; var loadedPart = partLoadedData.part; _this5.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADED, partLoadedData); var nextPart = partList[index + 1]; if (nextPart && nextPart.fragment === frag) { loadPartIndex(index + 1); } else { return resolve({ frag: frag, part: loadedPart, partsLoaded: partsLoaded }); } }).catch(reject); }; loadPartIndex(partIndex); }); }; _proto.handleFragLoadError = function handleFragLoadError(_ref) { var data = _ref.data; if (data && data.details === _errors__WEBPACK_IMPORTED_MODULE_6__["ErrorDetails"].INTERNAL_ABORTED) { this.handleFragLoadAborted(data.frag, data.part); } else { this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, data); } return null; }; _proto._handleTransmuxerFlush = function _handleTransmuxerFlush(chunkMeta) { var context = this.getCurrentContext(chunkMeta); if (!context || this.state !== State.PARSING) { if (!this.fragCurrent) { this.state = State.IDLE; } return; } var frag = context.frag, part = context.part, level = context.level; var now = self.performance.now(); frag.stats.parsing.end = now; if (part) { part.stats.parsing.end = now; } this.updateLevelTiming(frag, part, level, chunkMeta.partial); }; _proto.getCurrentContext = function getCurrentContext(chunkMeta) { var levels = this.levels; var levelIndex = chunkMeta.level, sn = chunkMeta.sn, partIndex = chunkMeta.part; if (!levels || !levels[levelIndex]) { this.warn("Levels object was unset while buffering fragment " + sn + " of level " + levelIndex + ". The current chunk will not be buffered."); return null; } var level = levels[levelIndex]; var part = partIndex > -1 ? Object(_level_helper__WEBPACK_IMPORTED_MODULE_11__["getPartWith"])(level, sn, partIndex) : null; var frag = part ? part.fragment : Object(_level_helper__WEBPACK_IMPORTED_MODULE_11__["getFragmentWithSN"])(level, sn, this.fragCurrent); if (!frag) { return null; } return { frag: frag, part: part, level: level }; }; _proto.bufferFragmentData = function bufferFragmentData(data, frag, part, chunkMeta) { if (!data || this.state !== State.PARSING) { return; } var data1 = data.data1, data2 = data.data2; var buffer = data1; if (data1 && data2) { // Combine the moof + mdat so that we buffer with a single append buffer = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_8__["appendUint8Array"])(data1, data2); } if (!buffer || !buffer.length) { return; } var segment = { type: data.type, frag: frag, part: part, chunkMeta: chunkMeta, parent: frag.type, data: buffer }; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].BUFFER_APPENDING, segment); if (data.dropped && data.independent && !part) { // Clear buffer so that we reload previous segments sequentially if required this.flushBufferGap(frag); } }; _proto.flushBufferGap = function flushBufferGap(frag) { var media = this.media; if (!media) { return; } // If currentTime is not buffered, clear the back buffer so that we can backtrack as much as needed if (!_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].isBuffered(media, media.currentTime)) { this.flushMainBuffer(0, frag.start); return; } // Remove back-buffer without interrupting playback to allow back tracking var currentTime = media.currentTime; var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(media, currentTime, 0); var fragDuration = frag.duration; var segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25); var start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction); if (frag.start - start > segmentFraction) { this.flushMainBuffer(start, frag.start); } }; _proto.getFwdBufferInfo = function getFwdBufferInfo(bufferable, type) { var config = this.config; var pos = this.getLoadPosition(); if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(pos)) { return null; } var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(bufferable, pos, config.maxBufferHole); // Workaround flaw in getting forward buffer when maxBufferHole is smaller than gap at current pos if (bufferInfo.len === 0 && bufferInfo.nextStart !== undefined) { var bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type); if (bufferedFragAtPos && bufferInfo.nextStart < bufferedFragAtPos.end) { return _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(bufferable, pos, Math.max(bufferInfo.nextStart, config.maxBufferHole)); } } return bufferInfo; }; _proto.getMaxBufferLength = function getMaxBufferLength(levelBitrate) { var config = this.config; var maxBufLen; if (levelBitrate) { maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength); } else { maxBufLen = config.maxBufferLength; } return Math.min(maxBufLen, config.maxMaxBufferLength); }; _proto.reduceMaxBufferLength = function reduceMaxBufferLength(threshold) { var config = this.config; var minLength = threshold || config.maxBufferLength; if (config.maxMaxBufferLength >= minLength) { // reduce max buffer length as it might be too high. we do this to avoid loop flushing ... config.maxMaxBufferLength /= 2; this.warn("Reduce max buffer length to " + config.maxMaxBufferLength + "s"); return true; } return false; }; _proto.getNextFragment = function getNextFragment(pos, levelDetails) { var _frag, _frag2; var fragments = levelDetails.fragments; var fragLen = fragments.length; if (!fragLen) { return null; } // find fragment index, contiguous with end of buffer position var config = this.config; var start = fragments[0].start; var frag; if (levelDetails.live) { var initialLiveManifestSize = config.initialLiveManifestSize; if (fragLen < initialLiveManifestSize) { this.warn("Not enough fragments to start playback (have: " + fragLen + ", need: " + initialLiveManifestSize + ")"); return null; } // The real fragment start times for a live stream are only known after the PTS range for that level is known. // In order to discover the range, we load the best matching fragment for that level and demux it. // Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that // we get the fragment matching that start time if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1) { frag = this.getInitialLiveFragment(levelDetails, fragments); this.startPosition = frag ? this.hls.liveSyncPosition || frag.start : pos; } } else if (pos <= start) { // VoD playlist: if loadPosition before start of playlist, load first fragment frag = fragments[0]; } // If we haven't run into any special cases already, just load the fragment most closely matching the requested position if (!frag) { var end = config.lowLatencyMode ? levelDetails.partEnd : levelDetails.fragmentEnd; frag = this.getFragmentAtPosition(pos, end, levelDetails); } // If an initSegment is present, it must be buffered first if ((_frag = frag) !== null && _frag !== void 0 && _frag.initSegment && !((_frag2 = frag) !== null && _frag2 !== void 0 && _frag2.initSegment.data) && !this.bitrateTest) { frag = frag.initSegment; } return frag; }; _proto.getNextPart = function getNextPart(partList, frag, targetBufferTime) { var nextPart = -1; var contiguous = false; var independentAttrOmitted = true; for (var i = 0, len = partList.length; i < len; i++) { var part = partList[i]; independentAttrOmitted = independentAttrOmitted && !part.independent; if (nextPart > -1 && targetBufferTime < part.start) { break; } var loaded = part.loaded; if (!loaded && (contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) { nextPart = i; } contiguous = loaded; } return nextPart; }; _proto.loadedEndOfParts = function loadedEndOfParts(partList, targetBufferTime) { var lastPart = partList[partList.length - 1]; return lastPart && targetBufferTime > lastPart.start && lastPart.loaded; } /* This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the "sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real start and end times for each fragment in the playlist (after which this method will not need to be called). */ ; _proto.getInitialLiveFragment = function getInitialLiveFragment(levelDetails, fragments) { var fragPrevious = this.fragPrevious; var frag = null; if (fragPrevious) { if (levelDetails.hasProgramDateTime) { // Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding this.log("Live playlist, switching playlist, load frag with same PDT: " + fragPrevious.programDateTime); frag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_10__["findFragmentByPDT"])(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance); } if (!frag) { // SN does not need to be accurate between renditions, but depending on the packaging it may be so. var targetSN = fragPrevious.sn + 1; if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) { var fragNext = fragments[targetSN - levelDetails.startSN]; // Ensure that we're staying within the continuity range, since PTS resets upon a new range if (fragPrevious.cc === fragNext.cc) { frag = fragNext; this.log("Live playlist, switching playlist, load frag with next SN: " + frag.sn); } } // It's important to stay within the continuity range if available; otherwise the fragments in the playlist // will have the wrong start times if (!frag) { frag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_10__["findFragWithCC"])(fragments, fragPrevious.cc); if (frag) { this.log("Live playlist, switching playlist, load frag with same CC: " + frag.sn); } } } } else { // Find a new start fragment when fragPrevious is null var liveStart = this.hls.liveSyncPosition; if (liveStart !== null) { frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails); } } return frag; } /* This method finds the best matching fragment given the provided position. */ ; _proto.getFragmentAtPosition = function getFragmentAtPosition(bufferEnd, end, levelDetails) { var config = this.config, fragPrevious = this.fragPrevious; var fragments = levelDetails.fragments, endSN = levelDetails.endSN; var fragmentHint = levelDetails.fragmentHint; var tolerance = config.maxFragLookUpTolerance; var loadingParts = !!(config.lowLatencyMode && levelDetails.partList && fragmentHint); if (loadingParts && fragmentHint && !this.bitrateTest) { // Include incomplete fragment with parts at end fragments = fragments.concat(fragmentHint); endSN = fragmentHint.sn; } var frag; if (bufferEnd < end) { var lookupTolerance = bufferEnd > end - tolerance ? 0 : tolerance; // Remove the tolerance if it would put the bufferEnd past the actual end of stream // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE) frag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_10__["findFragmentByPTS"])(fragPrevious, fragments, bufferEnd, lookupTolerance); } else { // reach end of playlist frag = fragments[fragments.length - 1]; } if (frag) { var curSNIdx = frag.sn - levelDetails.startSN; var sameLevel = fragPrevious && frag.level === fragPrevious.level; var nextFrag = fragments[curSNIdx + 1]; var fragState = this.fragmentTracker.getState(frag); if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].BACKTRACKED) { frag = null; var i = curSNIdx; while (fragments[i] && this.fragmentTracker.getState(fragments[i]) === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].BACKTRACKED) { // When fragPrevious is null, backtrack to first the first fragment is not BACKTRACKED for loading // When fragPrevious is set, we want the first BACKTRACKED fragment for parsing and buffering if (!fragPrevious) { frag = fragments[--i]; } else { frag = fragments[i--]; } } if (!frag) { frag = nextFrag; } } else if (fragPrevious && frag.sn === fragPrevious.sn && !loadingParts) { // Force the next fragment to load if the previous one was already selected. This can occasionally happen with // non-uniform fragment durations if (sameLevel) { if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].OK) { this.log("SN " + frag.sn + " just loaded, load next one: " + nextFrag.sn); frag = nextFrag; } else { frag = null; } } } } return frag; }; _proto.synchronizeToLiveEdge = function synchronizeToLiveEdge(levelDetails) { var config = this.config, media = this.media; if (!media) { return; } var liveSyncPosition = this.hls.liveSyncPosition; var currentTime = media.currentTime; var start = levelDetails.fragments[0].start; var end = levelDetails.edge; var withinSlidingWindow = currentTime >= start - config.maxFragLookUpTolerance && currentTime <= end; // Continue if we can seek forward to sync position or if current time is outside of sliding window if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) { // Continue if buffer is starving or if current time is behind max latency var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration; if (!withinSlidingWindow && media.readyState < 4 || currentTime < end - maxLatency) { if (!this.loadedmetadata) { this.nextLoadPosition = liveSyncPosition; } // Only seek if ready and there is not a significant forward buffer available for playback if (media.readyState) { this.warn("Playback: " + currentTime.toFixed(3) + " is located too far from the end of live sliding playlist: " + end + ", reset currentTime to : " + liveSyncPosition.toFixed(3)); media.currentTime = liveSyncPosition; } } } }; _proto.alignPlaylists = function alignPlaylists(details, previousDetails) { var levels = this.levels, levelLastLoaded = this.levelLastLoaded, fragPrevious = this.fragPrevious; var lastLevel = levelLastLoaded !== null ? levels[levelLastLoaded] : null; // FIXME: If not for `shouldAlignOnDiscontinuities` requiring fragPrevious.cc, // this could all go in level-helper mergeDetails() var length = details.fragments.length; if (!length) { this.warn("No fragments in live playlist"); return 0; } var slidingStart = details.fragments[0].start; var firstLevelLoad = !previousDetails; var aligned = details.alignedSliding && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(slidingStart); if (firstLevelLoad || !aligned && !slidingStart) { Object(_utils_discontinuities__WEBPACK_IMPORTED_MODULE_9__["alignStream"])(fragPrevious, lastLevel, details); var alignedSlidingStart = details.fragments[0].start; this.log("Live playlist sliding: " + alignedSlidingStart.toFixed(2) + " start-sn: " + (previousDetails ? previousDetails.startSN : 'na') + "->" + details.startSN + " prev-sn: " + (fragPrevious ? fragPrevious.sn : 'na') + " fragments: " + length); return alignedSlidingStart; } return slidingStart; }; _proto.waitForCdnTuneIn = function waitForCdnTuneIn(details) { // Wait for Low-Latency CDN Tune-in to get an updated playlist var advancePartLimit = 3; return details.live && details.canBlockReload && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit); }; _proto.setStartPosition = function setStartPosition(details, sliding) { // compute start position if set to -1. use it straight away if value is defined var startPosition = this.startPosition; if (startPosition < sliding) { startPosition = -1; } if (startPosition === -1 || this.lastCurrentTime === -1) { // first, check if start time offset has been set in playlist, if yes, use this value var startTimeOffset = details.startTimeOffset; if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(startTimeOffset)) { startPosition = sliding + startTimeOffset; if (startTimeOffset < 0) { startPosition += details.totalduration; } startPosition = Math.min(Math.max(sliding, startPosition), sliding + details.totalduration); this.log("Start time offset " + startTimeOffset + " found in playlist, adjust startPosition to " + startPosition); this.startPosition = startPosition; } else if (details.live) { // Leave this.startPosition at -1, so that we can use `getInitialLiveFragment` logic when startPosition has // not been specified via the config or an as an argument to startLoad (#3736). startPosition = this.hls.liveSyncPosition || sliding; } else { this.startPosition = startPosition = 0; } this.lastCurrentTime = startPosition; } this.nextLoadPosition = startPosition; }; _proto.getLoadPosition = function getLoadPosition() { var media = this.media; // if we have not yet loaded any fragment, start loading from start position var pos = 0; if (this.loadedmetadata && media) { pos = media.currentTime; } else if (this.nextLoadPosition) { pos = this.nextLoadPosition; } return pos; }; _proto.handleFragLoadAborted = function handleFragLoadAborted(frag, part) { if (this.transmuxer && frag.sn !== 'initSegment' && frag.stats.aborted) { this.warn("Fragment " + frag.sn + (part ? ' part' + part.index : '') + " of level " + frag.level + " was aborted"); this.resetFragmentLoading(frag); } }; _proto.resetFragmentLoading = function resetFragmentLoading(frag) { if (!this.fragCurrent || !this.fragContextChanged(frag)) { this.state = State.IDLE; } }; _proto.onFragmentOrKeyLoadError = function onFragmentOrKeyLoadError(filterType, data) { if (data.fatal) { return; } var frag = data.frag; // Handle frag error related to caller's filterType if (!frag || frag.type !== filterType) { return; } var fragCurrent = this.fragCurrent; console.assert(fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level && frag.urlId === fragCurrent.urlId, 'Frag load error must match current frag to retry'); var config = this.config; // keep retrying until the limit will be reached if (this.fragLoadError + 1 <= config.fragLoadingMaxRetry) { if (this.resetLiveStartWhenNotLoaded(frag.level)) { return; } // exponential backoff capped to config.fragLoadingMaxRetryTimeout var delay = Math.min(Math.pow(2, this.fragLoadError) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout); this.warn("Fragment " + frag.sn + " of " + filterType + " " + frag.level + " failed to load, retrying in " + delay + "ms"); this.retryDate = self.performance.now() + delay; this.fragLoadError++; this.state = State.FRAG_LOADING_WAITING_RETRY; } else if (data.levelRetry) { if (filterType === _types_loader__WEBPACK_IMPORTED_MODULE_15__["PlaylistLevelType"].AUDIO) { // Reset current fragment since audio track audio is essential and may not have a fail-over track this.fragCurrent = null; } // Fragment errors that result in a level switch or redundant fail-over // should reset the stream controller state to idle this.fragLoadError = 0; this.state = State.IDLE; } else { _utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"].error(data.details + " reaches max retry, redispatch as fatal ..."); // switch error to fatal data.fatal = true; this.hls.stopLoad(); this.state = State.ERROR; } }; _proto.afterBufferFlushed = function afterBufferFlushed(media, bufferType, playlistType) { if (!media) { return; } // After successful buffer flushing, filter flushed fragments from bufferedFrags use mediaBuffered instead of media // (so that we will check against video.buffered ranges in case of alt audio track) var bufferedTimeRanges = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].getBuffered(media); this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType); if (this.state === State.ENDED) { this.resetLoadingState(); } }; _proto.resetLoadingState = function resetLoadingState() { this.fragCurrent = null; this.fragPrevious = null; this.state = State.IDLE; }; _proto.resetLiveStartWhenNotLoaded = function resetLiveStartWhenNotLoaded(level) { // if loadedmetadata is not set, it means that we are emergency switch down on first frag // in that case, reset startFragRequested flag if (!this.loadedmetadata) { this.startFragRequested = false; var details = this.levels ? this.levels[level].details : null; if (details !== null && details !== void 0 && details.live) { // We can't afford to retry after a delay in a live scenario. Update the start position and return to IDLE. this.startPosition = -1; this.setStartPosition(details, 0); this.resetLoadingState(); return true; } this.nextLoadPosition = this.startPosition; } return false; }; _proto.updateLevelTiming = function updateLevelTiming(frag, part, level, partial) { var _this6 = this; var details = level.details; console.assert(!!details, 'level.details must be defined'); var parsed = Object.keys(frag.elementaryStreams).reduce(function (result, type) { var info = frag.elementaryStreams[type]; if (info) { var parsedDuration = info.endPTS - info.startPTS; if (parsedDuration <= 0) { // Destroy the transmuxer after it's next time offset failed to advance because duration was <= 0. // The new transmuxer will be configured with a time offset matching the next fragment start, // preventing the timeline from shifting. _this6.warn("Could not parse fragment " + frag.sn + " " + type + " duration reliably (" + parsedDuration + ") resetting transmuxer to fallback to playlist timing"); _this6.resetTransmuxer(); return result || false; } var drift = partial ? 0 : Object(_level_helper__WEBPACK_IMPORTED_MODULE_11__["updateFragPTSDTS"])(details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS); _this6.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].LEVEL_PTS_UPDATED, { details: details, level: level, drift: drift, type: type, frag: frag, start: info.startPTS, end: info.endPTS }); return true; } return result; }, false); if (parsed) { this.state = State.PARSED; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_PARSED, { frag: frag, part: part }); } else { this.resetLoadingState(); } }; _proto.resetTransmuxer = function resetTransmuxer() { if (this.transmuxer) { this.transmuxer.destroy(); this.transmuxer = null; } }; _createClass(BaseStreamController, [{ key: "state", get: function get() { return this._state; }, set: function set(nextState) { var previousState = this._state; if (previousState !== nextState) { this._state = nextState; this.log(previousState + "->" + nextState); } } }]); return BaseStreamController; }(_task_loop__WEBPACK_IMPORTED_MODULE_1__["default"]); /***/ }), /***/ "./src/controller/buffer-controller.ts": /*!*********************************************!*\ !*** ./src/controller/buffer-controller.ts ***! \*********************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BufferController; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts"); /* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/mediasource-helper */ "./src/utils/mediasource-helper.ts"); /* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts"); /* harmony import */ var _buffer_operation_queue__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./buffer-operation-queue */ "./src/controller/buffer-operation-queue.ts"); var MediaSource = Object(_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__["getMediaSource"])(); var VIDEO_CODEC_PROFILE_REPACE = /([ha]vc.)(?:\.[^.,]+)+/; var BufferController = /*#__PURE__*/function () { // The level details used to determine duration, target-duration and live // cache the self generated object url to detect hijack of video tag // A queue of buffer operations which require the SourceBuffer to not be updating upon execution // References to event listeners for each SourceBuffer, so that they can be referenced for event removal // The number of BUFFER_CODEC events received before any sourceBuffers are created // The total number of BUFFER_CODEC events received // A reference to the attached media element // A reference to the active media source // counters function BufferController(_hls) { var _this = this; this.details = null; this._objectUrl = null; this.operationQueue = void 0; this.listeners = void 0; this.hls = void 0; this.bufferCodecEventsExpected = 0; this._bufferCodecEventsTotal = 0; this.media = null; this.mediaSource = null; this.appendError = 0; this.tracks = {}; this.pendingTracks = {}; this.sourceBuffer = void 0; this._onMediaSourceOpen = function () { var hls = _this.hls, media = _this.media, mediaSource = _this.mediaSource; _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media source opened'); if (media) { _this.updateMediaElementDuration(); hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHED, { media: media }); } if (mediaSource) { // once received, don't listen anymore to sourceopen event mediaSource.removeEventListener('sourceopen', _this._onMediaSourceOpen); } _this.checkPendingTracks(); }; this._onMediaSourceClose = function () { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media source closed'); }; this._onMediaSourceEnded = function () { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media source ended'); }; this.hls = _hls; this._initSourceBuffer(); this.registerListeners(); } var _proto = BufferController.prototype; _proto.hasSourceTypes = function hasSourceTypes() { return this.getSourceBufferTypes().length > 0 || Object.keys(this.pendingTracks).length > 0; }; _proto.destroy = function destroy() { this.unregisterListeners(); this.details = null; }; _proto.registerListeners = function registerListeners() { var hls = this.hls; hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_PARSED, this.onManifestParsed, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_RESET, this.onBufferReset, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_APPENDING, this.onBufferAppending, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_CODECS, this.onBufferCodecs, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_EOS, this.onBufferEos, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_PARSED, this.onFragParsed, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_CHANGED, this.onFragChanged, this); }; _proto.unregisterListeners = function unregisterListeners() { var hls = this.hls; hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_PARSED, this.onManifestParsed, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_RESET, this.onBufferReset, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_APPENDING, this.onBufferAppending, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_CODECS, this.onBufferCodecs, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_EOS, this.onBufferEos, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_PARSED, this.onFragParsed, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_CHANGED, this.onFragChanged, this); }; _proto._initSourceBuffer = function _initSourceBuffer() { this.sourceBuffer = {}; this.operationQueue = new _buffer_operation_queue__WEBPACK_IMPORTED_MODULE_7__["default"](this.sourceBuffer); this.listeners = { audio: [], video: [], audiovideo: [] }; }; _proto.onManifestParsed = function onManifestParsed(event, data) { // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller // sourcebuffers will be created all at once when the expected nb of tracks will be reached // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller // it will contain the expected nb of source buffers, no need to compute it var codecEvents = 2; if (data.audio && !data.video || !data.altAudio) { codecEvents = 1; } this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents; this.details = null; _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log(this.bufferCodecEventsExpected + " bufferCodec event(s) expected"); }; _proto.onMediaAttaching = function onMediaAttaching(event, data) { var media = this.media = data.media; if (media && MediaSource) { var ms = this.mediaSource = new MediaSource(); // MediaSource listeners are arrow functions with a lexical scope, and do not need to be bound ms.addEventListener('sourceopen', this._onMediaSourceOpen); ms.addEventListener('sourceended', this._onMediaSourceEnded); ms.addEventListener('sourceclose', this._onMediaSourceClose); // link video and media Source media.src = self.URL.createObjectURL(ms); // cache the locally generated object url this._objectUrl = media.src; } }; _proto.onMediaDetaching = function onMediaDetaching() { var media = this.media, mediaSource = this.mediaSource, _objectUrl = this._objectUrl; if (mediaSource) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: media source detaching'); if (mediaSource.readyState === 'open') { try { // endOfStream could trigger exception if any sourcebuffer is in updating state // we don't really care about checking sourcebuffer state here, // as we are anyway detaching the MediaSource // let's just avoid this exception to propagate mediaSource.endOfStream(); } catch (err) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: onMediaDetaching: " + err.message + " while calling endOfStream"); } } // Clean up the SourceBuffers by invoking onBufferReset this.onBufferReset(); mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen); mediaSource.removeEventListener('sourceended', this._onMediaSourceEnded); mediaSource.removeEventListener('sourceclose', this._onMediaSourceClose); // Detach properly the MediaSource from the HTMLMediaElement as // suggested in https://github.com/w3c/media-source/issues/53. if (media) { if (_objectUrl) { self.URL.revokeObjectURL(_objectUrl); } // clean up video tag src only if it's our own url. some external libraries might // hijack the video tag and change its 'src' without destroying the Hls instance first if (media.src === _objectUrl) { media.removeAttribute('src'); media.load(); } else { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('[buffer-controller]: media.src was changed by a third party - skip cleanup'); } } this.mediaSource = null; this.media = null; this._objectUrl = null; this.bufferCodecEventsExpected = this._bufferCodecEventsTotal; this.pendingTracks = {}; this.tracks = {}; } this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHED, undefined); }; _proto.onBufferReset = function onBufferReset() { var _this2 = this; this.getSourceBufferTypes().forEach(function (type) { var sb = _this2.sourceBuffer[type]; try { if (sb) { _this2.removeBufferListeners(type); if (_this2.mediaSource) { _this2.mediaSource.removeSourceBuffer(sb); } // Synchronously remove the SB from the map before the next call in order to prevent an async function from // accessing it _this2.sourceBuffer[type] = undefined; } } catch (err) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Failed to reset the " + type + " buffer", err); } }); this._initSourceBuffer(); }; _proto.onBufferCodecs = function onBufferCodecs(event, data) { var _this3 = this; var sourceBufferCount = this.getSourceBufferTypes().length; Object.keys(data).forEach(function (trackName) { if (sourceBufferCount) { // check if SourceBuffer codec needs to change var track = _this3.tracks[trackName]; if (track && typeof track.buffer.changeType === 'function') { var _data$trackName = data[trackName], codec = _data$trackName.codec, levelCodec = _data$trackName.levelCodec, container = _data$trackName.container; var currentCodec = (track.levelCodec || track.codec).replace(VIDEO_CODEC_PROFILE_REPACE, '$1'); var nextCodec = (levelCodec || codec).replace(VIDEO_CODEC_PROFILE_REPACE, '$1'); if (currentCodec !== nextCodec) { var mimeType = container + ";codecs=" + (levelCodec || codec); _this3.appendChangeType(trackName, mimeType); } } } else { // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks _this3.pendingTracks[trackName] = data[trackName]; } }); // if sourcebuffers already created, do nothing ... if (sourceBufferCount) { return; } this.bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0); if (this.mediaSource && this.mediaSource.readyState === 'open') { this.checkPendingTracks(); } }; _proto.appendChangeType = function appendChangeType(type, mimeType) { var _this4 = this; var operationQueue = this.operationQueue; var operation = { execute: function execute() { var sb = _this4.sourceBuffer[type]; if (sb) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: changing " + type + " sourceBuffer type to " + mimeType); sb.changeType(mimeType); } operationQueue.shiftAndExecuteNext(type); }, onStart: function onStart() {}, onComplete: function onComplete() {}, onError: function onError(e) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Failed to change " + type + " SourceBuffer type", e); } }; operationQueue.append(operation, type); }; _proto.onBufferAppending = function onBufferAppending(event, eventData) { var _this5 = this; var hls = this.hls, operationQueue = this.operationQueue, tracks = this.tracks; var data = eventData.data, type = eventData.type, frag = eventData.frag, part = eventData.part, chunkMeta = eventData.chunkMeta; var chunkStats = chunkMeta.buffering[type]; var bufferAppendingStart = self.performance.now(); chunkStats.start = bufferAppendingStart; var fragBuffering = frag.stats.buffering; var partBuffering = part ? part.stats.buffering : null; if (fragBuffering.start === 0) { fragBuffering.start = bufferAppendingStart; } if (partBuffering && partBuffering.start === 0) { partBuffering.start = bufferAppendingStart; } // TODO: Only update timestampOffset when audio/mpeg fragment or part is not contiguous with previously appended // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended) // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset` // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos). // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486 var audioTrack = tracks.audio; var checkTimestampOffset = type === 'audio' && chunkMeta.id === 1 && (audioTrack === null || audioTrack === void 0 ? void 0 : audioTrack.container) === 'audio/mpeg'; var operation = { execute: function execute() { chunkStats.executeStart = self.performance.now(); if (checkTimestampOffset) { var sb = _this5.sourceBuffer[type]; if (sb) { var delta = frag.start - sb.timestampOffset; if (Math.abs(delta) >= 0.1) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: Updating audio SourceBuffer timestampOffset to " + frag.start + " (delta: " + delta + ") sn: " + frag.sn + ")"); sb.timestampOffset = frag.start; } } } _this5.appendExecutor(data, type); }, onStart: function onStart() {// logger.debug(`[buffer-controller]: ${type} SourceBuffer updatestart`); }, onComplete: function onComplete() { // logger.debug(`[buffer-controller]: ${type} SourceBuffer updateend`); var end = self.performance.now(); chunkStats.executeEnd = chunkStats.end = end; if (fragBuffering.first === 0) { fragBuffering.first = end; } if (partBuffering && partBuffering.first === 0) { partBuffering.first = end; } var sourceBuffer = _this5.sourceBuffer; var timeRanges = {}; for (var _type in sourceBuffer) { timeRanges[_type] = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(sourceBuffer[_type]); } _this5.appendError = 0; _this5.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_APPENDED, { type: type, frag: frag, part: part, chunkMeta: chunkMeta, parent: frag.type, timeRanges: timeRanges }); }, onError: function onError(err) { // in case any error occured while appending, put back segment in segments table _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: Error encountered while trying to append to the " + type + " SourceBuffer", err); var event = { type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR, parent: frag.type, details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_APPEND_ERROR, err: err, fatal: false }; if (err.code === DOMException.QUOTA_EXCEEDED_ERR) { // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror // let's stop appending any segments, and report BUFFER_FULL_ERROR error event.details = _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_FULL_ERROR; } else { _this5.appendError++; event.details = _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_APPEND_ERROR; /* with UHD content, we could get loop of quota exceeded error until browser is able to evict some data from sourcebuffer. Retrying can help recover. */ if (_this5.appendError > hls.config.appendErrorMaxRetry) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: Failed " + hls.config.appendErrorMaxRetry + " times to append segment in sourceBuffer"); event.fatal = true; } } hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, event); } }; operationQueue.append(operation, type); }; _proto.onBufferFlushing = function onBufferFlushing(event, data) { var _this6 = this; var operationQueue = this.operationQueue; var flushOperation = function flushOperation(type) { return { execute: _this6.removeExecutor.bind(_this6, type, data.startOffset, data.endOffset), onStart: function onStart() {// logger.debug(`[buffer-controller]: Started flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`); }, onComplete: function onComplete() { // logger.debug(`[buffer-controller]: Finished flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`); _this6.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHED, { type: type }); }, onError: function onError(e) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Failed to remove from " + type + " SourceBuffer", e); } }; }; if (data.type) { operationQueue.append(flushOperation(data.type), data.type); } else { this.getSourceBufferTypes().forEach(function (type) { operationQueue.append(flushOperation(type), type); }); } }; _proto.onFragParsed = function onFragParsed(event, data) { var _this7 = this; var frag = data.frag, part = data.part; var buffersAppendedTo = []; var elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams; if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__["ElementaryStreamTypes"].AUDIOVIDEO]) { buffersAppendedTo.push('audiovideo'); } else { if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__["ElementaryStreamTypes"].AUDIO]) { buffersAppendedTo.push('audio'); } if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__["ElementaryStreamTypes"].VIDEO]) { buffersAppendedTo.push('video'); } } var onUnblocked = function onUnblocked() { var now = self.performance.now(); frag.stats.buffering.end = now; if (part) { part.stats.buffering.end = now; } var stats = part ? part.stats : frag.stats; _this7.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_BUFFERED, { frag: frag, part: part, stats: stats, id: frag.type }); }; if (buffersAppendedTo.length === 0) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("Fragments must have at least one ElementaryStreamType set. type: " + frag.type + " level: " + frag.level + " sn: " + frag.sn); } this.blockBuffers(onUnblocked, buffersAppendedTo); }; _proto.onFragChanged = function onFragChanged(event, data) { this.flushBackBuffer(); } // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos() // an undefined data.type will mark all buffers as EOS. ; _proto.onBufferEos = function onBufferEos(event, data) { var _this8 = this; var ended = this.getSourceBufferTypes().reduce(function (acc, type) { var sb = _this8.sourceBuffer[type]; if (!data.type || data.type === type) { if (sb && !sb.ended) { sb.ended = true; _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: " + type + " sourceBuffer now EOS"); } } return acc && !!(!sb || sb.ended); }, true); if (ended) { this.blockBuffers(function () { var mediaSource = _this8.mediaSource; if (!mediaSource || mediaSource.readyState !== 'open') { return; } // Allow this to throw and be caught by the enqueueing function mediaSource.endOfStream(); }); } }; _proto.onLevelUpdated = function onLevelUpdated(event, _ref) { var details = _ref.details; if (!details.fragments.length) { return; } this.details = details; if (this.getSourceBufferTypes().length) { this.blockBuffers(this.updateMediaElementDuration.bind(this)); } else { this.updateMediaElementDuration(); } }; _proto.flushBackBuffer = function flushBackBuffer() { var hls = this.hls, details = this.details, media = this.media, sourceBuffer = this.sourceBuffer; if (!media || details === null) { return; } var sourceBufferTypes = this.getSourceBufferTypes(); if (!sourceBufferTypes.length) { return; } // Support for deprecated liveBackBufferLength var backBufferLength = details.live && hls.config.liveBackBufferLength !== null ? hls.config.liveBackBufferLength : hls.config.backBufferLength; if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(backBufferLength) || backBufferLength < 0) { return; } var currentTime = media.currentTime; var targetDuration = details.levelTargetDuration; var maxBackBufferLength = Math.max(backBufferLength, targetDuration); var targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength; sourceBufferTypes.forEach(function (type) { var sb = sourceBuffer[type]; if (sb) { var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(sb); // when target buffer start exceeds actual buffer start if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) { hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BACK_BUFFER_REACHED, { bufferEnd: targetBackBufferPosition }); // Support for deprecated event: if (details.live) { hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LIVE_BACK_BUFFER_REACHED, { bufferEnd: targetBackBufferPosition }); } hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, { startOffset: 0, endOffset: targetBackBufferPosition, type: type }); } } }); } /** * Update Media Source duration to current level duration or override to Infinity if configuration parameter * 'liveDurationInfinity` is set to `true` * More details: https://github.com/video-dev/hls.js/issues/355 */ ; _proto.updateMediaElementDuration = function updateMediaElementDuration() { if (!this.details || !this.media || !this.mediaSource || this.mediaSource.readyState !== 'open') { return; } var details = this.details, hls = this.hls, media = this.media, mediaSource = this.mediaSource; var levelDuration = details.fragments[0].start + details.totalduration; var mediaDuration = media.duration; var msDuration = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mediaSource.duration) ? mediaSource.duration : 0; if (details.live && hls.config.liveDurationInfinity) { // Override duration to Infinity _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media Source duration is set to Infinity'); mediaSource.duration = Infinity; this.updateSeekableRange(details); } else if (levelDuration > msDuration && levelDuration > mediaDuration || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mediaDuration)) { // levelDuration was the last value we set. // not using mediaSource.duration as the browser may tweak this value // only update Media Source duration if its value increase, this is to avoid // flushing already buffered portion when switching between quality level _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: Updating Media Source duration to " + levelDuration.toFixed(3)); mediaSource.duration = levelDuration; } }; _proto.updateSeekableRange = function updateSeekableRange(levelDetails) { var mediaSource = this.mediaSource; var fragments = levelDetails.fragments; var len = fragments.length; if (len && levelDetails.live && mediaSource !== null && mediaSource !== void 0 && mediaSource.setLiveSeekableRange) { var start = Math.max(0, fragments[0].start); var end = Math.max(start, start + levelDetails.totalduration); mediaSource.setLiveSeekableRange(start, end); } }; _proto.checkPendingTracks = function checkPendingTracks() { var bufferCodecEventsExpected = this.bufferCodecEventsExpected, operationQueue = this.operationQueue, pendingTracks = this.pendingTracks; // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once. // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after // data has been appended to existing ones. // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers. var pendingTracksCount = Object.keys(pendingTracks).length; if (pendingTracksCount && !bufferCodecEventsExpected || pendingTracksCount === 2) { // ok, let's create them now ! this.createSourceBuffers(pendingTracks); this.pendingTracks = {}; // append any pending segments now ! var buffers = this.getSourceBufferTypes(); if (buffers.length === 0) { this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_INCOMPATIBLE_CODECS_ERROR, fatal: true, reason: 'could not create source buffer for media codec(s)' }); return; } buffers.forEach(function (type) { operationQueue.executeNext(type); }); } }; _proto.createSourceBuffers = function createSourceBuffers(tracks) { var sourceBuffer = this.sourceBuffer, mediaSource = this.mediaSource; if (!mediaSource) { throw Error('createSourceBuffers called when mediaSource was null'); } var tracksCreated = 0; for (var trackName in tracks) { if (!sourceBuffer[trackName]) { var track = tracks[trackName]; if (!track) { throw Error("source buffer exists for track " + trackName + ", however track does not"); } // use levelCodec as first priority var codec = track.levelCodec || track.codec; var mimeType = track.container + ";codecs=" + codec; _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: creating sourceBuffer(" + mimeType + ")"); try { var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType); var sbName = trackName; this.addBufferListener(sbName, 'updatestart', this._onSBUpdateStart); this.addBufferListener(sbName, 'updateend', this._onSBUpdateEnd); this.addBufferListener(sbName, 'error', this._onSBUpdateError); this.tracks[trackName] = { buffer: sb, codec: codec, container: track.container, levelCodec: track.levelCodec, id: track.id }; tracksCreated++; } catch (err) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: error while trying to add sourceBuffer: " + err.message); this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_ADD_CODEC_ERROR, fatal: false, error: err, mimeType: mimeType }); } } } if (tracksCreated) { this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_CREATED, { tracks: this.tracks }); } } // Keep as arrow functions so that we can directly reference these functions directly as event listeners ; _proto._onSBUpdateStart = function _onSBUpdateStart(type) { var operationQueue = this.operationQueue; var operation = operationQueue.current(type); operation.onStart(); }; _proto._onSBUpdateEnd = function _onSBUpdateEnd(type) { var operationQueue = this.operationQueue; var operation = operationQueue.current(type); operation.onComplete(); operationQueue.shiftAndExecuteNext(type); }; _proto._onSBUpdateError = function _onSBUpdateError(type, event) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: " + type + " SourceBuffer error", event); // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error // SourceBuffer errors are not necessarily fatal; if so, the HTMLMediaElement will fire an error event this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_APPENDING_ERROR, fatal: false }); // updateend is always fired after error, so we'll allow that to shift the current operation off of the queue var operation = this.operationQueue.current(type); if (operation) { operation.onError(event); } } // This method must result in an updateend event; if remove is not called, _onSBUpdateEnd must be called manually ; _proto.removeExecutor = function removeExecutor(type, startOffset, endOffset) { var media = this.media, mediaSource = this.mediaSource, operationQueue = this.operationQueue, sourceBuffer = this.sourceBuffer; var sb = sourceBuffer[type]; if (!media || !mediaSource || !sb) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Attempting to remove from the " + type + " SourceBuffer, but it does not exist"); operationQueue.shiftAndExecuteNext(type); return; } var mediaDuration = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(media.duration) ? media.duration : Infinity; var msDuration = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mediaSource.duration) ? mediaSource.duration : Infinity; var removeStart = Math.max(0, startOffset); var removeEnd = Math.min(endOffset, mediaDuration, msDuration); if (removeEnd > removeStart) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: Removing [" + removeStart + "," + removeEnd + "] from the " + type + " SourceBuffer"); console.assert(!sb.updating, type + " sourceBuffer must not be updating"); sb.remove(removeStart, removeEnd); } else { // Cycle the queue operationQueue.shiftAndExecuteNext(type); } } // This method must result in an updateend event; if append is not called, _onSBUpdateEnd must be called manually ; _proto.appendExecutor = function appendExecutor(data, type) { var operationQueue = this.operationQueue, sourceBuffer = this.sourceBuffer; var sb = sourceBuffer[type]; if (!sb) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Attempting to append to the " + type + " SourceBuffer, but it does not exist"); operationQueue.shiftAndExecuteNext(type); return; } sb.ended = false; console.assert(!sb.updating, type + " sourceBuffer must not be updating"); sb.appendBuffer(data); } // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue // upon completion, since we already do it here ; _proto.blockBuffers = function blockBuffers(onUnblocked, buffers) { var _this9 = this; if (buffers === void 0) { buffers = this.getSourceBufferTypes(); } if (!buffers.length) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Blocking operation requested, but no SourceBuffers exist'); Promise.resolve(onUnblocked); return; } var operationQueue = this.operationQueue; // logger.debug(`[buffer-controller]: Blocking ${buffers} SourceBuffer`); var blockingOperations = buffers.map(function (type) { return operationQueue.appendBlocker(type); }); Promise.all(blockingOperations).then(function () { // logger.debug(`[buffer-controller]: Blocking operation resolved; unblocking ${buffers} SourceBuffer`); onUnblocked(); buffers.forEach(function (type) { var sb = _this9.sourceBuffer[type]; // Only cycle the queue if the SB is not updating. There's a bug in Chrome which sets the SB updating flag to // true when changing the MediaSource duration (https://bugs.chromium.org/p/chromium/issues/detail?id=959359&can=2&q=mediasource%20duration) // While this is a workaround, it's probably useful to have around if (!sb || !sb.updating) { operationQueue.shiftAndExecuteNext(type); } }); }); }; _proto.getSourceBufferTypes = function getSourceBufferTypes() { return Object.keys(this.sourceBuffer); }; _proto.addBufferListener = function addBufferListener(type, event, fn) { var buffer = this.sourceBuffer[type]; if (!buffer) { return; } var listener = fn.bind(this, type); this.listeners[type].push({ event: event, listener: listener }); buffer.addEventListener(event, listener); }; _proto.removeBufferListeners = function removeBufferListeners(type) { var buffer = this.sourceBuffer[type]; if (!buffer) { return; } this.listeners[type].forEach(function (l) { buffer.removeEventListener(l.event, l.listener); }); }; return BufferController; }(); /***/ }), /***/ "./src/controller/buffer-operation-queue.ts": /*!**************************************************!*\ !*** ./src/controller/buffer-operation-queue.ts ***! \**************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BufferOperationQueue; }); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); var BufferOperationQueue = /*#__PURE__*/function () { function BufferOperationQueue(sourceBufferReference) { this.buffers = void 0; this.queues = { video: [], audio: [], audiovideo: [] }; this.buffers = sourceBufferReference; } var _proto = BufferOperationQueue.prototype; _proto.append = function append(operation, type) { var queue = this.queues[type]; queue.push(operation); if (queue.length === 1 && this.buffers[type]) { this.executeNext(type); } }; _proto.insertAbort = function insertAbort(operation, type) { var queue = this.queues[type]; queue.unshift(operation); this.executeNext(type); }; _proto.appendBlocker = function appendBlocker(type) { var execute; var promise = new Promise(function (resolve) { execute = resolve; }); var operation = { execute: execute, onStart: function onStart() {}, onComplete: function onComplete() {}, onError: function onError() {} }; this.append(operation, type); return promise; }; _proto.executeNext = function executeNext(type) { var buffers = this.buffers, queues = this.queues; var sb = buffers[type]; var queue = queues[type]; if (queue.length) { var operation = queue[0]; try { // Operations are expected to result in an 'updateend' event being fired. If not, the queue will lock. Operations // which do not end with this event must call _onSBUpdateEnd manually operation.execute(); } catch (e) { _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].warn('[buffer-operation-queue]: Unhandled exception executing the current operation'); operation.onError(e); // Only shift the current operation off, otherwise the updateend handler will do this for us if (!sb || !sb.updating) { queue.shift(); this.executeNext(type); } } } }; _proto.shiftAndExecuteNext = function shiftAndExecuteNext(type) { this.queues[type].shift(); this.executeNext(type); }; _proto.current = function current(type) { return this.queues[type][0]; }; return BufferOperationQueue; }(); /***/ }), /***/ "./src/controller/cap-level-controller.ts": /*!************************************************!*\ !*** ./src/controller/cap-level-controller.ts ***! \************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts"); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } /* * cap stream level to media size dimension controller */ var CapLevelController = /*#__PURE__*/function () { function CapLevelController(hls) { this.autoLevelCapping = void 0; this.firstLevel = void 0; this.media = void 0; this.restrictedLevels = void 0; this.timer = void 0; this.hls = void 0; this.streamController = void 0; this.clientRect = void 0; this.hls = hls; this.autoLevelCapping = Number.POSITIVE_INFINITY; this.firstLevel = -1; this.media = null; this.restrictedLevels = []; this.timer = undefined; this.clientRect = null; this.registerListeners(); } var _proto = CapLevelController.prototype; _proto.setStreamController = function setStreamController(streamController) { this.streamController = streamController; }; _proto.destroy = function destroy() { this.unregisterListener(); if (this.hls.config.capLevelToPlayerSize) { this.stopCapping(); } this.media = null; this.clientRect = null; // @ts-ignore this.hls = this.streamController = null; }; _proto.registerListeners = function registerListeners() { var hls = this.hls; hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_CODECS, this.onBufferCodecs, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); }; _proto.unregisterListener = function unregisterListener() { var hls = this.hls; hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_CODECS, this.onBufferCodecs, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); }; _proto.onFpsDropLevelCapping = function onFpsDropLevelCapping(event, data) { // Don't add a restricted level more than once if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) { this.restrictedLevels.push(data.droppedLevel); } }; _proto.onMediaAttaching = function onMediaAttaching(event, data) { this.media = data.media instanceof HTMLVideoElement ? data.media : null; }; _proto.onManifestParsed = function onManifestParsed(event, data) { var hls = this.hls; this.restrictedLevels = []; this.firstLevel = data.firstLevel; if (hls.config.capLevelToPlayerSize && data.video) { // Start capping immediately if the manifest has signaled video codecs this.startCapping(); } } // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted // to the first level ; _proto.onBufferCodecs = function onBufferCodecs(event, data) { var hls = this.hls; if (hls.config.capLevelToPlayerSize && data.video) { // If the manifest did not signal a video codec capping has been deferred until we're certain video is present this.startCapping(); } }; _proto.onMediaDetaching = function onMediaDetaching() { this.stopCapping(); }; _proto.detectPlayerSize = function detectPlayerSize() { if (this.media && this.mediaHeight > 0 && this.mediaWidth > 0) { var levels = this.hls.levels; if (levels.length) { var hls = this.hls; hls.autoLevelCapping = this.getMaxLevel(levels.length - 1); if (hls.autoLevelCapping > this.autoLevelCapping && this.streamController) { // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch // usually happen when the user go to the fullscreen mode. this.streamController.nextLevelSwitch(); } this.autoLevelCapping = hls.autoLevelCapping; } } } /* * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled) */ ; _proto.getMaxLevel = function getMaxLevel(capLevelIndex) { var _this = this; var levels = this.hls.levels; if (!levels.length) { return -1; } var validLevels = levels.filter(function (level, index) { return CapLevelController.isLevelAllowed(index, _this.restrictedLevels) && index <= capLevelIndex; }); this.clientRect = null; return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight); }; _proto.startCapping = function startCapping() { if (this.timer) { // Don't reset capping if started twice; this can happen if the manifest signals a video codec return; } this.autoLevelCapping = Number.POSITIVE_INFINITY; this.hls.firstLevel = this.getMaxLevel(this.firstLevel); self.clearInterval(this.timer); this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1000); this.detectPlayerSize(); }; _proto.stopCapping = function stopCapping() { this.restrictedLevels = []; this.firstLevel = -1; this.autoLevelCapping = Number.POSITIVE_INFINITY; if (this.timer) { self.clearInterval(this.timer); this.timer = undefined; } }; _proto.getDimensions = function getDimensions() { if (this.clientRect) { return this.clientRect; } var media = this.media; var boundsRect = { width: 0, height: 0 }; if (media) { var clientRect = media.getBoundingClientRect(); boundsRect.width = clientRect.width; boundsRect.height = clientRect.height; if (!boundsRect.width && !boundsRect.height) { // When the media element has no width or height (equivalent to not being in the DOM), // then use its width and height attributes (media.width, media.height) boundsRect.width = clientRect.right - clientRect.left || media.width || 0; boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0; } } this.clientRect = boundsRect; return boundsRect; }; CapLevelController.isLevelAllowed = function isLevelAllowed(level, restrictedLevels) { if (restrictedLevels === void 0) { restrictedLevels = []; } return restrictedLevels.indexOf(level) === -1; }; CapLevelController.getMaxLevelByMediaSize = function getMaxLevelByMediaSize(levels, width, height) { if (!levels || !levels.length) { return -1; } // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next // to determine whether we've chosen the greatest bandwidth for the media's dimensions var atGreatestBandiwdth = function atGreatestBandiwdth(curLevel, nextLevel) { if (!nextLevel) { return true; } return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height; }; // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to // the max level var maxLevelIndex = levels.length - 1; for (var i = 0; i < levels.length; i += 1) { var level = levels[i]; if ((level.width >= width || level.height >= height) && atGreatestBandiwdth(level, levels[i + 1])) { maxLevelIndex = i; break; } } return maxLevelIndex; }; _createClass(CapLevelController, [{ key: "mediaWidth", get: function get() { return this.getDimensions().width * CapLevelController.contentScaleFactor; } }, { key: "mediaHeight", get: function get() { return this.getDimensions().height * CapLevelController.contentScaleFactor; } }], [{ key: "contentScaleFactor", get: function get() { var pixelRatio = 1; try { pixelRatio = self.devicePixelRatio; } catch (e) { /* no-op */ } return pixelRatio; } }]); return CapLevelController; }(); /* harmony default export */ __webpack_exports__["default"] = (CapLevelController); /***/ }), /***/ "./src/controller/fps-controller.ts": /*!******************************************!*\ !*** ./src/controller/fps-controller.ts ***! \******************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); var FPSController = /*#__PURE__*/function () { // stream controller must be provided as a dependency! function FPSController(hls) { this.hls = void 0; this.isVideoPlaybackQualityAvailable = false; this.timer = void 0; this.media = null; this.lastTime = void 0; this.lastDroppedFrames = 0; this.lastDecodedFrames = 0; this.streamController = void 0; this.hls = hls; this.registerListeners(); } var _proto = FPSController.prototype; _proto.setStreamController = function setStreamController(streamController) { this.streamController = streamController; }; _proto.registerListeners = function registerListeners() { this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this); }; _proto.unregisterListeners = function unregisterListeners() { this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching); }; _proto.destroy = function destroy() { if (this.timer) { clearInterval(this.timer); } this.unregisterListeners(); this.isVideoPlaybackQualityAvailable = false; this.media = null; }; _proto.onMediaAttaching = function onMediaAttaching(event, data) { var config = this.hls.config; if (config.capLevelOnFPSDrop) { var media = data.media instanceof self.HTMLVideoElement ? data.media : null; this.media = media; if (media && typeof media.getVideoPlaybackQuality === 'function') { this.isVideoPlaybackQualityAvailable = true; } self.clearInterval(this.timer); this.timer = self.setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod); } }; _proto.checkFPS = function checkFPS(video, decodedFrames, droppedFrames) { var currentTime = performance.now(); if (decodedFrames) { if (this.lastTime) { var currentPeriod = currentTime - this.lastTime; var currentDropped = droppedFrames - this.lastDroppedFrames; var currentDecoded = decodedFrames - this.lastDecodedFrames; var droppedFPS = 1000 * currentDropped / currentPeriod; var hls = this.hls; hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP, { currentDropped: currentDropped, currentDecoded: currentDecoded, totalDroppedFrames: droppedFrames }); if (droppedFPS > 0) { // logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod)); if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) { var currentLevel = hls.currentLevel; _utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel); if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) { currentLevel = currentLevel - 1; hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP_LEVEL_CAPPING, { level: currentLevel, droppedLevel: hls.currentLevel }); hls.autoLevelCapping = currentLevel; this.streamController.nextLevelSwitch(); } } } } this.lastTime = currentTime; this.lastDroppedFrames = droppedFrames; this.lastDecodedFrames = decodedFrames; } }; _proto.checkFPSInterval = function checkFPSInterval() { var video = this.media; if (video) { if (this.isVideoPlaybackQualityAvailable) { var videoPlaybackQuality = video.getVideoPlaybackQuality(); this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames); } else { // HTMLVideoElement doesn't include the webkit types this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount); } } }; return FPSController; }(); /* harmony default export */ __webpack_exports__["default"] = (FPSController); /***/ }), /***/ "./src/controller/fragment-finders.ts": /*!********************************************!*\ !*** ./src/controller/fragment-finders.ts ***! \********************************************/ /*! exports provided: findFragmentByPDT, findFragmentByPTS, fragmentWithinToleranceTest, pdtWithinToleranceTest, findFragWithCC */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFragmentByPDT", function() { return findFragmentByPDT; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFragmentByPTS", function() { return findFragmentByPTS; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fragmentWithinToleranceTest", function() { return fragmentWithinToleranceTest; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pdtWithinToleranceTest", function() { return pdtWithinToleranceTest; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFragWithCC", function() { return findFragWithCC; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/binary-search */ "./src/utils/binary-search.ts"); /** * Returns first fragment whose endPdt value exceeds the given PDT. * @param {Array<Fragment>} fragments - The array of candidate fragments * @param {number|null} [PDTValue = null] - The PDT value which must be exceeded * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start/end can be within in order to be considered contiguous * @returns {*|null} fragment - The best matching fragment */ function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) { if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(PDTValue)) { return null; } // if less than start var startPDT = fragments[0].programDateTime; if (PDTValue < (startPDT || 0)) { return null; } var endPDT = fragments[fragments.length - 1].endProgramDateTime; if (PDTValue >= (endPDT || 0)) { return null; } maxFragLookUpTolerance = maxFragLookUpTolerance || 0; for (var seg = 0; seg < fragments.length; ++seg) { var frag = fragments[seg]; if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) { return frag; } } return null; } /** * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer. * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus * breaking any traps which would cause the same fragment to be continuously selected within a small range. * @param {*} fragPrevious - The last frag successfully appended * @param {Array} fragments - The array of candidate fragments * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within * @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous * @returns {*} foundFrag - The best matching fragment */ function findFragmentByPTS(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance) { if (bufferEnd === void 0) { bufferEnd = 0; } if (maxFragLookUpTolerance === void 0) { maxFragLookUpTolerance = 0; } var fragNext = null; if (fragPrevious) { fragNext = fragments[fragPrevious.sn - fragments[0].sn + 1] || null; } else if (bufferEnd === 0 && fragments[0].start === 0) { fragNext = fragments[0]; } // Prefer the next fragment if it's within tolerance if (fragNext && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0) { return fragNext; } // We might be seeking past the tolerance so find the best match var foundFragment = _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__["default"].search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance)); if (foundFragment) { return foundFragment; } // If no match was found return the next fragment after fragPrevious, or null return fragNext; } /** * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions. * @param {*} candidate - The fragment to test * @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous * @returns {number} - 0 if it matches, 1 if too low, -1 if too high */ function fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, candidate) { if (bufferEnd === void 0) { bufferEnd = 0; } if (maxFragLookUpTolerance === void 0) { maxFragLookUpTolerance = 0; } // offset should be within fragment boundary - config.maxFragLookUpTolerance // this is to cope with situations like // bufferEnd = 9.991 // frag[Ø] : [0,10] // frag[1] : [10,20] // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here // frag start frag start+duration // |-----------------------------| // <---> <---> // ...--------><-----------------------------><---------.... // previous frag matching fragment next frag // return -1 return 0 return 1 // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`); // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)); if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) { return 1; } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) { // if maxFragLookUpTolerance will have negative value then don't return -1 for first element return -1; } return 0; } /** * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions. * This function tests the candidate's program date time values, as represented in Unix time * @param {*} candidate - The fragment to test * @param {number} [pdtBufferEnd = 0] - The Unix time representing the end of the current buffered range * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous * @returns {boolean} True if contiguous, false otherwise */ function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) { var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000; // endProgramDateTime can be null, default to zero var endProgramDateTime = candidate.endProgramDateTime || 0; return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd; } function findFragWithCC(fragments, cc) { return _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__["default"].search(fragments, function (candidate) { if (candidate.cc < cc) { return 1; } else if (candidate.cc > cc) { return -1; } else { return 0; } }); } /***/ }), /***/ "./src/controller/fragment-tracker.ts": /*!********************************************!*\ !*** ./src/controller/fragment-tracker.ts ***! \********************************************/ /*! exports provided: FragmentState, FragmentTracker */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FragmentState", function() { return FragmentState; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FragmentTracker", function() { return FragmentTracker; }); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts"); var FragmentState; (function (FragmentState) { FragmentState["NOT_LOADED"] = "NOT_LOADED"; FragmentState["BACKTRACKED"] = "BACKTRACKED"; FragmentState["APPENDING"] = "APPENDING"; FragmentState["PARTIAL"] = "PARTIAL"; FragmentState["OK"] = "OK"; })(FragmentState || (FragmentState = {})); var FragmentTracker = /*#__PURE__*/function () { function FragmentTracker(hls) { this.activeFragment = null; this.activeParts = null; this.fragments = Object.create(null); this.timeRanges = Object.create(null); this.bufferPadding = 0.2; this.hls = void 0; this.hls = hls; this._registerListeners(); } var _proto = FragmentTracker.prototype; _proto._registerListeners = function _registerListeners() { var hls = this.hls; hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_APPENDED, this.onBufferAppended, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_BUFFERED, this.onFragBuffered, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_LOADED, this.onFragLoaded, this); }; _proto._unregisterListeners = function _unregisterListeners() { var hls = this.hls; hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_APPENDED, this.onBufferAppended, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_BUFFERED, this.onFragBuffered, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_LOADED, this.onFragLoaded, this); }; _proto.destroy = function destroy() { this._unregisterListeners(); // @ts-ignore this.fragments = this.timeRanges = null; } /** * Return a Fragment with an appended range that matches the position and levelType. * If not found any Fragment, return null */ ; _proto.getAppendedFrag = function getAppendedFrag(position, levelType) { if (levelType === _types_loader__WEBPACK_IMPORTED_MODULE_1__["PlaylistLevelType"].MAIN) { var activeFragment = this.activeFragment, activeParts = this.activeParts; if (!activeFragment) { return null; } if (activeParts) { for (var i = activeParts.length; i--;) { var activePart = activeParts[i]; var appendedPTS = activePart ? activePart.end : activeFragment.appendedPTS; if (activePart.start <= position && appendedPTS !== undefined && position <= appendedPTS) { // 9 is a magic number. remove parts from lookup after a match but keep some short seeks back. if (i > 9) { this.activeParts = activeParts.slice(i - 9); } return activePart; } } } else if (activeFragment.start <= position && activeFragment.appendedPTS !== undefined && position <= activeFragment.appendedPTS) { return activeFragment; } } return this.getBufferedFrag(position, levelType); } /** * Return a buffered Fragment that matches the position and levelType. * A buffered Fragment is one whose loading, parsing and appending is done (completed or "partial" meaning aborted). * If not found any Fragment, return null */ ; _proto.getBufferedFrag = function getBufferedFrag(position, levelType) { var fragments = this.fragments; var keys = Object.keys(fragments); for (var i = keys.length; i--;) { var fragmentEntity = fragments[keys[i]]; if ((fragmentEntity === null || fragmentEntity === void 0 ? void 0 : fragmentEntity.body.type) === levelType && fragmentEntity.buffered) { var frag = fragmentEntity.body; if (frag.start <= position && position <= frag.end) { return frag; } } } return null; } /** * Partial fragments effected by coded frame eviction will be removed * The browser will unload parts of the buffer to free up memory for new buffer data * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable) */ ; _proto.detectEvictedFragments = function detectEvictedFragments(elementaryStream, timeRange, playlistType) { var _this = this; // Check if any flagged fragments have been unloaded Object.keys(this.fragments).forEach(function (key) { var fragmentEntity = _this.fragments[key]; if (!fragmentEntity) { return; } if (!fragmentEntity.buffered) { if (fragmentEntity.body.type === playlistType) { _this.removeFragment(fragmentEntity.body); } return; } var esData = fragmentEntity.range[elementaryStream]; if (!esData) { return; } esData.time.some(function (time) { var isNotBuffered = !_this.isTimeBuffered(time.startPTS, time.endPTS, timeRange); if (isNotBuffered) { // Unregister partial fragment as it needs to load again to be reused _this.removeFragment(fragmentEntity.body); } return isNotBuffered; }); }); } /** * Checks if the fragment passed in is loaded in the buffer properly * Partially loaded fragments will be registered as a partial fragment */ ; _proto.detectPartialFragments = function detectPartialFragments(data) { var _this2 = this; var timeRanges = this.timeRanges; var frag = data.frag, part = data.part; if (!timeRanges || frag.sn === 'initSegment') { return; } var fragKey = getFragmentKey(frag); var fragmentEntity = this.fragments[fragKey]; if (!fragmentEntity) { return; } Object.keys(timeRanges).forEach(function (elementaryStream) { var streamInfo = frag.elementaryStreams[elementaryStream]; if (!streamInfo) { return; } var timeRange = timeRanges[elementaryStream]; var partial = part !== null || streamInfo.partial === true; fragmentEntity.range[elementaryStream] = _this2.getBufferedTimes(frag, part, partial, timeRange); }); fragmentEntity.backtrack = fragmentEntity.loaded = null; if (Object.keys(fragmentEntity.range).length) { fragmentEntity.buffered = true; } else { // remove fragment if nothing was appended this.removeFragment(fragmentEntity.body); } }; _proto.fragBuffered = function fragBuffered(frag) { var fragKey = getFragmentKey(frag); var fragmentEntity = this.fragments[fragKey]; if (fragmentEntity) { fragmentEntity.backtrack = fragmentEntity.loaded = null; fragmentEntity.buffered = true; } }; _proto.getBufferedTimes = function getBufferedTimes(fragment, part, partial, timeRange) { var buffered = { time: [], partial: partial }; var startPTS = part ? part.start : fragment.start; var endPTS = part ? part.end : fragment.end; var minEndPTS = fragment.minEndPTS || endPTS; var maxStartPTS = fragment.maxStartPTS || startPTS; for (var i = 0; i < timeRange.length; i++) { var startTime = timeRange.start(i) - this.bufferPadding; var endTime = timeRange.end(i) + this.bufferPadding; if (maxStartPTS >= startTime && minEndPTS <= endTime) { // Fragment is entirely contained in buffer // No need to check the other timeRange times since it's completely playable buffered.time.push({ startPTS: Math.max(startPTS, timeRange.start(i)), endPTS: Math.min(endPTS, timeRange.end(i)) }); break; } else if (startPTS < endTime && endPTS > startTime) { buffered.partial = true; // Check for intersection with buffer // Get playable sections of the fragment buffered.time.push({ startPTS: Math.max(startPTS, timeRange.start(i)), endPTS: Math.min(endPTS, timeRange.end(i)) }); } else if (endPTS <= startTime) { // No need to check the rest of the timeRange as it is in order break; } } return buffered; } /** * Gets the partial fragment for a certain time */ ; _proto.getPartialFragment = function getPartialFragment(time) { var bestFragment = null; var timePadding; var startTime; var endTime; var bestOverlap = 0; var bufferPadding = this.bufferPadding, fragments = this.fragments; Object.keys(fragments).forEach(function (key) { var fragmentEntity = fragments[key]; if (!fragmentEntity) { return; } if (isPartial(fragmentEntity)) { startTime = fragmentEntity.body.start - bufferPadding; endTime = fragmentEntity.body.end + bufferPadding; if (time >= startTime && time <= endTime) { // Use the fragment that has the most padding from start and end time timePadding = Math.min(time - startTime, endTime - time); if (bestOverlap <= timePadding) { bestFragment = fragmentEntity.body; bestOverlap = timePadding; } } } }); return bestFragment; }; _proto.getState = function getState(fragment) { var fragKey = getFragmentKey(fragment); var fragmentEntity = this.fragments[fragKey]; if (fragmentEntity) { if (!fragmentEntity.buffered) { if (fragmentEntity.backtrack) { return FragmentState.BACKTRACKED; } return FragmentState.APPENDING; } else if (isPartial(fragmentEntity)) { return FragmentState.PARTIAL; } else { return FragmentState.OK; } } return FragmentState.NOT_LOADED; }; _proto.backtrack = function backtrack(frag, data) { var fragKey = getFragmentKey(frag); var fragmentEntity = this.fragments[fragKey]; if (!fragmentEntity || fragmentEntity.backtrack) { return null; } var backtrack = fragmentEntity.backtrack = data ? data : fragmentEntity.loaded; fragmentEntity.loaded = null; return backtrack; }; _proto.getBacktrackData = function getBacktrackData(fragment) { var fragKey = getFragmentKey(fragment); var fragmentEntity = this.fragments[fragKey]; if (fragmentEntity) { var _backtrack$payload; var backtrack = fragmentEntity.backtrack; // If data was already sent to Worker it is detached no longer available if (backtrack !== null && backtrack !== void 0 && (_backtrack$payload = backtrack.payload) !== null && _backtrack$payload !== void 0 && _backtrack$payload.byteLength) { return backtrack; } else { this.removeFragment(fragment); } } return null; }; _proto.isTimeBuffered = function isTimeBuffered(startPTS, endPTS, timeRange) { var startTime; var endTime; for (var i = 0; i < timeRange.length; i++) { startTime = timeRange.start(i) - this.bufferPadding; endTime = timeRange.end(i) + this.bufferPadding; if (startPTS >= startTime && endPTS <= endTime) { return true; } if (endPTS <= startTime) { // No need to check the rest of the timeRange as it is in order return false; } } return false; }; _proto.onFragLoaded = function onFragLoaded(event, data) { var frag = data.frag, part = data.part; // don't track initsegment (for which sn is not a number) // don't track frags used for bitrateTest, they're irrelevant. // don't track parts for memory efficiency if (frag.sn === 'initSegment' || frag.bitrateTest || part) { return; } var fragKey = getFragmentKey(frag); this.fragments[fragKey] = { body: frag, loaded: data, backtrack: null, buffered: false, range: Object.create(null) }; }; _proto.onBufferAppended = function onBufferAppended(event, data) { var _this3 = this; var frag = data.frag, part = data.part, timeRanges = data.timeRanges; if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_1__["PlaylistLevelType"].MAIN) { this.activeFragment = frag; if (part) { var activeParts = this.activeParts; if (!activeParts) { this.activeParts = activeParts = []; } activeParts.push(part); } else { this.activeParts = null; } } // Store the latest timeRanges loaded in the buffer this.timeRanges = timeRanges; Object.keys(timeRanges).forEach(function (elementaryStream) { var timeRange = timeRanges[elementaryStream]; _this3.detectEvictedFragments(elementaryStream, timeRange); if (!part) { for (var i = 0; i < timeRange.length; i++) { frag.appendedPTS = Math.max(timeRange.end(i), frag.appendedPTS || 0); } } }); }; _proto.onFragBuffered = function onFragBuffered(event, data) { this.detectPartialFragments(data); }; _proto.hasFragment = function hasFragment(fragment) { var fragKey = getFragmentKey(fragment); return !!this.fragments[fragKey]; }; _proto.removeFragmentsInRange = function removeFragmentsInRange(start, end, playlistType) { var _this4 = this; Object.keys(this.fragments).forEach(function (key) { var fragmentEntity = _this4.fragments[key]; if (!fragmentEntity) { return; } if (fragmentEntity.buffered) { var frag = fragmentEntity.body; if (frag.type === playlistType && frag.start < end && frag.end > start) { _this4.removeFragment(frag); } } }); }; _proto.removeFragment = function removeFragment(fragment) { var fragKey = getFragmentKey(fragment); fragment.stats.loaded = 0; fragment.clearElementaryStreamInfo(); delete this.fragments[fragKey]; }; _proto.removeAllFragments = function removeAllFragments() { this.fragments = Object.create(null); this.activeFragment = null; this.activeParts = null; }; return FragmentTracker; }(); function isPartial(fragmentEntity) { var _fragmentEntity$range, _fragmentEntity$range2; return fragmentEntity.buffered && (((_fragmentEntity$range = fragmentEntity.range.video) === null || _fragmentEntity$range === void 0 ? void 0 : _fragmentEntity$range.partial) || ((_fragmentEntity$range2 = fragmentEntity.range.audio) === null || _fragmentEntity$range2 === void 0 ? void 0 : _fragmentEntity$range2.partial)); } function getFragmentKey(fragment) { return fragment.type + "_" + fragment.level + "_" + fragment.urlId + "_" + fragment.sn; } /***/ }), /***/ "./src/controller/gap-controller.ts": /*!******************************************!*\ !*** ./src/controller/gap-controller.ts ***! \******************************************/ /*! exports provided: STALL_MINIMUM_DURATION_MS, MAX_START_GAP_JUMP, SKIP_BUFFER_HOLE_STEP_SECONDS, SKIP_BUFFER_RANGE_START, default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STALL_MINIMUM_DURATION_MS", function() { return STALL_MINIMUM_DURATION_MS; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MAX_START_GAP_JUMP", function() { return MAX_START_GAP_JUMP; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SKIP_BUFFER_HOLE_STEP_SECONDS", function() { return SKIP_BUFFER_HOLE_STEP_SECONDS; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SKIP_BUFFER_RANGE_START", function() { return SKIP_BUFFER_RANGE_START; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return GapController; }); /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); var STALL_MINIMUM_DURATION_MS = 250; var MAX_START_GAP_JUMP = 2.0; var SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1; var SKIP_BUFFER_RANGE_START = 0.05; var GapController = /*#__PURE__*/function () { function GapController(config, media, fragmentTracker, hls) { this.config = void 0; this.media = void 0; this.fragmentTracker = void 0; this.hls = void 0; this.nudgeRetry = 0; this.stallReported = false; this.stalled = null; this.moved = false; this.seeking = false; this.config = config; this.media = media; this.fragmentTracker = fragmentTracker; this.hls = hls; } var _proto = GapController.prototype; _proto.destroy = function destroy() { // @ts-ignore this.hls = this.fragmentTracker = this.media = null; } /** * Checks if the playhead is stuck within a gap, and if so, attempts to free it. * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range). * * @param {number} lastCurrentTime Previously read playhead position */ ; _proto.poll = function poll(lastCurrentTime) { var config = this.config, media = this.media, stalled = this.stalled; var currentTime = media.currentTime, seeking = media.seeking; var seeked = this.seeking && !seeking; var beginSeek = !this.seeking && seeking; this.seeking = seeking; // The playhead is moving, no-op if (currentTime !== lastCurrentTime) { this.moved = true; if (stalled !== null) { // The playhead is now moving, but was previously stalled if (this.stallReported) { var _stalledDuration = self.performance.now() - stalled; _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("playback not stuck anymore @" + currentTime + ", after " + Math.round(_stalledDuration) + "ms"); this.stallReported = false; } this.stalled = null; this.nudgeRetry = 0; } return; } // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek if (beginSeek || seeked) { this.stalled = null; } // The playhead should not be moving if (media.paused || media.ended || media.playbackRate === 0 || !_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].getBuffered(media).length) { return; } var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].bufferInfo(media, currentTime, 0); var isBuffered = bufferInfo.len > 0; var nextStart = bufferInfo.nextStart || 0; // There is no playable buffer (seeked, waiting for buffer) if (!isBuffered && !nextStart) { return; } if (seeking) { // Waiting for seeking in a buffered range to complete var hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP; // Next buffered range is too far ahead to jump to while still seeking var noBufferGap = !nextStart || nextStart - currentTime > MAX_START_GAP_JUMP && !this.fragmentTracker.getPartialFragment(currentTime); if (hasEnoughBuffer || noBufferGap) { return; } // Reset moved state when seeking to a point in or before a gap this.moved = false; } // Skip start gaps if we haven't played, but the last poll detected the start of a stall // The addition poll gives the browser a chance to jump the gap for us if (!this.moved && this.stalled !== null) { var _level$details; // Jump start gaps within jump threshold var startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime; // When joining a live stream with audio tracks, account for live playlist window sliding by allowing // a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment // that begins over 1 target duration after the video start position. var level = this.hls.levels ? this.hls.levels[this.hls.currentLevel] : null; var isLive = level === null || level === void 0 ? void 0 : (_level$details = level.details) === null || _level$details === void 0 ? void 0 : _level$details.live; var maxStartGapJump = isLive ? level.details.targetduration * 2 : MAX_START_GAP_JUMP; if (startJump > 0 && startJump <= maxStartGapJump) { this._trySkipBufferHole(null); return; } } // Start tracking stall time var tnow = self.performance.now(); if (stalled === null) { this.stalled = tnow; return; } var stalledDuration = tnow - stalled; if (!seeking && stalledDuration >= STALL_MINIMUM_DURATION_MS) { // Report stalling after trying to fix this._reportStall(bufferInfo.len); } var bufferedWithHoles = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].bufferInfo(media, currentTime, config.maxBufferHole); this._tryFixBufferStall(bufferedWithHoles, stalledDuration); } /** * Detects and attempts to fix known buffer stalling issues. * @param bufferInfo - The properties of the current buffer. * @param stalledDurationMs - The amount of time Hls.js has been stalling for. * @private */ ; _proto._tryFixBufferStall = function _tryFixBufferStall(bufferInfo, stalledDurationMs) { var config = this.config, fragmentTracker = this.fragmentTracker, media = this.media; var currentTime = media.currentTime; var partial = fragmentTracker.getPartialFragment(currentTime); if (partial) { // Try to skip over the buffer hole caused by a partial fragment // This method isn't limited by the size of the gap between buffered ranges var targetTime = this._trySkipBufferHole(partial); // we return here in this case, meaning // the branch below only executes when we don't handle a partial fragment if (targetTime) { return; } } // if we haven't had to skip over a buffer hole of a partial fragment // we may just have to "nudge" the playlist as the browser decoding/rendering engine // needs to cross some sort of threshold covering all source-buffers content // to start playing properly. if (bufferInfo.len > config.maxBufferHole && stalledDurationMs > config.highBufferWatchdogPeriod * 1000) { _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Trying to nudge playhead over buffer-hole'); // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds // We only try to jump the hole if it's under the configured size // Reset stalled so to rearm watchdog timer this.stalled = null; this._tryNudgeBuffer(); } } /** * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period. * @param bufferLen - The playhead distance from the end of the current buffer segment. * @private */ ; _proto._reportStall = function _reportStall(bufferLen) { var hls = this.hls, media = this.media, stallReported = this.stallReported; if (!stallReported) { // Report stalled error once this.stallReported = true; _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("Playback stalling at @" + media.currentTime + " due to low buffer (buffer=" + bufferLen + ")"); hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_STALLED_ERROR, fatal: false, buffer: bufferLen }); } } /** * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments * @param partial - The partial fragment found at the current time (where playback is stalling). * @private */ ; _proto._trySkipBufferHole = function _trySkipBufferHole(partial) { var config = this.config, hls = this.hls, media = this.media; var currentTime = media.currentTime; var lastEndTime = 0; // Check if currentTime is between unbuffered regions of partial fragments var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].getBuffered(media); for (var i = 0; i < buffered.length; i++) { var startTime = buffered.start(i); if (currentTime + config.maxBufferHole >= lastEndTime && currentTime < startTime) { var targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, media.currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS); _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("skipping hole, adjusting currentTime from " + currentTime + " to " + targetTime); this.moved = true; this.stalled = null; media.currentTime = targetTime; if (partial) { hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_SEEK_OVER_HOLE, fatal: false, reason: "fragment loaded with buffer holes, seeking from " + currentTime + " to " + targetTime, frag: partial }); } return targetTime; } lastEndTime = buffered.end(i); } return 0; } /** * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount. * @private */ ; _proto._tryNudgeBuffer = function _tryNudgeBuffer() { var config = this.config, hls = this.hls, media = this.media; var currentTime = media.currentTime; var nudgeRetry = (this.nudgeRetry || 0) + 1; this.nudgeRetry = nudgeRetry; if (nudgeRetry < config.nudgeMaxRetry) { var targetTime = currentTime + nudgeRetry * config.nudgeOffset; // playback stalled in buffered area ... let's nudge currentTime to try to overcome this _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("Nudging 'currentTime' from " + currentTime + " to " + targetTime); media.currentTime = targetTime; hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_NUDGE_ON_STALL, fatal: false }); } else { _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].error("Playhead still not moving while enough data buffered @" + currentTime + " after " + config.nudgeMaxRetry + " nudges"); hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_STALLED_ERROR, fatal: true }); } }; return GapController; }(); /***/ }), /***/ "./src/controller/id3-track-controller.ts": /*!************************************************!*\ !*** ./src/controller/id3-track-controller.ts ***! \************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/texttrack-utils */ "./src/utils/texttrack-utils.ts"); /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts"); var MIN_CUE_DURATION = 0.25; var ID3TrackController = /*#__PURE__*/function () { function ID3TrackController(hls) { this.hls = void 0; this.id3Track = null; this.media = null; this.hls = hls; this._registerListeners(); } var _proto = ID3TrackController.prototype; _proto.destroy = function destroy() { this._unregisterListeners(); }; _proto._registerListeners = function _registerListeners() { var hls = this.hls; hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_PARSING_METADATA, this.onFragParsingMetadata, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this); }; _proto._unregisterListeners = function _unregisterListeners() { var hls = this.hls; hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_PARSING_METADATA, this.onFragParsingMetadata, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this); } // Add ID3 metatadata text track. ; _proto.onMediaAttached = function onMediaAttached(event, data) { this.media = data.media; }; _proto.onMediaDetaching = function onMediaDetaching() { if (!this.id3Track) { return; } Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["clearCurrentCues"])(this.id3Track); this.id3Track = null; this.media = null; }; _proto.getID3Track = function getID3Track(textTracks) { if (!this.media) { return; } for (var i = 0; i < textTracks.length; i++) { var textTrack = textTracks[i]; if (textTrack.kind === 'metadata' && textTrack.label === 'id3') { // send 'addtrack' when reusing the textTrack for metadata, // same as what we do for captions Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["sendAddTrackEvent"])(textTrack, this.media); return textTrack; } } return this.media.addTextTrack('metadata', 'id3'); }; _proto.onFragParsingMetadata = function onFragParsingMetadata(event, data) { if (!this.media) { return; } var fragment = data.frag; var samples = data.samples; // create track dynamically if (!this.id3Track) { this.id3Track = this.getID3Track(this.media.textTracks); this.id3Track.mode = 'hidden'; } // Attempt to recreate Safari functionality by creating // WebKitDataCue objects when available and store the decoded // ID3 data in the value property of the cue var Cue = self.WebKitDataCue || self.VTTCue || self.TextTrackCue; for (var i = 0; i < samples.length; i++) { var frames = _demux_id3__WEBPACK_IMPORTED_MODULE_2__["getID3Frames"](samples[i].data); if (frames) { var startTime = samples[i].pts; var endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.end; var timeDiff = endTime - startTime; if (timeDiff <= 0) { endTime = startTime + MIN_CUE_DURATION; } for (var j = 0; j < frames.length; j++) { var frame = frames[j]; // Safari doesn't put the timestamp frame in the TextTrack if (!_demux_id3__WEBPACK_IMPORTED_MODULE_2__["isTimeStampFrame"](frame)) { var cue = new Cue(startTime, endTime, ''); cue.value = frame; this.id3Track.addCue(cue); } } } } }; _proto.onBufferFlushing = function onBufferFlushing(event, _ref) { var startOffset = _ref.startOffset, endOffset = _ref.endOffset, type = _ref.type; if (!type || type === 'audio') { // id3 cues come from parsed audio only remove cues when audio buffer is cleared var id3Track = this.id3Track; if (id3Track) { Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["removeCuesInRange"])(id3Track, startOffset, endOffset); } } }; return ID3TrackController; }(); /* harmony default export */ __webpack_exports__["default"] = (ID3TrackController); /***/ }), /***/ "./src/controller/latency-controller.ts": /*!**********************************************!*\ !*** ./src/controller/latency-controller.ts ***! \**********************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return LatencyController; }); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var LatencyController = /*#__PURE__*/function () { function LatencyController(hls) { var _this = this; this.hls = void 0; this.config = void 0; this.media = null; this.levelDetails = null; this.currentTime = 0; this.stallCount = 0; this._latency = null; this.timeupdateHandler = function () { return _this.timeupdate(); }; this.hls = hls; this.config = hls.config; this.registerListeners(); } var _proto = LatencyController.prototype; _proto.destroy = function destroy() { this.unregisterListeners(); this.onMediaDetaching(); this.levelDetails = null; // @ts-ignore this.hls = this.timeupdateHandler = null; }; _proto.registerListeners = function registerListeners() { this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this); this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this); this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated, this); this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError, this); }; _proto.unregisterListeners = function unregisterListeners() { this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHED, this.onMediaAttached); this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching); this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading); this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated); this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError); }; _proto.onMediaAttached = function onMediaAttached(event, data) { this.media = data.media; this.media.addEventListener('timeupdate', this.timeupdateHandler); }; _proto.onMediaDetaching = function onMediaDetaching() { if (this.media) { this.media.removeEventListener('timeupdate', this.timeupdateHandler); this.media = null; } }; _proto.onManifestLoading = function onManifestLoading() { this.levelDetails = null; this._latency = null; this.stallCount = 0; }; _proto.onLevelUpdated = function onLevelUpdated(event, _ref) { var details = _ref.details; this.levelDetails = details; if (details.advanced) { this.timeupdate(); } if (!details.live && this.media) { this.media.removeEventListener('timeupdate', this.timeupdateHandler); } }; _proto.onError = function onError(event, data) { if (data.details !== _errors__WEBPACK_IMPORTED_MODULE_0__["ErrorDetails"].BUFFER_STALLED_ERROR) { return; } this.stallCount++; _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('[playback-rate-controller]: Stall detected, adjusting target latency'); }; _proto.timeupdate = function timeupdate() { var media = this.media, levelDetails = this.levelDetails; if (!media || !levelDetails) { return; } this.currentTime = media.currentTime; var latency = this.computeLatency(); if (latency === null) { return; } this._latency = latency; // Adapt playbackRate to meet target latency in low-latency mode var _this$config = this.config, lowLatencyMode = _this$config.lowLatencyMode, maxLiveSyncPlaybackRate = _this$config.maxLiveSyncPlaybackRate; if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1) { return; } var targetLatency = this.targetLatency; if (targetLatency === null) { return; } var distanceFromTarget = latency - targetLatency; // Only adjust playbackRate when within one target duration of targetLatency // and more than one second from under-buffering. // Playback further than one target duration from target can be considered DVR playback. var liveMinLatencyDuration = Math.min(this.maxLatency, targetLatency + levelDetails.targetduration); var inLiveRange = distanceFromTarget < liveMinLatencyDuration; if (levelDetails.live && inLiveRange && distanceFromTarget > 0.05 && this.forwardBufferLength > 1) { var max = Math.min(2, Math.max(1.0, maxLiveSyncPlaybackRate)); var rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled)) * 20) / 20; media.playbackRate = Math.min(max, Math.max(1, rate)); } else if (media.playbackRate !== 1 && media.playbackRate !== 0) { media.playbackRate = 1; } }; _proto.estimateLiveEdge = function estimateLiveEdge() { var levelDetails = this.levelDetails; if (levelDetails === null) { return null; } return levelDetails.edge + levelDetails.age; }; _proto.computeLatency = function computeLatency() { var liveEdge = this.estimateLiveEdge(); if (liveEdge === null) { return null; } return liveEdge - this.currentTime; }; _createClass(LatencyController, [{ key: "latency", get: function get() { return this._latency || 0; } }, { key: "maxLatency", get: function get() { var config = this.config, levelDetails = this.levelDetails; if (config.liveMaxLatencyDuration !== undefined) { return config.liveMaxLatencyDuration; } return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0; } }, { key: "targetLatency", get: function get() { var levelDetails = this.levelDetails; if (levelDetails === null) { return null; } var holdBack = levelDetails.holdBack, partHoldBack = levelDetails.partHoldBack, targetduration = levelDetails.targetduration; var _this$config2 = this.config, liveSyncDuration = _this$config2.liveSyncDuration, liveSyncDurationCount = _this$config2.liveSyncDurationCount, lowLatencyMode = _this$config2.lowLatencyMode; var userConfig = this.hls.userConfig; var targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack; if (userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) { targetLatency = liveSyncDuration !== undefined ? liveSyncDuration : liveSyncDurationCount * targetduration; } var maxLiveSyncOnStallIncrease = targetduration; var liveSyncOnStallIncrease = 1.0; return targetLatency + Math.min(this.stallCount * liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease); } }, { key: "liveSyncPosition", get: function get() { var liveEdge = this.estimateLiveEdge(); var targetLatency = this.targetLatency; var levelDetails = this.levelDetails; if (liveEdge === null || targetLatency === null || levelDetails === null) { return null; } var edge = levelDetails.edge; var syncPosition = liveEdge - targetLatency - this.edgeStalled; var min = edge - levelDetails.totalduration; var max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration); return Math.min(Math.max(min, syncPosition), max); } }, { key: "drift", get: function get() { var levelDetails = this.levelDetails; if (levelDetails === null) { return 1; } return levelDetails.drift; } }, { key: "edgeStalled", get: function get() { var levelDetails = this.levelDetails; if (levelDetails === null) { return 0; } var maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3; return Math.max(levelDetails.age - maxLevelUpdateAge, 0); } }, { key: "forwardBufferLength", get: function get() { var media = this.media, levelDetails = this.levelDetails; if (!media || !levelDetails) { return 0; } var bufferedRanges = media.buffered.length; return bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge - this.currentTime; } }]); return LatencyController; }(); /***/ }), /***/ "./src/controller/level-controller.ts": /*!********************************************!*\ !*** ./src/controller/level-controller.ts ***! \********************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return LevelController; }); /* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _utils_codecs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/codecs */ "./src/utils/codecs.ts"); /* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts"); /* harmony import */ var _base_playlist_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./base-playlist-controller */ "./src/controller/base-playlist-controller.ts"); /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts"); function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /* * Level Controller */ var chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase()); var LevelController = /*#__PURE__*/function (_BasePlaylistControll) { _inheritsLoose(LevelController, _BasePlaylistControll); function LevelController(hls) { var _this; _this = _BasePlaylistControll.call(this, hls, '[level-controller]') || this; _this._levels = []; _this._firstLevel = -1; _this._startLevel = void 0; _this.currentLevelIndex = -1; _this.manualLevelIndex = -1; _this.onParsedComplete = void 0; _this._registerListeners(); return _this; } var _proto = LevelController.prototype; _proto._registerListeners = function _registerListeners() { var hls = this.hls; hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, this.onManifestLoaded, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADED, this.onLevelLoaded, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, this.onFragLoaded, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError, this); }; _proto._unregisterListeners = function _unregisterListeners() { var hls = this.hls; hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, this.onManifestLoaded, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADED, this.onLevelLoaded, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, this.onFragLoaded, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError, this); }; _proto.destroy = function destroy() { this._unregisterListeners(); this.manualLevelIndex = -1; this._levels.length = 0; _BasePlaylistControll.prototype.destroy.call(this); }; _proto.startLoad = function startLoad() { var levels = this._levels; // clean up live level details to force reload them, and reset load errors levels.forEach(function (level) { level.loadError = 0; }); _BasePlaylistControll.prototype.startLoad.call(this); }; _proto.onManifestLoaded = function onManifestLoaded(event, data) { var levels = []; var audioTracks = []; var subtitleTracks = []; var bitrateStart; var levelSet = {}; var levelFromSet; var resolutionFound = false; var videoCodecFound = false; var audioCodecFound = false; // regroup redundant levels together data.levels.forEach(function (levelParsed) { var attributes = levelParsed.attrs; resolutionFound = resolutionFound || !!(levelParsed.width && levelParsed.height); videoCodecFound = videoCodecFound || !!levelParsed.videoCodec; audioCodecFound = audioCodecFound || !!levelParsed.audioCodec; // erase audio codec info if browser does not support mp4a.40.34. // demuxer will autodetect codec and fallback to mpeg/audio if (chromeOrFirefox && levelParsed.audioCodec && levelParsed.audioCodec.indexOf('mp4a.40.34') !== -1) { levelParsed.audioCodec = undefined; } var levelKey = levelParsed.bitrate + "-" + levelParsed.attrs.RESOLUTION + "-" + levelParsed.attrs.CODECS; levelFromSet = levelSet[levelKey]; if (!levelFromSet) { levelFromSet = new _types_level__WEBPACK_IMPORTED_MODULE_0__["Level"](levelParsed); levelSet[levelKey] = levelFromSet; levels.push(levelFromSet); } else { levelFromSet.url.push(levelParsed.url); } if (attributes) { if (attributes.AUDIO) { Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["addGroupId"])(levelFromSet, 'audio', attributes.AUDIO); } if (attributes.SUBTITLES) { Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["addGroupId"])(levelFromSet, 'text', attributes.SUBTITLES); } } }); // remove audio-only level if we also have levels with video codecs or RESOLUTION signalled if ((resolutionFound || videoCodecFound) && audioCodecFound) { levels = levels.filter(function (_ref) { var videoCodec = _ref.videoCodec, width = _ref.width, height = _ref.height; return !!videoCodec || !!(width && height); }); } // only keep levels with supported audio/video codecs levels = levels.filter(function (_ref2) { var audioCodec = _ref2.audioCodec, videoCodec = _ref2.videoCodec; return (!audioCodec || Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_3__["isCodecSupportedInMp4"])(audioCodec, 'audio')) && (!videoCodec || Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_3__["isCodecSupportedInMp4"])(videoCodec, 'video')); }); if (data.audioTracks) { audioTracks = data.audioTracks.filter(function (track) { return !track.audioCodec || Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_3__["isCodecSupportedInMp4"])(track.audioCodec, 'audio'); }); // Assign ids after filtering as array indices by group-id Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["assignTrackIdsByGroup"])(audioTracks); } if (data.subtitles) { subtitleTracks = data.subtitles; Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["assignTrackIdsByGroup"])(subtitleTracks); } if (levels.length > 0) { // start bitrate is the first bitrate of the manifest bitrateStart = levels[0].bitrate; // sort level on bitrate levels.sort(function (a, b) { return a.bitrate - b.bitrate; }); this._levels = levels; // find index of first level in sorted levels for (var i = 0; i < levels.length; i++) { if (levels[i].bitrate === bitrateStart) { this._firstLevel = i; this.log("manifest loaded, " + levels.length + " level(s) found, first bitrate: " + bitrateStart); break; } } // Audio is only alternate if manifest include a URI along with the audio group tag, // and this is not an audio-only stream where levels contain audio-only var audioOnly = audioCodecFound && !videoCodecFound; var edata = { levels: levels, audioTracks: audioTracks, subtitleTracks: subtitleTracks, firstLevel: this._firstLevel, stats: data.stats, audio: audioCodecFound, video: videoCodecFound, altAudio: !audioOnly && audioTracks.some(function (t) { return !!t.url; }) }; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_PARSED, edata); // Initiate loading after all controllers have received MANIFEST_PARSED if (this.hls.config.autoStartLoad || this.hls.forceStartLoad) { this.hls.startLoad(this.hls.config.startPosition); } } else { this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_INCOMPATIBLE_CODECS_ERROR, fatal: true, url: data.url, reason: 'no level with compatible codecs found in manifest' }); } }; _proto.onError = function onError(event, data) { _BasePlaylistControll.prototype.onError.call(this, event, data); if (data.fatal) { return; } // Switch to redundant level when track fails to load var context = data.context; var level = this._levels[this.currentLevelIndex]; if (context && (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK && level.audioGroupIds && context.groupId === level.audioGroupIds[level.urlId] || context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK && level.textGroupIds && context.groupId === level.textGroupIds[level.urlId])) { this.redundantFailover(this.currentLevelIndex); return; } var levelError = false; var levelSwitch = true; var levelIndex; // try to recover not fatal errors switch (data.details) { case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].FRAG_LOAD_ERROR: case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].FRAG_LOAD_TIMEOUT: case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].KEY_LOAD_ERROR: case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].KEY_LOAD_TIMEOUT: if (data.frag) { var _level = this._levels[data.frag.level]; // Set levelIndex when we're out of fragment retries if (_level) { _level.fragmentError++; if (_level.fragmentError > this.hls.config.fragLoadingMaxRetry) { levelIndex = data.frag.level; } } else { levelIndex = data.frag.level; } } break; case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_ERROR: case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_TIMEOUT: // Do not perform level switch if an error occurred using delivery directives // Attempt to reload level without directives first if (context) { if (context.deliveryDirectives) { levelSwitch = false; } levelIndex = context.level; } levelError = true; break; case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].REMUX_ALLOC_ERROR: levelIndex = data.level; levelError = true; break; } if (levelIndex !== undefined) { this.recoverLevel(data, levelIndex, levelError, levelSwitch); } } /** * Switch to a redundant stream if any available. * If redundant stream is not available, emergency switch down if ABR mode is enabled. */ ; _proto.recoverLevel = function recoverLevel(errorEvent, levelIndex, levelError, levelSwitch) { var errorDetails = errorEvent.details; var level = this._levels[levelIndex]; level.loadError++; if (levelError) { var retrying = this.retryLoadingOrFail(errorEvent); if (retrying) { // boolean used to inform stream controller not to switch back to IDLE on non fatal error errorEvent.levelRetry = true; } else { this.currentLevelIndex = -1; return; } } if (levelSwitch) { var redundantLevels = level.url.length; // Try redundant fail-over until level.loadError reaches redundantLevels if (redundantLevels > 1 && level.loadError < redundantLevels) { errorEvent.levelRetry = true; this.redundantFailover(levelIndex); } else if (this.manualLevelIndex === -1) { // Search for available level in auto level selection mode, cycling from highest to lowest bitrate var nextLevel = levelIndex === 0 ? this._levels.length - 1 : levelIndex - 1; if (this.currentLevelIndex !== nextLevel && this._levels[nextLevel].loadError === 0) { this.warn(errorDetails + ": switch to " + nextLevel); errorEvent.levelRetry = true; this.hls.nextAutoLevel = nextLevel; } } } }; _proto.redundantFailover = function redundantFailover(levelIndex) { var level = this._levels[levelIndex]; var redundantLevels = level.url.length; if (redundantLevels > 1) { // Update the url id of all levels so that we stay on the same set of variants when level switching var newUrlId = (level.urlId + 1) % redundantLevels; this.warn("Switching to redundant URL-id " + newUrlId); this._levels.forEach(function (level) { level.urlId = newUrlId; }); this.level = levelIndex; } } // reset errors on the successful load of a fragment ; _proto.onFragLoaded = function onFragLoaded(event, _ref3) { var frag = _ref3.frag; if (frag !== undefined && frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN) { var level = this._levels[frag.level]; if (level !== undefined) { level.fragmentError = 0; level.loadError = 0; } } }; _proto.onLevelLoaded = function onLevelLoaded(event, data) { var _data$deliveryDirecti2; var level = data.level, details = data.details; var curLevel = this._levels[level]; if (!curLevel) { var _data$deliveryDirecti; this.warn("Invalid level index " + level); if ((_data$deliveryDirecti = data.deliveryDirectives) !== null && _data$deliveryDirecti !== void 0 && _data$deliveryDirecti.skip) { details.deltaUpdateFailed = true; } return; } // only process level loaded events matching with expected level if (level === this.currentLevelIndex) { // reset level load error counter on successful level loaded only if there is no issues with fragments if (curLevel.fragmentError === 0) { curLevel.loadError = 0; this.retryCount = 0; } this.playlistLoaded(level, data, curLevel.details); } else if ((_data$deliveryDirecti2 = data.deliveryDirectives) !== null && _data$deliveryDirecti2 !== void 0 && _data$deliveryDirecti2.skip) { // received a delta playlist update that cannot be merged details.deltaUpdateFailed = true; } }; _proto.onAudioTrackSwitched = function onAudioTrackSwitched(event, data) { var currentLevel = this.hls.levels[this.currentLevelIndex]; if (!currentLevel) { return; } if (currentLevel.audioGroupIds) { var urlId = -1; var audioGroupId = this.hls.audioTracks[data.id].groupId; for (var i = 0; i < currentLevel.audioGroupIds.length; i++) { if (currentLevel.audioGroupIds[i] === audioGroupId) { urlId = i; break; } } if (urlId !== currentLevel.urlId) { currentLevel.urlId = urlId; this.startLoad(); } } }; _proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) { var level = this.currentLevelIndex; var currentLevel = this._levels[level]; if (this.canLoad && currentLevel && currentLevel.url.length > 0) { var id = currentLevel.urlId; var url = currentLevel.url[id]; if (hlsUrlParameters) { try { url = hlsUrlParameters.addDirectives(url); } catch (error) { this.warn("Could not construct new URL with HLS Delivery Directives: " + error); } } this.log("Attempt loading level index " + level + (hlsUrlParameters ? ' at sn ' + hlsUrlParameters.msn + ' part ' + hlsUrlParameters.part : '') + " with URL-id " + id + " " + url); // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId); // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level); this.clearTimer(); this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADING, { url: url, level: level, id: id, deliveryDirectives: hlsUrlParameters || null }); } }; _proto.removeLevel = function removeLevel(levelIndex, urlId) { var filterLevelAndGroupByIdIndex = function filterLevelAndGroupByIdIndex(url, id) { return id !== urlId; }; var levels = this._levels.filter(function (level, index) { if (index !== levelIndex) { return true; } if (level.url.length > 1 && urlId !== undefined) { level.url = level.url.filter(filterLevelAndGroupByIdIndex); if (level.audioGroupIds) { level.audioGroupIds = level.audioGroupIds.filter(filterLevelAndGroupByIdIndex); } if (level.textGroupIds) { level.textGroupIds = level.textGroupIds.filter(filterLevelAndGroupByIdIndex); } level.urlId = 0; return true; } return false; }).map(function (level, index) { var details = level.details; if (details !== null && details !== void 0 && details.fragments) { details.fragments.forEach(function (fragment) { fragment.level = index; }); } return level; }); this._levels = levels; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVELS_UPDATED, { levels: levels }); }; _createClass(LevelController, [{ key: "levels", get: function get() { if (this._levels.length === 0) { return null; } return this._levels; } }, { key: "level", get: function get() { return this.currentLevelIndex; }, set: function set(newLevel) { var _levels$newLevel; var levels = this._levels; if (levels.length === 0) { return; } if (this.currentLevelIndex === newLevel && (_levels$newLevel = levels[newLevel]) !== null && _levels$newLevel !== void 0 && _levels$newLevel.details) { return; } // check if level idx is valid if (newLevel < 0 || newLevel >= levels.length) { // invalid level id given, trigger error var fatal = newLevel < 0; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].OTHER_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_SWITCH_ERROR, level: newLevel, fatal: fatal, reason: 'invalid level idx' }); if (fatal) { return; } newLevel = Math.min(newLevel, levels.length - 1); } // stopping live reloading timer if any this.clearTimer(); var lastLevelIndex = this.currentLevelIndex; var lastLevel = levels[lastLevelIndex]; var level = levels[newLevel]; this.log("switching to level " + newLevel + " from " + lastLevelIndex); this.currentLevelIndex = newLevel; var levelSwitchingData = _extends({}, level, { level: newLevel, maxBitrate: level.maxBitrate, uri: level.uri, urlId: level.urlId }); // @ts-ignore delete levelSwitchingData._urlId; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_SWITCHING, levelSwitchingData); // check if we need to load playlist for this level var levelDetails = level.details; if (!levelDetails || levelDetails.live) { // level not retrieved yet, or live playlist we need to (re)load it var hlsUrlParameters = this.switchParams(level.uri, lastLevel === null || lastLevel === void 0 ? void 0 : lastLevel.details); this.loadPlaylist(hlsUrlParameters); } } }, { key: "manualLevel", get: function get() { return this.manualLevelIndex; }, set: function set(newLevel) { this.manualLevelIndex = newLevel; if (this._startLevel === undefined) { this._startLevel = newLevel; } if (newLevel !== -1) { this.level = newLevel; } } }, { key: "firstLevel", get: function get() { return this._firstLevel; }, set: function set(newLevel) { this._firstLevel = newLevel; } }, { key: "startLevel", get: function get() { // hls.startLevel takes precedence over config.startLevel // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest) if (this._startLevel === undefined) { var configStartLevel = this.hls.config.startLevel; if (configStartLevel !== undefined) { return configStartLevel; } else { return this._firstLevel; } } else { return this._startLevel; } }, set: function set(newLevel) { this._startLevel = newLevel; } }, { key: "nextLoadLevel", get: function get() { if (this.manualLevelIndex !== -1) { return this.manualLevelIndex; } else { return this.hls.nextAutoLevel; } }, set: function set(nextLevel) { this.level = nextLevel; if (this.manualLevelIndex === -1) { this.hls.nextAutoLevel = nextLevel; } } }]); return LevelController; }(_base_playlist_controller__WEBPACK_IMPORTED_MODULE_5__["default"]); /***/ }), /***/ "./src/controller/level-helper.ts": /*!****************************************!*\ !*** ./src/controller/level-helper.ts ***! \****************************************/ /*! exports provided: addGroupId, assignTrackIdsByGroup, updatePTS, updateFragPTSDTS, mergeDetails, mapPartIntersection, mapFragmentIntersection, adjustSliding, addSliding, computeReloadInterval, getFragmentWithSN, getPartWith */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addGroupId", function() { return addGroupId; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "assignTrackIdsByGroup", function() { return assignTrackIdsByGroup; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updatePTS", function() { return updatePTS; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateFragPTSDTS", function() { return updateFragPTSDTS; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeDetails", function() { return mergeDetails; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapPartIntersection", function() { return mapPartIntersection; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapFragmentIntersection", function() { return mapFragmentIntersection; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "adjustSliding", function() { return adjustSliding; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addSliding", function() { return addSliding; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "computeReloadInterval", function() { return computeReloadInterval; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFragmentWithSN", function() { return getFragmentWithSN; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPartWith", function() { return getPartWith; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /** * @module LevelHelper * Providing methods dealing with playlist sliding and drift * */ function addGroupId(level, type, id) { switch (type) { case 'audio': if (!level.audioGroupIds) { level.audioGroupIds = []; } level.audioGroupIds.push(id); break; case 'text': if (!level.textGroupIds) { level.textGroupIds = []; } level.textGroupIds.push(id); break; } } function assignTrackIdsByGroup(tracks) { var groups = {}; tracks.forEach(function (track) { var groupId = track.groupId || ''; track.id = groups[groupId] = groups[groupId] || 0; groups[groupId]++; }); } function updatePTS(fragments, fromIdx, toIdx) { var fragFrom = fragments[fromIdx]; var fragTo = fragments[toIdx]; updateFromToPTS(fragFrom, fragTo); } function updateFromToPTS(fragFrom, fragTo) { var fragToPTS = fragTo.startPTS; // if we know startPTS[toIdx] if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(fragToPTS)) { // update fragment duration. // it helps to fix drifts between playlist reported duration and fragment real duration var duration = 0; var frag; if (fragTo.sn > fragFrom.sn) { duration = fragToPTS - fragFrom.start; frag = fragFrom; } else { duration = fragFrom.start - fragToPTS; frag = fragTo; } // TODO? Drift can go either way, or the playlist could be completely accurate // console.assert(duration > 0, // `duration of ${duration} computed for frag ${frag.sn}, level ${frag.level}, there should be some duration drift between playlist and fragment!`); if (frag.duration !== duration) { frag.duration = duration; } // we dont know startPTS[toIdx] } else if (fragTo.sn > fragFrom.sn) { var contiguous = fragFrom.cc === fragTo.cc; // TODO: With part-loading end/durations we need to confirm the whole fragment is loaded before using (or setting) minEndPTS if (contiguous && fragFrom.minEndPTS) { fragTo.start = fragFrom.start + (fragFrom.minEndPTS - fragFrom.start); } else { fragTo.start = fragFrom.start + fragFrom.duration; } } else { fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0); } } function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) { var parsedMediaDuration = endPTS - startPTS; if (parsedMediaDuration <= 0) { _utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('Fragment should have a positive duration', frag); endPTS = startPTS + frag.duration; endDTS = startDTS + frag.duration; } var maxStartPTS = startPTS; var minEndPTS = endPTS; var fragStartPts = frag.startPTS; var fragEndPts = frag.endPTS; if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(fragStartPts)) { // delta PTS between audio and video var deltaPTS = Math.abs(fragStartPts - startPTS); if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.deltaPTS)) { frag.deltaPTS = deltaPTS; } else { frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS); } maxStartPTS = Math.max(startPTS, fragStartPts); startPTS = Math.min(startPTS, fragStartPts); startDTS = Math.min(startDTS, frag.startDTS); minEndPTS = Math.min(endPTS, fragEndPts); endPTS = Math.max(endPTS, fragEndPts); endDTS = Math.max(endDTS, frag.endDTS); } frag.duration = endPTS - startPTS; var drift = startPTS - frag.start; frag.appendedPTS = endPTS; frag.start = frag.startPTS = startPTS; frag.maxStartPTS = maxStartPTS; frag.startDTS = startDTS; frag.endPTS = endPTS; frag.minEndPTS = minEndPTS; frag.endDTS = endDTS; var sn = frag.sn; // 'initSegment' // exit if sn out of range if (!details || sn < details.startSN || sn > details.endSN) { return 0; } var i; var fragIdx = sn - details.startSN; var fragments = details.fragments; // update frag reference in fragments array // rationale is that fragments array might not contain this frag object. // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS() // if we don't update frag, we won't be able to propagate PTS info on the playlist // resulting in invalid sliding computation fragments[fragIdx] = frag; // adjust fragment PTS/duration from seqnum-1 to frag 0 for (i = fragIdx; i > 0; i--) { updateFromToPTS(fragments[i], fragments[i - 1]); } // adjust fragment PTS/duration from seqnum to last frag for (i = fragIdx; i < fragments.length - 1; i++) { updateFromToPTS(fragments[i], fragments[i + 1]); } if (details.fragmentHint) { updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint); } details.PTSKnown = details.alignedSliding = true; return drift; } function mergeDetails(oldDetails, newDetails) { // Track the last initSegment processed. Initialize it to the last one on the timeline. var currentInitSegment = null; var oldFragments = oldDetails.fragments; for (var i = oldFragments.length - 1; i >= 0; i--) { var oldInit = oldFragments[i].initSegment; if (oldInit) { currentInitSegment = oldInit; break; } } if (oldDetails.fragmentHint) { // prevent PTS and duration from being adjusted on the next hint delete oldDetails.fragmentHint.endPTS; } // check if old/new playlists have fragments in common // loop through overlapping SN and update startPTS , cc, and duration if any found var ccOffset = 0; var PTSFrag; mapFragmentIntersection(oldDetails, newDetails, function (oldFrag, newFrag) { var _currentInitSegment; if (oldFrag.relurl) { // Do not compare CC if the old fragment has no url. This is a level.fragmentHint used by LL-HLS parts. // It maybe be off by 1 if it was created before any parts or discontinuity tags were appended to the end // of the playlist. ccOffset = oldFrag.cc - newFrag.cc; } if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(oldFrag.startPTS) && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(oldFrag.endPTS)) { newFrag.start = newFrag.startPTS = oldFrag.startPTS; newFrag.startDTS = oldFrag.startDTS; newFrag.appendedPTS = oldFrag.appendedPTS; newFrag.maxStartPTS = oldFrag.maxStartPTS; newFrag.endPTS = oldFrag.endPTS; newFrag.endDTS = oldFrag.endDTS; newFrag.minEndPTS = oldFrag.minEndPTS; newFrag.duration = oldFrag.endPTS - oldFrag.startPTS; if (newFrag.duration) { PTSFrag = newFrag; } // PTS is known when any segment has startPTS and endPTS newDetails.PTSKnown = newDetails.alignedSliding = true; } newFrag.elementaryStreams = oldFrag.elementaryStreams; newFrag.loader = oldFrag.loader; newFrag.stats = oldFrag.stats; newFrag.urlId = oldFrag.urlId; if (oldFrag.initSegment) { newFrag.initSegment = oldFrag.initSegment; currentInitSegment = oldFrag.initSegment; } else if (!newFrag.initSegment || newFrag.initSegment.relurl == ((_currentInitSegment = currentInitSegment) === null || _currentInitSegment === void 0 ? void 0 : _currentInitSegment.relurl)) { newFrag.initSegment = currentInitSegment; } }); if (newDetails.skippedSegments) { newDetails.deltaUpdateFailed = newDetails.fragments.some(function (frag) { return !frag; }); if (newDetails.deltaUpdateFailed) { _utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('[level-helper] Previous playlist missing segments skipped in delta playlist'); for (var _i = newDetails.skippedSegments; _i--;) { newDetails.fragments.shift(); } newDetails.startSN = newDetails.fragments[0].sn; newDetails.startCC = newDetails.fragments[0].cc; } } var newFragments = newDetails.fragments; if (ccOffset) { _utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('discontinuity sliding from playlist, take drift into account'); for (var _i2 = 0; _i2 < newFragments.length; _i2++) { newFragments[_i2].cc += ccOffset; } } if (newDetails.skippedSegments) { newDetails.startCC = newDetails.fragments[0].cc; } // Merge parts mapPartIntersection(oldDetails.partList, newDetails.partList, function (oldPart, newPart) { newPart.elementaryStreams = oldPart.elementaryStreams; newPart.stats = oldPart.stats; }); // if at least one fragment contains PTS info, recompute PTS information for all fragments if (PTSFrag) { updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS); } else { // ensure that delta is within oldFragments range // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61]) // in that case we also need to adjust start offset of all fragments adjustSliding(oldDetails, newDetails); } if (newFragments.length) { newDetails.totalduration = newDetails.edge - newFragments[0].start; } newDetails.driftStartTime = oldDetails.driftStartTime; newDetails.driftStart = oldDetails.driftStart; var advancedDateTime = newDetails.advancedDateTime; if (newDetails.advanced && advancedDateTime) { var edge = newDetails.edge; if (!newDetails.driftStart) { newDetails.driftStartTime = advancedDateTime; newDetails.driftStart = edge; } newDetails.driftEndTime = advancedDateTime; newDetails.driftEnd = edge; } else { newDetails.driftEndTime = oldDetails.driftEndTime; newDetails.driftEnd = oldDetails.driftEnd; newDetails.advancedDateTime = oldDetails.advancedDateTime; } } function mapPartIntersection(oldParts, newParts, intersectionFn) { if (oldParts && newParts) { var delta = 0; for (var i = 0, len = oldParts.length; i <= len; i++) { var _oldPart = oldParts[i]; var _newPart = newParts[i + delta]; if (_oldPart && _newPart && _oldPart.index === _newPart.index && _oldPart.fragment.sn === _newPart.fragment.sn) { intersectionFn(_oldPart, _newPart); } else { delta--; } } } } function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) { var skippedSegments = newDetails.skippedSegments; var start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN; var end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN; var delta = newDetails.startSN - oldDetails.startSN; var newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments; var oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments; for (var i = start; i <= end; i++) { var _oldFrag = oldFrags[delta + i]; var _newFrag = newFrags[i]; if (skippedSegments && !_newFrag && i < skippedSegments) { // Fill in skipped segments in delta playlist _newFrag = newDetails.fragments[i] = _oldFrag; } if (_oldFrag && _newFrag) { intersectionFn(_oldFrag, _newFrag); } } } function adjustSliding(oldDetails, newDetails) { var delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN; var oldFragments = oldDetails.fragments; if (delta < 0 || delta >= oldFragments.length) { return; } addSliding(newDetails, oldFragments[delta].start); } function addSliding(details, start) { if (start) { var fragments = details.fragments; for (var i = details.skippedSegments; i < fragments.length; i++) { fragments[i].start += start; } if (details.fragmentHint) { details.fragmentHint.start += start; } } } function computeReloadInterval(newDetails, stats) { var reloadInterval = 1000 * newDetails.levelTargetDuration; var reloadIntervalAfterMiss = reloadInterval / 2; var timeSinceLastModified = newDetails.age; var useLastModified = timeSinceLastModified > 0 && timeSinceLastModified < reloadInterval * 3; var roundTrip = stats.loading.end - stats.loading.start; var estimatedTimeUntilUpdate; var availabilityDelay = newDetails.availabilityDelay; // let estimate = 'average'; if (newDetails.updated === false) { if (useLastModified) { // estimate = 'miss round trip'; // We should have had a hit so try again in the time it takes to get a response, // but no less than 1/3 second. var minRetry = 333 * newDetails.misses; estimatedTimeUntilUpdate = Math.max(Math.min(reloadIntervalAfterMiss, roundTrip * 2), minRetry); newDetails.availabilityDelay = (newDetails.availabilityDelay || 0) + estimatedTimeUntilUpdate; } else { // estimate = 'miss half average'; // follow HLS Spec, If the client reloads a Playlist file and finds that it has not // changed then it MUST wait for a period of one-half the target // duration before retrying. estimatedTimeUntilUpdate = reloadIntervalAfterMiss; } } else if (useLastModified) { // estimate = 'next modified date'; // Get the closest we've been to timeSinceLastModified on update availabilityDelay = Math.min(availabilityDelay || reloadInterval / 2, timeSinceLastModified); newDetails.availabilityDelay = availabilityDelay; estimatedTimeUntilUpdate = availabilityDelay + reloadInterval - timeSinceLastModified; } else { estimatedTimeUntilUpdate = reloadInterval - roundTrip; } // console.log(`[computeReloadInterval] live reload ${newDetails.updated ? 'REFRESHED' : 'MISSED'}`, // '\n method', estimate, // '\n estimated time until update =>', estimatedTimeUntilUpdate, // '\n average target duration', reloadInterval, // '\n time since modified', timeSinceLastModified, // '\n time round trip', roundTrip, // '\n availability delay', availabilityDelay); return Math.round(estimatedTimeUntilUpdate); } function getFragmentWithSN(level, sn, fragCurrent) { if (!level || !level.details) { return null; } var levelDetails = level.details; var fragment = levelDetails.fragments[sn - levelDetails.startSN]; if (fragment) { return fragment; } fragment = levelDetails.fragmentHint; if (fragment && fragment.sn === sn) { return fragment; } if (sn < levelDetails.startSN && fragCurrent && fragCurrent.sn === sn) { return fragCurrent; } return null; } function getPartWith(level, sn, partIndex) { if (!level || !level.details) { return null; } var partList = level.details.partList; if (partList) { for (var i = partList.length; i--;) { var part = partList[i]; if (part.index === partIndex && part.fragment.sn === sn) { return part; } } } return null; } /***/ }), /***/ "./src/controller/stream-controller.ts": /*!*********************************************!*\ !*** ./src/controller/stream-controller.ts ***! \*********************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return StreamController; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base-stream-controller */ "./src/controller/base-stream-controller.ts"); /* harmony import */ var _is_supported__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../is-supported */ "./src/is-supported.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts"); /* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts"); /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts"); /* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts"); /* harmony import */ var _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../demux/transmuxer-interface */ "./src/demux/transmuxer-interface.ts"); /* harmony import */ var _types_transmuxer__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../types/transmuxer */ "./src/types/transmuxer.ts"); /* harmony import */ var _gap_controller__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./gap-controller */ "./src/controller/gap-controller.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var TICK_INTERVAL = 100; // how often to tick in ms var StreamController = /*#__PURE__*/function (_BaseStreamController) { _inheritsLoose(StreamController, _BaseStreamController); function StreamController(hls, fragmentTracker) { var _this; _this = _BaseStreamController.call(this, hls, fragmentTracker, '[stream-controller]') || this; _this.audioCodecSwap = false; _this.gapController = null; _this.level = -1; _this._forceStartLoad = false; _this.altAudio = false; _this.audioOnly = false; _this.fragPlaying = null; _this.onvplaying = null; _this.onvseeked = null; _this.fragLastKbps = 0; _this.stalled = false; _this.couldBacktrack = false; _this.audioCodecSwitch = false; _this.videoBuffer = null; _this._registerListeners(); return _this; } var _proto = StreamController.prototype; _proto._registerListeners = function _registerListeners() { var hls = this.hls; hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_LOADING, this.onManifestLoading, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_PARSED, this.onManifestParsed, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_LOADING, this.onLevelLoading, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_LOADED, this.onLevelLoaded, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, this.onError, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_CREATED, this.onBufferCreated, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_FLUSHED, this.onBufferFlushed, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVELS_UPDATED, this.onLevelsUpdated, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_BUFFERED, this.onFragBuffered, this); }; _proto._unregisterListeners = function _unregisterListeners() { var hls = this.hls; hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_LOADING, this.onManifestLoading, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_PARSED, this.onManifestParsed, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_LOADED, this.onLevelLoaded, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, this.onError, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_CREATED, this.onBufferCreated, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_FLUSHED, this.onBufferFlushed, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVELS_UPDATED, this.onLevelsUpdated, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_BUFFERED, this.onFragBuffered, this); }; _proto.onHandlerDestroying = function onHandlerDestroying() { this._unregisterListeners(); this.onMediaDetaching(); }; _proto.startLoad = function startLoad(startPosition) { if (this.levels) { var lastCurrentTime = this.lastCurrentTime, hls = this.hls; this.stopLoad(); this.setInterval(TICK_INTERVAL); this.level = -1; this.fragLoadError = 0; if (!this.startFragRequested) { // determine load level var startLevel = hls.startLevel; if (startLevel === -1) { if (hls.config.testBandwidth) { // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level startLevel = 0; this.bitrateTest = true; } else { startLevel = hls.nextAutoLevel; } } // set new level to playlist loader : this will trigger start level load // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded this.level = hls.nextLoadLevel = startLevel; this.loadedmetadata = false; } // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime if (lastCurrentTime > 0 && startPosition === -1) { this.log("Override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3)); startPosition = lastCurrentTime; } this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition; this.tick(); } else { this._forceStartLoad = true; this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].STOPPED; } }; _proto.stopLoad = function stopLoad() { this._forceStartLoad = false; _BaseStreamController.prototype.stopLoad.call(this); }; _proto.doTick = function doTick() { switch (this.state) { case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE: this.doTickIdle(); break; case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL: { var _levels$level; var levels = this.levels, level = this.level; var details = levels === null || levels === void 0 ? void 0 : (_levels$level = levels[level]) === null || _levels$level === void 0 ? void 0 : _levels$level.details; if (details && (!details.live || this.levelLastLoaded === this.level)) { if (this.waitForCdnTuneIn(details)) { break; } this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; break; } break; } case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING_WAITING_RETRY: { var _this$media; var now = self.performance.now(); var retryDate = this.retryDate; // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading if (!retryDate || now >= retryDate || (_this$media = this.media) !== null && _this$media !== void 0 && _this$media.seeking) { this.log('retryDate reached, switch back to IDLE state'); this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; } } break; default: break; } // check buffer // check/update current fragment this.onTickEnd(); }; _proto.onTickEnd = function onTickEnd() { _BaseStreamController.prototype.onTickEnd.call(this); this.checkBuffer(); this.checkFragmentChanged(); }; _proto.doTickIdle = function doTickIdle() { var _frag$decryptdata, _frag$decryptdata2; var hls = this.hls, levelLastLoaded = this.levelLastLoaded, levels = this.levels, media = this.media; var config = hls.config, level = hls.nextLoadLevel; // if start level not parsed yet OR // if video not attached AND start fragment already requested OR start frag prefetch not enabled // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment if (levelLastLoaded === null || !media && (this.startFragRequested || !config.startFragPrefetch)) { return; } // If the "main" level is audio-only but we are loading an alternate track in the same group, do not load anything if (this.altAudio && this.audioOnly) { return; } if (!levels || !levels[level]) { return; } var levelInfo = levels[level]; // if buffer length is less than maxBufLen try to load a new fragment // set next load level : this will trigger a playlist load if needed this.level = hls.nextLoadLevel = level; var levelDetails = levelInfo.details; // if level info not retrieved yet, switch state and wait for level retrieval // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist) if (!levelDetails || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL || levelDetails.live && this.levelLastLoaded !== level) { this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL; return; } var bufferInfo = this.getFwdBufferInfo(this.mediaBuffer ? this.mediaBuffer : media, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN); if (bufferInfo === null) { return; } var bufferLen = bufferInfo.len; // compute max Buffer Length that we could get from this load level, based on level bitrate. don't buffer more than 60 MB and more than 30s var maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate); // Stay idle if we are still with buffer margins if (bufferLen >= maxBufLen) { return; } if (this._streamEnded(bufferInfo, levelDetails)) { var data = {}; if (this.altAudio) { data.type = 'video'; } this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_EOS, data); this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ENDED; return; } var targetBufferTime = bufferInfo.end; var frag = this.getNextFragment(targetBufferTime, levelDetails); // Avoid backtracking after seeking or switching by loading an earlier segment in streams that could backtrack if (this.couldBacktrack && !this.fragPrevious && frag && frag.sn !== 'initSegment') { var fragIdx = frag.sn - levelDetails.startSN; if (fragIdx > 1) { frag = levelDetails.fragments[fragIdx - 1]; this.fragmentTracker.removeFragment(frag); } } // Avoid loop loading by using nextLoadPosition set for backtracking if (frag && this.fragmentTracker.getState(frag) === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].OK && this.nextLoadPosition > targetBufferTime) { // Cleanup the fragment tracker before trying to find the next unbuffered fragment var type = this.audioOnly && !this.altAudio ? _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO : _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].VIDEO; this.afterBufferFlushed(media, type, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN); frag = this.getNextFragment(this.nextLoadPosition, levelDetails); } if (!frag) { return; } if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) { frag = frag.initSegment; } // We want to load the key if we're dealing with an identity key, because we will decrypt // this content using the key we fetch. Other keys will be handled by the DRM CDM via EME. if (((_frag$decryptdata = frag.decryptdata) === null || _frag$decryptdata === void 0 ? void 0 : _frag$decryptdata.keyFormat) === 'identity' && !((_frag$decryptdata2 = frag.decryptdata) !== null && _frag$decryptdata2 !== void 0 && _frag$decryptdata2.key)) { this.loadKey(frag, levelDetails); } else { this.loadFragment(frag, levelDetails, targetBufferTime); } }; _proto.loadFragment = function loadFragment(frag, levelDetails, targetBufferTime) { var _this$media2; // Check if fragment is not loaded var fragState = this.fragmentTracker.getState(frag); this.fragCurrent = frag; // Use data from loaded backtracked fragment if available if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].BACKTRACKED) { var data = this.fragmentTracker.getBacktrackData(frag); if (data) { this._handleFragmentLoadProgress(data); this._handleFragmentLoadComplete(data); return; } else { fragState = _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].NOT_LOADED; } } if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].NOT_LOADED || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].PARTIAL) { if (frag.sn === 'initSegment') { this._loadInitSegment(frag); } else if (this.bitrateTest) { frag.bitrateTest = true; this.log("Fragment " + frag.sn + " of level " + frag.level + " is being downloaded to test bitrate and will not be buffered"); this._loadBitrateTestFrag(frag); } else { this.startFragRequested = true; _BaseStreamController.prototype.loadFragment.call(this, frag, levelDetails, targetBufferTime); } } else if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].APPENDING) { // Lower the buffer size and try again if (this.reduceMaxBufferLength(frag.duration)) { this.fragmentTracker.removeFragment(frag); } } else if (((_this$media2 = this.media) === null || _this$media2 === void 0 ? void 0 : _this$media2.buffered.length) === 0) { // Stop gap for bad tracker / buffer flush behavior this.fragmentTracker.removeAllFragments(); } }; _proto.getAppendedFrag = function getAppendedFrag(position) { var fragOrPart = this.fragmentTracker.getAppendedFrag(position, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN); if (fragOrPart && 'fragment' in fragOrPart) { return fragOrPart.fragment; } return fragOrPart; }; _proto.getBufferedFrag = function getBufferedFrag(position) { return this.fragmentTracker.getBufferedFrag(position, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN); }; _proto.followingBufferedFrag = function followingBufferedFrag(frag) { if (frag) { // try to get range of next fragment (500ms after this range) return this.getBufferedFrag(frag.end + 0.5); } return null; } /* on immediate level switch : - pause playback if playing - cancel any pending load request - and trigger a buffer flush */ ; _proto.immediateLevelSwitch = function immediateLevelSwitch() { this.abortCurrentFrag(); this.flushMainBuffer(0, Number.POSITIVE_INFINITY); } /** * try to switch ASAP without breaking video playback: * in order to ensure smooth but quick level switching, * we need to find the next flushable buffer range * we should take into account new segment fetch time */ ; _proto.nextLevelSwitch = function nextLevelSwitch() { var levels = this.levels, media = this.media; // ensure that media is defined and that metadata are available (to retrieve currentTime) if (media !== null && media !== void 0 && media.readyState) { var fetchdelay; var fragPlayingCurrent = this.getAppendedFrag(media.currentTime); if (fragPlayingCurrent && fragPlayingCurrent.start > 1) { // flush buffer preceding current fragment (flush until current fragment start offset) // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ... this.flushMainBuffer(0, fragPlayingCurrent.start - 1); } if (!media.paused && levels) { // add a safety delay of 1s var nextLevelId = this.hls.nextLoadLevel; var nextLevel = levels[nextLevelId]; var fragLastKbps = this.fragLastKbps; if (fragLastKbps && this.fragCurrent) { fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1000 * fragLastKbps) + 1; } else { fetchdelay = 0; } } else { fetchdelay = 0; } // this.log('fetchdelay:'+fetchdelay); // find buffer range that will be reached once new fragment will be fetched var bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay); if (bufferedFrag) { // we can flush buffer range following this one without stalling playback var nextBufferedFrag = this.followingBufferedFrag(bufferedFrag); if (nextBufferedFrag) { // if we are here, we can also cancel any loading/demuxing in progress, as they are useless this.abortCurrentFrag(); // start flush position is in next buffered frag. Leave some padding for non-independent segments and smoother playback. var maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start; var fragDuration = nextBufferedFrag.duration; var startPts = Math.max(bufferedFrag.end, maxStart + Math.min(Math.max(fragDuration - this.config.maxFragLookUpTolerance, fragDuration * 0.5), fragDuration * 0.75)); this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY); } } } }; _proto.abortCurrentFrag = function abortCurrentFrag() { var fragCurrent = this.fragCurrent; this.fragCurrent = null; if (fragCurrent !== null && fragCurrent !== void 0 && fragCurrent.loader) { fragCurrent.loader.abort(); } if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].KEY_LOADING) { this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; } this.nextLoadPosition = this.getLoadPosition(); }; _proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset) { _BaseStreamController.prototype.flushMainBuffer.call(this, startOffset, endOffset, this.altAudio ? 'video' : null); }; _proto.onMediaAttached = function onMediaAttached(event, data) { _BaseStreamController.prototype.onMediaAttached.call(this, event, data); var media = data.media; this.onvplaying = this.onMediaPlaying.bind(this); this.onvseeked = this.onMediaSeeked.bind(this); media.addEventListener('playing', this.onvplaying); media.addEventListener('seeked', this.onvseeked); this.gapController = new _gap_controller__WEBPACK_IMPORTED_MODULE_10__["default"](this.config, media, this.fragmentTracker, this.hls); }; _proto.onMediaDetaching = function onMediaDetaching() { var media = this.media; if (media) { media.removeEventListener('playing', this.onvplaying); media.removeEventListener('seeked', this.onvseeked); this.onvplaying = this.onvseeked = null; this.videoBuffer = null; } this.fragPlaying = null; if (this.gapController) { this.gapController.destroy(); this.gapController = null; } _BaseStreamController.prototype.onMediaDetaching.call(this); }; _proto.onMediaPlaying = function onMediaPlaying() { // tick to speed up FRAG_CHANGED triggering this.tick(); }; _proto.onMediaSeeked = function onMediaSeeked() { var media = this.media; var currentTime = media ? media.currentTime : null; if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(currentTime)) { this.log("Media seeked to " + currentTime.toFixed(3)); } // tick to speed up FRAG_CHANGED triggering this.tick(); }; _proto.onManifestLoading = function onManifestLoading() { // reset buffer on manifest loading this.log('Trigger BUFFER_RESET'); this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_RESET, undefined); this.fragmentTracker.removeAllFragments(); this.couldBacktrack = this.stalled = false; this.startPosition = this.lastCurrentTime = 0; this.fragPlaying = null; }; _proto.onManifestParsed = function onManifestParsed(event, data) { var aac = false; var heaac = false; var codec; data.levels.forEach(function (level) { // detect if we have different kind of audio codecs used amongst playlists codec = level.audioCodec; if (codec) { if (codec.indexOf('mp4a.40.2') !== -1) { aac = true; } if (codec.indexOf('mp4a.40.5') !== -1) { heaac = true; } } }); this.audioCodecSwitch = aac && heaac && !Object(_is_supported__WEBPACK_IMPORTED_MODULE_2__["changeTypeSupported"])(); if (this.audioCodecSwitch) { this.log('Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC'); } this.levels = data.levels; this.startFragRequested = false; }; _proto.onLevelLoading = function onLevelLoading(event, data) { var levels = this.levels; if (!levels || this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE) { return; } var level = levels[data.level]; if (!level.details || level.details.live && this.levelLastLoaded !== data.level || this.waitForCdnTuneIn(level.details)) { this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL; } }; _proto.onLevelLoaded = function onLevelLoaded(event, data) { var _curLevel$details; var levels = this.levels; var newLevelId = data.level; var newDetails = data.details; var duration = newDetails.totalduration; if (!levels) { this.warn("Levels were reset while loading level " + newLevelId); return; } this.log("Level " + newLevelId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "], cc [" + newDetails.startCC + ", " + newDetails.endCC + "] duration:" + duration); var fragCurrent = this.fragCurrent; if (fragCurrent && (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING_WAITING_RETRY)) { if (fragCurrent.level !== data.level && fragCurrent.loader) { this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; fragCurrent.loader.abort(); } } var curLevel = levels[newLevelId]; var sliding = 0; if (newDetails.live || (_curLevel$details = curLevel.details) !== null && _curLevel$details !== void 0 && _curLevel$details.live) { if (!newDetails.fragments[0]) { newDetails.deltaUpdateFailed = true; } if (newDetails.deltaUpdateFailed) { return; } sliding = this.alignPlaylists(newDetails, curLevel.details); } // override level info curLevel.details = newDetails; this.levelLastLoaded = newLevelId; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_UPDATED, { details: newDetails, level: newLevelId }); // only switch back to IDLE state if we were waiting for level to start downloading a new fragment if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL) { if (this.waitForCdnTuneIn(newDetails)) { // Wait for Low-Latency CDN Tune-in return; } this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; } if (!this.startFragRequested) { this.setStartPosition(newDetails, sliding); } else if (newDetails.live) { this.synchronizeToLiveEdge(newDetails); } // trigger handler right now this.tick(); }; _proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(data) { var _frag$initSegment; var frag = data.frag, part = data.part, payload = data.payload; var levels = this.levels; if (!levels) { this.warn("Levels were reset while fragment load was in progress. Fragment " + frag.sn + " of level " + frag.level + " will not be buffered"); return; } var currentLevel = levels[frag.level]; var details = currentLevel.details; if (!details) { this.warn("Dropping fragment " + frag.sn + " of level " + frag.level + " after level details were reset"); return; } var videoCodec = currentLevel.videoCodec; // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live) var accurateTimeOffset = details.PTSKnown || !details.live; var initSegmentData = (_frag$initSegment = frag.initSegment) === null || _frag$initSegment === void 0 ? void 0 : _frag$initSegment.data; var audioCodec = this._getAudioCodec(currentLevel); // transmux the MPEG-TS data to ISO-BMFF segments // this.log(`Transmuxing ${frag.sn} of [${details.startSN} ,${details.endSN}],level ${frag.level}, cc ${frag.cc}`); var transmuxer = this.transmuxer = this.transmuxer || new _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_8__["default"](this.hls, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this)); var partIndex = part ? part.index : -1; var partial = partIndex !== -1; var chunkMeta = new _types_transmuxer__WEBPACK_IMPORTED_MODULE_9__["ChunkMetadata"](frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial); var initPTS = this.initPTS[frag.cc]; transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS); }; _proto.onAudioTrackSwitching = function onAudioTrackSwitching(event, data) { // if any URL found on new audio track, it is an alternate audio track var fromAltAudio = this.altAudio; var altAudio = !!data.url; var trackId = data.id; // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered // don't do anything if we switch to alt audio: audio stream controller is handling it. // we will just have to change buffer scheduling on audioTrackSwitched if (!altAudio) { if (this.mediaBuffer !== this.media) { this.log('Switching on main audio, use media.buffered to schedule main fragment loading'); this.mediaBuffer = this.media; var fragCurrent = this.fragCurrent; // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch if (fragCurrent !== null && fragCurrent !== void 0 && fragCurrent.loader) { this.log('Switching to main audio track, cancel main fragment load'); fragCurrent.loader.abort(); } // destroy transmuxer to force init segment generation (following audio switch) this.resetTransmuxer(); // switch to IDLE state to load new fragment this.resetLoadingState(); } else if (this.audioOnly) { // Reset audio transmuxer so when switching back to main audio we're not still appending where we left off this.resetTransmuxer(); } var hls = this.hls; // If switching from alt to main audio, flush all audio and trigger track switched if (fromAltAudio) { hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' }); } hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHED, { id: trackId }); } }; _proto.onAudioTrackSwitched = function onAudioTrackSwitched(event, data) { var trackId = data.id; var altAudio = !!this.hls.audioTracks[trackId].url; if (altAudio) { var videoBuffer = this.videoBuffer; // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered if (videoBuffer && this.mediaBuffer !== videoBuffer) { this.log('Switching on alternate audio, use video.buffered to schedule main fragment loading'); this.mediaBuffer = videoBuffer; } } this.altAudio = altAudio; this.tick(); }; _proto.onBufferCreated = function onBufferCreated(event, data) { var tracks = data.tracks; var mediaTrack; var name; var alternate = false; for (var type in tracks) { var track = tracks[type]; if (track.id === 'main') { name = type; mediaTrack = track; // keep video source buffer reference if (type === 'video') { var videoTrack = tracks[type]; if (videoTrack) { this.videoBuffer = videoTrack.buffer; } } } else { alternate = true; } } if (alternate && mediaTrack) { this.log("Alternate track found, use " + name + ".buffered to schedule main fragment loading"); this.mediaBuffer = mediaTrack.buffer; } else { this.mediaBuffer = this.media; } }; _proto.onFragBuffered = function onFragBuffered(event, data) { var frag = data.frag, part = data.part; if (frag && frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN) { return; } if (this.fragContextChanged(frag)) { // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion // Avoid setting state back to IDLE, since that will interfere with a level switch this.warn("Fragment " + frag.sn + (part ? ' p: ' + part.index : '') + " of level " + frag.level + " finished buffering, but was aborted. state: " + this.state); if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSED) { this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; } return; } var stats = part ? part.stats : frag.stats; this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first)); if (frag.sn !== 'initSegment') { this.fragPrevious = frag; } this.fragBufferedComplete(frag, part); }; _proto.onError = function onError(event, data) { switch (data.details) { case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].FRAG_LOAD_ERROR: case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].FRAG_LOAD_TIMEOUT: case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].KEY_LOAD_ERROR: case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].KEY_LOAD_TIMEOUT: this.onFragmentOrKeyLoadError(_types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN, data); break; case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].LEVEL_LOAD_ERROR: case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].LEVEL_LOAD_TIMEOUT: if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ERROR) { if (data.fatal) { // if fatal error, stop processing this.warn("" + data.details); this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ERROR; } else { // in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE if (!data.levelRetry && this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL) { this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; } } } break; case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].BUFFER_FULL_ERROR: // if in appending state if (data.parent === 'main' && (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSED)) { var flushBuffer = true; var bufferedInfo = this.getFwdBufferInfo(this.media, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN); // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end // reduce max buf len if current position is buffered if (bufferedInfo && bufferedInfo.len > 0.5) { flushBuffer = !this.reduceMaxBufferLength(bufferedInfo.len); } if (flushBuffer) { // current position is not buffered, but browser is still complaining about buffer full error // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708 // in that case flush the whole buffer to recover this.warn('buffer full error also media.currentTime is not buffered, flush main'); // flush main buffer this.immediateLevelSwitch(); } this.resetLoadingState(); } break; default: break; } } // Checks the health of the buffer and attempts to resolve playback stalls. ; _proto.checkBuffer = function checkBuffer() { var media = this.media, gapController = this.gapController; if (!media || !gapController || !media.readyState) { // Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0) return; } // Check combined buffer var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(media); if (!this.loadedmetadata && buffered.length) { this.loadedmetadata = true; this.seekToStartPos(); } else { // Resolve gaps using the main buffer, whose ranges are the intersections of the A/V sourcebuffers gapController.poll(this.lastCurrentTime); } this.lastCurrentTime = media.currentTime; }; _proto.onFragLoadEmergencyAborted = function onFragLoadEmergencyAborted() { this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; // if loadedmetadata is not set, it means that we are emergency switch down on first frag // in that case, reset startFragRequested flag if (!this.loadedmetadata) { this.startFragRequested = false; this.nextLoadPosition = this.startPosition; } this.tickImmediate(); }; _proto.onBufferFlushed = function onBufferFlushed(event, _ref) { var type = _ref.type; if (type !== _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO || this.audioOnly && !this.altAudio) { var media = (type === _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media; this.afterBufferFlushed(media, type, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN); } }; _proto.onLevelsUpdated = function onLevelsUpdated(event, data) { this.levels = data.levels; }; _proto.swapAudioCodec = function swapAudioCodec() { this.audioCodecSwap = !this.audioCodecSwap; } /** * Seeks to the set startPosition if not equal to the mediaElement's current time. * @private */ ; _proto.seekToStartPos = function seekToStartPos() { var media = this.media; var currentTime = media.currentTime; var startPosition = this.startPosition; // only adjust currentTime if different from startPosition or if startPosition not buffered // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered if (startPosition >= 0 && currentTime < startPosition) { if (media.seeking) { _utils_logger__WEBPACK_IMPORTED_MODULE_12__["logger"].log("could not seek to " + startPosition + ", already seeking at " + currentTime); return; } var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(media); var bufferStart = buffered.length ? buffered.start(0) : 0; var delta = bufferStart - startPosition; if (delta > 0 && delta < this.config.maxBufferHole) { _utils_logger__WEBPACK_IMPORTED_MODULE_12__["logger"].log("adjusting start position by " + delta + " to match buffer start"); startPosition += delta; this.startPosition = startPosition; } this.log("seek to target start position " + startPosition + " from current time " + currentTime); media.currentTime = startPosition; } }; _proto._getAudioCodec = function _getAudioCodec(currentLevel) { var audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec; if (this.audioCodecSwap && audioCodec) { this.log('Swapping audio codec'); if (audioCodec.indexOf('mp4a.40.5') !== -1) { audioCodec = 'mp4a.40.2'; } else { audioCodec = 'mp4a.40.5'; } } return audioCodec; }; _proto._loadBitrateTestFrag = function _loadBitrateTestFrag(frag) { var _this2 = this; this._doFragLoad(frag).then(function (data) { var hls = _this2.hls; if (!data || hls.nextLoadLevel || _this2.fragContextChanged(frag)) { return; } _this2.fragLoadError = 0; _this2.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; _this2.startFragRequested = false; _this2.bitrateTest = false; var stats = frag.stats; // Bitrate tests fragments are neither parsed nor buffered stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now(); hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_LOADED, data); }); }; _proto._handleTransmuxComplete = function _handleTransmuxComplete(transmuxResult) { var _id3$samples; var id = 'main'; var hls = this.hls; var remuxResult = transmuxResult.remuxResult, chunkMeta = transmuxResult.chunkMeta; var context = this.getCurrentContext(chunkMeta); if (!context) { this.warn("The loading context changed while buffering fragment " + chunkMeta.sn + " of level " + chunkMeta.level + ". This chunk will not be buffered."); this.resetLiveStartWhenNotLoaded(chunkMeta.level); return; } var frag = context.frag, part = context.part, level = context.level; var video = remuxResult.video, text = remuxResult.text, id3 = remuxResult.id3, initSegment = remuxResult.initSegment; // The audio-stream-controller handles audio buffering if Hls.js is playing an alternate audio track var audio = this.altAudio ? undefined : remuxResult.audio; // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level. // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed. if (this.fragContextChanged(frag)) { return; } this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING; if (initSegment) { if (initSegment.tracks) { this._bufferInitSegment(level, initSegment.tracks, frag, chunkMeta); hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_PARSING_INIT_SEGMENT, { frag: frag, id: id, tracks: initSegment.tracks }); } // This would be nice if Number.isFinite acted as a typeguard, but it doesn't. See: https://github.com/Microsoft/TypeScript/issues/10038 var initPTS = initSegment.initPTS; var timescale = initSegment.timescale; if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(initPTS)) { this.initPTS[frag.cc] = initPTS; hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].INIT_PTS_FOUND, { frag: frag, id: id, initPTS: initPTS, timescale: timescale }); } } // Avoid buffering if backtracking this fragment if (video && remuxResult.independent !== false) { if (level.details) { var startPTS = video.startPTS, endPTS = video.endPTS, startDTS = video.startDTS, endDTS = video.endDTS; if (part) { part.elementaryStreams[video.type] = { startPTS: startPTS, endPTS: endPTS, startDTS: startDTS, endDTS: endDTS }; } else { if (video.firstKeyFrame && video.independent) { this.couldBacktrack = true; } if (video.dropped && video.independent) { // Backtrack if dropped frames create a gap after currentTime var pos = this.getLoadPosition() + this.config.maxBufferHole; if (pos < startPTS) { this.backtrack(frag); return; } // Set video stream start to fragment start so that truncated samples do not distort the timeline, and mark it partial frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true); } } frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS); this.bufferFragmentData(video, frag, part, chunkMeta); } } else if (remuxResult.independent === false) { this.backtrack(frag); return; } if (audio) { var _startPTS = audio.startPTS, _endPTS = audio.endPTS, _startDTS = audio.startDTS, _endDTS = audio.endDTS; if (part) { part.elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO] = { startPTS: _startPTS, endPTS: _endPTS, startDTS: _startDTS, endDTS: _endDTS }; } frag.setElementaryStreamInfo(_loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO, _startPTS, _endPTS, _startDTS, _endDTS); this.bufferFragmentData(audio, frag, part, chunkMeta); } if (id3 !== null && id3 !== void 0 && (_id3$samples = id3.samples) !== null && _id3$samples !== void 0 && _id3$samples.length) { var emittedID3 = { frag: frag, id: id, samples: id3.samples }; hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_PARSING_METADATA, emittedID3); } if (text) { var emittedText = { frag: frag, id: id, samples: text.samples }; hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_PARSING_USERDATA, emittedText); } }; _proto._bufferInitSegment = function _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) { var _this3 = this; if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING) { return; } this.audioOnly = !!tracks.audio && !tracks.video; // if audio track is expected to come from audio stream controller, discard any coming from main if (this.altAudio && !this.audioOnly) { delete tracks.audio; } // include levelCodec in audio and video tracks var audio = tracks.audio, video = tracks.video, audiovideo = tracks.audiovideo; if (audio) { var audioCodec = currentLevel.audioCodec; var ua = navigator.userAgent.toLowerCase(); if (this.audioCodecSwitch) { if (audioCodec) { if (audioCodec.indexOf('mp4a.40.5') !== -1) { audioCodec = 'mp4a.40.2'; } else { audioCodec = 'mp4a.40.5'; } } // In the case that AAC and HE-AAC audio codecs are signalled in manifest, // force HE-AAC, as it seems that most browsers prefers it. // don't force HE-AAC if mono stream, or in Firefox if (audio.metadata.channelCount !== 1 && ua.indexOf('firefox') === -1) { audioCodec = 'mp4a.40.5'; } } // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise if (ua.indexOf('android') !== -1 && audio.container !== 'audio/mpeg') { // Exclude mpeg audio audioCodec = 'mp4a.40.2'; this.log("Android: force audio codec to " + audioCodec); } if (currentLevel.audioCodec && currentLevel.audioCodec !== audioCodec) { this.log("Swapping manifest audio codec \"" + currentLevel.audioCodec + "\" for \"" + audioCodec + "\""); } audio.levelCodec = audioCodec; audio.id = 'main'; this.log("Init audio buffer, container:" + audio.container + ", codecs[selected/level/parsed]=[" + (audioCodec || '') + "/" + (currentLevel.audioCodec || '') + "/" + audio.codec + "]"); } if (video) { video.levelCodec = currentLevel.videoCodec; video.id = 'main'; this.log("Init video buffer, container:" + video.container + ", codecs[level/parsed]=[" + (currentLevel.videoCodec || '') + "/" + video.codec + "]"); } if (audiovideo) { this.log("Init audiovideo buffer, container:" + audiovideo.container + ", codecs[level/parsed]=[" + (currentLevel.attrs.CODECS || '') + "/" + audiovideo.codec + "]"); } this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_CODECS, tracks); // loop through tracks that are going to be provided to bufferController Object.keys(tracks).forEach(function (trackName) { var track = tracks[trackName]; var initSegment = track.initSegment; if (initSegment !== null && initSegment !== void 0 && initSegment.byteLength) { _this3.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_APPENDING, { type: trackName, data: initSegment, frag: frag, part: null, chunkMeta: chunkMeta, parent: frag.type }); } }); // trigger handler right now this.tick(); }; _proto.backtrack = function backtrack(frag) { this.couldBacktrack = true; // Causes findFragments to backtrack through fragments to find the keyframe this.resetTransmuxer(); this.flushBufferGap(frag); var data = this.fragmentTracker.backtrack(frag); this.fragPrevious = null; this.nextLoadPosition = frag.start; if (data) { this.resetFragmentLoading(frag); } else { // Change state to BACKTRACKING so that fragmentEntity.backtrack data can be added after _doFragLoad this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].BACKTRACKING; } }; _proto.checkFragmentChanged = function checkFragmentChanged() { var video = this.media; var fragPlayingCurrent = null; if (video && video.readyState > 1 && video.seeking === false) { var currentTime = video.currentTime; /* if video element is in seeked state, currentTime can only increase. (assuming that playback rate is positive ...) As sometimes currentTime jumps back to zero after a media decode error, check this, to avoid seeking back to wrong position after a media decode error */ if (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].isBuffered(video, currentTime)) { fragPlayingCurrent = this.getAppendedFrag(currentTime); } else if (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].isBuffered(video, currentTime + 0.1)) { /* ensure that FRAG_CHANGED event is triggered at startup, when first video frame is displayed and playback is paused. add a tolerance of 100ms, in case current position is not buffered, check if current pos+100ms is buffered and use that buffer range for FRAG_CHANGED event reporting */ fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1); } if (fragPlayingCurrent) { var fragPlaying = this.fragPlaying; var fragCurrentLevel = fragPlayingCurrent.level; if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel || fragPlayingCurrent.urlId !== fragPlaying.urlId) { this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_CHANGED, { frag: fragPlayingCurrent }); if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) { this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_SWITCHED, { level: fragCurrentLevel }); } this.fragPlaying = fragPlayingCurrent; } } } }; _createClass(StreamController, [{ key: "nextLevel", get: function get() { var frag = this.nextBufferedFrag; if (frag) { return frag.level; } else { return -1; } } }, { key: "currentLevel", get: function get() { var media = this.media; if (media) { var fragPlayingCurrent = this.getAppendedFrag(media.currentTime); if (fragPlayingCurrent) { return fragPlayingCurrent.level; } } return -1; } }, { key: "nextBufferedFrag", get: function get() { var media = this.media; if (media) { // first get end range of current fragment var fragPlayingCurrent = this.getAppendedFrag(media.currentTime); return this.followingBufferedFrag(fragPlayingCurrent); } else { return null; } } }, { key: "forceStartLoad", get: function get() { return this._forceStartLoad; } }]); return StreamController; }(_base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["default"]); /***/ }), /***/ "./src/crypt/aes-crypto.ts": /*!*********************************!*\ !*** ./src/crypt/aes-crypto.ts ***! \*********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AESCrypto; }); var AESCrypto = /*#__PURE__*/function () { function AESCrypto(subtle, iv) { this.subtle = void 0; this.aesIV = void 0; this.subtle = subtle; this.aesIV = iv; } var _proto = AESCrypto.prototype; _proto.decrypt = function decrypt(data, key) { return this.subtle.decrypt({ name: 'AES-CBC', iv: this.aesIV }, key, data); }; return AESCrypto; }(); /***/ }), /***/ "./src/crypt/aes-decryptor.ts": /*!************************************!*\ !*** ./src/crypt/aes-decryptor.ts ***! \************************************/ /*! exports provided: removePadding, default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removePadding", function() { return removePadding; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AESDecryptor; }); /* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/typed-array */ "./src/utils/typed-array.ts"); // PKCS7 function removePadding(array) { var outputBytes = array.byteLength; var paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1); if (paddingBytes) { return Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_0__["sliceUint8"])(array, 0, outputBytes - paddingBytes); } return array; } var AESDecryptor = /*#__PURE__*/function () { function AESDecryptor() { this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)]; this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)]; this.sBox = new Uint32Array(256); this.invSBox = new Uint32Array(256); this.key = new Uint32Array(0); this.ksRows = 0; this.keySize = 0; this.keySchedule = void 0; this.invKeySchedule = void 0; this.initTable(); } // Using view.getUint32() also swaps the byte order. var _proto = AESDecryptor.prototype; _proto.uint8ArrayToUint32Array_ = function uint8ArrayToUint32Array_(arrayBuffer) { var view = new DataView(arrayBuffer); var newArray = new Uint32Array(4); for (var i = 0; i < 4; i++) { newArray[i] = view.getUint32(i * 4); } return newArray; }; _proto.initTable = function initTable() { var sBox = this.sBox; var invSBox = this.invSBox; var subMix = this.subMix; var subMix0 = subMix[0]; var subMix1 = subMix[1]; var subMix2 = subMix[2]; var subMix3 = subMix[3]; var invSubMix = this.invSubMix; var invSubMix0 = invSubMix[0]; var invSubMix1 = invSubMix[1]; var invSubMix2 = invSubMix[2]; var invSubMix3 = invSubMix[3]; var d = new Uint32Array(256); var x = 0; var xi = 0; var i = 0; for (i = 0; i < 256; i++) { if (i < 128) { d[i] = i << 1; } else { d[i] = i << 1 ^ 0x11b; } } for (i = 0; i < 256; i++) { var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4; sx = sx >>> 8 ^ sx & 0xff ^ 0x63; sBox[x] = sx; invSBox[sx] = x; // Compute multiplication var x2 = d[x]; var x4 = d[x2]; var x8 = d[x4]; // Compute sub/invSub bytes, mix columns tables var t = d[sx] * 0x101 ^ sx * 0x1010100; subMix0[x] = t << 24 | t >>> 8; subMix1[x] = t << 16 | t >>> 16; subMix2[x] = t << 8 | t >>> 24; subMix3[x] = t; // Compute inv sub bytes, inv mix columns tables t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100; invSubMix0[sx] = t << 24 | t >>> 8; invSubMix1[sx] = t << 16 | t >>> 16; invSubMix2[sx] = t << 8 | t >>> 24; invSubMix3[sx] = t; // Compute next counter if (!x) { x = xi = 1; } else { x = x2 ^ d[d[d[x8 ^ x2]]]; xi ^= d[d[xi]]; } } }; _proto.expandKey = function expandKey(keyBuffer) { // convert keyBuffer to Uint32Array var key = this.uint8ArrayToUint32Array_(keyBuffer); var sameKey = true; var offset = 0; while (offset < key.length && sameKey) { sameKey = key[offset] === this.key[offset]; offset++; } if (sameKey) { return; } this.key = key; var keySize = this.keySize = key.length; if (keySize !== 4 && keySize !== 6 && keySize !== 8) { throw new Error('Invalid aes key size=' + keySize); } var ksRows = this.ksRows = (keySize + 6 + 1) * 4; var ksRow; var invKsRow; var keySchedule = this.keySchedule = new Uint32Array(ksRows); var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows); var sbox = this.sBox; var rcon = this.rcon; var invSubMix = this.invSubMix; var invSubMix0 = invSubMix[0]; var invSubMix1 = invSubMix[1]; var invSubMix2 = invSubMix[2]; var invSubMix3 = invSubMix[3]; var prev; var t; for (ksRow = 0; ksRow < ksRows; ksRow++) { if (ksRow < keySize) { prev = keySchedule[ksRow] = key[ksRow]; continue; } t = prev; if (ksRow % keySize === 0) { // Rot word t = t << 8 | t >>> 24; // Sub word t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff]; // Mix Rcon t ^= rcon[ksRow / keySize | 0] << 24; } else if (keySize > 6 && ksRow % keySize === 4) { // Sub word t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff]; } keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0; } for (invKsRow = 0; invKsRow < ksRows; invKsRow++) { ksRow = ksRows - invKsRow; if (invKsRow & 3) { t = keySchedule[ksRow]; } else { t = keySchedule[ksRow - 4]; } if (invKsRow < 4 || ksRow <= 4) { invKeySchedule[invKsRow] = t; } else { invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]]; } invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0; } } // Adding this as a method greatly improves performance. ; _proto.networkToHostOrderSwap = function networkToHostOrderSwap(word) { return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24; }; _proto.decrypt = function decrypt(inputArrayBuffer, offset, aesIV) { var nRounds = this.keySize + 6; var invKeySchedule = this.invKeySchedule; var invSBOX = this.invSBox; var invSubMix = this.invSubMix; var invSubMix0 = invSubMix[0]; var invSubMix1 = invSubMix[1]; var invSubMix2 = invSubMix[2]; var invSubMix3 = invSubMix[3]; var initVector = this.uint8ArrayToUint32Array_(aesIV); var initVector0 = initVector[0]; var initVector1 = initVector[1]; var initVector2 = initVector[2]; var initVector3 = initVector[3]; var inputInt32 = new Int32Array(inputArrayBuffer); var outputInt32 = new Int32Array(inputInt32.length); var t0, t1, t2, t3; var s0, s1, s2, s3; var inputWords0, inputWords1, inputWords2, inputWords3; var ksRow, i; var swapWord = this.networkToHostOrderSwap; while (offset < inputInt32.length) { inputWords0 = swapWord(inputInt32[offset]); inputWords1 = swapWord(inputInt32[offset + 1]); inputWords2 = swapWord(inputInt32[offset + 2]); inputWords3 = swapWord(inputInt32[offset + 3]); s0 = inputWords0 ^ invKeySchedule[0]; s1 = inputWords3 ^ invKeySchedule[1]; s2 = inputWords2 ^ invKeySchedule[2]; s3 = inputWords1 ^ invKeySchedule[3]; ksRow = 4; // Iterate through the rounds of decryption for (i = 1; i < nRounds; i++) { t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow]; t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1]; t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2]; t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3]; // Update state s0 = t0; s1 = t1; s2 = t2; s3 = t3; ksRow = ksRow + 4; } // Shift rows, sub bytes, add round key t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow]; t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1]; t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2]; t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3]; // Write outputInt32[offset] = swapWord(t0 ^ initVector0); outputInt32[offset + 1] = swapWord(t3 ^ initVector1); outputInt32[offset + 2] = swapWord(t2 ^ initVector2); outputInt32[offset + 3] = swapWord(t1 ^ initVector3); // reset initVector to last 4 unsigned int initVector0 = inputWords0; initVector1 = inputWords1; initVector2 = inputWords2; initVector3 = inputWords3; offset = offset + 4; } return outputInt32.buffer; }; return AESDecryptor; }(); /***/ }), /***/ "./src/crypt/decrypter.ts": /*!********************************!*\ !*** ./src/crypt/decrypter.ts ***! \********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Decrypter; }); /* harmony import */ var _aes_crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./aes-crypto */ "./src/crypt/aes-crypto.ts"); /* harmony import */ var _fast_aes_key__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./fast-aes-key */ "./src/crypt/fast-aes-key.ts"); /* harmony import */ var _aes_decryptor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./aes-decryptor */ "./src/crypt/aes-decryptor.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts"); /* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/typed-array */ "./src/utils/typed-array.ts"); var CHUNK_SIZE = 16; // 16 bytes, 128 bits var Decrypter = /*#__PURE__*/function () { function Decrypter(observer, config, _temp) { var _ref = _temp === void 0 ? {} : _temp, _ref$removePKCS7Paddi = _ref.removePKCS7Padding, removePKCS7Padding = _ref$removePKCS7Paddi === void 0 ? true : _ref$removePKCS7Paddi; this.logEnabled = true; this.observer = void 0; this.config = void 0; this.removePKCS7Padding = void 0; this.subtle = null; this.softwareDecrypter = null; this.key = null; this.fastAesKey = null; this.remainderData = null; this.currentIV = null; this.currentResult = null; this.observer = observer; this.config = config; this.removePKCS7Padding = removePKCS7Padding; // built in decryptor expects PKCS7 padding if (removePKCS7Padding) { try { var browserCrypto = self.crypto; if (browserCrypto) { this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle; } } catch (e) { /* no-op */ } } if (this.subtle === null) { this.config.enableSoftwareAES = true; } } var _proto = Decrypter.prototype; _proto.destroy = function destroy() { // @ts-ignore this.observer = null; }; _proto.isSync = function isSync() { return this.config.enableSoftwareAES; }; _proto.flush = function flush() { var currentResult = this.currentResult; if (!currentResult) { this.reset(); return; } var data = new Uint8Array(currentResult); this.reset(); if (this.removePKCS7Padding) { return Object(_aes_decryptor__WEBPACK_IMPORTED_MODULE_2__["removePadding"])(data); } return data; }; _proto.reset = function reset() { this.currentResult = null; this.currentIV = null; this.remainderData = null; if (this.softwareDecrypter) { this.softwareDecrypter = null; } }; _proto.decrypt = function decrypt(data, key, iv, callback) { if (this.config.enableSoftwareAES) { this.softwareDecrypt(new Uint8Array(data), key, iv); var decryptResult = this.flush(); if (decryptResult) { callback(decryptResult.buffer); } } else { this.webCryptoDecrypt(new Uint8Array(data), key, iv).then(callback); } }; _proto.softwareDecrypt = function softwareDecrypt(data, key, iv) { var currentIV = this.currentIV, currentResult = this.currentResult, remainderData = this.remainderData; this.logOnce('JS AES decrypt'); // The output is staggered during progressive parsing - the current result is cached, and emitted on the next call // This is done in order to strip PKCS7 padding, which is found at the end of each segment. We only know we've reached // the end on flush(), but by that time we have already received all bytes for the segment. // Progressive decryption does not work with WebCrypto if (remainderData) { data = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__["appendUint8Array"])(remainderData, data); this.remainderData = null; } // Byte length must be a multiple of 16 (AES-128 = 128 bit blocks = 16 bytes) var currentChunk = this.getValidChunk(data); if (!currentChunk.length) { return null; } if (currentIV) { iv = currentIV; } var softwareDecrypter = this.softwareDecrypter; if (!softwareDecrypter) { softwareDecrypter = this.softwareDecrypter = new _aes_decryptor__WEBPACK_IMPORTED_MODULE_2__["default"](); } softwareDecrypter.expandKey(key); var result = currentResult; this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv); this.currentIV = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__["sliceUint8"])(currentChunk, -16).buffer; if (!result) { return null; } return result; }; _proto.webCryptoDecrypt = function webCryptoDecrypt(data, key, iv) { var _this = this; var subtle = this.subtle; if (this.key !== key || !this.fastAesKey) { this.key = key; this.fastAesKey = new _fast_aes_key__WEBPACK_IMPORTED_MODULE_1__["default"](subtle, key); } return this.fastAesKey.expandKey().then(function (aesKey) { // decrypt using web crypto if (!subtle) { return Promise.reject(new Error('web crypto not initialized')); } var crypto = new _aes_crypto__WEBPACK_IMPORTED_MODULE_0__["default"](subtle, iv); return crypto.decrypt(data.buffer, aesKey); }).catch(function (err) { return _this.onWebCryptoError(err, data, key, iv); }); }; _proto.onWebCryptoError = function onWebCryptoError(err, data, key, iv) { _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('[decrypter.ts]: WebCrypto Error, disable WebCrypto API:', err); this.config.enableSoftwareAES = true; this.logEnabled = true; return this.softwareDecrypt(data, key, iv); }; _proto.getValidChunk = function getValidChunk(data) { var currentChunk = data; var splitPoint = data.length - data.length % CHUNK_SIZE; if (splitPoint !== data.length) { currentChunk = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__["sliceUint8"])(data, 0, splitPoint); this.remainderData = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__["sliceUint8"])(data, splitPoint); } return currentChunk; }; _proto.logOnce = function logOnce(msg) { if (!this.logEnabled) { return; } _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log("[decrypter.ts]: " + msg); this.logEnabled = false; }; return Decrypter; }(); /***/ }), /***/ "./src/crypt/fast-aes-key.ts": /*!***********************************!*\ !*** ./src/crypt/fast-aes-key.ts ***! \***********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return FastAESKey; }); var FastAESKey = /*#__PURE__*/function () { function FastAESKey(subtle, key) { this.subtle = void 0; this.key = void 0; this.subtle = subtle; this.key = key; } var _proto = FastAESKey.prototype; _proto.expandKey = function expandKey() { return this.subtle.importKey('raw', this.key, { name: 'AES-CBC' }, false, ['encrypt', 'decrypt']); }; return FastAESKey; }(); /***/ }), /***/ "./src/demux/aacdemuxer.ts": /*!*********************************!*\ !*** ./src/demux/aacdemuxer.ts ***! \*********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base-audio-demuxer */ "./src/demux/base-audio-demuxer.ts"); /* harmony import */ var _adts__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./adts */ "./src/demux/adts.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts"); function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * AAC demuxer */ var AACDemuxer = /*#__PURE__*/function (_BaseAudioDemuxer) { _inheritsLoose(AACDemuxer, _BaseAudioDemuxer); function AACDemuxer(observer, config) { var _this; _this = _BaseAudioDemuxer.call(this) || this; _this.observer = void 0; _this.config = void 0; _this.observer = observer; _this.config = config; return _this; } var _proto = AACDemuxer.prototype; _proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) { _BaseAudioDemuxer.prototype.resetInitSegment.call(this, audioCodec, videoCodec, duration); this._audioTrack = { container: 'audio/adts', type: 'audio', id: 0, pid: -1, sequenceNumber: 0, isAAC: true, samples: [], manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000, dropped: 0 }; } // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS ; AACDemuxer.probe = function probe(data) { if (!data) { return false; } // Check for the ADTS sync word // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1 // Layer bits (position 14 and 15) in header should be always 0 for ADTS // More info https://wiki.multimedia.cx/index.php?title=ADTS var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_3__["getID3Data"](data, 0) || []; var offset = id3Data.length; for (var length = data.length; offset < length; offset++) { if (_adts__WEBPACK_IMPORTED_MODULE_1__["probe"](data, offset)) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('ADTS sync word found !'); return true; } } return false; }; _proto.canParse = function canParse(data, offset) { return _adts__WEBPACK_IMPORTED_MODULE_1__["canParse"](data, offset); }; _proto.appendFrame = function appendFrame(track, data, offset) { _adts__WEBPACK_IMPORTED_MODULE_1__["initTrackConfig"](track, this.observer, data, offset, track.manifestCodec); var frame = _adts__WEBPACK_IMPORTED_MODULE_1__["appendFrame"](track, data, offset, this.initPTS, this.frameIndex); if (frame && frame.missing === 0) { return frame; } }; return AACDemuxer; }(_base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__["default"]); AACDemuxer.minProbeByteLength = 9; /* harmony default export */ __webpack_exports__["default"] = (AACDemuxer); /***/ }), /***/ "./src/demux/adts.ts": /*!***************************!*\ !*** ./src/demux/adts.ts ***! \***************************/ /*! exports provided: getAudioConfig, isHeaderPattern, getHeaderLength, getFullFrameLength, canGetFrameLength, isHeader, canParse, probe, initTrackConfig, getFrameDuration, parseFrameHeader, appendFrame */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getAudioConfig", function() { return getAudioConfig; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeaderPattern", function() { return isHeaderPattern; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getHeaderLength", function() { return getHeaderLength; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFullFrameLength", function() { return getFullFrameLength; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canGetFrameLength", function() { return canGetFrameLength; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeader", function() { return isHeader; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canParse", function() { return canParse; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "probe", function() { return probe; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initTrackConfig", function() { return initTrackConfig; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFrameDuration", function() { return getFrameDuration; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseFrameHeader", function() { return parseFrameHeader; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendFrame", function() { return appendFrame; }); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /** * ADTS parser helper * @link https://wiki.multimedia.cx/index.php?title=ADTS */ function getAudioConfig(observer, data, offset, audioCodec) { var adtsObjectType; var adtsExtensionSamplingIndex; var adtsChanelConfig; var config; var userAgent = navigator.userAgent.toLowerCase(); var manifestCodec = audioCodec; var adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; // byte 2 adtsObjectType = ((data[offset + 2] & 0xc0) >>> 6) + 1; var adtsSamplingIndex = (data[offset + 2] & 0x3c) >>> 2; if (adtsSamplingIndex > adtsSampleingRates.length - 1) { observer.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_PARSING_ERROR, fatal: true, reason: "invalid ADTS sampling index:" + adtsSamplingIndex }); return; } adtsChanelConfig = (data[offset + 2] & 0x01) << 2; // byte 3 adtsChanelConfig |= (data[offset + 3] & 0xc0) >>> 6; _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log("manifest codec:" + audioCodec + ", ADTS type:" + adtsObjectType + ", samplingIndex:" + adtsSamplingIndex); // firefox: freq less than 24kHz = AAC SBR (HE-AAC) if (/firefox/i.test(userAgent)) { if (adtsSamplingIndex >= 6) { adtsObjectType = 5; config = new Array(4); // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies // there is a factor 2 between frame sample rate and output sample rate // multiply frequency by 2 (see table below, equivalent to substract 3) adtsExtensionSamplingIndex = adtsSamplingIndex - 3; } else { adtsObjectType = 2; config = new Array(2); adtsExtensionSamplingIndex = adtsSamplingIndex; } // Android : always use AAC } else if (userAgent.indexOf('android') !== -1) { adtsObjectType = 2; config = new Array(2); adtsExtensionSamplingIndex = adtsSamplingIndex; } else { /* for other browsers (Chrome/Vivaldi/Opera ...) always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...) */ adtsObjectType = 5; config = new Array(4); // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz) if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSamplingIndex >= 6) { // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies // there is a factor 2 between frame sample rate and output sample rate // multiply frequency by 2 (see table below, equivalent to substract 3) adtsExtensionSamplingIndex = adtsSamplingIndex - 3; } else { // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio) // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo. if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && (adtsSamplingIndex >= 6 && adtsChanelConfig === 1 || /vivaldi/i.test(userAgent)) || !audioCodec && adtsChanelConfig === 1) { adtsObjectType = 2; config = new Array(2); } adtsExtensionSamplingIndex = adtsSamplingIndex; } } /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig() Audio Profile / Audio Object Type 0: Null 1: AAC Main 2: AAC LC (Low Complexity) 3: AAC SSR (Scalable Sample Rate) 4: AAC LTP (Long Term Prediction) 5: SBR (Spectral Band Replication) 6: AAC Scalable sampling freq 0: 96000 Hz 1: 88200 Hz 2: 64000 Hz 3: 48000 Hz 4: 44100 Hz 5: 32000 Hz 6: 24000 Hz 7: 22050 Hz 8: 16000 Hz 9: 12000 Hz 10: 11025 Hz 11: 8000 Hz 12: 7350 Hz 13: Reserved 14: Reserved 15: frequency is written explictly Channel Configurations These are the channel configurations: 0: Defined in AOT Specifc Config 1: 1 channel: front-center 2: 2 channels: front-left, front-right */ // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1 config[0] = adtsObjectType << 3; // samplingFrequencyIndex config[0] |= (adtsSamplingIndex & 0x0e) >> 1; config[1] |= (adtsSamplingIndex & 0x01) << 7; // channelConfiguration config[1] |= adtsChanelConfig << 3; if (adtsObjectType === 5) { // adtsExtensionSampleingIndex config[1] |= (adtsExtensionSamplingIndex & 0x0e) >> 1; config[2] = (adtsExtensionSamplingIndex & 0x01) << 7; // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ??? // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc config[2] |= 2 << 2; config[3] = 0; } return { config: config, samplerate: adtsSampleingRates[adtsSamplingIndex], channelCount: adtsChanelConfig, codec: 'mp4a.40.' + adtsObjectType, manifestCodec: manifestCodec }; } function isHeaderPattern(data, offset) { return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0; } function getHeaderLength(data, offset) { return data[offset + 1] & 0x01 ? 7 : 9; } function getFullFrameLength(data, offset) { return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xe0) >>> 5; } function canGetFrameLength(data, offset) { return offset + 5 < data.length; } function isHeader(data, offset) { // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1 // Layer bits (position 14 and 15) in header should be always 0 for ADTS // More info https://wiki.multimedia.cx/index.php?title=ADTS return offset + 1 < data.length && isHeaderPattern(data, offset); } function canParse(data, offset) { return canGetFrameLength(data, offset) && isHeaderPattern(data, offset) && getFullFrameLength(data, offset) <= data.length - offset; } function probe(data, offset) { // same as isHeader but we also check that ADTS frame follows last ADTS frame // or end of data is reached if (isHeader(data, offset)) { // ADTS header Length var headerLength = getHeaderLength(data, offset); if (offset + headerLength >= data.length) { return false; } // ADTS frame Length var frameLength = getFullFrameLength(data, offset); if (frameLength <= headerLength) { return false; } var newOffset = offset + frameLength; return newOffset === data.length || isHeader(data, newOffset); } return false; } function initTrackConfig(track, observer, data, offset, audioCodec) { if (!track.samplerate) { var config = getAudioConfig(observer, data, offset, audioCodec); if (!config) { return; } track.config = config.config; track.samplerate = config.samplerate; track.channelCount = config.channelCount; track.codec = config.codec; track.manifestCodec = config.manifestCodec; _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log("parsed codec:" + track.codec + ", rate:" + config.samplerate + ", channels:" + config.channelCount); } } function getFrameDuration(samplerate) { return 1024 * 90000 / samplerate; } function parseFrameHeader(data, offset, pts, frameIndex, frameDuration) { // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header var headerLength = getHeaderLength(data, offset); // retrieve frame size var frameLength = getFullFrameLength(data, offset); frameLength -= headerLength; if (frameLength > 0) { var stamp = pts + frameIndex * frameDuration; // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`); return { headerLength: headerLength, frameLength: frameLength, stamp: stamp }; } } function appendFrame(track, data, offset, pts, frameIndex) { var frameDuration = getFrameDuration(track.samplerate); var header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration); if (header) { var frameLength = header.frameLength, headerLength = header.headerLength, stamp = header.stamp; var length = headerLength + frameLength; var missing = Math.max(0, offset + length - data.length); // logger.log(`AAC frame ${frameIndex}, pts:${stamp} length@offset/total: ${frameLength}@${offset+headerLength}/${data.byteLength} missing: ${missing}`); var unit; if (missing) { unit = new Uint8Array(length - headerLength); unit.set(data.subarray(offset + headerLength, data.length), 0); } else { unit = data.subarray(offset + headerLength, offset + length); } var sample = { unit: unit, pts: stamp }; if (!missing) { track.samples.push(sample); } return { sample: sample, length: length, missing: missing }; } } /***/ }), /***/ "./src/demux/base-audio-demuxer.ts": /*!*****************************************!*\ !*** ./src/demux/base-audio-demuxer.ts ***! \*****************************************/ /*! exports provided: initPTSFn, default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initPTSFn", function() { return initPTSFn; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts"); /* harmony import */ var _dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./dummy-demuxed-track */ "./src/demux/dummy-demuxed-track.ts"); /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts"); /* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/typed-array */ "./src/utils/typed-array.ts"); var BaseAudioDemuxer = /*#__PURE__*/function () { function BaseAudioDemuxer() { this._audioTrack = void 0; this._id3Track = void 0; this.frameIndex = 0; this.cachedData = null; this.initPTS = null; } var _proto = BaseAudioDemuxer.prototype; _proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) { this._id3Track = { type: 'id3', id: 0, pid: -1, inputTimeScale: 90000, sequenceNumber: 0, samples: [], dropped: 0 }; }; _proto.resetTimeStamp = function resetTimeStamp() {}; _proto.resetContiguity = function resetContiguity() {}; _proto.canParse = function canParse(data, offset) { return false; }; _proto.appendFrame = function appendFrame(track, data, offset) {} // feed incoming data to the front of the parsing pipeline ; _proto.demux = function demux(data, timeOffset) { if (this.cachedData) { data = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_3__["appendUint8Array"])(this.cachedData, data); this.cachedData = null; } var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getID3Data"](data, 0); var offset = id3Data ? id3Data.length : 0; var lastDataIndex; var pts; var track = this._audioTrack; var id3Track = this._id3Track; var timestamp = id3Data ? _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getTimeStamp"](id3Data) : undefined; var length = data.length; if (this.frameIndex === 0 || this.initPTS === null) { this.initPTS = initPTSFn(timestamp, timeOffset); } // more expressive than alternative: id3Data?.length if (id3Data && id3Data.length > 0) { id3Track.samples.push({ pts: this.initPTS, dts: this.initPTS, data: id3Data }); } pts = this.initPTS; while (offset < length) { if (this.canParse(data, offset)) { var frame = this.appendFrame(track, data, offset); if (frame) { this.frameIndex++; pts = frame.sample.pts; offset += frame.length; lastDataIndex = offset; } else { offset = length; } } else if (_demux_id3__WEBPACK_IMPORTED_MODULE_1__["canParse"](data, offset)) { // after a ID3.canParse, a call to ID3.getID3Data *should* always returns some data id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getID3Data"](data, offset); id3Track.samples.push({ pts: pts, dts: pts, data: id3Data }); offset += id3Data.length; lastDataIndex = offset; } else { offset++; } if (offset === length && lastDataIndex !== length) { var partialData = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_4__["sliceUint8"])(data, lastDataIndex); if (this.cachedData) { this.cachedData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_3__["appendUint8Array"])(this.cachedData, partialData); } else { this.cachedData = partialData; } } } return { audioTrack: track, avcTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])(), id3Track: id3Track, textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])() }; }; _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) { return Promise.reject(new Error("[" + this + "] This demuxer does not support Sample-AES decryption")); }; _proto.flush = function flush(timeOffset) { // Parse cache in case of remaining frames. var cachedData = this.cachedData; if (cachedData) { this.cachedData = null; this.demux(cachedData, 0); } this.frameIndex = 0; return { audioTrack: this._audioTrack, avcTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])(), id3Track: this._id3Track, textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])() }; }; _proto.destroy = function destroy() {}; return BaseAudioDemuxer; }(); /** * Initialize PTS * <p> * use timestamp unless it is undefined, NaN or Infinity * </p> */ var initPTSFn = function initPTSFn(timestamp, timeOffset) { return Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(timestamp) ? timestamp * 90 : timeOffset * 90000; }; /* harmony default export */ __webpack_exports__["default"] = (BaseAudioDemuxer); /***/ }), /***/ "./src/demux/chunk-cache.ts": /*!**********************************!*\ !*** ./src/demux/chunk-cache.ts ***! \**********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ChunkCache; }); var ChunkCache = /*#__PURE__*/function () { function ChunkCache() { this.chunks = []; this.dataLength = 0; } var _proto = ChunkCache.prototype; _proto.push = function push(chunk) { this.chunks.push(chunk); this.dataLength += chunk.length; }; _proto.flush = function flush() { var chunks = this.chunks, dataLength = this.dataLength; var result; if (!chunks.length) { return new Uint8Array(0); } else if (chunks.length === 1) { result = chunks[0]; } else { result = concatUint8Arrays(chunks, dataLength); } this.reset(); return result; }; _proto.reset = function reset() { this.chunks.length = 0; this.dataLength = 0; }; return ChunkCache; }(); function concatUint8Arrays(chunks, dataLength) { var result = new Uint8Array(dataLength); var offset = 0; for (var i = 0; i < chunks.length; i++) { var chunk = chunks[i]; result.set(chunk, offset); offset += chunk.length; } return result; } /***/ }), /***/ "./src/demux/dummy-demuxed-track.ts": /*!******************************************!*\ !*** ./src/demux/dummy-demuxed-track.ts ***! \******************************************/ /*! exports provided: dummyTrack */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dummyTrack", function() { return dummyTrack; }); function dummyTrack() { return { type: '', id: -1, pid: -1, inputTimeScale: 90000, sequenceNumber: -1, samples: [], dropped: 0 }; } /***/ }), /***/ "./src/demux/exp-golomb.ts": /*!*********************************!*\ !*** ./src/demux/exp-golomb.ts ***! \*********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /** * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264. */ var ExpGolomb = /*#__PURE__*/function () { function ExpGolomb(data) { this.data = void 0; this.bytesAvailable = void 0; this.word = void 0; this.bitsAvailable = void 0; this.data = data; // the number of bytes left to examine in this.data this.bytesAvailable = data.byteLength; // the current word being examined this.word = 0; // :uint // the number of bits left to examine in the current word this.bitsAvailable = 0; // :uint } // ():void var _proto = ExpGolomb.prototype; _proto.loadWord = function loadWord() { var data = this.data; var bytesAvailable = this.bytesAvailable; var position = data.byteLength - bytesAvailable; var workingBytes = new Uint8Array(4); var availableBytes = Math.min(4, bytesAvailable); if (availableBytes === 0) { throw new Error('no bytes available'); } workingBytes.set(data.subarray(position, position + availableBytes)); this.word = new DataView(workingBytes.buffer).getUint32(0); // track the amount of this.data that has been processed this.bitsAvailable = availableBytes * 8; this.bytesAvailable -= availableBytes; } // (count:int):void ; _proto.skipBits = function skipBits(count) { var skipBytes; // :int if (this.bitsAvailable > count) { this.word <<= count; this.bitsAvailable -= count; } else { count -= this.bitsAvailable; skipBytes = count >> 3; count -= skipBytes >> 3; this.bytesAvailable -= skipBytes; this.loadWord(); this.word <<= count; this.bitsAvailable -= count; } } // (size:int):uint ; _proto.readBits = function readBits(size) { var bits = Math.min(this.bitsAvailable, size); // :uint var valu = this.word >>> 32 - bits; // :uint if (size > 32) { _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].error('Cannot read more than 32 bits at a time'); } this.bitsAvailable -= bits; if (this.bitsAvailable > 0) { this.word <<= bits; } else if (this.bytesAvailable > 0) { this.loadWord(); } bits = size - bits; if (bits > 0 && this.bitsAvailable) { return valu << bits | this.readBits(bits); } else { return valu; } } // ():uint ; _proto.skipLZ = function skipLZ() { var leadingZeroCount; // :uint for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) { if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) { // the first bit of working word is 1 this.word <<= leadingZeroCount; this.bitsAvailable -= leadingZeroCount; return leadingZeroCount; } } // we exhausted word and still have not found a 1 this.loadWord(); return leadingZeroCount + this.skipLZ(); } // ():void ; _proto.skipUEG = function skipUEG() { this.skipBits(1 + this.skipLZ()); } // ():void ; _proto.skipEG = function skipEG() { this.skipBits(1 + this.skipLZ()); } // ():uint ; _proto.readUEG = function readUEG() { var clz = this.skipLZ(); // :uint return this.readBits(clz + 1) - 1; } // ():int ; _proto.readEG = function readEG() { var valu = this.readUEG(); // :int if (0x01 & valu) { // the number is odd if the low order bit is set return 1 + valu >>> 1; // add 1 to make it even, and divide by 2 } else { return -1 * (valu >>> 1); // divide by two then make it negative } } // Some convenience functions // :Boolean ; _proto.readBoolean = function readBoolean() { return this.readBits(1) === 1; } // ():int ; _proto.readUByte = function readUByte() { return this.readBits(8); } // ():int ; _proto.readUShort = function readUShort() { return this.readBits(16); } // ():int ; _proto.readUInt = function readUInt() { return this.readBits(32); } /** * Advance the ExpGolomb decoder past a scaling list. The scaling * list is optionally transmitted as part of a sequence parameter * set and is not relevant to transmuxing. * @param count the number of entries in this scaling list * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1 */ ; _proto.skipScalingList = function skipScalingList(count) { var lastScale = 8; var nextScale = 8; var deltaScale; for (var j = 0; j < count; j++) { if (nextScale !== 0) { deltaScale = this.readEG(); nextScale = (lastScale + deltaScale + 256) % 256; } lastScale = nextScale === 0 ? lastScale : nextScale; } } /** * Read a sequence parameter set and return some interesting video * properties. A sequence parameter set is the H264 metadata that * describes the properties of upcoming video frames. * @param data {Uint8Array} the bytes of a sequence parameter set * @return {object} an object with configuration parsed from the * sequence parameter set, including the dimensions of the * associated video frames. */ ; _proto.readSPS = function readSPS() { var frameCropLeftOffset = 0; var frameCropRightOffset = 0; var frameCropTopOffset = 0; var frameCropBottomOffset = 0; var numRefFramesInPicOrderCntCycle; var scalingListCount; var i; var readUByte = this.readUByte.bind(this); var readBits = this.readBits.bind(this); var readUEG = this.readUEG.bind(this); var readBoolean = this.readBoolean.bind(this); var skipBits = this.skipBits.bind(this); var skipEG = this.skipEG.bind(this); var skipUEG = this.skipUEG.bind(this); var skipScalingList = this.skipScalingList.bind(this); readUByte(); var profileIdc = readUByte(); // profile_idc readBits(5); // profileCompat constraint_set[0-4]_flag, u(5) skipBits(3); // reserved_zero_3bits u(3), readUByte(); // level_idc u(8) skipUEG(); // seq_parameter_set_id // some profiles have more optional data we don't need if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) { var chromaFormatIdc = readUEG(); if (chromaFormatIdc === 3) { skipBits(1); } // separate_colour_plane_flag skipUEG(); // bit_depth_luma_minus8 skipUEG(); // bit_depth_chroma_minus8 skipBits(1); // qpprime_y_zero_transform_bypass_flag if (readBoolean()) { // seq_scaling_matrix_present_flag scalingListCount = chromaFormatIdc !== 3 ? 8 : 12; for (i = 0; i < scalingListCount; i++) { if (readBoolean()) { // seq_scaling_list_present_flag[ i ] if (i < 6) { skipScalingList(16); } else { skipScalingList(64); } } } } } skipUEG(); // log2_max_frame_num_minus4 var picOrderCntType = readUEG(); if (picOrderCntType === 0) { readUEG(); // log2_max_pic_order_cnt_lsb_minus4 } else if (picOrderCntType === 1) { skipBits(1); // delta_pic_order_always_zero_flag skipEG(); // offset_for_non_ref_pic skipEG(); // offset_for_top_to_bottom_field numRefFramesInPicOrderCntCycle = readUEG(); for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) { skipEG(); } // offset_for_ref_frame[ i ] } skipUEG(); // max_num_ref_frames skipBits(1); // gaps_in_frame_num_value_allowed_flag var picWidthInMbsMinus1 = readUEG(); var picHeightInMapUnitsMinus1 = readUEG(); var frameMbsOnlyFlag = readBits(1); if (frameMbsOnlyFlag === 0) { skipBits(1); } // mb_adaptive_frame_field_flag skipBits(1); // direct_8x8_inference_flag if (readBoolean()) { // frame_cropping_flag frameCropLeftOffset = readUEG(); frameCropRightOffset = readUEG(); frameCropTopOffset = readUEG(); frameCropBottomOffset = readUEG(); } var pixelRatio = [1, 1]; if (readBoolean()) { // vui_parameters_present_flag if (readBoolean()) { // aspect_ratio_info_present_flag var aspectRatioIdc = readUByte(); switch (aspectRatioIdc) { case 1: pixelRatio = [1, 1]; break; case 2: pixelRatio = [12, 11]; break; case 3: pixelRatio = [10, 11]; break; case 4: pixelRatio = [16, 11]; break; case 5: pixelRatio = [40, 33]; break; case 6: pixelRatio = [24, 11]; break; case 7: pixelRatio = [20, 11]; break; case 8: pixelRatio = [32, 11]; break; case 9: pixelRatio = [80, 33]; break; case 10: pixelRatio = [18, 11]; break; case 11: pixelRatio = [15, 11]; break; case 12: pixelRatio = [64, 33]; break; case 13: pixelRatio = [160, 99]; break; case 14: pixelRatio = [4, 3]; break; case 15: pixelRatio = [3, 2]; break; case 16: pixelRatio = [2, 1]; break; case 255: { pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()]; break; } } } } return { width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2), height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset), pixelRatio: pixelRatio }; }; _proto.readSliceType = function readSliceType() { // skip NALu type this.readUByte(); // discard first_mb_in_slice this.readUEG(); // return slice_type return this.readUEG(); }; return ExpGolomb; }(); /* harmony default export */ __webpack_exports__["default"] = (ExpGolomb); /***/ }), /***/ "./src/demux/id3.ts": /*!**************************!*\ !*** ./src/demux/id3.ts ***! \**************************/ /*! exports provided: isHeader, isFooter, getID3Data, canParse, getTimeStamp, isTimeStampFrame, getID3Frames, decodeFrame, utf8ArrayToStr, testables */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeader", function() { return isHeader; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFooter", function() { return isFooter; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getID3Data", function() { return getID3Data; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canParse", function() { return canParse; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getTimeStamp", function() { return getTimeStamp; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isTimeStampFrame", function() { return isTimeStampFrame; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getID3Frames", function() { return getID3Frames; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "decodeFrame", function() { return decodeFrame; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "utf8ArrayToStr", function() { return utf8ArrayToStr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "testables", function() { return testables; }); // breaking up those two types in order to clarify what is happening in the decoding path. /** * Returns true if an ID3 header can be found at offset in data * @param {Uint8Array} data - The data to search in * @param {number} offset - The offset at which to start searching * @return {boolean} - True if an ID3 header is found */ var isHeader = function isHeader(data, offset) { /* * http://id3.org/id3v2.3.0 * [0] = 'I' * [1] = 'D' * [2] = '3' * [3,4] = {Version} * [5] = {Flags} * [6-9] = {ID3 Size} * * An ID3v2 tag can be detected with the following pattern: * $49 44 33 yy yy xx zz zz zz zz * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80 */ if (offset + 10 <= data.length) { // look for 'ID3' identifier if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) { // check version is within range if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) { // check size is within range if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) { return true; } } } } return false; }; /** * Returns true if an ID3 footer can be found at offset in data * @param {Uint8Array} data - The data to search in * @param {number} offset - The offset at which to start searching * @return {boolean} - True if an ID3 footer is found */ var isFooter = function isFooter(data, offset) { /* * The footer is a copy of the header, but with a different identifier */ if (offset + 10 <= data.length) { // look for '3DI' identifier if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) { // check version is within range if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) { // check size is within range if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) { return true; } } } } return false; }; /** * Returns any adjacent ID3 tags found in data starting at offset, as one block of data * @param {Uint8Array} data - The data to search in * @param {number} offset - The offset at which to start searching * @return {Uint8Array | undefined} - The block of data containing any ID3 tags found * or *undefined* if no header is found at the starting offset */ var getID3Data = function getID3Data(data, offset) { var front = offset; var length = 0; while (isHeader(data, offset)) { // ID3 header is 10 bytes length += 10; var size = readSize(data, offset + 6); length += size; if (isFooter(data, offset + 10)) { // ID3 footer is 10 bytes length += 10; } offset += length; } if (length > 0) { return data.subarray(front, front + length); } return undefined; }; var readSize = function readSize(data, offset) { var size = 0; size = (data[offset] & 0x7f) << 21; size |= (data[offset + 1] & 0x7f) << 14; size |= (data[offset + 2] & 0x7f) << 7; size |= data[offset + 3] & 0x7f; return size; }; var canParse = function canParse(data, offset) { return isHeader(data, offset) && readSize(data, offset + 6) + 10 <= data.length - offset; }; /** * Searches for the Elementary Stream timestamp found in the ID3 data chunk * @param {Uint8Array} data - Block of data containing one or more ID3 tags * @return {number | undefined} - The timestamp */ var getTimeStamp = function getTimeStamp(data) { var frames = getID3Frames(data); for (var i = 0; i < frames.length; i++) { var frame = frames[i]; if (isTimeStampFrame(frame)) { return readTimeStamp(frame); } } return undefined; }; /** * Returns true if the ID3 frame is an Elementary Stream timestamp frame * @param {ID3 frame} frame */ var isTimeStampFrame = function isTimeStampFrame(frame) { return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp'; }; var getFrameData = function getFrameData(data) { /* Frame ID $xx xx xx xx (four characters) Size $xx xx xx xx Flags $xx xx */ var type = String.fromCharCode(data[0], data[1], data[2], data[3]); var size = readSize(data, 4); // skip frame id, size, and flags var offset = 10; return { type: type, size: size, data: data.subarray(offset, offset + size) }; }; /** * Returns an array of ID3 frames found in all the ID3 tags in the id3Data * @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags * @return {ID3.Frame[]} - Array of ID3 frame objects */ var getID3Frames = function getID3Frames(id3Data) { var offset = 0; var frames = []; while (isHeader(id3Data, offset)) { var size = readSize(id3Data, offset + 6); // skip past ID3 header offset += 10; var end = offset + size; // loop through frames in the ID3 tag while (offset + 8 < end) { var frameData = getFrameData(id3Data.subarray(offset)); var frame = decodeFrame(frameData); if (frame) { frames.push(frame); } // skip frame header and frame data offset += frameData.size + 10; } if (isFooter(id3Data, offset)) { offset += 10; } } return frames; }; var decodeFrame = function decodeFrame(frame) { if (frame.type === 'PRIV') { return decodePrivFrame(frame); } else if (frame.type[0] === 'W') { return decodeURLFrame(frame); } return decodeTextFrame(frame); }; var decodePrivFrame = function decodePrivFrame(frame) { /* Format: <text string>\0<binary data> */ if (frame.size < 2) { return undefined; } var owner = utf8ArrayToStr(frame.data, true); var privateData = new Uint8Array(frame.data.subarray(owner.length + 1)); return { key: frame.type, info: owner, data: privateData.buffer }; }; var decodeTextFrame = function decodeTextFrame(frame) { if (frame.size < 2) { return undefined; } if (frame.type === 'TXXX') { /* Format: [0] = {Text Encoding} [1-?] = {Description}\0{Value} */ var index = 1; var description = utf8ArrayToStr(frame.data.subarray(index), true); index += description.length + 1; var value = utf8ArrayToStr(frame.data.subarray(index)); return { key: frame.type, info: description, data: value }; } /* Format: [0] = {Text Encoding} [1-?] = {Value} */ var text = utf8ArrayToStr(frame.data.subarray(1)); return { key: frame.type, data: text }; }; var decodeURLFrame = function decodeURLFrame(frame) { if (frame.type === 'WXXX') { /* Format: [0] = {Text Encoding} [1-?] = {Description}\0{URL} */ if (frame.size < 2) { return undefined; } var index = 1; var description = utf8ArrayToStr(frame.data.subarray(index), true); index += description.length + 1; var value = utf8ArrayToStr(frame.data.subarray(index)); return { key: frame.type, info: description, data: value }; } /* Format: [0-?] = {URL} */ var url = utf8ArrayToStr(frame.data); return { key: frame.type, data: url }; }; var readTimeStamp = function readTimeStamp(timeStampFrame) { if (timeStampFrame.data.byteLength === 8) { var data = new Uint8Array(timeStampFrame.data); // timestamp is 33 bit expressed as a big-endian eight-octet number, // with the upper 31 bits set to zero. var pts33Bit = data[3] & 0x1; var timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7]; timestamp /= 45; if (pts33Bit) { timestamp += 47721858.84; } // 2^32 / 90 return Math.round(timestamp); } return undefined; }; // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197 // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt /* utf.js - UTF-8 <=> UTF-16 convertion * * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp> * Version: 1.0 * LastModified: Dec 25 1999 * This library is free. You can redistribute it and/or modify it. */ var utf8ArrayToStr = function utf8ArrayToStr(array, exitOnNull) { if (exitOnNull === void 0) { exitOnNull = false; } var decoder = getTextDecoder(); if (decoder) { var decoded = decoder.decode(array); if (exitOnNull) { // grab up to the first null var idx = decoded.indexOf('\0'); return idx !== -1 ? decoded.substring(0, idx) : decoded; } // remove any null characters return decoded.replace(/\0/g, ''); } var len = array.length; var c; var char2; var char3; var out = ''; var i = 0; while (i < len) { c = array[i++]; if (c === 0x00 && exitOnNull) { return out; } else if (c === 0x00 || c === 0x03) { // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it continue; } switch (c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: // 0xxxxxxx out += String.fromCharCode(c); break; case 12: case 13: // 110x xxxx 10xx xxxx char2 = array[i++]; out += String.fromCharCode((c & 0x1f) << 6 | char2 & 0x3f); break; case 14: // 1110 xxxx 10xx xxxx 10xx xxxx char2 = array[i++]; char3 = array[i++]; out += String.fromCharCode((c & 0x0f) << 12 | (char2 & 0x3f) << 6 | (char3 & 0x3f) << 0); break; default: } } return out; }; var testables = { decodeTextFrame: decodeTextFrame }; var decoder; function getTextDecoder() { if (!decoder && typeof self.TextDecoder !== 'undefined') { decoder = new self.TextDecoder('utf-8'); } return decoder; } /***/ }), /***/ "./src/demux/mp3demuxer.ts": /*!*********************************!*\ !*** ./src/demux/mp3demuxer.ts ***! \*********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base-audio-demuxer */ "./src/demux/base-audio-demuxer.ts"); /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _mpegaudio__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./mpegaudio */ "./src/demux/mpegaudio.ts"); function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * MP3 demuxer */ var MP3Demuxer = /*#__PURE__*/function (_BaseAudioDemuxer) { _inheritsLoose(MP3Demuxer, _BaseAudioDemuxer); function MP3Demuxer() { return _BaseAudioDemuxer.apply(this, arguments) || this; } var _proto = MP3Demuxer.prototype; _proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) { _BaseAudioDemuxer.prototype.resetInitSegment.call(this, audioCodec, videoCodec, duration); this._audioTrack = { container: 'audio/mpeg', type: 'audio', id: 0, pid: -1, sequenceNumber: 0, isAAC: false, samples: [], manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000, dropped: 0 }; }; MP3Demuxer.probe = function probe(data) { if (!data) { return false; } // check if data contains ID3 timestamp and MPEG sync word // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1 // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III) // More info http://www.mp3-tech.org/programmer/frame_header.html var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getID3Data"](data, 0) || []; var offset = id3Data.length; for (var length = data.length; offset < length; offset++) { if (_mpegaudio__WEBPACK_IMPORTED_MODULE_3__["probe"](data, offset)) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('MPEG Audio sync word found !'); return true; } } return false; }; _proto.canParse = function canParse(data, offset) { return _mpegaudio__WEBPACK_IMPORTED_MODULE_3__["canParse"](data, offset); }; _proto.appendFrame = function appendFrame(track, data, offset) { if (this.initPTS === null) { return; } return _mpegaudio__WEBPACK_IMPORTED_MODULE_3__["appendFrame"](track, data, offset, this.initPTS, this.frameIndex); }; return MP3Demuxer; }(_base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__["default"]); MP3Demuxer.minProbeByteLength = 4; /* harmony default export */ __webpack_exports__["default"] = (MP3Demuxer); /***/ }), /***/ "./src/demux/mp4demuxer.ts": /*!*********************************!*\ !*** ./src/demux/mp4demuxer.ts ***! \*********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts"); /* harmony import */ var _dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./dummy-demuxed-track */ "./src/demux/dummy-demuxed-track.ts"); /** * MP4 demuxer */ var MP4Demuxer = /*#__PURE__*/function () { function MP4Demuxer(observer, config) { this.remainderData = null; this.config = void 0; this.config = config; } var _proto = MP4Demuxer.prototype; _proto.resetTimeStamp = function resetTimeStamp() {}; _proto.resetInitSegment = function resetInitSegment() {}; _proto.resetContiguity = function resetContiguity() {}; MP4Demuxer.probe = function probe(data) { // ensure we find a moof box in the first 16 kB return Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["findBox"])({ data: data, start: 0, end: Math.min(data.length, 16384) }, ['moof']).length > 0; }; _proto.demux = function demux(data) { // Load all data into the avc track. The CMAF remuxer will look for the data in the samples object; the rest of the fields do not matter var avcSamples = data; var avcTrack = Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(); if (this.config.progressive) { // Split the bytestream into two ranges: one encompassing all data up until the start of the last moof, and everything else. // This is done to guarantee that we're sending valid data to MSE - when demuxing progressively, we have no guarantee // that the fetch loader gives us flush moof+mdat pairs. If we push jagged data to MSE, it will throw an exception. if (this.remainderData) { avcSamples = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["appendUint8Array"])(this.remainderData, data); } var segmentedData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["segmentValidRange"])(avcSamples); this.remainderData = segmentedData.remainder; avcTrack.samples = segmentedData.valid || new Uint8Array(); } else { avcTrack.samples = avcSamples; } return { audioTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(), avcTrack: avcTrack, id3Track: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(), textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])() }; }; _proto.flush = function flush() { var avcTrack = Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(); avcTrack.samples = this.remainderData || new Uint8Array(); this.remainderData = null; return { audioTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(), avcTrack: avcTrack, id3Track: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(), textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])() }; }; _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) { return Promise.reject(new Error('The MP4 demuxer does not support SAMPLE-AES decryption')); }; _proto.destroy = function destroy() {}; return MP4Demuxer; }(); MP4Demuxer.minProbeByteLength = 1024; /* harmony default export */ __webpack_exports__["default"] = (MP4Demuxer); /***/ }), /***/ "./src/demux/mpegaudio.ts": /*!********************************!*\ !*** ./src/demux/mpegaudio.ts ***! \********************************/ /*! exports provided: appendFrame, parseHeader, isHeaderPattern, isHeader, canParse, probe */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendFrame", function() { return appendFrame; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseHeader", function() { return parseHeader; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeaderPattern", function() { return isHeaderPattern; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeader", function() { return isHeader; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canParse", function() { return canParse; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "probe", function() { return probe; }); /** * MPEG parser helper */ var chromeVersion = null; var BitratesMap = [32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160]; var SamplingRateMap = [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000]; var SamplesCoefficients = [// MPEG 2.5 [0, // Reserved 72, // Layer3 144, // Layer2 12 // Layer1 ], // Reserved [0, // Reserved 0, // Layer3 0, // Layer2 0 // Layer1 ], // MPEG 2 [0, // Reserved 72, // Layer3 144, // Layer2 12 // Layer1 ], // MPEG 1 [0, // Reserved 144, // Layer3 144, // Layer2 12 // Layer1 ]]; var BytesInSlot = [0, // Reserved 1, // Layer3 1, // Layer2 4 // Layer1 ]; function appendFrame(track, data, offset, pts, frameIndex) { // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference if (offset + 24 > data.length) { return; } var header = parseHeader(data, offset); if (header && offset + header.frameLength <= data.length) { var frameDuration = header.samplesPerFrame * 90000 / header.sampleRate; var stamp = pts + frameIndex * frameDuration; var sample = { unit: data.subarray(offset, offset + header.frameLength), pts: stamp, dts: stamp }; track.config = []; track.channelCount = header.channelCount; track.samplerate = header.sampleRate; track.samples.push(sample); return { sample: sample, length: header.frameLength, missing: 0 }; } } function parseHeader(data, offset) { var mpegVersion = data[offset + 1] >> 3 & 3; var mpegLayer = data[offset + 1] >> 1 & 3; var bitRateIndex = data[offset + 2] >> 4 & 15; var sampleRateIndex = data[offset + 2] >> 2 & 3; if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) { var paddingBit = data[offset + 2] >> 1 & 1; var channelMode = data[offset + 3] >> 6; var columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4; var bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1000; var columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2; var sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex]; var channelCount = channelMode === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono) var sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer]; var bytesInSlot = BytesInSlot[mpegLayer]; var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot; var frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot; if (chromeVersion === null) { var userAgent = navigator.userAgent || ''; var result = userAgent.match(/Chrome\/(\d+)/i); chromeVersion = result ? parseInt(result[1]) : 0; } var needChromeFix = !!chromeVersion && chromeVersion <= 87; if (needChromeFix && mpegLayer === 2 && bitRate >= 224000 && channelMode === 0) { // Work around bug in Chromium by setting channelMode to dual-channel (01) instead of stereo (00) data[offset + 3] = data[offset + 3] | 0x80; } return { sampleRate: sampleRate, channelCount: channelCount, frameLength: frameLength, samplesPerFrame: samplesPerFrame }; } } function isHeaderPattern(data, offset) { return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00; } function isHeader(data, offset) { // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1 // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III) // More info http://www.mp3-tech.org/programmer/frame_header.html return offset + 1 < data.length && isHeaderPattern(data, offset); } function canParse(data, offset) { var headerSize = 4; return isHeaderPattern(data, offset) && headerSize <= data.length - offset; } function probe(data, offset) { // same as isHeader but we also check that MPEG frame follows last MPEG frame // or end of data is reached if (offset + 1 < data.length && isHeaderPattern(data, offset)) { // MPEG header Length var headerLength = 4; // MPEG frame Length var header = parseHeader(data, offset); var frameLength = headerLength; if (header !== null && header !== void 0 && header.frameLength) { frameLength = header.frameLength; } var newOffset = offset + frameLength; return newOffset === data.length || isHeader(data, newOffset); } return false; } /***/ }), /***/ "./src/demux/sample-aes.ts": /*!*********************************!*\ !*** ./src/demux/sample-aes.ts ***! \*********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.ts"); /* harmony import */ var _tsdemuxer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./tsdemuxer */ "./src/demux/tsdemuxer.ts"); /** * SAMPLE-AES decrypter */ var SampleAesDecrypter = /*#__PURE__*/function () { function SampleAesDecrypter(observer, config, keyData) { this.keyData = void 0; this.decrypter = void 0; this.keyData = keyData; this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_0__["default"](observer, config, { removePKCS7Padding: false }); } var _proto = SampleAesDecrypter.prototype; _proto.decryptBuffer = function decryptBuffer(encryptedData, callback) { this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer, callback); } // AAC - encrypt all full 16 bytes blocks starting from offset 16 ; _proto.decryptAacSample = function decryptAacSample(samples, sampleIndex, callback, sync) { var curUnit = samples[sampleIndex].unit; var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16); var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length); var localthis = this; this.decryptBuffer(encryptedBuffer, function (decryptedBuffer) { var decryptedData = new Uint8Array(decryptedBuffer); curUnit.set(decryptedData, 16); if (!sync) { localthis.decryptAacSamples(samples, sampleIndex + 1, callback); } }); }; _proto.decryptAacSamples = function decryptAacSamples(samples, sampleIndex, callback) { for (;; sampleIndex++) { if (sampleIndex >= samples.length) { callback(); return; } if (samples[sampleIndex].unit.length < 32) { continue; } var sync = this.decrypter.isSync(); this.decryptAacSample(samples, sampleIndex, callback, sync); if (!sync) { return; } } } // AVC - encrypt one 16 bytes block out of ten, starting from offset 32 ; _proto.getAvcEncryptedData = function getAvcEncryptedData(decodedData) { var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16; var encryptedData = new Int8Array(encryptedDataLen); var outputPos = 0; for (var inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) { encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos); } return encryptedData; }; _proto.getAvcDecryptedUnit = function getAvcDecryptedUnit(decodedData, decryptedData) { var uint8DecryptedData = new Uint8Array(decryptedData); var inputPos = 0; for (var outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) { decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos); } return decodedData; }; _proto.decryptAvcSample = function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync) { var decodedData = Object(_tsdemuxer__WEBPACK_IMPORTED_MODULE_1__["discardEPB"])(curUnit.data); var encryptedData = this.getAvcEncryptedData(decodedData); var localthis = this; this.decryptBuffer(encryptedData.buffer, function (decryptedBuffer) { curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedBuffer); if (!sync) { localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback); } }); }; _proto.decryptAvcSamples = function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) { if (samples instanceof Uint8Array) { throw new Error('Cannot decrypt samples of type Uint8Array'); } for (;; sampleIndex++, unitIndex = 0) { if (sampleIndex >= samples.length) { callback(); return; } var curUnits = samples[sampleIndex].units; for (;; unitIndex++) { if (unitIndex >= curUnits.length) { break; } var curUnit = curUnits[unitIndex]; if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) { continue; } var sync = this.decrypter.isSync(); this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync); if (!sync) { return; } } } }; return SampleAesDecrypter; }(); /* harmony default export */ __webpack_exports__["default"] = (SampleAesDecrypter); /***/ }), /***/ "./src/demux/transmuxer-interface.ts": /*!*******************************************!*\ !*** ./src/demux/transmuxer-interface.ts ***! \*******************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TransmuxerInterface; }); /* harmony import */ var webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! webworkify-webpack */ "./node_modules/webworkify-webpack/index.js"); /* harmony import */ var webworkify_webpack__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/transmuxer */ "./src/demux/transmuxer.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/mediasource-helper */ "./src/utils/mediasource-helper.ts"); /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js"); /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_6__); var MediaSource = Object(_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__["getMediaSource"])() || { isTypeSupported: function isTypeSupported() { return false; } }; var TransmuxerInterface = /*#__PURE__*/function () { function TransmuxerInterface(hls, id, onTransmuxComplete, onFlush) { var _this = this; this.hls = void 0; this.id = void 0; this.observer = void 0; this.frag = null; this.part = null; this.worker = void 0; this.onwmsg = void 0; this.transmuxer = null; this.onTransmuxComplete = void 0; this.onFlush = void 0; this.hls = hls; this.id = id; this.onTransmuxComplete = onTransmuxComplete; this.onFlush = onFlush; var config = hls.config; var forwardMessage = function forwardMessage(ev, data) { data = data || {}; data.frag = _this.frag; data.id = _this.id; hls.trigger(ev, data); }; // forward events to main thread this.observer = new eventemitter3__WEBPACK_IMPORTED_MODULE_6__["EventEmitter"](); this.observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_DECRYPTED, forwardMessage); this.observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, forwardMessage); var typeSupported = { mp4: MediaSource.isTypeSupported('video/mp4'), mpeg: MediaSource.isTypeSupported('audio/mpeg'), mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"') }; // navigator.vendor is not always available in Web Worker // refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator var vendor = navigator.vendor; if (config.enableWorker && typeof Worker !== 'undefined') { _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log('demuxing in webworker'); var worker; try { worker = this.worker = webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__(/*require.resolve*/(/*! ../demux/transmuxer-worker.ts */ "./src/demux/transmuxer-worker.ts")); this.onwmsg = this.onWorkerMessage.bind(this); worker.addEventListener('message', this.onwmsg); worker.onerror = function (event) { hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].OTHER_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].INTERNAL_EXCEPTION, fatal: true, event: 'demuxerWorker', error: new Error(event.message + " (" + event.filename + ":" + event.lineno + ")") }); }; worker.postMessage({ cmd: 'init', typeSupported: typeSupported, vendor: vendor, id: id, config: JSON.stringify(config) }); } catch (err) { _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Error in worker:', err); _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].error('Error while initializing DemuxerWorker, fallback to inline'); if (worker) { // revoke the Object URL that was used to create transmuxer worker, so as not to leak it self.URL.revokeObjectURL(worker.objectURL); } this.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["default"](this.observer, typeSupported, config, vendor, id); this.worker = null; } } else { this.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["default"](this.observer, typeSupported, config, vendor, id); } } var _proto = TransmuxerInterface.prototype; _proto.destroy = function destroy() { var w = this.worker; if (w) { w.removeEventListener('message', this.onwmsg); w.terminate(); this.worker = null; } else { var transmuxer = this.transmuxer; if (transmuxer) { transmuxer.destroy(); this.transmuxer = null; } } var observer = this.observer; if (observer) { observer.removeAllListeners(); } // @ts-ignore this.observer = null; }; _proto.push = function push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) { var _this2 = this; chunkMeta.transmuxing.start = self.performance.now(); var transmuxer = this.transmuxer, worker = this.worker; var timeOffset = part ? part.start : frag.start; var decryptdata = frag.decryptdata; var lastFrag = this.frag; var discontinuity = !(lastFrag && frag.cc === lastFrag.cc); var trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level); var snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1; var partDiff = this.part ? chunkMeta.part - this.part.index : 1; var contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && partDiff === 1); var now = self.performance.now(); if (trackSwitch || snDiff || frag.stats.parsing.start === 0) { frag.stats.parsing.start = now; } if (part && (partDiff || !contiguous)) { part.stats.parsing.start = now; } var state = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["TransmuxState"](discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset); if (!contiguous || discontinuity) { _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log("[transmuxer-interface, " + frag.type + "]: Starting new transmux session for sn: " + chunkMeta.sn + " p: " + chunkMeta.part + " level: " + chunkMeta.level + " id: " + chunkMeta.id + "\n discontinuity: " + discontinuity + "\n trackSwitch: " + trackSwitch + "\n contiguous: " + contiguous + "\n accurateTimeOffset: " + accurateTimeOffset + "\n timeOffset: " + timeOffset); var config = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["TransmuxConfig"](audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS); this.configureTransmuxer(config); } this.frag = frag; this.part = part; // Frags with sn of 'initSegment' are not transmuxed if (worker) { // post fragment payload as transferable objects for ArrayBuffer (no copy) worker.postMessage({ cmd: 'demux', data: data, decryptdata: decryptdata, chunkMeta: chunkMeta, state: state }, data instanceof ArrayBuffer ? [data] : []); } else if (transmuxer) { var _transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state); if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["isPromise"])(_transmuxResult)) { _transmuxResult.then(function (data) { _this2.handleTransmuxComplete(data); }); } else { this.handleTransmuxComplete(_transmuxResult); } } }; _proto.flush = function flush(chunkMeta) { var _this3 = this; chunkMeta.transmuxing.start = self.performance.now(); var transmuxer = this.transmuxer, worker = this.worker; if (worker) { worker.postMessage({ cmd: 'flush', chunkMeta: chunkMeta }); } else if (transmuxer) { var _transmuxResult2 = transmuxer.flush(chunkMeta); if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["isPromise"])(_transmuxResult2)) { _transmuxResult2.then(function (data) { _this3.handleFlushResult(data, chunkMeta); }); } else { this.handleFlushResult(_transmuxResult2, chunkMeta); } } }; _proto.handleFlushResult = function handleFlushResult(results, chunkMeta) { var _this4 = this; results.forEach(function (result) { _this4.handleTransmuxComplete(result); }); this.onFlush(chunkMeta); }; _proto.onWorkerMessage = function onWorkerMessage(ev) { var data = ev.data; var hls = this.hls; switch (data.event) { case 'init': { // revoke the Object URL that was used to create transmuxer worker, so as not to leak it self.URL.revokeObjectURL(this.worker.objectURL); break; } case 'transmuxComplete': { this.handleTransmuxComplete(data.data); break; } case 'flush': { this.onFlush(data.data); break; } /* falls through */ default: { data.data = data.data || {}; data.data.frag = this.frag; data.data.id = this.id; hls.trigger(data.event, data.data); break; } } }; _proto.configureTransmuxer = function configureTransmuxer(config) { var worker = this.worker, transmuxer = this.transmuxer; if (worker) { worker.postMessage({ cmd: 'configure', config: config }); } else if (transmuxer) { transmuxer.configure(config); } }; _proto.handleTransmuxComplete = function handleTransmuxComplete(result) { result.chunkMeta.transmuxing.end = self.performance.now(); this.onTransmuxComplete(result); }; return TransmuxerInterface; }(); /***/ }), /***/ "./src/demux/transmuxer-worker.ts": /*!****************************************!*\ !*** ./src/demux/transmuxer-worker.ts ***! \****************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TransmuxerWorker; }); /* harmony import */ var _demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../demux/transmuxer */ "./src/demux/transmuxer.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js"); /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_3__); function TransmuxerWorker(self) { var observer = new eventemitter3__WEBPACK_IMPORTED_MODULE_3__["EventEmitter"](); var forwardMessage = function forwardMessage(ev, data) { self.postMessage({ event: ev, data: data }); }; // forward events to main thread observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_DECRYPTED, forwardMessage); observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, forwardMessage); self.addEventListener('message', function (ev) { var data = ev.data; switch (data.cmd) { case 'init': { var config = JSON.parse(data.config); self.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__["default"](observer, data.typeSupported, config, data.vendor, data.id); Object(_utils_logger__WEBPACK_IMPORTED_MODULE_2__["enableLogs"])(config.debug); forwardMessage('init', null); break; } case 'configure': { self.transmuxer.configure(data.config); break; } case 'demux': { var transmuxResult = self.transmuxer.push(data.data, data.decryptdata, data.chunkMeta, data.state); if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__["isPromise"])(transmuxResult)) { transmuxResult.then(function (data) { emitTransmuxComplete(self, data); }); } else { emitTransmuxComplete(self, transmuxResult); } break; } case 'flush': { var id = data.chunkMeta; var _transmuxResult = self.transmuxer.flush(id); if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__["isPromise"])(_transmuxResult)) { _transmuxResult.then(function (results) { handleFlushResult(self, results, id); }); } else { handleFlushResult(self, _transmuxResult, id); } break; } default: break; } }); } function emitTransmuxComplete(self, transmuxResult) { if (isEmptyResult(transmuxResult.remuxResult)) { return; } var transferable = []; var _transmuxResult$remux = transmuxResult.remuxResult, audio = _transmuxResult$remux.audio, video = _transmuxResult$remux.video; if (audio) { addToTransferable(transferable, audio); } if (video) { addToTransferable(transferable, video); } self.postMessage({ event: 'transmuxComplete', data: transmuxResult }, transferable); } // Converts data to a transferable object https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast) // in order to minimize message passing overhead function addToTransferable(transferable, track) { if (track.data1) { transferable.push(track.data1.buffer); } if (track.data2) { transferable.push(track.data2.buffer); } } function handleFlushResult(self, results, chunkMeta) { results.forEach(function (result) { emitTransmuxComplete(self, result); }); self.postMessage({ event: 'flush', data: chunkMeta }); } function isEmptyResult(remuxResult) { return !remuxResult.audio && !remuxResult.video && !remuxResult.text && !remuxResult.id3 && !remuxResult.initSegment; } /***/ }), /***/ "./src/demux/transmuxer.ts": /*!*********************************!*\ !*** ./src/demux/transmuxer.ts ***! \*********************************/ /*! exports provided: default, isPromise, TransmuxConfig, TransmuxState */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Transmuxer; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPromise", function() { return isPromise; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransmuxConfig", function() { return TransmuxConfig; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransmuxState", function() { return TransmuxState; }); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.ts"); /* harmony import */ var _demux_aacdemuxer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/aacdemuxer */ "./src/demux/aacdemuxer.ts"); /* harmony import */ var _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../demux/mp4demuxer */ "./src/demux/mp4demuxer.ts"); /* harmony import */ var _demux_tsdemuxer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../demux/tsdemuxer */ "./src/demux/tsdemuxer.ts"); /* harmony import */ var _demux_mp3demuxer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../demux/mp3demuxer */ "./src/demux/mp3demuxer.ts"); /* harmony import */ var _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../remux/mp4-remuxer */ "./src/remux/mp4-remuxer.ts"); /* harmony import */ var _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../remux/passthrough-remuxer */ "./src/remux/passthrough-remuxer.ts"); /* harmony import */ var _chunk_cache__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./chunk-cache */ "./src/demux/chunk-cache.ts"); /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); var now; // performance.now() not available on WebWorker, at least on Safari Desktop try { now = self.performance.now.bind(self.performance); } catch (err) { _utils_logger__WEBPACK_IMPORTED_MODULE_11__["logger"].debug('Unable to use Performance API on this environment'); now = self.Date.now; } var muxConfig = [{ demux: _demux_tsdemuxer__WEBPACK_IMPORTED_MODULE_5__["default"], remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__["default"] }, { demux: _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__["default"], remux: _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__["default"] }, { demux: _demux_aacdemuxer__WEBPACK_IMPORTED_MODULE_3__["default"], remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__["default"] }, { demux: _demux_mp3demuxer__WEBPACK_IMPORTED_MODULE_6__["default"], remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__["default"] }]; var minProbeByteLength = 1024; muxConfig.forEach(function (_ref) { var demux = _ref.demux; minProbeByteLength = Math.max(minProbeByteLength, demux.minProbeByteLength); }); var Transmuxer = /*#__PURE__*/function () { function Transmuxer(observer, typeSupported, config, vendor, id) { this.observer = void 0; this.typeSupported = void 0; this.config = void 0; this.vendor = void 0; this.id = void 0; this.demuxer = void 0; this.remuxer = void 0; this.decrypter = void 0; this.probe = void 0; this.decryptionPromise = null; this.transmuxConfig = void 0; this.currentTransmuxState = void 0; this.cache = new _chunk_cache__WEBPACK_IMPORTED_MODULE_9__["default"](); this.observer = observer; this.typeSupported = typeSupported; this.config = config; this.vendor = vendor; this.id = id; } var _proto = Transmuxer.prototype; _proto.configure = function configure(transmuxConfig) { this.transmuxConfig = transmuxConfig; if (this.decrypter) { this.decrypter.reset(); } }; _proto.push = function push(data, decryptdata, chunkMeta, state) { var _this = this; var stats = chunkMeta.transmuxing; stats.executeStart = now(); var uintData = new Uint8Array(data); var cache = this.cache, config = this.config, currentTransmuxState = this.currentTransmuxState, transmuxConfig = this.transmuxConfig; if (state) { this.currentTransmuxState = state; } var keyData = getEncryptionType(uintData, decryptdata); if (keyData && keyData.method === 'AES-128') { var decrypter = this.getDecrypter(); // Software decryption is synchronous; webCrypto is not if (config.enableSoftwareAES) { // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached // data is handled in the flush() call var decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer); if (!decryptedData) { stats.executeEnd = now(); return emptyResult(chunkMeta); } uintData = new Uint8Array(decryptedData); } else { this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer).then(function (decryptedData) { // Calling push here is important; if flush() is called while this is still resolving, this ensures that // the decrypted data has been transmuxed var result = _this.push(decryptedData, null, chunkMeta); _this.decryptionPromise = null; return result; }); return this.decryptionPromise; } } var _ref2 = state || currentTransmuxState, contiguous = _ref2.contiguous, discontinuity = _ref2.discontinuity, trackSwitch = _ref2.trackSwitch, accurateTimeOffset = _ref2.accurateTimeOffset, timeOffset = _ref2.timeOffset; var audioCodec = transmuxConfig.audioCodec, videoCodec = transmuxConfig.videoCodec, defaultInitPts = transmuxConfig.defaultInitPts, duration = transmuxConfig.duration, initSegmentData = transmuxConfig.initSegmentData; // Reset muxers before probing to ensure that their state is clean, even if flushing occurs before a successful probe if (discontinuity || trackSwitch) { this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration); } if (discontinuity) { this.resetInitialTimestamp(defaultInitPts); } if (!contiguous) { this.resetContiguity(); } if (this.needsProbing(uintData, discontinuity, trackSwitch)) { if (cache.dataLength) { var cachedData = cache.flush(); uintData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_10__["appendUint8Array"])(cachedData, uintData); } this.configureTransmuxer(uintData, transmuxConfig); } var result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta); var currentState = this.currentTransmuxState; currentState.contiguous = true; currentState.discontinuity = false; currentState.trackSwitch = false; stats.executeEnd = now(); return result; } // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type) ; _proto.flush = function flush(chunkMeta) { var _this2 = this; var stats = chunkMeta.transmuxing; stats.executeStart = now(); var decrypter = this.decrypter, cache = this.cache, currentTransmuxState = this.currentTransmuxState, decryptionPromise = this.decryptionPromise; if (decryptionPromise) { // Upon resolution, the decryption promise calls push() and returns its TransmuxerResult up the stack. Therefore // only flushing is required for async decryption return decryptionPromise.then(function () { return _this2.flush(chunkMeta); }); } var transmuxResults = []; var timeOffset = currentTransmuxState.timeOffset; if (decrypter) { // The decrypter may have data cached, which needs to be demuxed. In this case we'll have two TransmuxResults // This happens in the case that we receive only 1 push call for a segment (either for non-progressive downloads, // or for progressive downloads with small segments) var decryptedData = decrypter.flush(); if (decryptedData) { // Push always returns a TransmuxerResult if decryptdata is null transmuxResults.push(this.push(decryptedData, null, chunkMeta)); } } var bytesSeen = cache.dataLength; cache.reset(); var demuxer = this.demuxer, remuxer = this.remuxer; if (!demuxer || !remuxer) { // If probing failed, and each demuxer saw enough bytes to be able to probe, then Hls.js has been given content its not able to handle if (bytesSeen >= minProbeByteLength) { this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_PARSING_ERROR, fatal: true, reason: 'no demux matching with content found' }); } stats.executeEnd = now(); return [emptyResult(chunkMeta)]; } var demuxResultOrPromise = demuxer.flush(timeOffset); if (isPromise(demuxResultOrPromise)) { // Decrypt final SAMPLE-AES samples return demuxResultOrPromise.then(function (demuxResult) { _this2.flushRemux(transmuxResults, demuxResult, chunkMeta); return transmuxResults; }); } this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta); return transmuxResults; }; _proto.flushRemux = function flushRemux(transmuxResults, demuxResult, chunkMeta) { var audioTrack = demuxResult.audioTrack, avcTrack = demuxResult.avcTrack, id3Track = demuxResult.id3Track, textTrack = demuxResult.textTrack; var _this$currentTransmux = this.currentTransmuxState, accurateTimeOffset = _this$currentTransmux.accurateTimeOffset, timeOffset = _this$currentTransmux.timeOffset; _utils_logger__WEBPACK_IMPORTED_MODULE_11__["logger"].log("[transmuxer.ts]: Flushed fragment " + chunkMeta.sn + (chunkMeta.part > -1 ? ' p: ' + chunkMeta.part : '') + " of level " + chunkMeta.level); var remuxResult = this.remuxer.remux(audioTrack, avcTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true, this.id); transmuxResults.push({ remuxResult: remuxResult, chunkMeta: chunkMeta }); chunkMeta.transmuxing.executeEnd = now(); }; _proto.resetInitialTimestamp = function resetInitialTimestamp(defaultInitPts) { var demuxer = this.demuxer, remuxer = this.remuxer; if (!demuxer || !remuxer) { return; } demuxer.resetTimeStamp(defaultInitPts); remuxer.resetTimeStamp(defaultInitPts); }; _proto.resetContiguity = function resetContiguity() { var demuxer = this.demuxer, remuxer = this.remuxer; if (!demuxer || !remuxer) { return; } demuxer.resetContiguity(); remuxer.resetNextTimestamp(); }; _proto.resetInitSegment = function resetInitSegment(initSegmentData, audioCodec, videoCodec, duration) { var demuxer = this.demuxer, remuxer = this.remuxer; if (!demuxer || !remuxer) { return; } demuxer.resetInitSegment(audioCodec, videoCodec, duration); remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec); }; _proto.destroy = function destroy() { if (this.demuxer) { this.demuxer.destroy(); this.demuxer = undefined; } if (this.remuxer) { this.remuxer.destroy(); this.remuxer = undefined; } }; _proto.transmux = function transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) { var result; if (keyData && keyData.method === 'SAMPLE-AES') { result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta); } else { result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta); } return result; }; _proto.transmuxUnencrypted = function transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) { var _demux = this.demuxer.demux(data, timeOffset, false, !this.config.progressive), audioTrack = _demux.audioTrack, avcTrack = _demux.avcTrack, id3Track = _demux.id3Track, textTrack = _demux.textTrack; var remuxResult = this.remuxer.remux(audioTrack, avcTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false, this.id); return { remuxResult: remuxResult, chunkMeta: chunkMeta }; }; _proto.transmuxSampleAes = function transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) { var _this3 = this; return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then(function (demuxResult) { var remuxResult = _this3.remuxer.remux(demuxResult.audioTrack, demuxResult.avcTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false, _this3.id); return { remuxResult: remuxResult, chunkMeta: chunkMeta }; }); }; _proto.configureTransmuxer = function configureTransmuxer(data, transmuxConfig) { var config = this.config, observer = this.observer, typeSupported = this.typeSupported, vendor = this.vendor; var audioCodec = transmuxConfig.audioCodec, defaultInitPts = transmuxConfig.defaultInitPts, duration = transmuxConfig.duration, initSegmentData = transmuxConfig.initSegmentData, videoCodec = transmuxConfig.videoCodec; // probe for content type var mux; for (var i = 0, len = muxConfig.length; i < len; i++) { if (muxConfig[i].demux.probe(data)) { mux = muxConfig[i]; break; } } if (!mux) { // If probing previous configs fail, use mp4 passthrough _utils_logger__WEBPACK_IMPORTED_MODULE_11__["logger"].warn('Failed to find demuxer by probing frag, treating as mp4 passthrough'); mux = { demux: _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__["default"], remux: _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__["default"] }; } // so let's check that current remuxer and demuxer are still valid var demuxer = this.demuxer; var remuxer = this.remuxer; var Remuxer = mux.remux; var Demuxer = mux.demux; if (!remuxer || !(remuxer instanceof Remuxer)) { this.remuxer = new Remuxer(observer, config, typeSupported, vendor); } if (!demuxer || !(demuxer instanceof Demuxer)) { this.demuxer = new Demuxer(observer, config, typeSupported); this.probe = Demuxer.probe; } // Ensure that muxers are always initialized with an initSegment this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration); this.resetInitialTimestamp(defaultInitPts); }; _proto.needsProbing = function needsProbing(data, discontinuity, trackSwitch) { // in case of continuity change, or track switch // we might switch from content type (AAC container to TS container, or TS to fmp4 for example) return !this.demuxer || !this.remuxer || discontinuity || trackSwitch; }; _proto.getDecrypter = function getDecrypter() { var decrypter = this.decrypter; if (!decrypter) { decrypter = this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_2__["default"](this.observer, this.config); } return decrypter; }; return Transmuxer; }(); function getEncryptionType(data, decryptData) { var encryptionType = null; if (data.byteLength > 0 && decryptData != null && decryptData.key != null && decryptData.iv !== null && decryptData.method != null) { encryptionType = decryptData; } return encryptionType; } var emptyResult = function emptyResult(chunkMeta) { return { remuxResult: {}, chunkMeta: chunkMeta }; }; function isPromise(p) { return 'then' in p && p.then instanceof Function; } var TransmuxConfig = function TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) { this.audioCodec = void 0; this.videoCodec = void 0; this.initSegmentData = void 0; this.duration = void 0; this.defaultInitPts = void 0; this.audioCodec = audioCodec; this.videoCodec = videoCodec; this.initSegmentData = initSegmentData; this.duration = duration; this.defaultInitPts = defaultInitPts; }; var TransmuxState = function TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset) { this.discontinuity = void 0; this.contiguous = void 0; this.accurateTimeOffset = void 0; this.trackSwitch = void 0; this.timeOffset = void 0; this.discontinuity = discontinuity; this.contiguous = contiguous; this.accurateTimeOffset = accurateTimeOffset; this.trackSwitch = trackSwitch; this.timeOffset = timeOffset; }; /***/ }), /***/ "./src/demux/tsdemuxer.ts": /*!********************************!*\ !*** ./src/demux/tsdemuxer.ts ***! \********************************/ /*! exports provided: discardEPB, default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "discardEPB", function() { return discardEPB; }); /* harmony import */ var _adts__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./adts */ "./src/demux/adts.ts"); /* harmony import */ var _mpegaudio__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./mpegaudio */ "./src/demux/mpegaudio.ts"); /* harmony import */ var _exp_golomb__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./exp-golomb */ "./src/demux/exp-golomb.ts"); /* harmony import */ var _id3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./id3 */ "./src/demux/id3.ts"); /* harmony import */ var _sample_aes__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./sample-aes */ "./src/demux/sample-aes.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /** * highly optimized TS demuxer: * parse PAT, PMT * extract PES packet from audio and video PIDs * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet * trigger the remuxer upon parsing completion * it also tries to workaround as best as it can audio codec switch (HE-AAC to AAC and vice versa), without having to restart the MediaSource. * it also controls the remuxing process : * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state. */ // We are using fixed track IDs for driving the MP4 remuxer // instead of following the TS PIDs. // There is no reason not to do this and some browsers/SourceBuffer-demuxers // may not like if there are TrackID "switches" // See https://github.com/video-dev/hls.js/issues/1331 // Here we are mapping our internal track types to constant MP4 track IDs // With MSE currently one can only have one track of each, and we are muxing // whatever video/audio rendition in them. var RemuxerTrackIdConfig = { video: 1, audio: 2, id3: 3, text: 4 }; var TSDemuxer = /*#__PURE__*/function () { function TSDemuxer(observer, config, typeSupported) { this.observer = void 0; this.config = void 0; this.typeSupported = void 0; this.sampleAes = null; this.pmtParsed = false; this.audioCodec = void 0; this.videoCodec = void 0; this._duration = 0; this.aacLastPTS = null; this._initPTS = null; this._initDTS = null; this._pmtId = -1; this._avcTrack = void 0; this._audioTrack = void 0; this._id3Track = void 0; this._txtTrack = void 0; this.aacOverFlow = null; this.avcSample = null; this.remainderData = null; this.observer = observer; this.config = config; this.typeSupported = typeSupported; } TSDemuxer.probe = function probe(data) { var syncOffset = TSDemuxer.syncOffset(data); if (syncOffset < 0) { return false; } else { if (syncOffset) { _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn("MPEG2-TS detected but first sync word found @ offset " + syncOffset + ", junk ahead ?"); } return true; } }; TSDemuxer.syncOffset = function syncOffset(data) { // scan 1000 first bytes var scanwindow = Math.min(1000, data.length - 3 * 188); var i = 0; while (i < scanwindow) { // a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47 if (data[i] === 0x47 && data[i + 188] === 0x47 && data[i + 2 * 188] === 0x47) { return i; } else { i++; } } return -1; } /** * Creates a track model internal to demuxer used to drive remuxing input * * @param type 'audio' | 'video' | 'id3' | 'text' * @param duration * @return TSDemuxer's internal track model */ ; TSDemuxer.createTrack = function createTrack(type, duration) { return { container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined, type: type, id: RemuxerTrackIdConfig[type], pid: -1, inputTimeScale: 90000, sequenceNumber: 0, samples: [], dropped: 0, duration: type === 'audio' ? duration : undefined }; } /** * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start) * Resets all internal track instances of the demuxer. */ ; var _proto = TSDemuxer.prototype; _proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) { this.pmtParsed = false; this._pmtId = -1; this._avcTrack = TSDemuxer.createTrack('video', duration); this._audioTrack = TSDemuxer.createTrack('audio', duration); this._id3Track = TSDemuxer.createTrack('id3', duration); this._txtTrack = TSDemuxer.createTrack('text', duration); this._audioTrack.isAAC = true; // flush any partial content this.aacOverFlow = null; this.aacLastPTS = null; this.avcSample = null; this.audioCodec = audioCodec; this.videoCodec = videoCodec; this._duration = duration; }; _proto.resetTimeStamp = function resetTimeStamp() {}; _proto.resetContiguity = function resetContiguity() { var _audioTrack = this._audioTrack, _avcTrack = this._avcTrack, _id3Track = this._id3Track; if (_audioTrack) { _audioTrack.pesData = null; } if (_avcTrack) { _avcTrack.pesData = null; } if (_id3Track) { _id3Track.pesData = null; } this.aacOverFlow = null; this.aacLastPTS = null; }; _proto.demux = function demux(data, timeOffset, isSampleAes, flush) { if (isSampleAes === void 0) { isSampleAes = false; } if (flush === void 0) { flush = false; } if (!isSampleAes) { this.sampleAes = null; } var pes; var avcTrack = this._avcTrack; var audioTrack = this._audioTrack; var id3Track = this._id3Track; var avcId = avcTrack.pid; var avcData = avcTrack.pesData; var audioId = audioTrack.pid; var id3Id = id3Track.pid; var audioData = audioTrack.pesData; var id3Data = id3Track.pesData; var unknownPIDs = false; var pmtParsed = this.pmtParsed; var pmtId = this._pmtId; var len = data.length; if (this.remainderData) { data = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_6__["appendUint8Array"])(this.remainderData, data); len = data.length; this.remainderData = null; } if (len < 188 && !flush) { this.remainderData = data; return { audioTrack: audioTrack, avcTrack: avcTrack, id3Track: id3Track, textTrack: this._txtTrack }; } var syncOffset = Math.max(0, TSDemuxer.syncOffset(data)); len -= (len + syncOffset) % 188; if (len < data.byteLength && !flush) { this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len); } // loop through TS packets for (var start = syncOffset; start < len; start += 188) { if (data[start] === 0x47) { var stt = !!(data[start + 1] & 0x40); // pid is a 13-bit field starting at the last bit of TS[1] var pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2]; var atf = (data[start + 3] & 0x30) >> 4; // if an adaption field is present, its length is specified by the fifth byte of the TS packet header. var offset = void 0; if (atf > 1) { offset = start + 5 + data[start + 4]; // continue if there is only adaptation field if (offset === start + 188) { continue; } } else { offset = start + 4; } switch (pid) { case avcId: if (stt) { if (avcData && (pes = parsePES(avcData))) { this.parseAVCPES(pes, false); } avcData = { data: [], size: 0 }; } if (avcData) { avcData.data.push(data.subarray(offset, start + 188)); avcData.size += start + 188 - offset; } break; case audioId: if (stt) { if (audioData && (pes = parsePES(audioData))) { if (audioTrack.isAAC) { this.parseAACPES(pes); } else { this.parseMPEGPES(pes); } } audioData = { data: [], size: 0 }; } if (audioData) { audioData.data.push(data.subarray(offset, start + 188)); audioData.size += start + 188 - offset; } break; case id3Id: if (stt) { if (id3Data && (pes = parsePES(id3Data))) { this.parseID3PES(pes); } id3Data = { data: [], size: 0 }; } if (id3Data) { id3Data.data.push(data.subarray(offset, start + 188)); id3Data.size += start + 188 - offset; } break; case 0: if (stt) { offset += data[offset] + 1; } pmtId = this._pmtId = parsePAT(data, offset); break; case pmtId: { if (stt) { offset += data[offset] + 1; } var parsedPIDs = parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true, isSampleAes); // only update track id if track PID found while parsing PMT // this is to avoid resetting the PID to -1 in case // track PID transiently disappears from the stream // this could happen in case of transient missing audio samples for example // NOTE this is only the PID of the track as found in TS, // but we are not using this for MP4 track IDs. avcId = parsedPIDs.avc; if (avcId > 0) { avcTrack.pid = avcId; } audioId = parsedPIDs.audio; if (audioId > 0) { audioTrack.pid = audioId; audioTrack.isAAC = parsedPIDs.isAAC; } id3Id = parsedPIDs.id3; if (id3Id > 0) { id3Track.pid = id3Id; } if (unknownPIDs && !pmtParsed) { _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('reparse from beginning'); unknownPIDs = false; // we set it to -188, the += 188 in the for loop will reset start to 0 start = syncOffset - 188; } pmtParsed = this.pmtParsed = true; break; } case 17: case 0x1fff: break; default: unknownPIDs = true; break; } } else { this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorDetails"].FRAG_PARSING_ERROR, fatal: false, reason: 'TS packet did not start with 0x47' }); } } avcTrack.pesData = avcData; audioTrack.pesData = audioData; id3Track.pesData = id3Data; var demuxResult = { audioTrack: audioTrack, avcTrack: avcTrack, id3Track: id3Track, textTrack: this._txtTrack }; if (flush) { this.extractRemainingSamples(demuxResult); } return demuxResult; }; _proto.flush = function flush() { var remainderData = this.remainderData; this.remainderData = null; var result; if (remainderData) { result = this.demux(remainderData, -1, false, true); } else { result = { audioTrack: this._audioTrack, avcTrack: this._avcTrack, textTrack: this._txtTrack, id3Track: this._id3Track }; } this.extractRemainingSamples(result); if (this.sampleAes) { return this.decrypt(result, this.sampleAes); } return result; }; _proto.extractRemainingSamples = function extractRemainingSamples(demuxResult) { var audioTrack = demuxResult.audioTrack, avcTrack = demuxResult.avcTrack, id3Track = demuxResult.id3Track; var avcData = avcTrack.pesData; var audioData = audioTrack.pesData; var id3Data = id3Track.pesData; // try to parse last PES packets var pes; if (avcData && (pes = parsePES(avcData))) { this.parseAVCPES(pes, true); avcTrack.pesData = null; } else { // either avcData null or PES truncated, keep it for next frag parsing avcTrack.pesData = avcData; } if (audioData && (pes = parsePES(audioData))) { if (audioTrack.isAAC) { this.parseAACPES(pes); } else { this.parseMPEGPES(pes); } audioTrack.pesData = null; } else { if (audioData !== null && audioData !== void 0 && audioData.size) { _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('last AAC PES packet truncated,might overlap between fragments'); } // either audioData null or PES truncated, keep it for next frag parsing audioTrack.pesData = audioData; } if (id3Data && (pes = parsePES(id3Data))) { this.parseID3PES(pes); id3Track.pesData = null; } else { // either id3Data null or PES truncated, keep it for next frag parsing id3Track.pesData = id3Data; } }; _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) { var demuxResult = this.demux(data, timeOffset, true, !this.config.progressive); var sampleAes = this.sampleAes = new _sample_aes__WEBPACK_IMPORTED_MODULE_4__["default"](this.observer, this.config, keyData); return this.decrypt(demuxResult, sampleAes); }; _proto.decrypt = function decrypt(demuxResult, sampleAes) { return new Promise(function (resolve) { var audioTrack = demuxResult.audioTrack, avcTrack = demuxResult.avcTrack; if (audioTrack.samples && audioTrack.isAAC) { sampleAes.decryptAacSamples(audioTrack.samples, 0, function () { if (avcTrack.samples) { sampleAes.decryptAvcSamples(avcTrack.samples, 0, 0, function () { resolve(demuxResult); }); } else { resolve(demuxResult); } }); } else if (avcTrack.samples) { sampleAes.decryptAvcSamples(avcTrack.samples, 0, 0, function () { resolve(demuxResult); }); } }); }; _proto.destroy = function destroy() { this._initPTS = this._initDTS = null; this._duration = 0; }; _proto.parseAVCPES = function parseAVCPES(pes, last) { var _this = this; var track = this._avcTrack; var units = this.parseAVCNALu(pes.data); var debug = false; var avcSample = this.avcSample; var push; var spsfound = false; // free pes.data to save up some memory pes.data = null; // if new NAL units found and last sample still there, let's push ... // this helps parsing streams with missing AUD (only do this if AUD never found) if (avcSample && units.length && !track.audFound) { pushAccessUnit(avcSample, track); avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, ''); } units.forEach(function (unit) { switch (unit.type) { // NDR case 1: { push = true; if (!avcSample) { avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, ''); } if (debug) { avcSample.debug += 'NDR '; } avcSample.frame = true; var data = unit.data; // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...) if (spsfound && data.length > 4) { // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR var sliceType = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__["default"](data).readSliceType(); // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples. // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice. // I slice: A slice that is not an SI slice that is decoded using intra prediction only. // if (sliceType === 2 || sliceType === 7) { if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) { avcSample.key = true; } } break; // IDR } case 5: push = true; // handle PES not starting with AUD if (!avcSample) { avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, ''); } if (debug) { avcSample.debug += 'IDR '; } avcSample.key = true; avcSample.frame = true; break; // SEI case 6: { push = true; if (debug && avcSample) { avcSample.debug += 'SEI '; } var expGolombDecoder = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__["default"](discardEPB(unit.data)); // skip frameType expGolombDecoder.readUByte(); var payloadType = 0; var payloadSize = 0; var endOfCaptions = false; var b = 0; while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) { payloadType = 0; do { b = expGolombDecoder.readUByte(); payloadType += b; } while (b === 0xff); // Parse payload size. payloadSize = 0; do { b = expGolombDecoder.readUByte(); payloadSize += b; } while (b === 0xff); // TODO: there can be more than one payload in an SEI packet... // TODO: need to read type and size in a while loop to get them all if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) { endOfCaptions = true; var countryCode = expGolombDecoder.readUByte(); if (countryCode === 181) { var providerCode = expGolombDecoder.readUShort(); if (providerCode === 49) { var userStructure = expGolombDecoder.readUInt(); if (userStructure === 0x47413934) { var userDataType = expGolombDecoder.readUByte(); // Raw CEA-608 bytes wrapped in CEA-708 packet if (userDataType === 3) { var firstByte = expGolombDecoder.readUByte(); var secondByte = expGolombDecoder.readUByte(); var totalCCs = 31 & firstByte; var byteArray = [firstByte, secondByte]; for (var i = 0; i < totalCCs; i++) { // 3 bytes per CC byteArray.push(expGolombDecoder.readUByte()); byteArray.push(expGolombDecoder.readUByte()); byteArray.push(expGolombDecoder.readUByte()); } insertSampleInOrder(_this._txtTrack.samples, { type: 3, pts: pes.pts, bytes: byteArray }); } } } } } else if (payloadType === 5 && expGolombDecoder.bytesAvailable !== 0) { endOfCaptions = true; if (payloadSize > 16) { var uuidStrArray = []; for (var _i = 0; _i < 16; _i++) { uuidStrArray.push(expGolombDecoder.readUByte().toString(16)); if (_i === 3 || _i === 5 || _i === 7 || _i === 9) { uuidStrArray.push('-'); } } var length = payloadSize - 16; var userDataPayloadBytes = new Uint8Array(length); for (var _i2 = 0; _i2 < length; _i2++) { userDataPayloadBytes[_i2] = expGolombDecoder.readUByte(); } insertSampleInOrder(_this._txtTrack.samples, { pts: pes.pts, payloadType: payloadType, uuid: uuidStrArray.join(''), userData: Object(_id3__WEBPACK_IMPORTED_MODULE_3__["utf8ArrayToStr"])(userDataPayloadBytes), userDataBytes: userDataPayloadBytes }); } } else if (payloadSize < expGolombDecoder.bytesAvailable) { for (var _i3 = 0; _i3 < payloadSize; _i3++) { expGolombDecoder.readUByte(); } } } break; // SPS } case 7: push = true; spsfound = true; if (debug && avcSample) { avcSample.debug += 'SPS '; } if (!track.sps) { var _expGolombDecoder = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__["default"](unit.data); var config = _expGolombDecoder.readSPS(); track.width = config.width; track.height = config.height; track.pixelRatio = config.pixelRatio; // TODO: `track.sps` is defined as a `number[]`, but we're setting it to a `Uint8Array[]`. track.sps = [unit.data]; track.duration = _this._duration; var codecarray = unit.data.subarray(1, 4); var codecstring = 'avc1.'; for (var _i4 = 0; _i4 < 3; _i4++) { var h = codecarray[_i4].toString(16); if (h.length < 2) { h = '0' + h; } codecstring += h; } track.codec = codecstring; } break; // PPS case 8: push = true; if (debug && avcSample) { avcSample.debug += 'PPS '; } if (!track.pps) { // TODO: `track.pss` is defined as a `number[]`, but we're setting it to a `Uint8Array[]`. track.pps = [unit.data]; } break; // AUD case 9: push = false; track.audFound = true; if (avcSample) { pushAccessUnit(avcSample, track); } avcSample = _this.avcSample = createAVCSample(false, pes.pts, pes.dts, debug ? 'AUD ' : ''); break; // Filler Data case 12: push = false; break; default: push = false; if (avcSample) { avcSample.debug += 'unknown NAL ' + unit.type + ' '; } break; } if (avcSample && push) { var _units = avcSample.units; _units.push(unit); } }); // if last PES packet, push samples if (last && avcSample) { pushAccessUnit(avcSample, track); this.avcSample = null; } }; _proto.getLastNalUnit = function getLastNalUnit() { var _avcSample; var avcSample = this.avcSample; var lastUnit; // try to fallback to previous sample if current one is empty if (!avcSample || avcSample.units.length === 0) { var samples = this._avcTrack.samples; avcSample = samples[samples.length - 1]; } if ((_avcSample = avcSample) !== null && _avcSample !== void 0 && _avcSample.units) { var units = avcSample.units; lastUnit = units[units.length - 1]; } return lastUnit; }; _proto.parseAVCNALu = function parseAVCNALu(array) { var len = array.byteLength; var track = this._avcTrack; var state = track.naluState || 0; var lastState = state; var units = []; var i = 0; var value; var overflow; var unitType; var lastUnitStart = -1; var lastUnitType = 0; // logger.log('PES:' + Hex.hexDump(array)); if (state === -1) { // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet lastUnitStart = 0; // NALu type is value read from offset 0 lastUnitType = array[0] & 0x1f; state = 0; i = 1; } while (i < len) { value = array[i++]; // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case if (!state) { state = value ? 0 : 1; continue; } if (state === 1) { state = value ? 0 : 2; continue; } // here we have state either equal to 2 or 3 if (!value) { state = 3; } else if (value === 1) { if (lastUnitStart >= 0) { var unit = { data: array.subarray(lastUnitStart, i - state - 1), type: lastUnitType }; // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength); units.push(unit); } else { // lastUnitStart is undefined => this is the first start code found in this PES packet // first check if start code delimiter is overlapping between 2 PES packets, // ie it started in last packet (lastState not zero) // and ended at the beginning of this PES packet (i <= 4 - lastState) var lastUnit = this.getLastNalUnit(); if (lastUnit) { if (lastState && i <= 4 - lastState) { // start delimiter overlapping between PES packets // strip start delimiter bytes from the end of last NAL unit // check if lastUnit had a state different from zero if (lastUnit.state) { // strip last bytes lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState); } } // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit. overflow = i - state - 1; if (overflow > 0) { // logger.log('first NALU found with overflow:' + overflow); var tmp = new Uint8Array(lastUnit.data.byteLength + overflow); tmp.set(lastUnit.data, 0); tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength); lastUnit.data = tmp; } } } // check if we can read unit type if (i < len) { unitType = array[i] & 0x1f; // logger.log('find NALU @ offset:' + i + ',type:' + unitType); lastUnitStart = i; lastUnitType = unitType; state = 0; } else { // not enough byte to read unit type. let's read it on next PES parsing state = -1; } } else { state = 0; } } if (lastUnitStart >= 0 && state >= 0) { var _unit = { data: array.subarray(lastUnitStart, len), type: lastUnitType, state: state }; units.push(_unit); // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state); } // no NALu found if (units.length === 0) { // append pes.data to previous NAL unit var _lastUnit = this.getLastNalUnit(); if (_lastUnit) { var _tmp = new Uint8Array(_lastUnit.data.byteLength + array.byteLength); _tmp.set(_lastUnit.data, 0); _tmp.set(array, _lastUnit.data.byteLength); _lastUnit.data = _tmp; } } track.naluState = state; return units; }; _proto.parseAACPES = function parseAACPES(pes) { var startOffset = 0; var track = this._audioTrack; var aacOverFlow = this.aacOverFlow; var data = pes.data; if (aacOverFlow) { this.aacOverFlow = null; var sampleLength = aacOverFlow.sample.unit.byteLength; var frameMissingBytes = Math.min(aacOverFlow.missing, sampleLength); var frameOverflowBytes = sampleLength - frameMissingBytes; aacOverFlow.sample.unit.set(data.subarray(0, frameMissingBytes), frameOverflowBytes); track.samples.push(aacOverFlow.sample); // logger.log(`AAC: append overflowing ${frameOverflowBytes} bytes to beginning of new PES`); startOffset = aacOverFlow.missing; } // look for ADTS header (0xFFFx) var offset; var len; for (offset = startOffset, len = data.length; offset < len - 1; offset++) { if (_adts__WEBPACK_IMPORTED_MODULE_0__["isHeader"](data, offset)) { break; } } // if ADTS header does not start straight from the beginning of the PES payload, raise an error if (offset !== startOffset) { var reason; var fatal; if (offset < len - 1) { reason = "AAC PES did not start with ADTS header,offset:" + offset; fatal = false; } else { reason = 'no ADTS header found in AAC PES'; fatal = true; } _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn("parsing error:" + reason); this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorTypes"].MEDIA_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorDetails"].FRAG_PARSING_ERROR, fatal: fatal, reason: reason }); if (fatal) { return; } } _adts__WEBPACK_IMPORTED_MODULE_0__["initTrackConfig"](track, this.observer, data, offset, this.audioCodec); var pts; if (pes.pts !== undefined) { pts = pes.pts; } else if (aacOverFlow) { // if last AAC frame is overflowing, we should ensure timestamps are contiguous: // first sample PTS should be equal to last sample PTS + frameDuration var frameDuration = _adts__WEBPACK_IMPORTED_MODULE_0__["getFrameDuration"](track.samplerate); pts = aacOverFlow.sample.pts + frameDuration; } else { _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('[tsdemuxer]: AAC PES unknown PTS'); return; } // scan for aac samples var frameIndex = 0; while (offset < len) { if (_adts__WEBPACK_IMPORTED_MODULE_0__["isHeader"](data, offset)) { if (offset + 5 < len) { var frame = _adts__WEBPACK_IMPORTED_MODULE_0__["appendFrame"](track, data, offset, pts, frameIndex); if (frame) { if (frame.missing) { this.aacOverFlow = frame; } else { offset += frame.length; frameIndex++; continue; } } } // We are at an ADTS header, but do not have enough data for a frame // Remaining data will be added to aacOverFlow break; } else { // nothing found, keep looking offset++; } } }; _proto.parseMPEGPES = function parseMPEGPES(pes) { var data = pes.data; var length = data.length; var frameIndex = 0; var offset = 0; var pts = pes.pts; if (pts === undefined) { _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('[tsdemuxer]: MPEG PES unknown PTS'); return; } while (offset < length) { if (_mpegaudio__WEBPACK_IMPORTED_MODULE_1__["isHeader"](data, offset)) { var frame = _mpegaudio__WEBPACK_IMPORTED_MODULE_1__["appendFrame"](this._audioTrack, data, offset, pts, frameIndex); if (frame) { offset += frame.length; frameIndex++; } else { // logger.log('Unable to parse Mpeg audio frame'); break; } } else { // nothing found, keep looking offset++; } } }; _proto.parseID3PES = function parseID3PES(pes) { if (pes.pts === undefined) { _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('[tsdemuxer]: ID3 PES unknown PTS'); return; } this._id3Track.samples.push(pes); }; return TSDemuxer; }(); TSDemuxer.minProbeByteLength = 188; function createAVCSample(key, pts, dts, debug) { return { key: key, frame: false, pts: pts, dts: dts, units: [], debug: debug, length: 0 }; } function parsePAT(data, offset) { // skip the PSI header and parse the first PMT entry return (data[offset + 10] & 0x1f) << 8 | data[offset + 11]; // logger.log('PMT PID:' + this._pmtId); } function parsePMT(data, offset, mpegSupported, isSampleAes) { var result = { audio: -1, avc: -1, id3: -1, isAAC: true }; var sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2]; var tableEnd = offset + 3 + sectionLength - 4; // to determine where the table is, we have to figure out how // long the program info descriptors are var programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11]; // advance the offset to the first entry in the mapping table offset += 12 + programInfoLength; while (offset < tableEnd) { var pid = (data[offset + 1] & 0x1f) << 8 | data[offset + 2]; switch (data[offset]) { case 0xcf: // SAMPLE-AES AAC if (!isSampleAes) { _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream'); break; } /* falls through */ case 0x0f: // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio) // logger.log('AAC PID:' + pid); if (result.audio === -1) { result.audio = pid; } break; // Packetized metadata (ID3) case 0x15: // logger.log('ID3 PID:' + pid); if (result.id3 === -1) { result.id3 = pid; } break; case 0xdb: // SAMPLE-AES AVC if (!isSampleAes) { _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('H.264 with AES-128-CBC slice encryption found in unencrypted stream'); break; } /* falls through */ case 0x1b: // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video) // logger.log('AVC PID:' + pid); if (result.avc === -1) { result.avc = pid; } break; // ISO/IEC 11172-3 (MPEG-1 audio) // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio) case 0x03: case 0x04: // logger.log('MPEG PID:' + pid); if (!mpegSupported) { _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('MPEG audio found, not supported in this browser'); } else if (result.audio === -1) { result.audio = pid; result.isAAC = false; } break; case 0x24: _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('Unsupported HEVC stream type found'); break; default: // logger.log('unknown stream type:' + data[offset]); break; } // move to the next table entry // skip past the elementary stream descriptors, if present offset += ((data[offset + 3] & 0x0f) << 8 | data[offset + 4]) + 5; } return result; } function parsePES(stream) { var i = 0; var frag; var pesLen; var pesHdrLen; var pesPts; var pesDts; var data = stream.data; // safety check if (!stream || stream.size === 0) { return null; } // we might need up to 19 bytes to read PES header // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes // usually only one merge is needed (and this is rare ...) while (data[0].length < 19 && data.length > 1) { var newData = new Uint8Array(data[0].length + data[1].length); newData.set(data[0]); newData.set(data[1], data[0].length); data[0] = newData; data.splice(1, 1); } // retrieve PTS/DTS from first fragment frag = data[0]; var pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2]; if (pesPrefix === 1) { pesLen = (frag[4] << 8) + frag[5]; // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated // minus 6 : PES header size if (pesLen && pesLen > stream.size - 6) { return null; } var pesFlags = frag[7]; if (pesFlags & 0xc0) { /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html as PTS / DTS is 33 bit we cannot use bitwise operator in JS, as Bitwise operators treat their operands as a sequence of 32 bits */ pesPts = (frag[9] & 0x0e) * 536870912 + // 1 << 29 (frag[10] & 0xff) * 4194304 + // 1 << 22 (frag[11] & 0xfe) * 16384 + // 1 << 14 (frag[12] & 0xff) * 128 + // 1 << 7 (frag[13] & 0xfe) / 2; if (pesFlags & 0x40) { pesDts = (frag[14] & 0x0e) * 536870912 + // 1 << 29 (frag[15] & 0xff) * 4194304 + // 1 << 22 (frag[16] & 0xfe) * 16384 + // 1 << 14 (frag[17] & 0xff) * 128 + // 1 << 7 (frag[18] & 0xfe) / 2; if (pesPts - pesDts > 60 * 90000) { _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn(Math.round((pesPts - pesDts) / 90000) + "s delta between PTS and DTS, align them"); pesPts = pesDts; } } else { pesDts = pesPts; } } pesHdrLen = frag[8]; // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension var payloadStartOffset = pesHdrLen + 9; if (stream.size <= payloadStartOffset) { return null; } stream.size -= payloadStartOffset; // reassemble PES packet var pesData = new Uint8Array(stream.size); for (var j = 0, dataLen = data.length; j < dataLen; j++) { frag = data[j]; var len = frag.byteLength; if (payloadStartOffset) { if (payloadStartOffset > len) { // trim full frag if PES header bigger than frag payloadStartOffset -= len; continue; } else { // trim partial frag if PES header smaller than frag frag = frag.subarray(payloadStartOffset); len -= payloadStartOffset; payloadStartOffset = 0; } } pesData.set(frag, i); i += len; } if (pesLen) { // payload size : remove PES header + PES extension pesLen -= pesHdrLen + 3; } return { data: pesData, pts: pesPts, dts: pesDts, len: pesLen }; } return null; } function pushAccessUnit(avcSample, avcTrack) { if (avcSample.units.length && avcSample.frame) { // if sample does not have PTS/DTS, patch with last sample PTS/DTS if (avcSample.pts === undefined) { var samples = avcTrack.samples; var nbSamples = samples.length; if (nbSamples) { var lastSample = samples[nbSamples - 1]; avcSample.pts = lastSample.pts; avcSample.dts = lastSample.dts; } else { // dropping samples, no timestamp found avcTrack.dropped++; return; } } avcTrack.samples.push(avcSample); } if (avcSample.debug.length) { _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug); } } function insertSampleInOrder(arr, data) { var len = arr.length; if (len > 0) { if (data.pts >= arr[len - 1].pts) { arr.push(data); } else { for (var pos = len - 1; pos >= 0; pos--) { if (data.pts < arr[pos].pts) { arr.splice(pos, 0, data); break; } } } } else { arr.push(data); } } /** * remove Emulation Prevention bytes from a RBSP */ function discardEPB(data) { var length = data.byteLength; var EPBPositions = []; var i = 1; // Find all `Emulation Prevention Bytes` while (i < length - 2) { if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) { EPBPositions.push(i + 2); i += 2; } else { i++; } } // If no Emulation Prevention Bytes were found just return the original // array if (EPBPositions.length === 0) { return data; } // Create a new array to hold the NAL unit data var newLength = length - EPBPositions.length; var newData = new Uint8Array(newLength); var sourceIndex = 0; for (i = 0; i < newLength; sourceIndex++, i++) { if (sourceIndex === EPBPositions[0]) { // Skip this byte sourceIndex++; // Remove this position index EPBPositions.shift(); } newData[i] = data[sourceIndex]; } return newData; } /* harmony default export */ __webpack_exports__["default"] = (TSDemuxer); /***/ }), /***/ "./src/empty.js": /*!**********************!*\ !*** ./src/empty.js ***! \**********************/ /*! no static exports found */ /***/ (function(module, exports) { // This file is inserted as a shim for modules which we do not want to include into the distro. // This replacement is done in the "resolve" section of the webpack config. module.exports = undefined; /***/ }), /***/ "./src/errors.ts": /*!***********************!*\ !*** ./src/errors.ts ***! \***********************/ /*! exports provided: ErrorTypes, ErrorDetails */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorTypes", function() { return ErrorTypes; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorDetails", function() { return ErrorDetails; }); var ErrorTypes; /** * @enum {ErrorDetails} * @typedef {string} ErrorDetail */ (function (ErrorTypes) { ErrorTypes["NETWORK_ERROR"] = "networkError"; ErrorTypes["MEDIA_ERROR"] = "mediaError"; ErrorTypes["KEY_SYSTEM_ERROR"] = "keySystemError"; ErrorTypes["MUX_ERROR"] = "muxError"; ErrorTypes["OTHER_ERROR"] = "otherError"; })(ErrorTypes || (ErrorTypes = {})); var ErrorDetails; (function (ErrorDetails) { ErrorDetails["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys"; ErrorDetails["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess"; ErrorDetails["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession"; ErrorDetails["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed"; ErrorDetails["KEY_SYSTEM_NO_INIT_DATA"] = "keySystemNoInitData"; ErrorDetails["MANIFEST_LOAD_ERROR"] = "manifestLoadError"; ErrorDetails["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut"; ErrorDetails["MANIFEST_PARSING_ERROR"] = "manifestParsingError"; ErrorDetails["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError"; ErrorDetails["LEVEL_EMPTY_ERROR"] = "levelEmptyError"; ErrorDetails["LEVEL_LOAD_ERROR"] = "levelLoadError"; ErrorDetails["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut"; ErrorDetails["LEVEL_SWITCH_ERROR"] = "levelSwitchError"; ErrorDetails["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError"; ErrorDetails["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut"; ErrorDetails["SUBTITLE_LOAD_ERROR"] = "subtitleTrackLoadError"; ErrorDetails["SUBTITLE_TRACK_LOAD_TIMEOUT"] = "subtitleTrackLoadTimeOut"; ErrorDetails["FRAG_LOAD_ERROR"] = "fragLoadError"; ErrorDetails["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut"; ErrorDetails["FRAG_DECRYPT_ERROR"] = "fragDecryptError"; ErrorDetails["FRAG_PARSING_ERROR"] = "fragParsingError"; ErrorDetails["REMUX_ALLOC_ERROR"] = "remuxAllocError"; ErrorDetails["KEY_LOAD_ERROR"] = "keyLoadError"; ErrorDetails["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut"; ErrorDetails["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError"; ErrorDetails["BUFFER_INCOMPATIBLE_CODECS_ERROR"] = "bufferIncompatibleCodecsError"; ErrorDetails["BUFFER_APPEND_ERROR"] = "bufferAppendError"; ErrorDetails["BUFFER_APPENDING_ERROR"] = "bufferAppendingError"; ErrorDetails["BUFFER_STALLED_ERROR"] = "bufferStalledError"; ErrorDetails["BUFFER_FULL_ERROR"] = "bufferFullError"; ErrorDetails["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole"; ErrorDetails["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall"; ErrorDetails["INTERNAL_EXCEPTION"] = "internalException"; ErrorDetails["INTERNAL_ABORTED"] = "aborted"; ErrorDetails["UNKNOWN"] = "unknown"; })(ErrorDetails || (ErrorDetails = {})); /***/ }), /***/ "./src/events.ts": /*!***********************!*\ !*** ./src/events.ts ***! \***********************/ /*! exports provided: Events */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Events", function() { return Events; }); /** * @readonly * @enum {string} */ var Events; (function (Events) { Events["MEDIA_ATTACHING"] = "hlsMediaAttaching"; Events["MEDIA_ATTACHED"] = "hlsMediaAttached"; Events["MEDIA_DETACHING"] = "hlsMediaDetaching"; Events["MEDIA_DETACHED"] = "hlsMediaDetached"; Events["BUFFER_RESET"] = "hlsBufferReset"; Events["BUFFER_CODECS"] = "hlsBufferCodecs"; Events["BUFFER_CREATED"] = "hlsBufferCreated"; Events["BUFFER_APPENDING"] = "hlsBufferAppending"; Events["BUFFER_APPENDED"] = "hlsBufferAppended"; Events["BUFFER_EOS"] = "hlsBufferEos"; Events["BUFFER_FLUSHING"] = "hlsBufferFlushing"; Events["BUFFER_FLUSHED"] = "hlsBufferFlushed"; Events["MANIFEST_LOADING"] = "hlsManifestLoading"; Events["MANIFEST_LOADED"] = "hlsManifestLoaded"; Events["MANIFEST_PARSED"] = "hlsManifestParsed"; Events["LEVEL_SWITCHING"] = "hlsLevelSwitching"; Events["LEVEL_SWITCHED"] = "hlsLevelSwitched"; Events["LEVEL_LOADING"] = "hlsLevelLoading"; Events["LEVEL_LOADED"] = "hlsLevelLoaded"; Events["LEVEL_UPDATED"] = "hlsLevelUpdated"; Events["LEVEL_PTS_UPDATED"] = "hlsLevelPtsUpdated"; Events["LEVELS_UPDATED"] = "hlsLevelsUpdated"; Events["AUDIO_TRACKS_UPDATED"] = "hlsAudioTracksUpdated"; Events["AUDIO_TRACK_SWITCHING"] = "hlsAudioTrackSwitching"; Events["AUDIO_TRACK_SWITCHED"] = "hlsAudioTrackSwitched"; Events["AUDIO_TRACK_LOADING"] = "hlsAudioTrackLoading"; Events["AUDIO_TRACK_LOADED"] = "hlsAudioTrackLoaded"; Events["SUBTITLE_TRACKS_UPDATED"] = "hlsSubtitleTracksUpdated"; Events["SUBTITLE_TRACKS_CLEARED"] = "hlsSubtitleTracksCleared"; Events["SUBTITLE_TRACK_SWITCH"] = "hlsSubtitleTrackSwitch"; Events["SUBTITLE_TRACK_LOADING"] = "hlsSubtitleTrackLoading"; Events["SUBTITLE_TRACK_LOADED"] = "hlsSubtitleTrackLoaded"; Events["SUBTITLE_FRAG_PROCESSED"] = "hlsSubtitleFragProcessed"; Events["CUES_PARSED"] = "hlsCuesParsed"; Events["NON_NATIVE_TEXT_TRACKS_FOUND"] = "hlsNonNativeTextTracksFound"; Events["INIT_PTS_FOUND"] = "hlsInitPtsFound"; Events["FRAG_LOADING"] = "hlsFragLoading"; Events["FRAG_LOAD_EMERGENCY_ABORTED"] = "hlsFragLoadEmergencyAborted"; Events["FRAG_LOADED"] = "hlsFragLoaded"; Events["FRAG_DECRYPTED"] = "hlsFragDecrypted"; Events["FRAG_PARSING_INIT_SEGMENT"] = "hlsFragParsingInitSegment"; Events["FRAG_PARSING_USERDATA"] = "hlsFragParsingUserdata"; Events["FRAG_PARSING_METADATA"] = "hlsFragParsingMetadata"; Events["FRAG_PARSED"] = "hlsFragParsed"; Events["FRAG_BUFFERED"] = "hlsFragBuffered"; Events["FRAG_CHANGED"] = "hlsFragChanged"; Events["FPS_DROP"] = "hlsFpsDrop"; Events["FPS_DROP_LEVEL_CAPPING"] = "hlsFpsDropLevelCapping"; Events["ERROR"] = "hlsError"; Events["DESTROYING"] = "hlsDestroying"; Events["KEY_LOADING"] = "hlsKeyLoading"; Events["KEY_LOADED"] = "hlsKeyLoaded"; Events["LIVE_BACK_BUFFER_REACHED"] = "hlsLiveBackBufferReached"; Events["BACK_BUFFER_REACHED"] = "hlsBackBufferReached"; })(Events || (Events = {})); /***/ }), /***/ "./src/hls.ts": /*!********************!*\ !*** ./src/hls.ts ***! \********************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Hls; }); /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js"); /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _loader_playlist_loader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./loader/playlist-loader */ "./src/loader/playlist-loader.ts"); /* harmony import */ var _loader_key_loader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./loader/key-loader */ "./src/loader/key-loader.ts"); /* harmony import */ var _controller_id3_track_controller__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./controller/id3-track-controller */ "./src/controller/id3-track-controller.ts"); /* harmony import */ var _controller_latency_controller__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./controller/latency-controller */ "./src/controller/latency-controller.ts"); /* harmony import */ var _controller_level_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./controller/level-controller */ "./src/controller/level-controller.ts"); /* harmony import */ var _controller_fragment_tracker__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./controller/fragment-tracker */ "./src/controller/fragment-tracker.ts"); /* harmony import */ var _controller_stream_controller__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./controller/stream-controller */ "./src/controller/stream-controller.ts"); /* harmony import */ var _is_supported__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./is-supported */ "./src/is-supported.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./config */ "./src/config.ts"); /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js"); /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_11__); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./events */ "./src/events.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./errors */ "./src/errors.ts"); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } /** * @module Hls * @class * @constructor */ var Hls = /*#__PURE__*/function () { Hls.isSupported = function isSupported() { return Object(_is_supported__WEBPACK_IMPORTED_MODULE_8__["isSupported"])(); }; /** * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`. * * @constructs Hls * @param {HlsConfig} config */ function Hls(userConfig) { if (userConfig === void 0) { userConfig = {}; } this.config = void 0; this.userConfig = void 0; this.coreComponents = void 0; this.networkControllers = void 0; this._emitter = new eventemitter3__WEBPACK_IMPORTED_MODULE_11__["EventEmitter"](); this._autoLevelCapping = void 0; this.abrController = void 0; this.bufferController = void 0; this.capLevelController = void 0; this.latencyController = void 0; this.levelController = void 0; this.streamController = void 0; this.audioTrackController = void 0; this.subtitleTrackController = void 0; this.emeController = void 0; this._media = null; this.url = null; var config = this.config = Object(_config__WEBPACK_IMPORTED_MODULE_10__["mergeConfig"])(Hls.DefaultConfig, userConfig); this.userConfig = userConfig; Object(_utils_logger__WEBPACK_IMPORTED_MODULE_9__["enableLogs"])(config.debug); this._autoLevelCapping = -1; if (config.progressive) { Object(_config__WEBPACK_IMPORTED_MODULE_10__["enableStreamingMode"])(config); } // core controllers and network loaders var ConfigAbrController = config.abrController, ConfigBufferController = config.bufferController, ConfigCapLevelController = config.capLevelController, ConfigFpsController = config.fpsController; var abrController = this.abrController = new ConfigAbrController(this); var bufferController = this.bufferController = new ConfigBufferController(this); var capLevelController = this.capLevelController = new ConfigCapLevelController(this); var fpsController = new ConfigFpsController(this); var playListLoader = new _loader_playlist_loader__WEBPACK_IMPORTED_MODULE_1__["default"](this); var keyLoader = new _loader_key_loader__WEBPACK_IMPORTED_MODULE_2__["default"](this); var id3TrackController = new _controller_id3_track_controller__WEBPACK_IMPORTED_MODULE_3__["default"](this); // network controllers var levelController = this.levelController = new _controller_level_controller__WEBPACK_IMPORTED_MODULE_5__["default"](this); // FragmentTracker must be defined before StreamController because the order of event handling is important var fragmentTracker = new _controller_fragment_tracker__WEBPACK_IMPORTED_MODULE_6__["FragmentTracker"](this); var streamController = this.streamController = new _controller_stream_controller__WEBPACK_IMPORTED_MODULE_7__["default"](this, fragmentTracker); // Cap level controller uses streamController to flush the buffer capLevelController.setStreamController(streamController); // fpsController uses streamController to switch when frames are being dropped fpsController.setStreamController(streamController); var networkControllers = [levelController, streamController]; this.networkControllers = networkControllers; var coreComponents = [playListLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker]; this.audioTrackController = this.createController(config.audioTrackController, null, networkControllers); this.createController(config.audioStreamController, fragmentTracker, networkControllers); // subtitleTrackController must be defined before because the order of event handling is important this.subtitleTrackController = this.createController(config.subtitleTrackController, null, networkControllers); this.createController(config.subtitleStreamController, fragmentTracker, networkControllers); this.createController(config.timelineController, null, coreComponents); this.emeController = this.createController(config.emeController, null, coreComponents); this.latencyController = this.createController(_controller_latency_controller__WEBPACK_IMPORTED_MODULE_4__["default"], null, coreComponents); this.coreComponents = coreComponents; } var _proto = Hls.prototype; _proto.createController = function createController(ControllerClass, fragmentTracker, components) { if (ControllerClass) { var controllerInstance = fragmentTracker ? new ControllerClass(this, fragmentTracker) : new ControllerClass(this); if (components) { components.push(controllerInstance); } return controllerInstance; } return null; } // Delegate the EventEmitter through the public API of Hls.js ; _proto.on = function on(event, listener, context) { if (context === void 0) { context = this; } this._emitter.on(event, listener, context); }; _proto.once = function once(event, listener, context) { if (context === void 0) { context = this; } this._emitter.once(event, listener, context); }; _proto.removeAllListeners = function removeAllListeners(event) { this._emitter.removeAllListeners(event); }; _proto.off = function off(event, listener, context, once) { if (context === void 0) { context = this; } this._emitter.off(event, listener, context, once); }; _proto.listeners = function listeners(event) { return this._emitter.listeners(event); }; _proto.emit = function emit(event, name, eventObject) { return this._emitter.emit(event, name, eventObject); }; _proto.trigger = function trigger(event, eventObject) { if (this.config.debug) { return this.emit(event, event, eventObject); } else { try { return this.emit(event, event, eventObject); } catch (e) { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].error('An internal error happened while handling event ' + event + '. Error message: "' + e.message + '". Here is a stacktrace:', e); this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorTypes"].OTHER_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].INTERNAL_EXCEPTION, fatal: false, event: event, error: e }); } } return false; }; _proto.listenerCount = function listenerCount(event) { return this._emitter.listenerCount(event); } /** * Dispose of the instance */ ; _proto.destroy = function destroy() { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('destroy'); this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].DESTROYING, undefined); this.detachMedia(); this.removeAllListeners(); this._autoLevelCapping = -1; this.url = null; this.networkControllers.forEach(function (component) { return component.destroy(); }); this.networkControllers.length = 0; this.coreComponents.forEach(function (component) { return component.destroy(); }); this.coreComponents.length = 0; } /** * Attaches Hls.js to a media element * @param {HTMLMediaElement} media */ ; _proto.attachMedia = function attachMedia(media) { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('attachMedia'); this._media = media; this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].MEDIA_ATTACHING, { media: media }); } /** * Detach Hls.js from the media */ ; _proto.detachMedia = function detachMedia() { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('detachMedia'); this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].MEDIA_DETACHING, undefined); this._media = null; } /** * Set the source URL. Can be relative or absolute. * @param {string} url */ ; _proto.loadSource = function loadSource(url) { this.stopLoad(); var media = this.media; var loadedSource = this.url; var loadingSource = this.url = url_toolkit__WEBPACK_IMPORTED_MODULE_0__["buildAbsoluteURL"](self.location.href, url, { alwaysNormalize: true }); _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("loadSource:" + loadingSource); if (media && loadedSource && loadedSource !== loadingSource && this.bufferController.hasSourceTypes()) { this.detachMedia(); this.attachMedia(media); } // when attaching to a source URL, trigger a playlist load this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].MANIFEST_LOADING, { url: url }); } /** * Start loading data from the stream source. * Depending on default config, client starts loading automatically when a source is set. * * @param {number} startPosition Set the start position to stream from * @default -1 None (from earliest point) */ ; _proto.startLoad = function startLoad(startPosition) { if (startPosition === void 0) { startPosition = -1; } _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("startLoad(" + startPosition + ")"); this.networkControllers.forEach(function (controller) { controller.startLoad(startPosition); }); } /** * Stop loading of any stream data. */ ; _proto.stopLoad = function stopLoad() { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('stopLoad'); this.networkControllers.forEach(function (controller) { controller.stopLoad(); }); } /** * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1) */ ; _proto.swapAudioCodec = function swapAudioCodec() { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('swapAudioCodec'); this.streamController.swapAudioCodec(); } /** * When the media-element fails, this allows to detach and then re-attach it * as one call (convenience method). * * Automatic recovery of media-errors by this process is configurable. */ ; _proto.recoverMediaError = function recoverMediaError() { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('recoverMediaError'); var media = this._media; this.detachMedia(); if (media) { this.attachMedia(media); } }; _proto.removeLevel = function removeLevel(levelIndex, urlId) { if (urlId === void 0) { urlId = 0; } this.levelController.removeLevel(levelIndex, urlId); } /** * @type {Level[]} */ ; _createClass(Hls, [{ key: "levels", get: function get() { var levels = this.levelController.levels; return levels ? levels : []; } /** * Index of quality level currently played * @type {number} */ }, { key: "currentLevel", get: function get() { return this.streamController.currentLevel; } /** * Set quality level index immediately . * This will flush the current buffer to replace the quality asap. * That means playback will interrupt at least shortly to re-buffer and re-sync eventually. * @type {number} -1 for automatic level selection */ , set: function set(newLevel) { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set currentLevel:" + newLevel); this.loadLevel = newLevel; this.abrController.clearTimer(); this.streamController.immediateLevelSwitch(); } /** * Index of next quality level loaded as scheduled by stream controller. * @type {number} */ }, { key: "nextLevel", get: function get() { return this.streamController.nextLevel; } /** * Set quality level index for next loaded data. * This will switch the video quality asap, without interrupting playback. * May abort current loading of data, and flush parts of buffer (outside currently played fragment region). * @type {number} -1 for automatic level selection */ , set: function set(newLevel) { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set nextLevel:" + newLevel); this.levelController.manualLevel = newLevel; this.streamController.nextLevelSwitch(); } /** * Return the quality level of the currently or last (of none is loaded currently) segment * @type {number} */ }, { key: "loadLevel", get: function get() { return this.levelController.level; } /** * Set quality level index for next loaded data in a conservative way. * This will switch the quality without flushing, but interrupt current loading. * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer. * @type {number} newLevel -1 for automatic level selection */ , set: function set(newLevel) { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set loadLevel:" + newLevel); this.levelController.manualLevel = newLevel; } /** * get next quality level loaded * @type {number} */ }, { key: "nextLoadLevel", get: function get() { return this.levelController.nextLoadLevel; } /** * Set quality level of next loaded segment in a fully "non-destructive" way. * Same as `loadLevel` but will wait for next switch (until current loading is done). * @type {number} level */ , set: function set(level) { this.levelController.nextLoadLevel = level; } /** * Return "first level": like a default level, if not set, * falls back to index of first level referenced in manifest * @type {number} */ }, { key: "firstLevel", get: function get() { return Math.max(this.levelController.firstLevel, this.minAutoLevel); } /** * Sets "first-level", see getter. * @type {number} */ , set: function set(newLevel) { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set firstLevel:" + newLevel); this.levelController.firstLevel = newLevel; } /** * Return start level (level of first fragment that will be played back) * if not overrided by user, first level appearing in manifest will be used as start level * if -1 : automatic start level selection, playback will start from level matching download bandwidth * (determined from download of first segment) * @type {number} */ }, { key: "startLevel", get: function get() { return this.levelController.startLevel; } /** * set start level (level of first fragment that will be played back) * if not overrided by user, first level appearing in manifest will be used as start level * if -1 : automatic start level selection, playback will start from level matching download bandwidth * (determined from download of first segment) * @type {number} newLevel */ , set: function set(newLevel) { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set startLevel:" + newLevel); // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel if (newLevel !== -1) { newLevel = Math.max(newLevel, this.minAutoLevel); } this.levelController.startLevel = newLevel; } /** * Get the current setting for capLevelToPlayerSize * * @type {boolean} */ }, { key: "capLevelToPlayerSize", get: function get() { return this.config.capLevelToPlayerSize; } /** * set dynamically set capLevelToPlayerSize against (`CapLevelController`) * * @type {boolean} */ , set: function set(shouldStartCapping) { var newCapLevelToPlayerSize = !!shouldStartCapping; if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) { if (newCapLevelToPlayerSize) { this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size. } else { this.capLevelController.stopCapping(); this.autoLevelCapping = -1; this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap. } this.config.capLevelToPlayerSize = newCapLevelToPlayerSize; } } /** * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`) * @type {number} */ }, { key: "autoLevelCapping", get: function get() { return this._autoLevelCapping; } /** * get bandwidth estimate * @type {number} */ , set: /** * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`) * @type {number} */ function set(newLevel) { if (this._autoLevelCapping !== newLevel) { _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set autoLevelCapping:" + newLevel); this._autoLevelCapping = newLevel; } } /** * True when automatic level selection enabled * @type {boolean} */ }, { key: "bandwidthEstimate", get: function get() { var bwEstimator = this.abrController.bwEstimator; if (!bwEstimator) { return NaN; } return bwEstimator.getEstimate(); } }, { key: "autoLevelEnabled", get: function get() { return this.levelController.manualLevel === -1; } /** * Level set manually (if any) * @type {number} */ }, { key: "manualLevel", get: function get() { return this.levelController.manualLevel; } /** * min level selectable in auto mode according to config.minAutoBitrate * @type {number} */ }, { key: "minAutoLevel", get: function get() { var levels = this.levels, minAutoBitrate = this.config.minAutoBitrate; if (!levels) return 0; var len = levels.length; for (var i = 0; i < len; i++) { if (levels[i].maxBitrate > minAutoBitrate) { return i; } } return 0; } /** * max level selectable in auto mode according to autoLevelCapping * @type {number} */ }, { key: "maxAutoLevel", get: function get() { var levels = this.levels, autoLevelCapping = this.autoLevelCapping; var maxAutoLevel; if (autoLevelCapping === -1 && levels && levels.length) { maxAutoLevel = levels.length - 1; } else { maxAutoLevel = autoLevelCapping; } return maxAutoLevel; } /** * next automatically selected quality level * @type {number} */ }, { key: "nextAutoLevel", get: function get() { // ensure next auto level is between min and max auto level return Math.min(Math.max(this.abrController.nextAutoLevel, this.minAutoLevel), this.maxAutoLevel); } /** * this setter is used to force next auto level. * this is useful to force a switch down in auto mode: * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example) * forced value is valid for one fragment. upon succesful frag loading at forced level, * this value will be resetted to -1 by ABR controller. * @type {number} */ , set: function set(nextLevel) { this.abrController.nextAutoLevel = Math.max(this.minAutoLevel, nextLevel); } /** * @type {AudioTrack[]} */ }, { key: "audioTracks", get: function get() { var audioTrackController = this.audioTrackController; return audioTrackController ? audioTrackController.audioTracks : []; } /** * index of the selected audio track (index in audio track lists) * @type {number} */ }, { key: "audioTrack", get: function get() { var audioTrackController = this.audioTrackController; return audioTrackController ? audioTrackController.audioTrack : -1; } /** * selects an audio track, based on its index in audio track lists * @type {number} */ , set: function set(audioTrackId) { var audioTrackController = this.audioTrackController; if (audioTrackController) { audioTrackController.audioTrack = audioTrackId; } } /** * get alternate subtitle tracks list from playlist * @type {MediaPlaylist[]} */ }, { key: "subtitleTracks", get: function get() { var subtitleTrackController = this.subtitleTrackController; return subtitleTrackController ? subtitleTrackController.subtitleTracks : []; } /** * index of the selected subtitle track (index in subtitle track lists) * @type {number} */ }, { key: "subtitleTrack", get: function get() { var subtitleTrackController = this.subtitleTrackController; return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1; }, set: /** * select an subtitle track, based on its index in subtitle track lists * @type {number} */ function set(subtitleTrackId) { var subtitleTrackController = this.subtitleTrackController; if (subtitleTrackController) { subtitleTrackController.subtitleTrack = subtitleTrackId; } } /** * @type {boolean} */ }, { key: "media", get: function get() { return this._media; } }, { key: "subtitleDisplay", get: function get() { var subtitleTrackController = this.subtitleTrackController; return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false; } /** * Enable/disable subtitle display rendering * @type {boolean} */ , set: function set(value) { var subtitleTrackController = this.subtitleTrackController; if (subtitleTrackController) { subtitleTrackController.subtitleDisplay = value; } } /** * get mode for Low-Latency HLS loading * @type {boolean} */ }, { key: "lowLatencyMode", get: function get() { return this.config.lowLatencyMode; } /** * Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK. * @type {boolean} */ , set: function set(mode) { this.config.lowLatencyMode = mode; } /** * position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```) * @type {number} */ }, { key: "liveSyncPosition", get: function get() { return this.latencyController.liveSyncPosition; } /** * estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced) * returns 0 before first playlist is loaded * @type {number} */ }, { key: "latency", get: function get() { return this.latencyController.latency; } /** * maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition``` * configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration``` * returns 0 before first playlist is loaded * @type {number} */ }, { key: "maxLatency", get: function get() { return this.latencyController.maxLatency; } /** * target distance from the edge as calculated by the latency controller * @type {number} */ }, { key: "targetLatency", get: function get() { return this.latencyController.targetLatency; } /** * the rate at which the edge of the current live playlist is advancing or 1 if there is none * @type {number} */ }, { key: "drift", get: function get() { return this.latencyController.drift; } /** * set to true when startLoad is called before MANIFEST_PARSED event * @type {boolean} */ }, { key: "forceStartLoad", get: function get() { return this.streamController.forceStartLoad; } }], [{ key: "version", get: function get() { return "1.0.8-0.canary.7582"; } }, { key: "Events", get: function get() { return _events__WEBPACK_IMPORTED_MODULE_12__["Events"]; } }, { key: "ErrorTypes", get: function get() { return _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorTypes"]; } }, { key: "ErrorDetails", get: function get() { return _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"]; } }, { key: "DefaultConfig", get: function get() { if (!Hls.defaultConfig) { return _config__WEBPACK_IMPORTED_MODULE_10__["hlsDefaultConfig"]; } return Hls.defaultConfig; } /** * @type {HlsConfig} */ , set: function set(defaultConfig) { Hls.defaultConfig = defaultConfig; } }]); return Hls; }(); Hls.defaultConfig = void 0; /***/ }), /***/ "./src/is-supported.ts": /*!*****************************!*\ !*** ./src/is-supported.ts ***! \*****************************/ /*! exports provided: isSupported, changeTypeSupported */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isSupported", function() { return isSupported; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "changeTypeSupported", function() { return changeTypeSupported; }); /* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/mediasource-helper */ "./src/utils/mediasource-helper.ts"); function getSourceBuffer() { return self.SourceBuffer || self.WebKitSourceBuffer; } function isSupported() { var mediaSource = Object(_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_0__["getMediaSource"])(); if (!mediaSource) { return false; } var sourceBuffer = getSourceBuffer(); var isTypeSupported = mediaSource && typeof mediaSource.isTypeSupported === 'function' && mediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'); // if SourceBuffer is exposed ensure its API is valid // safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible var sourceBufferValidAPI = !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function'; return !!isTypeSupported && !!sourceBufferValidAPI; } function changeTypeSupported() { var _sourceBuffer$prototy; var sourceBuffer = getSourceBuffer(); return typeof (sourceBuffer === null || sourceBuffer === void 0 ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) === null || _sourceBuffer$prototy === void 0 ? void 0 : _sourceBuffer$prototy.changeType) === 'function'; } /***/ }), /***/ "./src/loader/fragment-loader.ts": /*!***************************************!*\ !*** ./src/loader/fragment-loader.ts ***! \***************************************/ /*! exports provided: default, LoadError */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return FragmentLoader; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoadError", function() { return LoadError; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var MIN_CHUNK_SIZE = Math.pow(2, 17); // 128kb var FragmentLoader = /*#__PURE__*/function () { function FragmentLoader(config) { this.config = void 0; this.loader = null; this.partLoadTimeout = -1; this.config = config; } var _proto = FragmentLoader.prototype; _proto.destroy = function destroy() { if (this.loader) { this.loader.destroy(); this.loader = null; } }; _proto.abort = function abort() { if (this.loader) { // Abort the loader for current fragment. Only one may load at any given time this.loader.abort(); } }; _proto.load = function load(frag, _onProgress) { var _this = this; var url = frag.url; if (!url) { return Promise.reject(new LoadError({ type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_ERROR, fatal: false, frag: frag, networkDetails: null }, "Fragment does not have a " + (url ? 'part list' : 'url'))); } this.abort(); var config = this.config; var FragmentILoader = config.fLoader; var DefaultILoader = config.loader; return new Promise(function (resolve, reject) { if (_this.loader) { _this.loader.destroy(); } var loader = _this.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config); var loaderContext = createLoaderContext(frag); var loaderConfig = { timeout: config.fragLoadingTimeOut, maxRetry: 0, retryDelay: 0, maxRetryDelay: config.fragLoadingMaxRetryTimeout, highWaterMark: MIN_CHUNK_SIZE }; // Assign frag stats to the loader's stats reference frag.stats = loader.stats; loader.load(loaderContext, loaderConfig, { onSuccess: function onSuccess(response, stats, context, networkDetails) { _this.resetLoader(frag, loader); resolve({ frag: frag, part: null, payload: response.data, networkDetails: networkDetails }); }, onError: function onError(response, context, networkDetails) { _this.resetLoader(frag, loader); reject(new LoadError({ type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_ERROR, fatal: false, frag: frag, response: response, networkDetails: networkDetails })); }, onAbort: function onAbort(stats, context, networkDetails) { _this.resetLoader(frag, loader); reject(new LoadError({ type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].INTERNAL_ABORTED, fatal: false, frag: frag, networkDetails: networkDetails })); }, onTimeout: function onTimeout(response, context, networkDetails) { _this.resetLoader(frag, loader); reject(new LoadError({ type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_TIMEOUT, fatal: false, frag: frag, networkDetails: networkDetails })); }, onProgress: function onProgress(stats, context, data, networkDetails) { if (_onProgress) { _onProgress({ frag: frag, part: null, payload: data, networkDetails: networkDetails }); } } }); }); }; _proto.loadPart = function loadPart(frag, part, onProgress) { var _this2 = this; this.abort(); var config = this.config; var FragmentILoader = config.fLoader; var DefaultILoader = config.loader; return new Promise(function (resolve, reject) { if (_this2.loader) { _this2.loader.destroy(); } var loader = _this2.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config); var loaderContext = createLoaderContext(frag, part); var loaderConfig = { timeout: config.fragLoadingTimeOut, maxRetry: 0, retryDelay: 0, maxRetryDelay: config.fragLoadingMaxRetryTimeout, highWaterMark: MIN_CHUNK_SIZE }; // Assign part stats to the loader's stats reference part.stats = loader.stats; loader.load(loaderContext, loaderConfig, { onSuccess: function onSuccess(response, stats, context, networkDetails) { _this2.resetLoader(frag, loader); _this2.updateStatsFromPart(frag, part); var partLoadedData = { frag: frag, part: part, payload: response.data, networkDetails: networkDetails }; onProgress(partLoadedData); resolve(partLoadedData); }, onError: function onError(response, context, networkDetails) { _this2.resetLoader(frag, loader); reject(new LoadError({ type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_ERROR, fatal: false, frag: frag, part: part, response: response, networkDetails: networkDetails })); }, onAbort: function onAbort(stats, context, networkDetails) { frag.stats.aborted = part.stats.aborted; _this2.resetLoader(frag, loader); reject(new LoadError({ type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].INTERNAL_ABORTED, fatal: false, frag: frag, part: part, networkDetails: networkDetails })); }, onTimeout: function onTimeout(response, context, networkDetails) { _this2.resetLoader(frag, loader); reject(new LoadError({ type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_TIMEOUT, fatal: false, frag: frag, part: part, networkDetails: networkDetails })); } }); }); }; _proto.updateStatsFromPart = function updateStatsFromPart(frag, part) { var fragStats = frag.stats; var partStats = part.stats; var partTotal = partStats.total; fragStats.loaded += partStats.loaded; if (partTotal) { var estTotalParts = Math.round(frag.duration / part.duration); var estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts); var estRemainingParts = estTotalParts - estLoadedParts; var estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts); fragStats.total = fragStats.loaded + estRemainingBytes; } else { fragStats.total = Math.max(fragStats.loaded, fragStats.total); } var fragLoading = fragStats.loading; var partLoading = partStats.loading; if (fragLoading.start) { // add to fragment loader latency fragLoading.first += partLoading.first - partLoading.start; } else { fragLoading.start = partLoading.start; fragLoading.first = partLoading.first; } fragLoading.end = partLoading.end; }; _proto.resetLoader = function resetLoader(frag, loader) { frag.loader = null; if (this.loader === loader) { self.clearTimeout(this.partLoadTimeout); this.loader = null; } loader.destroy(); }; return FragmentLoader; }(); function createLoaderContext(frag, part) { if (part === void 0) { part = null; } var segment = part || frag; var loaderContext = { frag: frag, part: part, responseType: 'arraybuffer', url: segment.url, rangeStart: 0, rangeEnd: 0 }; var start = segment.byteRangeStartOffset; var end = segment.byteRangeEndOffset; if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(start) && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(end)) { loaderContext.rangeStart = start; loaderContext.rangeEnd = end; } return loaderContext; } var LoadError = /*#__PURE__*/function (_Error) { _inheritsLoose(LoadError, _Error); function LoadError(data) { var _this3; for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { params[_key - 1] = arguments[_key]; } _this3 = _Error.call.apply(_Error, [this].concat(params)) || this; _this3.data = void 0; _this3.data = data; return _this3; } return LoadError; }( /*#__PURE__*/_wrapNativeSuper(Error)); /***/ }), /***/ "./src/loader/fragment.ts": /*!********************************!*\ !*** ./src/loader/fragment.ts ***! \********************************/ /*! exports provided: ElementaryStreamTypes, BaseSegment, Fragment, Part */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ElementaryStreamTypes", function() { return ElementaryStreamTypes; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BaseSegment", function() { return BaseSegment; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Fragment", function() { return Fragment; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Part", function() { return Part; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js"); /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_1__); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _level_key__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./level-key */ "./src/loader/level-key.ts"); /* harmony import */ var _load_stats__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./load-stats */ "./src/loader/load-stats.ts"); function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var ElementaryStreamTypes; (function (ElementaryStreamTypes) { ElementaryStreamTypes["AUDIO"] = "audio"; ElementaryStreamTypes["VIDEO"] = "video"; ElementaryStreamTypes["AUDIOVIDEO"] = "audiovideo"; })(ElementaryStreamTypes || (ElementaryStreamTypes = {})); var BaseSegment = /*#__PURE__*/function () { // baseurl is the URL to the playlist // relurl is the portion of the URL that comes from inside the playlist. // Holds the types of data this fragment supports function BaseSegment(baseurl) { var _this$elementaryStrea; this._byteRange = null; this._url = null; this.baseurl = void 0; this.relurl = void 0; this.elementaryStreams = (_this$elementaryStrea = {}, _this$elementaryStrea[ElementaryStreamTypes.AUDIO] = null, _this$elementaryStrea[ElementaryStreamTypes.VIDEO] = null, _this$elementaryStrea[ElementaryStreamTypes.AUDIOVIDEO] = null, _this$elementaryStrea); this.baseurl = baseurl; } // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array var _proto = BaseSegment.prototype; _proto.setByteRange = function setByteRange(value, previous) { var params = value.split('@', 2); var byteRange = []; if (params.length === 1) { byteRange[0] = previous ? previous.byteRangeEndOffset : 0; } else { byteRange[0] = parseInt(params[1]); } byteRange[1] = parseInt(params[0]) + byteRange[0]; this._byteRange = byteRange; }; _createClass(BaseSegment, [{ key: "byteRange", get: function get() { if (!this._byteRange) { return []; } return this._byteRange; } }, { key: "byteRangeStartOffset", get: function get() { return this.byteRange[0]; } }, { key: "byteRangeEndOffset", get: function get() { return this.byteRange[1]; } }, { key: "url", get: function get() { if (!this._url && this.baseurl && this.relurl) { this._url = Object(url_toolkit__WEBPACK_IMPORTED_MODULE_1__["buildAbsoluteURL"])(this.baseurl, this.relurl, { alwaysNormalize: true }); } return this._url || ''; }, set: function set(value) { this._url = value; } }]); return BaseSegment; }(); var Fragment = /*#__PURE__*/function (_BaseSegment) { _inheritsLoose(Fragment, _BaseSegment); // EXTINF has to be present for a m38 to be considered valid // sn notates the sequence number for a segment, and if set to a string can be 'initSegment' // levelkey is the EXT-X-KEY that applies to this segment for decryption // core difference from the private field _decryptdata is the lack of the initialized IV // _decryptdata will set the IV for this segment based on the segment number in the fragment // A string representing the fragment type // A reference to the loader. Set while the fragment is loading, and removed afterwards. Used to abort fragment loading // The level/track index to which the fragment belongs // The continuity counter of the fragment // The starting Presentation Time Stamp (PTS) of the fragment. Set after transmux complete. // The ending Presentation Time Stamp (PTS) of the fragment. Set after transmux complete. // The latest Presentation Time Stamp (PTS) appended to the buffer. // The starting Decode Time Stamp (DTS) of the fragment. Set after transmux complete. // The ending Decode Time Stamp (DTS) of the fragment. Set after transmux complete. // The start time of the fragment, as listed in the manifest. Updated after transmux complete. // Set by `updateFragPTSDTS` in level-helper // The maximum starting Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete. // The minimum ending Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete. // Load/parse timing information // A flag indicating whether the segment was downloaded in order to test bitrate, and was not buffered // #EXTINF segment title // The Media Initialization Section for this segment function Fragment(type, baseurl) { var _this; _this = _BaseSegment.call(this, baseurl) || this; _this._decryptdata = null; _this.rawProgramDateTime = null; _this.programDateTime = null; _this.tagList = []; _this.duration = 0; _this.sn = 0; _this.levelkey = void 0; _this.type = void 0; _this.loader = null; _this.level = -1; _this.cc = 0; _this.startPTS = void 0; _this.endPTS = void 0; _this.appendedPTS = void 0; _this.startDTS = void 0; _this.endDTS = void 0; _this.start = 0; _this.deltaPTS = void 0; _this.maxStartPTS = void 0; _this.minEndPTS = void 0; _this.stats = new _load_stats__WEBPACK_IMPORTED_MODULE_4__["LoadStats"](); _this.urlId = 0; _this.data = void 0; _this.bitrateTest = false; _this.title = null; _this.initSegment = null; _this.type = type; return _this; } var _proto2 = Fragment.prototype; /** * Utility method for parseLevelPlaylist to create an initialization vector for a given segment * @param {number} segmentNumber - segment number to generate IV with * @returns {Uint8Array} */ _proto2.createInitializationVector = function createInitializationVector(segmentNumber) { var uint8View = new Uint8Array(16); for (var i = 12; i < 16; i++) { uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff; } return uint8View; } /** * Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data * @param levelkey - a playlist's encryption info * @param segmentNumber - the fragment's segment number * @returns {LevelKey} - an object to be applied as a fragment's decryptdata */ ; _proto2.setDecryptDataFromLevelKey = function setDecryptDataFromLevelKey(levelkey, segmentNumber) { var decryptdata = levelkey; if ((levelkey === null || levelkey === void 0 ? void 0 : levelkey.method) === 'AES-128' && levelkey.uri && !levelkey.iv) { decryptdata = _level_key__WEBPACK_IMPORTED_MODULE_3__["LevelKey"].fromURI(levelkey.uri); decryptdata.method = levelkey.method; decryptdata.iv = this.createInitializationVector(segmentNumber); decryptdata.keyFormat = 'identity'; } return decryptdata; }; _proto2.setElementaryStreamInfo = function setElementaryStreamInfo(type, startPTS, endPTS, startDTS, endDTS, partial) { if (partial === void 0) { partial = false; } var elementaryStreams = this.elementaryStreams; var info = elementaryStreams[type]; if (!info) { elementaryStreams[type] = { startPTS: startPTS, endPTS: endPTS, startDTS: startDTS, endDTS: endDTS, partial: partial }; return; } info.startPTS = Math.min(info.startPTS, startPTS); info.endPTS = Math.max(info.endPTS, endPTS); info.startDTS = Math.min(info.startDTS, startDTS); info.endDTS = Math.max(info.endDTS, endDTS); }; _proto2.clearElementaryStreamInfo = function clearElementaryStreamInfo() { var elementaryStreams = this.elementaryStreams; elementaryStreams[ElementaryStreamTypes.AUDIO] = null; elementaryStreams[ElementaryStreamTypes.VIDEO] = null; elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null; }; _createClass(Fragment, [{ key: "decryptdata", get: function get() { if (!this.levelkey && !this._decryptdata) { return null; } if (!this._decryptdata && this.levelkey) { var sn = this.sn; if (typeof sn !== 'number') { // We are fetching decryption data for a initialization segment // If the segment was encrypted with AES-128 // It must have an IV defined. We cannot substitute the Segment Number in. if (this.levelkey && this.levelkey.method === 'AES-128' && !this.levelkey.iv) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("missing IV for initialization segment with method=\"" + this.levelkey.method + "\" - compliance issue"); } /* Be converted to a Number. 'initSegment' will become NaN. NaN, which when converted through ToInt32() -> +0. --- Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation. */ sn = 0; } this._decryptdata = this.setDecryptDataFromLevelKey(this.levelkey, sn); } return this._decryptdata; } }, { key: "end", get: function get() { return this.start + this.duration; } }, { key: "endProgramDateTime", get: function get() { if (this.programDateTime === null) { return null; } if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.programDateTime)) { return null; } var duration = !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.duration) ? 0 : this.duration; return this.programDateTime + duration * 1000; } }, { key: "encrypted", get: function get() { var _this$decryptdata; // At the m3u8-parser level we need to add support for manifest signalled keyformats // when we want the fragment to start reporting that it is encrypted. // Currently, keyFormat will only be set for identity keys if ((_this$decryptdata = this.decryptdata) !== null && _this$decryptdata !== void 0 && _this$decryptdata.keyFormat && this.decryptdata.uri) { return true; } return false; } }]); return Fragment; }(BaseSegment); var Part = /*#__PURE__*/function (_BaseSegment2) { _inheritsLoose(Part, _BaseSegment2); function Part(partAttrs, frag, baseurl, index, previous) { var _this2; _this2 = _BaseSegment2.call(this, baseurl) || this; _this2.fragOffset = 0; _this2.duration = 0; _this2.gap = false; _this2.independent = false; _this2.relurl = void 0; _this2.fragment = void 0; _this2.index = void 0; _this2.stats = new _load_stats__WEBPACK_IMPORTED_MODULE_4__["LoadStats"](); _this2.duration = partAttrs.decimalFloatingPoint('DURATION'); _this2.gap = partAttrs.bool('GAP'); _this2.independent = partAttrs.bool('INDEPENDENT'); _this2.relurl = partAttrs.enumeratedString('URI'); _this2.fragment = frag; _this2.index = index; var byteRange = partAttrs.enumeratedString('BYTERANGE'); if (byteRange) { _this2.setByteRange(byteRange, previous); } if (previous) { _this2.fragOffset = previous.fragOffset + previous.duration; } return _this2; } _createClass(Part, [{ key: "start", get: function get() { return this.fragment.start + this.fragOffset; } }, { key: "end", get: function get() { return this.start + this.duration; } }, { key: "loaded", get: function get() { var elementaryStreams = this.elementaryStreams; return !!(elementaryStreams.audio || elementaryStreams.video || elementaryStreams.audiovideo); } }]); return Part; }(BaseSegment); /***/ }), /***/ "./src/loader/key-loader.ts": /*!**********************************!*\ !*** ./src/loader/key-loader.ts ***! \**********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return KeyLoader; }); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* * Decrypt key Loader */ var KeyLoader = /*#__PURE__*/function () { function KeyLoader(hls) { this.hls = void 0; this.loaders = {}; this.decryptkey = null; this.decrypturl = null; this.hls = hls; this._registerListeners(); } var _proto = KeyLoader.prototype; _proto._registerListeners = function _registerListeners() { this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADING, this.onKeyLoading, this); }; _proto._unregisterListeners = function _unregisterListeners() { this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADING, this.onKeyLoading); }; _proto.destroy = function destroy() { this._unregisterListeners(); for (var loaderName in this.loaders) { var loader = this.loaders[loaderName]; if (loader) { loader.destroy(); } } this.loaders = {}; }; _proto.onKeyLoading = function onKeyLoading(event, data) { var frag = data.frag; var type = frag.type; var loader = this.loaders[type]; if (!frag.decryptdata) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('Missing decryption data on fragment in onKeyLoading'); return; } // Load the key if the uri is different from previous one, or if the decrypt key has not yet been retrieved var uri = frag.decryptdata.uri; if (uri !== this.decrypturl || this.decryptkey === null) { var config = this.hls.config; if (loader) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("abort previous key loader for type:" + type); loader.abort(); } if (!uri) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('key uri is falsy'); return; } var Loader = config.loader; var fragLoader = frag.loader = this.loaders[type] = new Loader(config); this.decrypturl = uri; this.decryptkey = null; var loaderContext = { url: uri, frag: frag, responseType: 'arraybuffer' }; // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times, // key-loader will trigger an error and rely on stream-controller to handle retry logic. // this will also align retry logic with fragment-loader var loaderConfig = { timeout: config.fragLoadingTimeOut, maxRetry: 0, retryDelay: config.fragLoadingRetryDelay, maxRetryDelay: config.fragLoadingMaxRetryTimeout, highWaterMark: 0 }; var loaderCallbacks = { onSuccess: this.loadsuccess.bind(this), onError: this.loaderror.bind(this), onTimeout: this.loadtimeout.bind(this) }; fragLoader.load(loaderContext, loaderConfig, loaderCallbacks); } else if (this.decryptkey) { // Return the key if it's already been loaded frag.decryptdata.key = this.decryptkey; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADED, { frag: frag }); } }; _proto.loadsuccess = function loadsuccess(response, stats, context) { var frag = context.frag; if (!frag.decryptdata) { _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('after key load, decryptdata unset'); return; } this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data); // detach fragment loader on load success frag.loader = null; delete this.loaders[frag.type]; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADED, { frag: frag }); }; _proto.loaderror = function loaderror(response, context) { var frag = context.frag; var loader = frag.loader; if (loader) { loader.abort(); } delete this.loaders[frag.type]; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_LOAD_ERROR, fatal: false, frag: frag, response: response }); }; _proto.loadtimeout = function loadtimeout(stats, context) { var frag = context.frag; var loader = frag.loader; if (loader) { loader.abort(); } delete this.loaders[frag.type]; this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_LOAD_TIMEOUT, fatal: false, frag: frag }); }; return KeyLoader; }(); /***/ }), /***/ "./src/loader/level-details.ts": /*!*************************************!*\ !*** ./src/loader/level-details.ts ***! \*************************************/ /*! exports provided: LevelDetails */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LevelDetails", function() { return LevelDetails; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var DEFAULT_TARGET_DURATION = 10; var LevelDetails = /*#__PURE__*/function () { // Manifest reload synchronization function LevelDetails(baseUrl) { this.PTSKnown = false; this.alignedSliding = false; this.averagetargetduration = void 0; this.endCC = 0; this.endSN = 0; this.fragments = void 0; this.fragmentHint = void 0; this.partList = null; this.live = true; this.ageHeader = 0; this.advancedDateTime = void 0; this.updated = true; this.advanced = true; this.availabilityDelay = void 0; this.misses = 0; this.needSidxRanges = false; this.startCC = 0; this.startSN = 0; this.startTimeOffset = null; this.targetduration = 0; this.totalduration = 0; this.type = null; this.url = void 0; this.m3u8 = ''; this.version = null; this.canBlockReload = false; this.canSkipUntil = 0; this.canSkipDateRanges = false; this.skippedSegments = 0; this.recentlyRemovedDateranges = void 0; this.partHoldBack = 0; this.holdBack = 0; this.partTarget = 0; this.preloadHint = void 0; this.renditionReports = void 0; this.tuneInGoal = 0; this.deltaUpdateFailed = void 0; this.driftStartTime = 0; this.driftEndTime = 0; this.driftStart = 0; this.driftEnd = 0; this.fragments = []; this.url = baseUrl; } var _proto = LevelDetails.prototype; _proto.reloaded = function reloaded(previous) { if (!previous) { this.advanced = true; this.updated = true; return; } var partSnDiff = this.lastPartSn - previous.lastPartSn; var partIndexDiff = this.lastPartIndex - previous.lastPartIndex; this.updated = this.endSN !== previous.endSN || !!partIndexDiff || !!partSnDiff; this.advanced = this.endSN > previous.endSN || partSnDiff > 0 || partSnDiff === 0 && partIndexDiff > 0; if (this.updated || this.advanced) { this.misses = Math.floor(previous.misses * 0.6); } else { this.misses = previous.misses + 1; } this.availabilityDelay = previous.availabilityDelay; }; _createClass(LevelDetails, [{ key: "hasProgramDateTime", get: function get() { if (this.fragments.length) { return Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.fragments[this.fragments.length - 1].programDateTime); } return false; } }, { key: "levelTargetDuration", get: function get() { return this.averagetargetduration || this.targetduration || DEFAULT_TARGET_DURATION; } }, { key: "drift", get: function get() { var runTime = this.driftEndTime - this.driftStartTime; if (runTime > 0) { var runDuration = this.driftEnd - this.driftStart; return runDuration * 1000 / runTime; } return 1; } }, { key: "edge", get: function get() { return this.partEnd || this.fragmentEnd; } }, { key: "partEnd", get: function get() { var _this$partList; if ((_this$partList = this.partList) !== null && _this$partList !== void 0 && _this$partList.length) { return this.partList[this.partList.length - 1].end; } return this.fragmentEnd; } }, { key: "fragmentEnd", get: function get() { var _this$fragments; if ((_this$fragments = this.fragments) !== null && _this$fragments !== void 0 && _this$fragments.length) { return this.fragments[this.fragments.length - 1].end; } return 0; } }, { key: "age", get: function get() { if (this.advancedDateTime) { return Math.max(Date.now() - this.advancedDateTime, 0) / 1000; } return 0; } }, { key: "lastPartIndex", get: function get() { var _this$partList2; if ((_this$partList2 = this.partList) !== null && _this$partList2 !== void 0 && _this$partList2.length) { return this.partList[this.partList.length - 1].index; } return -1; } }, { key: "lastPartSn", get: function get() { var _this$partList3; if ((_this$partList3 = this.partList) !== null && _this$partList3 !== void 0 && _this$partList3.length) { return this.partList[this.partList.length - 1].fragment.sn; } return this.endSN; } }]); return LevelDetails; }(); /***/ }), /***/ "./src/loader/level-key.ts": /*!*********************************!*\ !*** ./src/loader/level-key.ts ***! \*********************************/ /*! exports provided: LevelKey */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LevelKey", function() { return LevelKey; }); /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js"); /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_0__); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var LevelKey = /*#__PURE__*/function () { LevelKey.fromURL = function fromURL(baseUrl, relativeUrl) { return new LevelKey(baseUrl, relativeUrl); }; LevelKey.fromURI = function fromURI(uri) { return new LevelKey(uri); }; function LevelKey(absoluteOrBaseURI, relativeURL) { this._uri = null; this.method = null; this.keyFormat = null; this.keyFormatVersions = null; this.keyID = null; this.key = null; this.iv = null; if (relativeURL) { this._uri = Object(url_toolkit__WEBPACK_IMPORTED_MODULE_0__["buildAbsoluteURL"])(absoluteOrBaseURI, relativeURL, { alwaysNormalize: true }); } else { this._uri = absoluteOrBaseURI; } } _createClass(LevelKey, [{ key: "uri", get: function get() { return this._uri; } }]); return LevelKey; }(); /***/ }), /***/ "./src/loader/load-stats.ts": /*!**********************************!*\ !*** ./src/loader/load-stats.ts ***! \**********************************/ /*! exports provided: LoadStats */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoadStats", function() { return LoadStats; }); var LoadStats = function LoadStats() { this.aborted = false; this.loaded = 0; this.retry = 0; this.total = 0; this.chunkCount = 0; this.bwEstimate = 0; this.loading = { start: 0, first: 0, end: 0 }; this.parsing = { start: 0, end: 0 }; this.buffering = { start: 0, first: 0, end: 0 }; }; /***/ }), /***/ "./src/loader/m3u8-parser.ts": /*!***********************************!*\ !*** ./src/loader/m3u8-parser.ts ***! \***********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return M3U8Parser; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js"); /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_1__); /* harmony import */ var _fragment__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./fragment */ "./src/loader/fragment.ts"); /* harmony import */ var _level_details__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./level-details */ "./src/loader/level-details.ts"); /* harmony import */ var _level_key__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./level-key */ "./src/loader/level-key.ts"); /* harmony import */ var _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/attr-list */ "./src/utils/attr-list.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _utils_codecs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/codecs */ "./src/utils/codecs.ts"); // https://regex101.com is your friend var MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-SESSION-DATA:([^\r\n]*)[\r\n]+/g; var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g; var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title /(?!#) *(\S[\S ]*)/.source, // segment URI, group 3 => the URI (note newline is not eaten) /#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y) /#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec /#.*/.source // All other non-segment oriented tags will match with all groups empty ].join('|'), 'g'); var LEVEL_PLAYLIST_REGEX_SLOW = new RegExp([/#(EXTM3U)/.source, /#EXT-X-(PLAYLIST-TYPE):(.+)/.source, /#EXT-X-(MEDIA-SEQUENCE): *(\d+)/.source, /#EXT-X-(SKIP):(.+)/.source, /#EXT-X-(TARGETDURATION): *(\d+)/.source, /#EXT-X-(KEY):(.+)/.source, /#EXT-X-(START):(.+)/.source, /#EXT-X-(ENDLIST)/.source, /#EXT-X-(DISCONTINUITY-SEQ)UENCE: *(\d+)/.source, /#EXT-X-(DIS)CONTINUITY/.source, /#EXT-X-(VERSION):(\d+)/.source, /#EXT-X-(MAP):(.+)/.source, /#EXT-X-(SERVER-CONTROL):(.+)/.source, /#EXT-X-(PART-INF):(.+)/.source, /#EXT-X-(GAP)/.source, /#EXT-X-(BITRATE):\s*(\d+)/.source, /#EXT-X-(PART):(.+)/.source, /#EXT-X-(PRELOAD-HINT):(.+)/.source, /#EXT-X-(RENDITION-REPORT):(.+)/.source, /(#)([^:]*):(.*)/.source, /(#)(.*)(?:.*)\r?\n?/.source].join('|')); var MP4_REGEX_SUFFIX = /\.(mp4|m4s|m4v|m4a)$/i; function isMP4Url(url) { var _URLToolkit$parseURL$, _URLToolkit$parseURL; return MP4_REGEX_SUFFIX.test((_URLToolkit$parseURL$ = (_URLToolkit$parseURL = url_toolkit__WEBPACK_IMPORTED_MODULE_1__["parseURL"](url)) === null || _URLToolkit$parseURL === void 0 ? void 0 : _URLToolkit$parseURL.path) != null ? _URLToolkit$parseURL$ : ''); } var M3U8Parser = /*#__PURE__*/function () { function M3U8Parser() {} M3U8Parser.findGroup = function findGroup(groups, mediaGroupId) { for (var i = 0; i < groups.length; i++) { var group = groups[i]; if (group.id === mediaGroupId) { return group; } } }; M3U8Parser.convertAVC1ToAVCOTI = function convertAVC1ToAVCOTI(codec) { // Convert avc1 codec string from RFC-4281 to RFC-6381 for MediaSource.isTypeSupported var avcdata = codec.split('.'); if (avcdata.length > 2) { var result = avcdata.shift() + '.'; result += parseInt(avcdata.shift()).toString(16); result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4); return result; } return codec; }; M3U8Parser.resolve = function resolve(url, baseUrl) { return url_toolkit__WEBPACK_IMPORTED_MODULE_1__["buildAbsoluteURL"](baseUrl, url, { alwaysNormalize: true }); }; M3U8Parser.parseMasterPlaylist = function parseMasterPlaylist(string, baseurl) { var levels = []; var sessionData = {}; var hasSessionData = false; MASTER_PLAYLIST_REGEX.lastIndex = 0; var result; while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) { if (result[1]) { // '#EXT-X-STREAM-INF' is found, parse level tag in group 1 var attrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](result[1]); var level = { attrs: attrs, bitrate: attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH'), name: attrs.NAME, url: M3U8Parser.resolve(result[2], baseurl) }; var resolution = attrs.decimalResolution('RESOLUTION'); if (resolution) { level.width = resolution.width; level.height = resolution.height; } setCodecs((attrs.CODECS || '').split(/[ ,]+/).filter(function (c) { return c; }), level); if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) { level.videoCodec = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec); } levels.push(level); } else if (result[3]) { // '#EXT-X-SESSION-DATA' is found, parse session data in group 3 var sessionAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](result[3]); if (sessionAttrs['DATA-ID']) { hasSessionData = true; sessionData[sessionAttrs['DATA-ID']] = sessionAttrs; } } } return { levels: levels, sessionData: hasSessionData ? sessionData : null }; }; M3U8Parser.parseMasterPlaylistMedia = function parseMasterPlaylistMedia(string, baseurl, type, groups) { if (groups === void 0) { groups = []; } var result; var medias = []; var id = 0; MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0; while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) { var attrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](result[1]); if (attrs.TYPE === type) { var media = { attrs: attrs, bitrate: 0, id: id++, groupId: attrs['GROUP-ID'], instreamId: attrs['INSTREAM-ID'], name: attrs.NAME || attrs.LANGUAGE || '', type: type, default: attrs.bool('DEFAULT'), autoselect: attrs.bool('AUTOSELECT'), forced: attrs.bool('FORCED'), lang: attrs.LANGUAGE, url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : '' }; if (groups.length) { // If there are audio or text groups signalled in the manifest, let's look for a matching codec string for this track // If we don't find the track signalled, lets use the first audio groups codec we have // Acting as a best guess var groupCodec = M3U8Parser.findGroup(groups, media.groupId) || groups[0]; assignCodec(media, groupCodec, 'audioCodec'); assignCodec(media, groupCodec, 'textCodec'); } medias.push(media); } } return medias; }; M3U8Parser.parseLevelPlaylist = function parseLevelPlaylist(string, baseurl, id, type, levelUrlId) { var level = new _level_details__WEBPACK_IMPORTED_MODULE_3__["LevelDetails"](baseurl); var fragments = level.fragments; // The most recent init segment seen (applies to all subsequent segments) var currentInitSegment = null; var currentSN = 0; var currentPart = 0; var totalduration = 0; var discontinuityCounter = 0; var prevFrag = null; var frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Fragment"](type, baseurl); var result; var i; var levelkey; var firstPdtIndex = -1; var createNextFrag = false; LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0; level.m3u8 = string; while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) { if (createNextFrag) { createNextFrag = false; frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Fragment"](type, baseurl); // setup the next fragment for part loading frag.start = totalduration; frag.sn = currentSN; frag.cc = discontinuityCounter; frag.level = id; if (currentInitSegment) { frag.initSegment = currentInitSegment; frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime; } } var duration = result[1]; if (duration) { // INF frag.duration = parseFloat(duration); // avoid sliced strings https://github.com/video-dev/hls.js/issues/939 var title = (' ' + result[2]).slice(1); frag.title = title || null; frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]); } else if (result[3]) { // url if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.duration)) { frag.start = totalduration; if (levelkey) { frag.levelkey = levelkey; } frag.sn = currentSN; frag.level = id; frag.cc = discontinuityCounter; frag.urlId = levelUrlId; fragments.push(frag); // avoid sliced strings https://github.com/video-dev/hls.js/issues/939 frag.relurl = (' ' + result[3]).slice(1); assignProgramDateTime(frag, prevFrag); prevFrag = frag; totalduration += frag.duration; currentSN++; currentPart = 0; createNextFrag = true; } } else if (result[4]) { // X-BYTERANGE var data = (' ' + result[4]).slice(1); if (prevFrag) { frag.setByteRange(data, prevFrag); } else { frag.setByteRange(data); } } else if (result[5]) { // PROGRAM-DATE-TIME // avoid sliced strings https://github.com/video-dev/hls.js/issues/939 frag.rawProgramDateTime = (' ' + result[5]).slice(1); frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]); if (firstPdtIndex === -1) { firstPdtIndex = fragments.length; } } else { result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW); if (!result) { _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn('No matches on slow regex match for level playlist!'); continue; } for (i = 1; i < result.length; i++) { if (typeof result[i] !== 'undefined') { break; } } // avoid sliced strings https://github.com/video-dev/hls.js/issues/939 var tag = (' ' + result[i]).slice(1); var value1 = (' ' + result[i + 1]).slice(1); var value2 = result[i + 2] ? (' ' + result[i + 2]).slice(1) : ''; switch (tag) { case 'PLAYLIST-TYPE': level.type = value1.toUpperCase(); break; case 'MEDIA-SEQUENCE': currentSN = level.startSN = parseInt(value1); break; case 'SKIP': { var skipAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1); var skippedSegments = skipAttrs.decimalInteger('SKIPPED-SEGMENTS'); if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(skippedSegments)) { level.skippedSegments = skippedSegments; // This will result in fragments[] containing undefined values, which we will fill in with `mergeDetails` for (var _i = skippedSegments; _i--;) { fragments.unshift(null); } currentSN += skippedSegments; } var recentlyRemovedDateranges = skipAttrs.enumeratedString('RECENTLY-REMOVED-DATERANGES'); if (recentlyRemovedDateranges) { level.recentlyRemovedDateranges = recentlyRemovedDateranges.split('\t'); } break; } case 'TARGETDURATION': level.targetduration = parseFloat(value1); break; case 'VERSION': level.version = parseInt(value1); break; case 'EXTM3U': break; case 'ENDLIST': level.live = false; break; case '#': if (value1 || value2) { frag.tagList.push(value2 ? [value1, value2] : [value1]); } break; case 'DIS': discontinuityCounter++; /* falls through */ case 'GAP': frag.tagList.push([tag]); break; case 'BITRATE': frag.tagList.push([tag, value1]); break; case 'DISCONTINUITY-SEQ': discontinuityCounter = parseInt(value1); break; case 'KEY': { var _keyAttrs$enumeratedS; // https://tools.ietf.org/html/rfc8216#section-4.3.2.4 var keyAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1); var decryptmethod = keyAttrs.enumeratedString('METHOD'); var decrypturi = keyAttrs.URI; var decryptiv = keyAttrs.hexadecimalInteger('IV'); var decryptkeyformatversions = keyAttrs.enumeratedString('KEYFORMATVERSIONS'); var decryptkeyid = keyAttrs.enumeratedString('KEYID'); // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of "identity". var decryptkeyformat = (_keyAttrs$enumeratedS = keyAttrs.enumeratedString('KEYFORMAT')) != null ? _keyAttrs$enumeratedS : 'identity'; var unsupportedKnownKeyformatsInManifest = ['com.apple.streamingkeydelivery', 'com.microsoft.playready', 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed', // widevine (v2) 'com.widevine' // earlier widevine (v1) ]; if (unsupportedKnownKeyformatsInManifest.indexOf(decryptkeyformat) > -1) { _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn("Keyformat " + decryptkeyformat + " is not supported from the manifest"); continue; } else if (decryptkeyformat !== 'identity') { // We are supposed to skip keys we don't understand. // As we currently only officially support identity keys // from the manifest we shouldn't save any other key. continue; } // TODO: multiple keys can be defined on a fragment, and we need to support this // for clients that support both playready and widevine if (decryptmethod) { // TODO: need to determine if the level key is actually a relative URL // if it isn't, then we should instead construct the LevelKey using fromURI. levelkey = _level_key__WEBPACK_IMPORTED_MODULE_4__["LevelKey"].fromURL(baseurl, decrypturi); if (decrypturi && ['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].indexOf(decryptmethod) >= 0) { levelkey.method = decryptmethod; levelkey.keyFormat = decryptkeyformat; if (decryptkeyid) { levelkey.keyID = decryptkeyid; } if (decryptkeyformatversions) { levelkey.keyFormatVersions = decryptkeyformatversions; } // Initialization Vector (IV) levelkey.iv = decryptiv; } } break; } case 'START': { var startAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1); var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET'); // TIME-OFFSET can be 0 if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(startTimeOffset)) { level.startTimeOffset = startTimeOffset; } break; } case 'MAP': { var mapAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1); frag.relurl = mapAttrs.URI; if (mapAttrs.BYTERANGE) { frag.setByteRange(mapAttrs.BYTERANGE); } frag.level = id; frag.sn = 'initSegment'; if (levelkey) { frag.levelkey = levelkey; } frag.initSegment = null; currentInitSegment = frag; createNextFrag = true; break; } case 'SERVER-CONTROL': { var serverControlAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1); level.canBlockReload = serverControlAttrs.bool('CAN-BLOCK-RELOAD'); level.canSkipUntil = serverControlAttrs.optionalFloat('CAN-SKIP-UNTIL', 0); level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool('CAN-SKIP-DATERANGES'); level.partHoldBack = serverControlAttrs.optionalFloat('PART-HOLD-BACK', 0); level.holdBack = serverControlAttrs.optionalFloat('HOLD-BACK', 0); break; } case 'PART-INF': { var partInfAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1); level.partTarget = partInfAttrs.decimalFloatingPoint('PART-TARGET'); break; } case 'PART': { var partList = level.partList; if (!partList) { partList = level.partList = []; } var previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : undefined; var index = currentPart++; var part = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Part"](new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1), frag, baseurl, index, previousFragmentPart); partList.push(part); frag.duration += part.duration; break; } case 'PRELOAD-HINT': { var preloadHintAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1); level.preloadHint = preloadHintAttrs; break; } case 'RENDITION-REPORT': { var renditionReportAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1); level.renditionReports = level.renditionReports || []; level.renditionReports.push(renditionReportAttrs); break; } default: _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn("line parsed but not handled: " + result); break; } } } if (prevFrag && !prevFrag.relurl) { fragments.pop(); totalduration -= prevFrag.duration; if (level.partList) { level.fragmentHint = prevFrag; } } else if (level.partList) { assignProgramDateTime(frag, prevFrag); frag.cc = discontinuityCounter; level.fragmentHint = frag; } var fragmentLength = fragments.length; var firstFragment = fragments[0]; var lastFragment = fragments[fragmentLength - 1]; totalduration += level.skippedSegments * level.targetduration; if (totalduration > 0 && fragmentLength && lastFragment) { level.averagetargetduration = totalduration / fragmentLength; var lastSn = lastFragment.sn; level.endSN = lastSn !== 'initSegment' ? lastSn : 0; if (firstFragment) { level.startCC = firstFragment.cc; if (!firstFragment.initSegment) { // this is a bit lurky but HLS really has no other way to tell us // if the fragments are TS or MP4, except if we download them :/ // but this is to be able to handle SIDX. if (level.fragments.every(function (frag) { return frag.relurl && isMP4Url(frag.relurl); })) { _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX'); frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Fragment"](type, baseurl); frag.relurl = lastFragment.relurl; frag.level = id; frag.sn = 'initSegment'; firstFragment.initSegment = frag; level.needSidxRanges = true; } } } } else { level.endSN = 0; level.startCC = 0; } if (level.fragmentHint) { totalduration += level.fragmentHint.duration; } level.totalduration = totalduration; level.endCC = discontinuityCounter; /** * Backfill any missing PDT values * "If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after * one or more Media Segment URIs, the client SHOULD extrapolate * backward from that tag (using EXTINF durations and/or media * timestamps) to associate dates with those segments." * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs * computed. */ if (firstPdtIndex > 0) { backfillProgramDateTimes(fragments, firstPdtIndex); } return level; }; return M3U8Parser; }(); function setCodecs(codecs, level) { ['video', 'audio', 'text'].forEach(function (type) { var filtered = codecs.filter(function (codec) { return Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_7__["isCodecType"])(codec, type); }); if (filtered.length) { var preferred = filtered.filter(function (codec) { return codec.lastIndexOf('avc1', 0) === 0 || codec.lastIndexOf('mp4a', 0) === 0; }); level[type + "Codec"] = preferred.length > 0 ? preferred[0] : filtered[0]; // remove from list codecs = codecs.filter(function (codec) { return filtered.indexOf(codec) === -1; }); } }); level.unknownCodecs = codecs; } function assignCodec(media, groupItem, codecProperty) { var codecValue = groupItem[codecProperty]; if (codecValue) { media[codecProperty] = codecValue; } } function backfillProgramDateTimes(fragments, firstPdtIndex) { var fragPrev = fragments[firstPdtIndex]; for (var i = firstPdtIndex; i--;) { var frag = fragments[i]; // Exit on delta-playlist skipped segments if (!frag) { return; } frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000; fragPrev = frag; } } function assignProgramDateTime(frag, prevFrag) { if (frag.rawProgramDateTime) { frag.programDateTime = Date.parse(frag.rawProgramDateTime); } else if (prevFrag !== null && prevFrag !== void 0 && prevFrag.programDateTime) { frag.programDateTime = prevFrag.endProgramDateTime; } if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.programDateTime)) { frag.programDateTime = null; frag.rawProgramDateTime = null; } } /***/ }), /***/ "./src/loader/playlist-loader.ts": /*!***************************************!*\ !*** ./src/loader/playlist-loader.ts ***! \***************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts"); /* harmony import */ var _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./m3u8-parser */ "./src/loader/m3u8-parser.ts"); /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts"); /* harmony import */ var _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/attr-list */ "./src/utils/attr-list.ts"); /** * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models. * * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks. * * Uses loader(s) set in config to do actual internal loading of resource tasks. * * @module * */ function mapContextToLevelType(context) { var type = context.type; switch (type) { case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK: return _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO; case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK: return _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].SUBTITLE; default: return _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN; } } function getResponseUrl(response, context) { var url = response.url; // responseURL not supported on some browsers (it is used to detect URL redirection) // data-uri mode also not supported (but no need to detect redirection) if (url === undefined || url.indexOf('data:') === 0) { // fallback to initial URL url = context.url; } return url; } var PlaylistLoader = /*#__PURE__*/function () { function PlaylistLoader(hls) { this.hls = void 0; this.loaders = Object.create(null); this.hls = hls; this.registerListeners(); } var _proto = PlaylistLoader.prototype; _proto.registerListeners = function registerListeners() { var hls = this.hls; hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADING, this.onLevelLoading, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this); hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this); }; _proto.unregisterListeners = function unregisterListeners() { var hls = this.hls; hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADING, this.onLevelLoading, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this); hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this); } /** * Returns defaults or configured loader-type overloads (pLoader and loader config params) */ ; _proto.createInternalLoader = function createInternalLoader(context) { var config = this.hls.config; var PLoader = config.pLoader; var Loader = config.loader; var InternalLoader = PLoader || Loader; var loader = new InternalLoader(config); context.loader = loader; this.loaders[context.type] = loader; return loader; }; _proto.getInternalLoader = function getInternalLoader(context) { return this.loaders[context.type]; }; _proto.resetInternalLoader = function resetInternalLoader(contextType) { if (this.loaders[contextType]) { delete this.loaders[contextType]; } } /** * Call `destroy` on all internal loader instances mapped (one per context type) */ ; _proto.destroyInternalLoaders = function destroyInternalLoaders() { for (var contextType in this.loaders) { var loader = this.loaders[contextType]; if (loader) { loader.destroy(); } this.resetInternalLoader(contextType); } }; _proto.destroy = function destroy() { this.unregisterListeners(); this.destroyInternalLoaders(); }; _proto.onManifestLoading = function onManifestLoading(event, data) { var url = data.url; this.load({ id: null, groupId: null, level: 0, responseType: 'text', type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST, url: url, deliveryDirectives: null }); }; _proto.onLevelLoading = function onLevelLoading(event, data) { var id = data.id, level = data.level, url = data.url, deliveryDirectives = data.deliveryDirectives; this.load({ id: id, groupId: null, level: level, responseType: 'text', type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL, url: url, deliveryDirectives: deliveryDirectives }); }; _proto.onAudioTrackLoading = function onAudioTrackLoading(event, data) { var id = data.id, groupId = data.groupId, url = data.url, deliveryDirectives = data.deliveryDirectives; this.load({ id: id, groupId: groupId, level: null, responseType: 'text', type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK, url: url, deliveryDirectives: deliveryDirectives }); }; _proto.onSubtitleTrackLoading = function onSubtitleTrackLoading(event, data) { var id = data.id, groupId = data.groupId, url = data.url, deliveryDirectives = data.deliveryDirectives; this.load({ id: id, groupId: groupId, level: null, responseType: 'text', type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK, url: url, deliveryDirectives: deliveryDirectives }); }; _proto.load = function load(context) { var _context$deliveryDire; var config = this.hls.config; // logger.debug(`[playlist-loader]: Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`); // Check if a loader for this context already exists var loader = this.getInternalLoader(context); if (loader) { var loaderContext = loader.context; if (loaderContext && loaderContext.url === context.url) { // same URL can't overlap _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].trace('[playlist-loader]: playlist request ongoing'); return; } _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log("[playlist-loader]: aborting previous loader for type: " + context.type); loader.abort(); } var maxRetry; var timeout; var retryDelay; var maxRetryDelay; // apply different configs for retries depending on // context (manifest, level, audio/subs playlist) switch (context.type) { case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST: maxRetry = config.manifestLoadingMaxRetry; timeout = config.manifestLoadingTimeOut; retryDelay = config.manifestLoadingRetryDelay; maxRetryDelay = config.manifestLoadingMaxRetryTimeout; break; case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL: case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK: case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK: // Manage retries in Level/Track Controller maxRetry = 0; timeout = config.levelLoadingTimeOut; break; default: maxRetry = config.levelLoadingMaxRetry; timeout = config.levelLoadingTimeOut; retryDelay = config.levelLoadingRetryDelay; maxRetryDelay = config.levelLoadingMaxRetryTimeout; break; } loader = this.createInternalLoader(context); // Override level/track timeout for LL-HLS requests // (the default of 10000ms is counter productive to blocking playlist reload requests) if ((_context$deliveryDire = context.deliveryDirectives) !== null && _context$deliveryDire !== void 0 && _context$deliveryDire.part) { var levelDetails; if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL && context.level !== null) { levelDetails = this.hls.levels[context.level].details; } else if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK && context.id !== null) { levelDetails = this.hls.audioTracks[context.id].details; } else if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK && context.id !== null) { levelDetails = this.hls.subtitleTracks[context.id].details; } if (levelDetails) { var partTarget = levelDetails.partTarget; var targetDuration = levelDetails.targetduration; if (partTarget && targetDuration) { timeout = Math.min(Math.max(partTarget * 3, targetDuration * 0.8) * 1000, timeout); } } } var loaderConfig = { timeout: timeout, maxRetry: maxRetry, retryDelay: retryDelay, maxRetryDelay: maxRetryDelay, highWaterMark: 0 }; var loaderCallbacks = { onSuccess: this.loadsuccess.bind(this), onError: this.loaderror.bind(this), onTimeout: this.loadtimeout.bind(this) }; // logger.debug(`[playlist-loader]: Calling internal loader delegate for URL: ${context.url}`); loader.load(context, loaderConfig, loaderCallbacks); }; _proto.loadsuccess = function loadsuccess(response, stats, context, networkDetails) { if (networkDetails === void 0) { networkDetails = null; } if (context.isSidxRequest) { this.handleSidxRequest(response, context); this.handlePlaylistLoaded(response, stats, context, networkDetails); return; } this.resetInternalLoader(context.type); var string = response.data; // Validate if it is an M3U8 at all if (string.indexOf('#EXTM3U') !== 0) { this.handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails); return; } stats.parsing.start = performance.now(); // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present) if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) { this.handleTrackOrLevelPlaylist(response, stats, context, networkDetails); } else { this.handleMasterPlaylist(response, stats, context, networkDetails); } }; _proto.loaderror = function loaderror(response, context, networkDetails) { if (networkDetails === void 0) { networkDetails = null; } this.handleNetworkError(context, networkDetails, false, response); }; _proto.loadtimeout = function loadtimeout(stats, context, networkDetails) { if (networkDetails === void 0) { networkDetails = null; } this.handleNetworkError(context, networkDetails, true); }; _proto.handleMasterPlaylist = function handleMasterPlaylist(response, stats, context, networkDetails) { var hls = this.hls; var string = response.data; var url = getResponseUrl(response, context); var _M3U8Parser$parseMast = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylist(string, url), levels = _M3U8Parser$parseMast.levels, sessionData = _M3U8Parser$parseMast.sessionData; if (!levels.length) { this.handleManifestParsingError(response, context, 'no level found in manifest', networkDetails); return; } // multi level playlist, parse level info var audioGroups = levels.map(function (level) { return { id: level.attrs.AUDIO, audioCodec: level.audioCodec }; }); var subtitleGroups = levels.map(function (level) { return { id: level.attrs.SUBTITLES, textCodec: level.textCodec }; }); var audioTracks = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups); var subtitles = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylistMedia(string, url, 'SUBTITLES', subtitleGroups); var captions = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylistMedia(string, url, 'CLOSED-CAPTIONS'); if (audioTracks.length) { // check if we have found an audio track embedded in main playlist (audio track without URI attribute) var embeddedAudioFound = audioTracks.some(function (audioTrack) { return !audioTrack.url; }); // if no embedded audio track defined, but audio codec signaled in quality level, // we need to signal this main audio track this could happen with playlists with // alt audio rendition in which quality levels (main) // contains both audio+video. but with mixed audio track not signaled if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) { _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log('[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one'); audioTracks.unshift({ type: 'main', name: 'main', default: false, autoselect: false, forced: false, id: -1, attrs: new _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__["AttrList"]({}), bitrate: 0, url: '' }); } } hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, { levels: levels, audioTracks: audioTracks, subtitles: subtitles, captions: captions, url: url, stats: stats, networkDetails: networkDetails, sessionData: sessionData }); }; _proto.handleTrackOrLevelPlaylist = function handleTrackOrLevelPlaylist(response, stats, context, networkDetails) { var hls = this.hls; var id = context.id, level = context.level, type = context.type; var url = getResponseUrl(response, context); var levelUrlId = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(id) ? id : 0; var levelId = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(level) ? level : levelUrlId; var levelType = mapContextToLevelType(context); var levelDetails = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId); if (!levelDetails.fragments.length) { hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].NETWORK_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_EMPTY_ERROR, fatal: false, url: url, reason: 'no fragments found in level', level: typeof context.level === 'number' ? context.level : undefined }); return; } // We have done our first request (Manifest-type) and receive // not a master playlist but a chunk-list (track/level) // We fire the manifest-loaded event anyway with the parsed level-details // by creating a single-level structure for it. if (type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST) { var singleLevel = { attrs: new _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__["AttrList"]({}), bitrate: 0, details: levelDetails, name: '', url: url }; hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, { levels: [singleLevel], audioTracks: [], url: url, stats: stats, networkDetails: networkDetails, sessionData: null }); } // save parsing time stats.parsing.end = performance.now(); // in case we need SIDX ranges // return early after calling load for // the SIDX box. if (levelDetails.needSidxRanges) { var _levelDetails$fragmen; var sidxUrl = (_levelDetails$fragmen = levelDetails.fragments[0].initSegment) === null || _levelDetails$fragmen === void 0 ? void 0 : _levelDetails$fragmen.url; this.load({ url: sidxUrl, isSidxRequest: true, type: type, level: level, levelDetails: levelDetails, id: id, groupId: null, rangeStart: 0, rangeEnd: 2048, responseType: 'arraybuffer', deliveryDirectives: null }); return; } // extend the context with the new levelDetails property context.levelDetails = levelDetails; this.handlePlaylistLoaded(response, stats, context, networkDetails); }; _proto.handleSidxRequest = function handleSidxRequest(response, context) { var sidxInfo = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__["parseSegmentIndex"])(new Uint8Array(response.data)); // if provided fragment does not contain sidx, early return if (!sidxInfo) { return; } var sidxReferences = sidxInfo.references; var levelDetails = context.levelDetails; sidxReferences.forEach(function (segmentRef, index) { var segRefInfo = segmentRef.info; var frag = levelDetails.fragments[index]; if (frag.byteRange.length === 0) { frag.setByteRange(String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start)); } if (frag.initSegment) { frag.initSegment.setByteRange(String(sidxInfo.moovEndOffset) + '@0'); } }); }; _proto.handleManifestParsingError = function handleManifestParsingError(response, context, reason, networkDetails) { this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].NETWORK_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_PARSING_ERROR, fatal: context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST, url: response.url, reason: reason, response: response, context: context, networkDetails: networkDetails }); }; _proto.handleNetworkError = function handleNetworkError(context, networkDetails, timeout, response) { if (timeout === void 0) { timeout = false; } _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("[playlist-loader]: A network " + (timeout ? 'timeout' : 'error') + " occurred while loading " + context.type + " level: " + context.level + " id: " + context.id + " group-id: \"" + context.groupId + "\""); var details = _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].UNKNOWN; var fatal = false; var loader = this.getInternalLoader(context); switch (context.type) { case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST: details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_LOAD_ERROR; fatal = true; break; case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL: details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_ERROR; fatal = false; break; case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK: details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].AUDIO_TRACK_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR; fatal = false; break; case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK: details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].SUBTITLE_TRACK_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].SUBTITLE_LOAD_ERROR; fatal = false; break; } if (loader) { this.resetInternalLoader(context.type); } var errorData = { type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].NETWORK_ERROR, details: details, fatal: fatal, url: context.url, loader: loader, context: context, networkDetails: networkDetails }; if (response) { errorData.response = response; } this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, errorData); }; _proto.handlePlaylistLoaded = function handlePlaylistLoaded(response, stats, context, networkDetails) { var type = context.type, level = context.level, id = context.id, groupId = context.groupId, loader = context.loader, levelDetails = context.levelDetails, deliveryDirectives = context.deliveryDirectives; if (!(levelDetails !== null && levelDetails !== void 0 && levelDetails.targetduration)) { this.handleManifestParsingError(response, context, 'invalid target duration', networkDetails); return; } if (!loader) { return; } if (levelDetails.live) { if (loader.getCacheAge) { levelDetails.ageHeader = loader.getCacheAge() || 0; } if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) { levelDetails.ageHeader = 0; } } switch (type) { case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST: case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL: this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADED, { details: levelDetails, level: level || 0, id: id || 0, stats: stats, networkDetails: networkDetails, deliveryDirectives: deliveryDirectives }); break; case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK: this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_LOADED, { details: levelDetails, id: id || 0, groupId: groupId || '', stats: stats, networkDetails: networkDetails, deliveryDirectives: deliveryDirectives }); break; case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK: this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACK_LOADED, { details: levelDetails, id: id || 0, groupId: groupId || '', stats: stats, networkDetails: networkDetails, deliveryDirectives: deliveryDirectives }); break; } }; return PlaylistLoader; }(); /* harmony default export */ __webpack_exports__["default"] = (PlaylistLoader); /***/ }), /***/ "./src/polyfills/number.ts": /*!*********************************!*\ !*** ./src/polyfills/number.ts ***! \*********************************/ /*! exports provided: isFiniteNumber, MAX_SAFE_INTEGER */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFiniteNumber", function() { return isFiniteNumber; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MAX_SAFE_INTEGER", function() { return MAX_SAFE_INTEGER; }); var isFiniteNumber = Number.isFinite || function (value) { return typeof value === 'number' && isFinite(value); }; var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; /***/ }), /***/ "./src/remux/aac-helper.ts": /*!*********************************!*\ !*** ./src/remux/aac-helper.ts ***! \*********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * AAC helper */ var AAC = /*#__PURE__*/function () { function AAC() {} AAC.getSilentFrame = function getSilentFrame(codec, channelCount) { switch (codec) { case 'mp4a.40.2': if (channelCount === 1) { return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]); } else if (channelCount === 2) { return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]); } else if (channelCount === 3) { return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]); } else if (channelCount === 4) { return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]); } else if (channelCount === 5) { return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]); } else if (channelCount === 6) { return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2, 0x00, 0x20, 0x08, 0xe0]); } break; // handle HE-AAC below (mp4a.40.5 / mp4a.40.29) default: if (channelCount === 1) { // ffmpeg -y -f lavfi -i "aevalsrc=0:d=0.05" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x4e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x1c, 0x6, 0xf1, 0xc1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]); } else if (channelCount === 2) { // ffmpeg -y -f lavfi -i "aevalsrc=0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]); } else if (channelCount === 3) { // ffmpeg -y -f lavfi -i "aevalsrc=0|0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]); } break; } return undefined; }; return AAC; }(); /* harmony default export */ __webpack_exports__["default"] = (AAC); /***/ }), /***/ "./src/remux/mp4-generator.ts": /*!************************************!*\ !*** ./src/remux/mp4-generator.ts ***! \************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * Generate MP4 Box */ var UINT32_MAX = Math.pow(2, 32) - 1; var MP4 = /*#__PURE__*/function () { function MP4() {} MP4.init = function init() { MP4.types = { avc1: [], // codingname avcC: [], btrt: [], dinf: [], dref: [], esds: [], ftyp: [], hdlr: [], mdat: [], mdhd: [], mdia: [], mfhd: [], minf: [], moof: [], moov: [], mp4a: [], '.mp3': [], mvex: [], mvhd: [], pasp: [], sdtp: [], stbl: [], stco: [], stsc: [], stsd: [], stsz: [], stts: [], tfdt: [], tfhd: [], traf: [], trak: [], trun: [], trex: [], tkhd: [], vmhd: [], smhd: [] }; var i; for (i in MP4.types) { if (MP4.types.hasOwnProperty(i)) { MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)]; } } var videoHdlr = new Uint8Array([0x00, // version 0 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x00, // pre_defined 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide' 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler' ]); var audioHdlr = new Uint8Array([0x00, // version 0 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x00, // pre_defined 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun' 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler' ]); MP4.HDLR_TYPES = { video: videoHdlr, audio: audioHdlr }; var dref = new Uint8Array([0x00, // version 0 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x01, // entry_count 0x00, 0x00, 0x00, 0x0c, // entry_size 0x75, 0x72, 0x6c, 0x20, // 'url' type 0x00, // version 0 0x00, 0x00, 0x01 // entry_flags ]); var stco = new Uint8Array([0x00, // version 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x00 // entry_count ]); MP4.STTS = MP4.STSC = MP4.STCO = stco; MP4.STSZ = new Uint8Array([0x00, // version 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x00, // sample_size 0x00, 0x00, 0x00, 0x00 // sample_count ]); MP4.VMHD = new Uint8Array([0x00, // version 0x00, 0x00, 0x01, // flags 0x00, 0x00, // graphicsmode 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor ]); MP4.SMHD = new Uint8Array([0x00, // version 0x00, 0x00, 0x00, // flags 0x00, 0x00, // balance 0x00, 0x00 // reserved ]); MP4.STSD = new Uint8Array([0x00, // version 0 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x01]); // entry_count var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1 var minorVersion = new Uint8Array([0, 0, 0, 1]); MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand); MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref)); }; MP4.box = function box(type) { var size = 8; for (var _len = arguments.length, payload = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { payload[_key - 1] = arguments[_key]; } var i = payload.length; var len = i; // calculate the total size we need to allocate while (i--) { size += payload[i].byteLength; } var result = new Uint8Array(size); result[0] = size >> 24 & 0xff; result[1] = size >> 16 & 0xff; result[2] = size >> 8 & 0xff; result[3] = size & 0xff; result.set(type, 4); // copy the payload into the result for (i = 0, size = 8; i < len; i++) { // copy payload[i] array @ offset size result.set(payload[i], size); size += payload[i].byteLength; } return result; }; MP4.hdlr = function hdlr(type) { return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]); }; MP4.mdat = function mdat(data) { return MP4.box(MP4.types.mdat, data); }; MP4.mdhd = function mdhd(timescale, duration) { duration *= timescale; var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)); var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1)); return MP4.box(MP4.types.mdhd, new Uint8Array([0x01, // version 1 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff, // timescale upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x55, 0xc4, // 'und' language (undetermined) 0x00, 0x00])); }; MP4.mdia = function mdia(track) { return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track)); }; MP4.mfhd = function mfhd(sequenceNumber) { return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags sequenceNumber >> 24, sequenceNumber >> 16 & 0xff, sequenceNumber >> 8 & 0xff, sequenceNumber & 0xff // sequence_number ])); }; MP4.minf = function minf(track) { if (track.type === 'audio') { return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track)); } else { return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track)); } }; MP4.moof = function moof(sn, baseMediaDecodeTime, track) { return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime)); } /** * @param tracks... (optional) {array} the tracks associated with this movie */ ; MP4.moov = function moov(tracks) { var i = tracks.length; var boxes = []; while (i--) { boxes[i] = MP4.trak(tracks[i]); } return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks))); }; MP4.mvex = function mvex(tracks) { var i = tracks.length; var boxes = []; while (i--) { boxes[i] = MP4.trex(tracks[i]); } return MP4.box.apply(null, [MP4.types.mvex].concat(boxes)); }; MP4.mvhd = function mvhd(timescale, duration) { duration *= timescale; var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)); var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1)); var bytes = new Uint8Array([0x01, // version 1 0x00, 0x00, 0x00, // flags 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff, // timescale upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x01, 0x00, 0x00, // 1.0 rate 0x01, 0x00, // 1.0 volume 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined 0xff, 0xff, 0xff, 0xff // next_track_ID ]); return MP4.box(MP4.types.mvhd, bytes); }; MP4.sdtp = function sdtp(track) { var samples = track.samples || []; var bytes = new Uint8Array(4 + samples.length); var i; var flags; // leave the full box header (4 bytes) all zero // write the sample table for (i = 0; i < samples.length; i++) { flags = samples[i].flags; bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy; } return MP4.box(MP4.types.sdtp, bytes); }; MP4.stbl = function stbl(track) { return MP4.box(MP4.types.stbl, MP4.stsd(track), MP4.box(MP4.types.stts, MP4.STTS), MP4.box(MP4.types.stsc, MP4.STSC), MP4.box(MP4.types.stsz, MP4.STSZ), MP4.box(MP4.types.stco, MP4.STCO)); }; MP4.avc1 = function avc1(track) { var sps = []; var pps = []; var i; var data; var len; // assemble the SPSs for (i = 0; i < track.sps.length; i++) { data = track.sps[i]; len = data.byteLength; sps.push(len >>> 8 & 0xff); sps.push(len & 0xff); // SPS sps = sps.concat(Array.prototype.slice.call(data)); } // assemble the PPSs for (i = 0; i < track.pps.length; i++) { data = track.pps[i]; len = data.byteLength; pps.push(len >>> 8 & 0xff); pps.push(len & 0xff); pps = pps.concat(Array.prototype.slice.call(data)); } var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01, // version sps[3], // profile sps[4], // profile compat sps[5], // level 0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes 0xe0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets ].concat(sps).concat([track.pps.length // numOfPictureParameterSets ]).concat(pps))); // "PPS" var width = track.width; var height = track.height; var hSpacing = track.pixelRatio[0]; var vSpacing = track.pixelRatio[1]; return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, // reserved 0x00, 0x01, // data_reference_index 0x00, 0x00, // pre_defined 0x00, 0x00, // reserved 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined width >> 8 & 0xff, width & 0xff, // width height >> 8 & 0xff, height & 0xff, // height 0x00, 0x48, 0x00, 0x00, // horizresolution 0x00, 0x48, 0x00, 0x00, // vertresolution 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x01, // frame_count 0x12, 0x64, 0x61, 0x69, 0x6c, // dailymotion/hls.js 0x79, 0x6d, 0x6f, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x68, 0x6c, 0x73, 0x2e, 0x6a, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname 0x00, 0x18, // depth = 24 0x11, 0x11]), // pre_defined = -1 avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate 0x00, 0x2d, 0xc6, 0xc0])), // avgBitrate MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24, // hSpacing hSpacing >> 16 & 0xff, hSpacing >> 8 & 0xff, hSpacing & 0xff, vSpacing >> 24, // vSpacing vSpacing >> 16 & 0xff, vSpacing >> 8 & 0xff, vSpacing & 0xff]))); }; MP4.esds = function esds(track) { var configlen = track.config.length; return new Uint8Array([0x00, // version 0 0x00, 0x00, 0x00, // flags 0x03, // descriptor_type 0x17 + configlen, // length 0x00, 0x01, // es_id 0x00, // stream_priority 0x04, // descriptor_type 0x0f + configlen, // length 0x40, // codec : mpeg4_audio 0x15, // stream_type 0x00, 0x00, 0x00, // buffer_size 0x00, 0x00, 0x00, 0x00, // maxBitrate 0x00, 0x00, 0x00, 0x00, // avgBitrate 0x05 // descriptor_type ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor }; MP4.mp4a = function mp4a(track) { var samplerate = track.samplerate; return MP4.box(MP4.types.mp4a, new Uint8Array([0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, // reserved 0x00, 0x01, // data_reference_index 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved 0x00, track.channelCount, // channelcount 0x00, 0x10, // sampleSize:16bits 0x00, 0x00, 0x00, 0x00, // reserved2 samplerate >> 8 & 0xff, samplerate & 0xff, // 0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track))); }; MP4.mp3 = function mp3(track) { var samplerate = track.samplerate; return MP4.box(MP4.types['.mp3'], new Uint8Array([0x00, 0x00, 0x00, // reserved 0x00, 0x00, 0x00, // reserved 0x00, 0x01, // data_reference_index 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved 0x00, track.channelCount, // channelcount 0x00, 0x10, // sampleSize:16bits 0x00, 0x00, 0x00, 0x00, // reserved2 samplerate >> 8 & 0xff, samplerate & 0xff, // 0x00, 0x00])); }; MP4.stsd = function stsd(track) { if (track.type === 'audio') { if (!track.isAAC && track.codec === 'mp3') { return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track)); } return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track)); } else { return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track)); } }; MP4.tkhd = function tkhd(track) { var id = track.id; var duration = track.duration * track.timescale; var width = track.width; var height = track.height; var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)); var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1)); return MP4.box(MP4.types.tkhd, new Uint8Array([0x01, // version 1 0x00, 0x00, 0x07, // flags 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time id >> 24 & 0xff, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff, // track_ID 0x00, 0x00, 0x00, 0x00, // reserved upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved 0x00, 0x00, // layer 0x00, 0x00, // alternate_group 0x00, 0x00, // non-audio track volume 0x00, 0x00, // reserved 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix width >> 8 & 0xff, width & 0xff, 0x00, 0x00, // width height >> 8 & 0xff, height & 0xff, 0x00, 0x00 // height ])); }; MP4.traf = function traf(track, baseMediaDecodeTime) { var sampleDependencyTable = MP4.sdtp(track); var id = track.id; var upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1)); var lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1)); return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00, // version 0 0x00, 0x00, 0x00, // flags id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff // track_ID ])), MP4.box(MP4.types.tfdt, new Uint8Array([0x01, // version 1 0x00, 0x00, 0x00, // flags upperWordBaseMediaDecodeTime >> 24, upperWordBaseMediaDecodeTime >> 16 & 0xff, upperWordBaseMediaDecodeTime >> 8 & 0xff, upperWordBaseMediaDecodeTime & 0xff, lowerWordBaseMediaDecodeTime >> 24, lowerWordBaseMediaDecodeTime >> 16 & 0xff, lowerWordBaseMediaDecodeTime >> 8 & 0xff, lowerWordBaseMediaDecodeTime & 0xff])), MP4.trun(track, sampleDependencyTable.length + 16 + // tfhd 20 + // tfdt 8 + // traf header 16 + // mfhd 8 + // moof header 8), // mdat header sampleDependencyTable); } /** * Generate a track box. * @param track {object} a track definition * @return {Uint8Array} the track box */ ; MP4.trak = function trak(track) { track.duration = track.duration || 0xffffffff; return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track)); }; MP4.trex = function trex(track) { var id = track.id; return MP4.box(MP4.types.trex, new Uint8Array([0x00, // version 0 0x00, 0x00, 0x00, // flags id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff, // track_ID 0x00, 0x00, 0x00, 0x01, // default_sample_description_index 0x00, 0x00, 0x00, 0x00, // default_sample_duration 0x00, 0x00, 0x00, 0x00, // default_sample_size 0x00, 0x01, 0x00, 0x01 // default_sample_flags ])); }; MP4.trun = function trun(track, offset) { var samples = track.samples || []; var len = samples.length; var arraylen = 12 + 16 * len; var array = new Uint8Array(arraylen); var i; var sample; var duration; var size; var flags; var cts; offset += 8 + arraylen; array.set([0x00, // version 0 0x00, 0x0f, 0x01, // flags len >>> 24 & 0xff, len >>> 16 & 0xff, len >>> 8 & 0xff, len & 0xff, // sample_count offset >>> 24 & 0xff, offset >>> 16 & 0xff, offset >>> 8 & 0xff, offset & 0xff // data_offset ], 0); for (i = 0; i < len; i++) { sample = samples[i]; duration = sample.duration; size = sample.size; flags = sample.flags; cts = sample.cts; array.set([duration >>> 24 & 0xff, duration >>> 16 & 0xff, duration >>> 8 & 0xff, duration & 0xff, // sample_duration size >>> 24 & 0xff, size >>> 16 & 0xff, size >>> 8 & 0xff, size & 0xff, // sample_size flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xf0 << 8, flags.degradPrio & 0x0f, // sample_flags cts >>> 24 & 0xff, cts >>> 16 & 0xff, cts >>> 8 & 0xff, cts & 0xff // sample_composition_time_offset ], 12 + 16 * i); } return MP4.box(MP4.types.trun, array); }; MP4.initSegment = function initSegment(tracks) { if (!MP4.types) { MP4.init(); } var movie = MP4.moov(tracks); var result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength); result.set(MP4.FTYP); result.set(movie, MP4.FTYP.byteLength); return result; }; return MP4; }(); MP4.types = void 0; MP4.HDLR_TYPES = void 0; MP4.STTS = void 0; MP4.STSC = void 0; MP4.STCO = void 0; MP4.STSZ = void 0; MP4.VMHD = void 0; MP4.SMHD = void 0; MP4.STSD = void 0; MP4.FTYP = void 0; MP4.DINF = void 0; /* harmony default export */ __webpack_exports__["default"] = (MP4); /***/ }), /***/ "./src/remux/mp4-remuxer.ts": /*!**********************************!*\ !*** ./src/remux/mp4-remuxer.ts ***! \**********************************/ /*! exports provided: default, normalizePts */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return MP4Remuxer; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "normalizePts", function() { return normalizePts; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _aac_helper__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./aac-helper */ "./src/remux/aac-helper.ts"); /* harmony import */ var _mp4_generator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./mp4-generator */ "./src/remux/mp4-generator.ts"); /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../events */ "./src/events.ts"); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts"); /* harmony import */ var _utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/timescale-conversion */ "./src/utils/timescale-conversion.ts"); function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } var MAX_SILENT_FRAME_DURATION = 10 * 1000; // 10 seconds var AAC_SAMPLES_PER_FRAME = 1024; var MPEG_AUDIO_SAMPLE_PER_FRAME = 1152; var chromeVersion = null; var safariWebkitVersion = null; var requiresPositiveDts = false; var MP4Remuxer = /*#__PURE__*/function () { function MP4Remuxer(observer, config, typeSupported, vendor) { if (vendor === void 0) { vendor = ''; } this.observer = void 0; this.config = void 0; this.typeSupported = void 0; this.ISGenerated = false; this._initPTS = void 0; this._initDTS = void 0; this.nextAvcDts = null; this.nextAudioPts = null; this.isAudioContiguous = false; this.isVideoContiguous = false; this.observer = observer; this.config = config; this.typeSupported = typeSupported; this.ISGenerated = false; if (chromeVersion === null) { var userAgent = navigator.userAgent || ''; var result = userAgent.match(/Chrome\/(\d+)/i); chromeVersion = result ? parseInt(result[1]) : 0; } if (safariWebkitVersion === null) { var _result = navigator.userAgent.match(/Safari\/(\d+)/i); safariWebkitVersion = _result ? parseInt(_result[1]) : 0; } requiresPositiveDts = !!chromeVersion && chromeVersion < 75 || !!safariWebkitVersion && safariWebkitVersion < 600; } var _proto = MP4Remuxer.prototype; _proto.destroy = function destroy() {}; _proto.resetTimeStamp = function resetTimeStamp(defaultTimeStamp) { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: initPTS & initDTS reset'); this._initPTS = this._initDTS = defaultTimeStamp; }; _proto.resetNextTimestamp = function resetNextTimestamp() { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: reset next timestamp'); this.isVideoContiguous = false; this.isAudioContiguous = false; }; _proto.resetInitSegment = function resetInitSegment() { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: ISGenerated flag reset'); this.ISGenerated = false; }; _proto.getVideoStartPts = function getVideoStartPts(videoSamples) { var rolloverDetected = false; var startPTS = videoSamples.reduce(function (minPTS, sample) { var delta = sample.pts - minPTS; if (delta < -4294967296) { // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation rolloverDetected = true; return normalizePts(minPTS, sample.pts); } else if (delta > 0) { return minPTS; } else { return sample.pts; } }, videoSamples[0].pts); if (rolloverDetected) { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].debug('PTS rollover detected'); } return startPTS; }; _proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush, playlistType) { var video; var audio; var initSegment; var text; var id3; var independent; var audioTimeOffset = timeOffset; var videoTimeOffset = timeOffset; // If we're remuxing audio and video progressively, wait until we've received enough samples for each track before proceeding. // This is done to synchronize the audio and video streams. We know if the current segment will have samples if the "pid" // parameter is greater than -1. The pid is set when the PMT is parsed, which contains the tracks list. // However, if the initSegment has already been generated, or we've reached the end of a segment (flush), // then we can remux one track without waiting for the other. var hasAudio = audioTrack.pid > -1; var hasVideo = videoTrack.pid > -1; var length = videoTrack.samples.length; var enoughAudioSamples = audioTrack.samples.length > 0; var enoughVideoSamples = length > 1; var canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush; if (canRemuxAvc) { if (!this.ISGenerated) { initSegment = this.generateIS(audioTrack, videoTrack, timeOffset); } var isVideoContiguous = this.isVideoContiguous; var firstKeyFrameIndex = -1; if (enoughVideoSamples) { firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples); if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) { independent = true; if (firstKeyFrameIndex > 0) { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("[mp4-remuxer]: Dropped " + firstKeyFrameIndex + " out of " + length + " video samples due to a missing keyframe"); var startPTS = this.getVideoStartPts(videoTrack.samples); videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex); videoTrack.dropped += firstKeyFrameIndex; videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / (videoTrack.timescale || 90000); } else if (firstKeyFrameIndex === -1) { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("[mp4-remuxer]: No keyframe found out of " + length + " video samples"); independent = false; } } } if (this.ISGenerated) { if (enoughAudioSamples && enoughVideoSamples) { // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS) // if first audio DTS is not aligned with first video DTS then we need to take that into account // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small // drift between audio and video streams var _startPTS = this.getVideoStartPts(videoTrack.samples); var tsDelta = normalizePts(audioTrack.samples[0].pts, _startPTS) - _startPTS; var audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale; audioTimeOffset += Math.max(0, audiovideoTimestampDelta); videoTimeOffset += Math.max(0, -audiovideoTimestampDelta); } // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is calculated in remuxAudio. if (enoughAudioSamples) { // if initSegment was generated without audio samples, regenerate it again if (!audioTrack.samplerate) { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn('[mp4-remuxer]: regenerate InitSegment as audio detected'); initSegment = this.generateIS(audioTrack, videoTrack, timeOffset); } audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO ? videoTimeOffset : undefined); if (enoughVideoSamples) { var audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0; // if initSegment was generated without video samples, regenerate it again if (!videoTrack.inputTimeScale) { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn('[mp4-remuxer]: regenerate InitSegment as video detected'); initSegment = this.generateIS(audioTrack, videoTrack, timeOffset); } video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength); } } else if (enoughVideoSamples) { video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0); } if (video) { video.firstKeyFrame = firstKeyFrameIndex; video.independent = firstKeyFrameIndex !== -1; } } } // Allow ID3 and text to remux, even if more audio/video samples are required if (this.ISGenerated) { if (id3Track.samples.length) { id3 = this.remuxID3(id3Track, timeOffset); } if (textTrack.samples.length) { text = this.remuxText(textTrack, timeOffset); } } return { audio: audio, video: video, initSegment: initSegment, independent: independent, text: text, id3: id3 }; }; _proto.generateIS = function generateIS(audioTrack, videoTrack, timeOffset) { var audioSamples = audioTrack.samples; var videoSamples = videoTrack.samples; var typeSupported = this.typeSupported; var tracks = {}; var computePTSDTS = !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this._initPTS); var container = 'audio/mp4'; var initPTS; var initDTS; var timescale; if (computePTSDTS) { initPTS = initDTS = Infinity; } if (audioTrack.config && audioSamples.length) { // let's use audio sampling rate as MP4 time scale. // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC) // using audio sampling rate here helps having an integer MP4 frame duration // this avoids potential rounding issue and AV sync issue audioTrack.timescale = audioTrack.samplerate; if (!audioTrack.isAAC) { if (typeSupported.mpeg) { // Chrome and Safari container = 'audio/mpeg'; audioTrack.codec = ''; } else if (typeSupported.mp3) { // Firefox audioTrack.codec = 'mp3'; } } tracks.audio = { id: 'audio', container: container, codec: audioTrack.codec, initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array(0) : _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].initSegment([audioTrack]), metadata: { channelCount: audioTrack.channelCount } }; if (computePTSDTS) { timescale = audioTrack.inputTimeScale; // remember first PTS of this demuxing context. for audio, PTS = DTS initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * timeOffset); } } if (videoTrack.sps && videoTrack.pps && videoSamples.length) { // let's use input time scale as MP4 video timescale // we use input time scale straight away to avoid rounding issues on frame duration / cts computation videoTrack.timescale = videoTrack.inputTimeScale; tracks.video = { id: 'main', container: 'video/mp4', codec: videoTrack.codec, initSegment: _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].initSegment([videoTrack]), metadata: { width: videoTrack.width, height: videoTrack.height } }; if (computePTSDTS) { timescale = videoTrack.inputTimeScale; var startPTS = this.getVideoStartPts(videoSamples); var startOffset = Math.round(timescale * timeOffset); initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset); initPTS = Math.min(initPTS, startPTS - startOffset); } } if (Object.keys(tracks).length) { this.ISGenerated = true; if (computePTSDTS) { this._initPTS = initPTS; this._initDTS = initDTS; } return { tracks: tracks, initPTS: initPTS, timescale: timescale }; } }; _proto.remuxVideo = function remuxVideo(track, timeOffset, contiguous, audioTrackLength) { var timeScale = track.inputTimeScale; var inputSamples = track.samples; var outputSamples = []; var nbSamples = inputSamples.length; var initPTS = this._initPTS; var nextAvcDts = this.nextAvcDts; var offset = 8; var mp4SampleDuration; var firstDTS; var lastDTS; var minPTS = Number.POSITIVE_INFINITY; var maxPTS = Number.NEGATIVE_INFINITY; var ptsDtsShift = 0; var sortSamples = false; // if parsed fragment is contiguous with last one, let's use last DTS value as reference if (!contiguous || nextAvcDts === null) { var pts = timeOffset * timeScale; var cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts); // if not contiguous, let's use target timeOffset nextAvcDts = pts - cts; } // PTS is coded on 33bits, and can loop from -2^32 to 2^32 // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value for (var i = 0; i < nbSamples; i++) { var sample = inputSamples[i]; sample.pts = normalizePts(sample.pts - initPTS, nextAvcDts); sample.dts = normalizePts(sample.dts - initPTS, nextAvcDts); if (sample.dts > sample.pts) { var PTS_DTS_SHIFT_TOLERANCE_90KHZ = 90000 * 0.2; ptsDtsShift = Math.max(Math.min(ptsDtsShift, sample.pts - sample.dts), -1 * PTS_DTS_SHIFT_TOLERANCE_90KHZ); } if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) { sortSamples = true; } } // sort video samples by DTS then PTS then demux id order if (sortSamples) { inputSamples.sort(function (a, b) { var deltadts = a.dts - b.dts; var deltapts = a.pts - b.pts; return deltadts || deltapts; }); } // Get first/last DTS firstDTS = inputSamples[0].dts; lastDTS = inputSamples[inputSamples.length - 1].dts; // on Safari let's signal the same sample duration for all samples // sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS // set this constant duration as being the avg delta between consecutive DTS. var averageSampleDuration = Math.round((lastDTS - firstDTS) / (nbSamples - 1)); // handle broken streams with PTS < DTS, tolerance up 0.2 seconds if (ptsDtsShift < 0) { if (ptsDtsShift < averageSampleDuration * -2) { // Fix for "CNN special report, with CC" in test-streams (including Safari browser) // With large PTS < DTS errors such as this, we want to correct CTS while maintaining increasing DTS values _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("PTS < DTS detected in video samples, offsetting DTS from PTS by " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(-averageSampleDuration, true) + " ms"); var lastDts = ptsDtsShift; for (var _i = 0; _i < nbSamples; _i++) { inputSamples[_i].dts = lastDts = Math.max(lastDts, inputSamples[_i].pts - averageSampleDuration); inputSamples[_i].pts = Math.max(lastDts, inputSamples[_i].pts); } } else { // Fix for "Custom IV with bad PTS DTS" in test-streams // With smaller PTS < DTS errors we can simply move all DTS back. This increases CTS without causing buffer gaps or decode errors in Safari _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("PTS < DTS detected in video samples, shifting DTS by " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(ptsDtsShift, true) + " ms to overcome this issue"); for (var _i2 = 0; _i2 < nbSamples; _i2++) { inputSamples[_i2].dts = inputSamples[_i2].dts + ptsDtsShift; } } firstDTS = inputSamples[0].dts; } // if fragment are contiguous, detect hole/overlapping between fragments if (contiguous) { // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole) var delta = firstDTS - nextAvcDts; var foundHole = delta > averageSampleDuration; var foundOverlap = delta < -1; if (foundHole || foundOverlap) { if (foundHole) { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("AVC: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(delta, true) + " ms (" + delta + "dts) hole between fragments detected, filling it"); } else { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("AVC: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(-delta, true) + " ms (" + delta + "dts) overlapping between fragments detected"); } firstDTS = nextAvcDts; var firstPTS = inputSamples[0].pts - delta; inputSamples[0].dts = firstDTS; inputSamples[0].pts = firstPTS; _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log("Video: First PTS/DTS adjusted: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(firstPTS, true) + "/" + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(firstDTS, true) + ", delta: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(delta, true) + " ms"); } } if (requiresPositiveDts) { firstDTS = Math.max(0, firstDTS); } var nbNalu = 0; var naluLen = 0; for (var _i3 = 0; _i3 < nbSamples; _i3++) { // compute total/avc sample length and nb of NAL units var _sample = inputSamples[_i3]; var units = _sample.units; var nbUnits = units.length; var sampleLen = 0; for (var j = 0; j < nbUnits; j++) { sampleLen += units[j].data.length; } naluLen += sampleLen; nbNalu += nbUnits; _sample.length = sampleLen; // normalize PTS/DTS // ensure sample monotonic DTS _sample.dts = Math.max(_sample.dts, firstDTS); // ensure that computed value is greater or equal than sample DTS _sample.pts = Math.max(_sample.pts, _sample.dts, 0); minPTS = Math.min(_sample.pts, minPTS); maxPTS = Math.max(_sample.pts, maxPTS); } lastDTS = inputSamples[nbSamples - 1].dts; /* concatenate the video data and construct the mdat in place (need 8 more bytes to fill length and mpdat type) */ var mdatSize = naluLen + 4 * nbNalu + 8; var mdat; try { mdat = new Uint8Array(mdatSize); } catch (err) { this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].MUX_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: "fail allocating video mdat " + mdatSize }); return; } var view = new DataView(mdat.buffer); view.setUint32(0, mdatSize); mdat.set(_mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].types.mdat, 4); for (var _i4 = 0; _i4 < nbSamples; _i4++) { var avcSample = inputSamples[_i4]; var avcSampleUnits = avcSample.units; var mp4SampleLength = 0; // convert NALU bitstream to MP4 format (prepend NALU with size field) for (var _j = 0, _nbUnits = avcSampleUnits.length; _j < _nbUnits; _j++) { var unit = avcSampleUnits[_j]; var unitData = unit.data; var unitDataLen = unit.data.byteLength; view.setUint32(offset, unitDataLen); offset += 4; mdat.set(unitData, offset); offset += unitDataLen; mp4SampleLength += 4 + unitDataLen; } // expected sample duration is the Decoding Timestamp diff of consecutive samples if (_i4 < nbSamples - 1) { mp4SampleDuration = inputSamples[_i4 + 1].dts - avcSample.dts; } else { var config = this.config; var lastFrameDuration = avcSample.dts - inputSamples[_i4 > 0 ? _i4 - 1 : _i4].dts; if (config.stretchShortVideoTrack && this.nextAudioPts !== null) { // In some cases, a segment's audio track duration may exceed the video track duration. // Since we've already remuxed audio, and we know how long the audio track is, we look to // see if the delta to the next segment is longer than maxBufferHole. // If so, playback would potentially get stuck, so we artificially inflate // the duration of the last frame to minimize any potential gap between segments. var gapTolerance = Math.floor(config.maxBufferHole * timeScale); var deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts; if (deltaToFrameEnd > gapTolerance) { // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video // frame overlap. maxBufferHole should be >> lastFrameDuration anyway. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration; if (mp4SampleDuration < 0) { mp4SampleDuration = lastFrameDuration; } _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log("[mp4-remuxer]: It is approximately " + deltaToFrameEnd / 90 + " ms to the next segment; using duration " + mp4SampleDuration / 90 + " ms for the last video frame."); } else { mp4SampleDuration = lastFrameDuration; } } else { mp4SampleDuration = lastFrameDuration; } } var compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts); outputSamples.push(new Mp4Sample(avcSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset)); } if (outputSamples.length && chromeVersion && chromeVersion < 70) { // Chrome workaround, mark first sample as being a Random Access Point (keyframe) to avoid sourcebuffer append issue // https://code.google.com/p/chromium/issues/detail?id=229412 var flags = outputSamples[0].flags; flags.dependsOn = 2; flags.isNonSync = 0; } console.assert(mp4SampleDuration !== undefined, 'mp4SampleDuration must be computed'); // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale) this.nextAvcDts = nextAvcDts = lastDTS + mp4SampleDuration; this.isVideoContiguous = true; var moof = _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].moof(track.sequenceNumber++, firstDTS, _extends({}, track, { samples: outputSamples })); var type = 'video'; var data = { data1: moof, data2: mdat, startPTS: minPTS / timeScale, endPTS: (maxPTS + mp4SampleDuration) / timeScale, startDTS: firstDTS / timeScale, endDTS: nextAvcDts / timeScale, type: type, hasAudio: false, hasVideo: true, nb: outputSamples.length, dropped: track.dropped }; track.samples = []; track.dropped = 0; console.assert(mdat.length, 'MDAT length must not be zero'); return data; }; _proto.remuxAudio = function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) { var inputTimeScale = track.inputTimeScale; var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale; var scaleFactor = inputTimeScale / mp4timeScale; var mp4SampleDuration = track.isAAC ? AAC_SAMPLES_PER_FRAME : MPEG_AUDIO_SAMPLE_PER_FRAME; var inputSampleDuration = mp4SampleDuration * scaleFactor; var initPTS = this._initPTS; var rawMPEG = !track.isAAC && this.typeSupported.mpeg; var outputSamples = []; var inputSamples = track.samples; var offset = rawMPEG ? 0 : 8; var nextAudioPts = this.nextAudioPts || -1; // window.audioSamples ? window.audioSamples.push(inputSamples.map(s => s.pts)) : (window.audioSamples = [inputSamples.map(s => s.pts)]); // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs), // for sake of clarity: // consecutive fragments are frags with // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR // - less than 20 audio frames distance // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1) // this helps ensuring audio continuity // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame var timeOffsetMpegTS = timeOffset * inputTimeScale; this.isAudioContiguous = contiguous = contiguous || inputSamples.length && nextAudioPts > 0 && (accurateTimeOffset && Math.abs(timeOffsetMpegTS - nextAudioPts) < 9000 || Math.abs(normalizePts(inputSamples[0].pts - initPTS, timeOffsetMpegTS) - nextAudioPts) < 20 * inputSampleDuration); // compute normalized PTS inputSamples.forEach(function (sample) { sample.pts = normalizePts(sample.pts - initPTS, timeOffsetMpegTS); }); if (!contiguous || nextAudioPts < 0) { // filter out sample with negative PTS that are not playable anyway // if we don't remove these negative samples, they will shift all audio samples forward. // leading to audio overlap between current / next fragment inputSamples = inputSamples.filter(function (sample) { return sample.pts >= 0; }); // in case all samples have negative PTS, and have been filtered out, return now if (!inputSamples.length) { return; } if (videoTimeOffset === 0) { // Set the start to 0 to match video so that start gaps larger than inputSampleDuration are filled with silence nextAudioPts = 0; } else if (accurateTimeOffset) { // When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS nextAudioPts = Math.max(0, timeOffsetMpegTS); } else { // if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS nextAudioPts = inputSamples[0].pts; } } // If the audio track is missing samples, the frames seem to get "left-shifted" within the // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment. // In an effort to prevent this from happening, we inject frames here where there are gaps. // When possible, we inject a silent frame; when that's not possible, we duplicate the last // frame. if (track.isAAC) { var alignedWithVideo = videoTimeOffset !== undefined; var maxAudioFramesDrift = this.config.maxAudioFramesDrift; for (var i = 0, nextPts = nextAudioPts; i < inputSamples.length; i++) { // First, let's see how far off this frame is from where we expect it to be var sample = inputSamples[i]; var pts = sample.pts; var delta = pts - nextPts; var duration = Math.abs(1000 * delta / inputTimeScale); // When remuxing with video, if we're overlapping by more than a duration, drop this sample to stay in sync if (delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo) { if (i === 0) { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("Audio frame @ " + (pts / inputTimeScale).toFixed(3) + "s overlaps nextAudioPts by " + Math.round(1000 * delta / inputTimeScale) + " ms."); this.nextAudioPts = nextAudioPts = nextPts = pts; } } // eslint-disable-line brace-style // Insert missing frames if: // 1: We're more than maxAudioFramesDrift frame away // 2: Not more than MAX_SILENT_FRAME_DURATION away // 3: currentTime (aka nextPtsNorm) is not 0 // 4: remuxing with video (videoTimeOffset !== undefined) else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && alignedWithVideo) { var missing = Math.round(delta / inputSampleDuration); // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from // later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration. nextPts = pts - missing * inputSampleDuration; if (nextPts < 0) { missing--; nextPts += inputSampleDuration; } if (i === 0) { this.nextAudioPts = nextAudioPts = nextPts; } _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("[mp4-remuxer]: Injecting " + missing + " audio frame @ " + (nextPts / inputTimeScale).toFixed(3) + "s due to " + Math.round(1000 * delta / inputTimeScale) + " ms gap."); for (var j = 0; j < missing; j++) { var newStamp = Math.max(nextPts, 0); var fillFrame = _aac_helper__WEBPACK_IMPORTED_MODULE_1__["default"].getSilentFrame(track.manifestCodec || track.codec, track.channelCount); if (!fillFrame) { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead.'); fillFrame = sample.unit.subarray(); } inputSamples.splice(i, 0, { unit: fillFrame, pts: newStamp }); nextPts += inputSampleDuration; i++; } } sample.pts = nextPts; nextPts += inputSampleDuration; } } var firstPTS = null; var lastPTS = null; var mdat; var mdatSize = 0; var sampleLength = inputSamples.length; while (sampleLength--) { mdatSize += inputSamples[sampleLength].unit.byteLength; } for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) { var audioSample = inputSamples[_j2]; var unit = audioSample.unit; var _pts = audioSample.pts; if (lastPTS !== null) { // If we have more than one sample, set the duration of the sample to the "real" duration; the PTS diff with // the previous sample var prevSample = outputSamples[_j2 - 1]; prevSample.duration = Math.round((_pts - lastPTS) / scaleFactor); } else { if (contiguous && track.isAAC) { // set PTS/DTS to expected PTS/DTS _pts = nextAudioPts; } // remember first PTS of our audioSamples firstPTS = _pts; if (mdatSize > 0) { /* concatenate the audio data and construct the mdat in place (need 8 more bytes to fill length and mdat type) */ mdatSize += offset; try { mdat = new Uint8Array(mdatSize); } catch (err) { this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, { type: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].MUX_ERROR, details: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: "fail allocating audio mdat " + mdatSize }); return; } if (!rawMPEG) { var view = new DataView(mdat.buffer); view.setUint32(0, mdatSize); mdat.set(_mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].types.mdat, 4); } } else { // no audio samples return; } } mdat.set(unit, offset); var unitLen = unit.byteLength; offset += unitLen; // Default the sample's duration to the computed mp4SampleDuration, which will either be 1024 for AAC or 1152 for MPEG // In the case that we have 1 sample, this will be the duration. If we have more than one sample, the duration // becomes the PTS diff with the previous sample outputSamples.push(new Mp4Sample(true, mp4SampleDuration, unitLen, 0)); lastPTS = _pts; } // We could end up with no audio samples if all input samples were overlapping with the previously remuxed ones var nbSamples = outputSamples.length; if (!nbSamples) { return; } // The next audio sample PTS should be equal to last sample PTS + duration var lastSample = outputSamples[outputSamples.length - 1]; this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSample.duration; // Set the track samples from inputSamples to outputSamples before remuxing var moof = rawMPEG ? new Uint8Array(0) : _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].moof(track.sequenceNumber++, firstPTS / scaleFactor, _extends({}, track, { samples: outputSamples })); // Clear the track samples. This also clears the samples array in the demuxer, since the reference is shared track.samples = []; var start = firstPTS / inputTimeScale; var end = nextAudioPts / inputTimeScale; var type = 'audio'; var audioData = { data1: moof, data2: mdat, startPTS: start, endPTS: end, startDTS: start, endDTS: end, type: type, hasAudio: true, hasVideo: false, nb: nbSamples }; this.isAudioContiguous = true; console.assert(mdat.length, 'MDAT length must not be zero'); return audioData; }; _proto.remuxEmptyAudio = function remuxEmptyAudio(track, timeOffset, contiguous, videoData) { var inputTimeScale = track.inputTimeScale; var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale; var scaleFactor = inputTimeScale / mp4timeScale; var nextAudioPts = this.nextAudioPts; // sync with video's timestamp var startDTS = (nextAudioPts !== null ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS; var endDTS = videoData.endDTS * inputTimeScale + this._initDTS; // one sample's duration value var frameDuration = scaleFactor * AAC_SAMPLES_PER_FRAME; // samples count of this segment's duration var nbSamples = Math.ceil((endDTS - startDTS) / frameDuration); // silent frame var silentFrame = _aac_helper__WEBPACK_IMPORTED_MODULE_1__["default"].getSilentFrame(track.manifestCodec || track.codec, track.channelCount); _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn('[mp4-remuxer]: remux empty Audio'); // Can't remux if we can't generate a silent frame... if (!silentFrame) { _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].trace('[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec'); return; } var samples = []; for (var i = 0; i < nbSamples; i++) { var stamp = startDTS + i * frameDuration; samples.push({ unit: silentFrame, pts: stamp, dts: stamp }); } track.samples = samples; return this.remuxAudio(track, timeOffset, contiguous, false); }; _proto.remuxID3 = function remuxID3(track, timeOffset) { var length = track.samples.length; if (!length) { return; } var inputTimeScale = track.inputTimeScale; var initPTS = this._initPTS; var initDTS = this._initDTS; for (var index = 0; index < length; index++) { var sample = track.samples[index]; // setting id3 pts, dts to relative time // using this._initPTS and this._initDTS to calculate relative time sample.pts = normalizePts(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale; sample.dts = normalizePts(sample.dts - initDTS, timeOffset * inputTimeScale) / inputTimeScale; } var samples = track.samples; track.samples = []; return { samples: samples }; }; _proto.remuxText = function remuxText(track, timeOffset) { var length = track.samples.length; if (!length) { return; } var inputTimeScale = track.inputTimeScale; var initPTS = this._initPTS; for (var index = 0; index < length; index++) { var sample = track.samples[index]; // setting text pts, dts to relative time // using this._initPTS and this._initDTS to calculate relative time sample.pts = normalizePts(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale; } track.samples.sort(function (a, b) { return a.pts - b.pts; }); var samples = track.samples; track.samples = []; return { samples: samples }; }; return MP4Remuxer; }(); function normalizePts(value, reference) { var offset; if (reference === null) { return value; } if (reference < value) { // - 2^33 offset = -8589934592; } else { // + 2^33 offset = 8589934592; } /* PTS is 33bit (from 0 to 2^33 -1) if diff between value and reference is bigger than half of the amplitude (2^32) then it means that PTS looping occured. fill the gap */ while (Math.abs(value - reference) > 4294967296) { value += offset; } return value; } function findKeyframeIndex(samples) { for (var i = 0; i < samples.length; i++) { if (samples[i].key) { return i; } } return -1; } var Mp4Sample = function Mp4Sample(isKeyframe, duration, size, cts) { this.size = void 0; this.duration = void 0; this.cts = void 0; this.flags = void 0; this.duration = duration; this.size = size; this.cts = cts; this.flags = new Mp4SampleFlags(isKeyframe); }; var Mp4SampleFlags = function Mp4SampleFlags(isKeyframe) { this.isLeading = 0; this.isDependedOn = 0; this.hasRedundancy = 0; this.degradPrio = 0; this.dependsOn = 1; this.isNonSync = 1; this.dependsOn = isKeyframe ? 2 : 1; this.isNonSync = isKeyframe ? 0 : 1; }; /***/ }), /***/ "./src/remux/passthrough-remuxer.ts": /*!******************************************!*\ !*** ./src/remux/passthrough-remuxer.ts ***! \******************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts"); /* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts"); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); var PassThroughRemuxer = /*#__PURE__*/function () { function PassThroughRemuxer() { this.emitInitSegment = false; this.audioCodec = void 0; this.videoCodec = void 0; this.initData = void 0; this.initPTS = void 0; this.initTracks = void 0; this.lastEndDTS = null; } var _proto = PassThroughRemuxer.prototype; _proto.destroy = function destroy() {}; _proto.resetTimeStamp = function resetTimeStamp(defaultInitPTS) { this.initPTS = defaultInitPTS; this.lastEndDTS = null; }; _proto.resetNextTimestamp = function resetNextTimestamp() { this.lastEndDTS = null; }; _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec) { this.audioCodec = audioCodec; this.videoCodec = videoCodec; this.generateInitSegment(initSegment); this.emitInitSegment = true; }; _proto.generateInitSegment = function generateInitSegment(initSegment) { var audioCodec = this.audioCodec, videoCodec = this.videoCodec; if (!initSegment || !initSegment.byteLength) { this.initTracks = undefined; this.initData = undefined; return; } var initData = this.initData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["parseInitSegment"])(initSegment); // Get codec from initSegment or fallback to default if (!audioCodec) { audioCodec = getParsedTrackCodec(initData.audio, _loader_fragment__WEBPACK_IMPORTED_MODULE_2__["ElementaryStreamTypes"].AUDIO); } if (!videoCodec) { videoCodec = getParsedTrackCodec(initData.video, _loader_fragment__WEBPACK_IMPORTED_MODULE_2__["ElementaryStreamTypes"].VIDEO); } var tracks = {}; if (initData.audio && initData.video) { tracks.audiovideo = { container: 'video/mp4', codec: audioCodec + ',' + videoCodec, initSegment: initSegment, id: 'main' }; } else if (initData.audio) { tracks.audio = { container: 'audio/mp4', codec: audioCodec, initSegment: initSegment, id: 'audio' }; } else if (initData.video) { tracks.video = { container: 'video/mp4', codec: videoCodec, initSegment: initSegment, id: 'main' }; } else { _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes.'); } this.initTracks = tracks; }; _proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset) { var initPTS = this.initPTS, lastEndDTS = this.lastEndDTS; var result = { audio: undefined, video: undefined, text: textTrack, id3: id3Track, initSegment: undefined }; // If we haven't yet set a lastEndDTS, or it was reset, set it to the provided timeOffset. We want to use the // lastEndDTS over timeOffset whenever possible; during progressive playback, the media source will not update // the media duration (which is what timeOffset is provided as) before we need to process the next chunk. if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(lastEndDTS)) { lastEndDTS = this.lastEndDTS = timeOffset || 0; } // The binary segment data is added to the videoTrack in the mp4demuxer. We don't check to see if the data is only // audio or video (or both); adding it to video was an arbitrary choice. var data = videoTrack.samples; if (!data || !data.length) { return result; } var initSegment = { initPTS: undefined, timescale: 1 }; var initData = this.initData; if (!initData || !initData.length) { this.generateInitSegment(data); initData = this.initData; } if (!initData || !initData.length) { // We can't remux if the initSegment could not be generated _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('[passthrough-remuxer.ts]: Failed to generate initSegment.'); return result; } if (this.emitInitSegment) { initSegment.tracks = this.initTracks; this.emitInitSegment = false; } if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(initPTS)) { this.initPTS = initSegment.initPTS = initPTS = computeInitPTS(initData, data, lastEndDTS); } var duration = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["getDuration"])(data, initData); var startDTS = lastEndDTS; var endDTS = duration + startDTS; Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["offsetStartDTS"])(initData, data, initPTS); if (duration > 0) { this.lastEndDTS = endDTS; } else { _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Duration parsed from mp4 should be greater than zero'); this.resetNextTimestamp(); } var hasAudio = !!initData.audio; var hasVideo = !!initData.video; var type = ''; if (hasAudio) { type += 'audio'; } if (hasVideo) { type += 'video'; } var track = { data1: data, startPTS: startDTS, startDTS: startDTS, endPTS: endDTS, endDTS: endDTS, type: type, hasAudio: hasAudio, hasVideo: hasVideo, nb: 1, dropped: 0 }; result.audio = track.type === 'audio' ? track : undefined; result.video = track.type !== 'audio' ? track : undefined; result.text = textTrack; result.id3 = id3Track; result.initSegment = initSegment; return result; }; return PassThroughRemuxer; }(); var computeInitPTS = function computeInitPTS(initData, data, timeOffset) { return Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["getStartDTS"])(initData, data) - timeOffset; }; function getParsedTrackCodec(track, type) { var parsedCodec = track === null || track === void 0 ? void 0 : track.codec; if (parsedCodec && parsedCodec.length > 4) { return parsedCodec; } // Since mp4-tools cannot parse full codec string (see 'TODO: Parse codec details'... in mp4-tools) // Provide defaults based on codec type // This allows for some playback of some fmp4 playlists without CODECS defined in manifest if (parsedCodec === 'hvc1') { return 'hvc1.1.c.L120.90'; } if (parsedCodec === 'av01') { return 'av01.0.04M.08'; } if (parsedCodec === 'avc1' || type === _loader_fragment__WEBPACK_IMPORTED_MODULE_2__["ElementaryStreamTypes"].VIDEO) { return 'avc1.42e01e'; } return 'mp4a.40.5'; } /* harmony default export */ __webpack_exports__["default"] = (PassThroughRemuxer); /***/ }), /***/ "./src/task-loop.ts": /*!**************************!*\ !*** ./src/task-loop.ts ***! \**************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TaskLoop; }); /** * Sub-class specialization of EventHandler base class. * * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop, * scheduled asynchroneously, avoiding recursive calls in the same tick. * * The task itself is implemented in `doTick`. It can be requested and called for single execution * using the `tick` method. * * It will be assured that the task execution method (`tick`) only gets called once per main loop "tick", * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly. * * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`, * and cancelled with `clearNextTick`. * * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`). * * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine. * * Further explanations: * * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks. * * When the task execution (`tick` method) is called in re-entrant way this is detected and * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further * task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo). */ var TaskLoop = /*#__PURE__*/function () { function TaskLoop() { this._boundTick = void 0; this._tickTimer = null; this._tickInterval = null; this._tickCallCount = 0; this._boundTick = this.tick.bind(this); } var _proto = TaskLoop.prototype; _proto.destroy = function destroy() { this.onHandlerDestroying(); this.onHandlerDestroyed(); }; _proto.onHandlerDestroying = function onHandlerDestroying() { // clear all timers before unregistering from event bus this.clearNextTick(); this.clearInterval(); }; _proto.onHandlerDestroyed = function onHandlerDestroyed() {} /** * @returns {boolean} */ ; _proto.hasInterval = function hasInterval() { return !!this._tickInterval; } /** * @returns {boolean} */ ; _proto.hasNextTick = function hasNextTick() { return !!this._tickTimer; } /** * @param {number} millis Interval time (ms) * @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect) */ ; _proto.setInterval = function setInterval(millis) { if (!this._tickInterval) { this._tickInterval = self.setInterval(this._boundTick, millis); return true; } return false; } /** * @returns {boolean} True when interval was cleared, false when none was set (no effect) */ ; _proto.clearInterval = function clearInterval() { if (this._tickInterval) { self.clearInterval(this._tickInterval); this._tickInterval = null; return true; } return false; } /** * @returns {boolean} True when timeout was cleared, false when none was set (no effect) */ ; _proto.clearNextTick = function clearNextTick() { if (this._tickTimer) { self.clearTimeout(this._tickTimer); this._tickTimer = null; return true; } return false; } /** * Will call the subclass doTick implementation in this main loop tick * or in the next one (via setTimeout(,0)) in case it has already been called * in this tick (in case this is a re-entrant call). */ ; _proto.tick = function tick() { this._tickCallCount++; if (this._tickCallCount === 1) { this.doTick(); // re-entrant call to tick from previous doTick call stack // -> schedule a call on the next main loop iteration to process this task processing request if (this._tickCallCount > 1) { // make sure only one timer exists at any time at max this.tickImmediate(); } this._tickCallCount = 0; } }; _proto.tickImmediate = function tickImmediate() { this.clearNextTick(); this._tickTimer = self.setTimeout(this._boundTick, 0); } /** * For subclass to implement task logic * @abstract */ ; _proto.doTick = function doTick() {}; return TaskLoop; }(); /***/ }), /***/ "./src/types/level.ts": /*!****************************!*\ !*** ./src/types/level.ts ***! \****************************/ /*! exports provided: HlsSkip, getSkipValue, HlsUrlParameters, Level */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HlsSkip", function() { return HlsSkip; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getSkipValue", function() { return getSkipValue; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HlsUrlParameters", function() { return HlsUrlParameters; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Level", function() { return Level; }); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var HlsSkip; (function (HlsSkip) { HlsSkip["No"] = ""; HlsSkip["Yes"] = "YES"; HlsSkip["v2"] = "v2"; })(HlsSkip || (HlsSkip = {})); function getSkipValue(details, msn) { var canSkipUntil = details.canSkipUntil, canSkipDateRanges = details.canSkipDateRanges, endSN = details.endSN; var snChangeGoal = msn !== undefined ? msn - endSN : 0; if (canSkipUntil && snChangeGoal < canSkipUntil) { if (canSkipDateRanges) { return HlsSkip.v2; } return HlsSkip.Yes; } return HlsSkip.No; } var HlsUrlParameters = /*#__PURE__*/function () { function HlsUrlParameters(msn, part, skip) { this.msn = void 0; this.part = void 0; this.skip = void 0; this.msn = msn; this.part = part; this.skip = skip; } var _proto = HlsUrlParameters.prototype; _proto.addDirectives = function addDirectives(uri) { var url = new self.URL(uri); if (this.msn !== undefined) { url.searchParams.set('_HLS_msn', this.msn.toString()); } if (this.part !== undefined) { url.searchParams.set('_HLS_part', this.part.toString()); } if (this.skip) { url.searchParams.set('_HLS_skip', this.skip); } return url.toString(); }; return HlsUrlParameters; }(); var Level = /*#__PURE__*/function () { function Level(data) { this.attrs = void 0; this.audioCodec = void 0; this.bitrate = void 0; this.codecSet = void 0; this.height = void 0; this.id = void 0; this.name = void 0; this.videoCodec = void 0; this.width = void 0; this.unknownCodecs = void 0; this.audioGroupIds = void 0; this.details = void 0; this.fragmentError = 0; this.loadError = 0; this.loaded = void 0; this.realBitrate = 0; this.textGroupIds = void 0; this.url = void 0; this._urlId = 0; this.url = [data.url]; this.attrs = data.attrs; this.bitrate = data.bitrate; if (data.details) { this.details = data.details; } this.id = data.id || 0; this.name = data.name; this.width = data.width || 0; this.height = data.height || 0; this.audioCodec = data.audioCodec; this.videoCodec = data.videoCodec; this.unknownCodecs = data.unknownCodecs; this.codecSet = [data.videoCodec, data.audioCodec].filter(function (c) { return c; }).join(',').replace(/\.[^.,]+/g, ''); } _createClass(Level, [{ key: "maxBitrate", get: function get() { return Math.max(this.realBitrate, this.bitrate); } }, { key: "uri", get: function get() { return this.url[this._urlId] || ''; } }, { key: "urlId", get: function get() { return this._urlId; }, set: function set(value) { var newValue = value % this.url.length; if (this._urlId !== newValue) { this.details = undefined; this._urlId = newValue; } } }]); return Level; }(); /***/ }), /***/ "./src/types/loader.ts": /*!*****************************!*\ !*** ./src/types/loader.ts ***! \*****************************/ /*! exports provided: PlaylistContextType, PlaylistLevelType */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaylistContextType", function() { return PlaylistContextType; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaylistLevelType", function() { return PlaylistLevelType; }); var PlaylistContextType; (function (PlaylistContextType) { PlaylistContextType["MANIFEST"] = "manifest"; PlaylistContextType["LEVEL"] = "level"; PlaylistContextType["AUDIO_TRACK"] = "audioTrack"; PlaylistContextType["SUBTITLE_TRACK"] = "subtitleTrack"; })(PlaylistContextType || (PlaylistContextType = {})); var PlaylistLevelType; (function (PlaylistLevelType) { PlaylistLevelType["MAIN"] = "main"; PlaylistLevelType["AUDIO"] = "audio"; PlaylistLevelType["SUBTITLE"] = "subtitle"; })(PlaylistLevelType || (PlaylistLevelType = {})); /***/ }), /***/ "./src/types/transmuxer.ts": /*!*********************************!*\ !*** ./src/types/transmuxer.ts ***! \*********************************/ /*! exports provided: ChunkMetadata */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ChunkMetadata", function() { return ChunkMetadata; }); var ChunkMetadata = function ChunkMetadata(level, sn, id, size, part, partial) { if (size === void 0) { size = 0; } if (part === void 0) { part = -1; } if (partial === void 0) { partial = false; } this.level = void 0; this.sn = void 0; this.part = void 0; this.id = void 0; this.size = void 0; this.partial = void 0; this.transmuxing = getNewPerformanceTiming(); this.buffering = { audio: getNewPerformanceTiming(), video: getNewPerformanceTiming(), audiovideo: getNewPerformanceTiming() }; this.level = level; this.sn = sn; this.id = id; this.size = size; this.part = part; this.partial = partial; }; function getNewPerformanceTiming() { return { start: 0, executeStart: 0, executeEnd: 0, end: 0 }; } /***/ }), /***/ "./src/utils/attr-list.ts": /*!********************************!*\ !*** ./src/utils/attr-list.ts ***! \********************************/ /*! exports provided: AttrList */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AttrList", function() { return AttrList; }); var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/; // eslint-disable-line no-useless-escape var ATTR_LIST_REGEX = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape // adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js var AttrList = /*#__PURE__*/function () { function AttrList(attrs) { if (typeof attrs === 'string') { attrs = AttrList.parseAttrList(attrs); } for (var attr in attrs) { if (attrs.hasOwnProperty(attr)) { this[attr] = attrs[attr]; } } } var _proto = AttrList.prototype; _proto.decimalInteger = function decimalInteger(attrName) { var intValue = parseInt(this[attrName], 10); if (intValue > Number.MAX_SAFE_INTEGER) { return Infinity; } return intValue; }; _proto.hexadecimalInteger = function hexadecimalInteger(attrName) { if (this[attrName]) { var stringValue = (this[attrName] || '0x').slice(2); stringValue = (stringValue.length & 1 ? '0' : '') + stringValue; var value = new Uint8Array(stringValue.length / 2); for (var i = 0; i < stringValue.length / 2; i++) { value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16); } return value; } else { return null; } }; _proto.hexadecimalIntegerAsNumber = function hexadecimalIntegerAsNumber(attrName) { var intValue = parseInt(this[attrName], 16); if (intValue > Number.MAX_SAFE_INTEGER) { return Infinity; } return intValue; }; _proto.decimalFloatingPoint = function decimalFloatingPoint(attrName) { return parseFloat(this[attrName]); }; _proto.optionalFloat = function optionalFloat(attrName, defaultValue) { var value = this[attrName]; return value ? parseFloat(value) : defaultValue; }; _proto.enumeratedString = function enumeratedString(attrName) { return this[attrName]; }; _proto.bool = function bool(attrName) { return this[attrName] === 'YES'; }; _proto.decimalResolution = function decimalResolution(attrName) { var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]); if (res === null) { return undefined; } return { width: parseInt(res[1], 10), height: parseInt(res[2], 10) }; }; AttrList.parseAttrList = function parseAttrList(input) { var match; var attrs = {}; var quote = '"'; ATTR_LIST_REGEX.lastIndex = 0; while ((match = ATTR_LIST_REGEX.exec(input)) !== null) { var value = match[2]; if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) { value = value.slice(1, -1); } attrs[match[1]] = value; } return attrs; }; return AttrList; }(); /***/ }), /***/ "./src/utils/binary-search.ts": /*!************************************!*\ !*** ./src/utils/binary-search.ts ***! \************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); var BinarySearch = { /** * Searches for an item in an array which matches a certain condition. * This requires the condition to only match one item in the array, * and for the array to be ordered. * * @param {Array<T>} list The array to search. * @param {BinarySearchComparison<T>} comparisonFn * Called and provided a candidate item as the first argument. * Should return: * > -1 if the item should be located at a lower index than the provided item. * > 1 if the item should be located at a higher index than the provided item. * > 0 if the item is the item you're looking for. * * @return {T | null} The object if it is found or null otherwise. */ search: function search(list, comparisonFn) { var minIndex = 0; var maxIndex = list.length - 1; var currentIndex = null; var currentElement = null; while (minIndex <= maxIndex) { currentIndex = (minIndex + maxIndex) / 2 | 0; currentElement = list[currentIndex]; var comparisonResult = comparisonFn(currentElement); if (comparisonResult > 0) { minIndex = currentIndex + 1; } else if (comparisonResult < 0) { maxIndex = currentIndex - 1; } else { return currentElement; } } return null; } }; /* harmony default export */ __webpack_exports__["default"] = (BinarySearch); /***/ }), /***/ "./src/utils/buffer-helper.ts": /*!************************************!*\ !*** ./src/utils/buffer-helper.ts ***! \************************************/ /*! exports provided: BufferHelper */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BufferHelper", function() { return BufferHelper; }); /* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./logger */ "./src/utils/logger.ts"); /** * @module BufferHelper * * Providing methods dealing with buffer length retrieval for example. * * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property. * * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered */ var noopBuffered = { length: 0, start: function start() { return 0; }, end: function end() { return 0; } }; var BufferHelper = /*#__PURE__*/function () { function BufferHelper() {} /** * Return true if `media`'s buffered include `position` * @param {Bufferable} media * @param {number} position * @returns {boolean} */ BufferHelper.isBuffered = function isBuffered(media, position) { try { if (media) { var buffered = BufferHelper.getBuffered(media); for (var i = 0; i < buffered.length; i++) { if (position >= buffered.start(i) && position <= buffered.end(i)) { return true; } } } } catch (error) {// this is to catch // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer': // This SourceBuffer has been removed from the parent media source } return false; }; BufferHelper.bufferInfo = function bufferInfo(media, pos, maxHoleDuration) { try { if (media) { var vbuffered = BufferHelper.getBuffered(media); var buffered = []; var i; for (i = 0; i < vbuffered.length; i++) { buffered.push({ start: vbuffered.start(i), end: vbuffered.end(i) }); } return this.bufferedInfo(buffered, pos, maxHoleDuration); } } catch (error) {// this is to catch // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer': // This SourceBuffer has been removed from the parent media source } return { len: 0, start: pos, end: pos, nextStart: undefined }; }; BufferHelper.bufferedInfo = function bufferedInfo(buffered, pos, maxHoleDuration) { pos = Math.max(0, pos); // sort on buffer.start/smaller end (IE does not always return sorted buffered range) buffered.sort(function (a, b) { var diff = a.start - b.start; if (diff) { return diff; } else { return b.end - a.end; } }); var buffered2 = []; if (maxHoleDuration) { // there might be some small holes between buffer time range // consider that holes smaller than maxHoleDuration are irrelevant and build another // buffer time range representations that discards those holes for (var i = 0; i < buffered.length; i++) { var buf2len = buffered2.length; if (buf2len) { var buf2end = buffered2[buf2len - 1].end; // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative) if (buffered[i].start - buf2end < maxHoleDuration) { // merge overlapping time ranges // update lastRange.end only if smaller than item.end // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end) // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15]) if (buffered[i].end > buf2end) { buffered2[buf2len - 1].end = buffered[i].end; } } else { // big hole buffered2.push(buffered[i]); } } else { // first value buffered2.push(buffered[i]); } } } else { buffered2 = buffered; } var bufferLen = 0; // bufferStartNext can possibly be undefined based on the conditional logic below var bufferStartNext; // bufferStart and bufferEnd are buffer boundaries around current video position var bufferStart = pos; var bufferEnd = pos; for (var _i = 0; _i < buffered2.length; _i++) { var start = buffered2[_i].start; var end = buffered2[_i].end; // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i)); if (pos + maxHoleDuration >= start && pos < end) { // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length bufferStart = start; bufferEnd = end; bufferLen = bufferEnd - pos; } else if (pos + maxHoleDuration < start) { bufferStartNext = start; break; } } return { len: bufferLen, start: bufferStart || 0, end: bufferEnd || 0, nextStart: bufferStartNext }; } /** * Safe method to get buffered property. * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource */ ; BufferHelper.getBuffered = function getBuffered(media) { try { return media.buffered; } catch (e) { _logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log('failed to get media.buffered', e); return noopBuffered; } }; return BufferHelper; }(); /***/ }), /***/ "./src/utils/codecs.ts": /*!*****************************!*\ !*** ./src/utils/codecs.ts ***! \*****************************/ /*! exports provided: isCodecType, isCodecSupportedInMp4 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isCodecType", function() { return isCodecType; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isCodecSupportedInMp4", function() { return isCodecSupportedInMp4; }); // from http://mp4ra.org/codecs.html var sampleEntryCodesISO = { audio: { a3ds: true, 'ac-3': true, 'ac-4': true, alac: true, alaw: true, dra1: true, 'dts+': true, 'dts-': true, dtsc: true, dtse: true, dtsh: true, 'ec-3': true, enca: true, g719: true, g726: true, m4ae: true, mha1: true, mha2: true, mhm1: true, mhm2: true, mlpa: true, mp4a: true, 'raw ': true, Opus: true, samr: true, sawb: true, sawp: true, sevc: true, sqcp: true, ssmv: true, twos: true, ulaw: true }, video: { avc1: true, avc2: true, avc3: true, avc4: true, avcp: true, av01: true, drac: true, dvav: true, dvhe: true, encv: true, hev1: true, hvc1: true, mjp2: true, mp4v: true, mvc1: true, mvc2: true, mvc3: true, mvc4: true, resv: true, rv60: true, s263: true, svc1: true, svc2: true, 'vc-1': true, vp08: true, vp09: true }, text: { stpp: true, wvtt: true } }; function isCodecType(codec, type) { var typeCodes = sampleEntryCodesISO[type]; return !!typeCodes && typeCodes[codec.slice(0, 4)] === true; } function isCodecSupportedInMp4(codec, type) { return MediaSource.isTypeSupported((type || 'video') + "/mp4;codecs=\"" + codec + "\""); } /***/ }), /***/ "./src/utils/discontinuities.ts": /*!**************************************!*\ !*** ./src/utils/discontinuities.ts ***! \**************************************/ /*! exports provided: findFirstFragWithCC, shouldAlignOnDiscontinuities, findDiscontinuousReferenceFrag, adjustSlidingStart, alignStream, alignPDT */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFirstFragWithCC", function() { return findFirstFragWithCC; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "shouldAlignOnDiscontinuities", function() { return shouldAlignOnDiscontinuities; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findDiscontinuousReferenceFrag", function() { return findDiscontinuousReferenceFrag; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "adjustSlidingStart", function() { return adjustSlidingStart; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alignStream", function() { return alignStream; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alignPDT", function() { return alignPDT; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./logger */ "./src/utils/logger.ts"); /* harmony import */ var _controller_level_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../controller/level-helper */ "./src/controller/level-helper.ts"); function findFirstFragWithCC(fragments, cc) { var firstFrag = null; for (var i = 0, len = fragments.length; i < len; i++) { var currentFrag = fragments[i]; if (currentFrag && currentFrag.cc === cc) { firstFrag = currentFrag; break; } } return firstFrag; } function shouldAlignOnDiscontinuities(lastFrag, lastLevel, details) { if (lastLevel.details) { if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) { return true; } } return false; } // Find the first frag in the previous level which matches the CC of the first frag of the new level function findDiscontinuousReferenceFrag(prevDetails, curDetails) { var prevFrags = prevDetails.fragments; var curFrags = curDetails.fragments; if (!curFrags.length || !prevFrags.length) { _logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log('No fragments to align'); return; } var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc); if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) { _logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log('No frag in previous level to align on'); return; } return prevStartFrag; } function adjustFragmentStart(frag, sliding) { if (frag) { var start = frag.start + sliding; frag.start = frag.startPTS = start; frag.endPTS = start + frag.duration; } } function adjustSlidingStart(sliding, details) { // Update segments var fragments = details.fragments; for (var i = 0, len = fragments.length; i < len; i++) { adjustFragmentStart(fragments[i], sliding); } // Update LL-HLS parts at the end of the playlist if (details.fragmentHint) { adjustFragmentStart(details.fragmentHint, sliding); } details.alignedSliding = true; } /** * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a * contiguous stream with the last fragments. * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time * and an extra download. * @param lastFrag * @param lastLevel * @param details */ function alignStream(lastFrag, lastLevel, details) { if (!lastLevel) { return; } alignDiscontinuities(lastFrag, details, lastLevel); if (!details.alignedSliding && lastLevel.details) { // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level. // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same // discontinuity sequence. alignPDT(details, lastLevel.details); } if (!details.alignedSliding && lastLevel.details && !details.skippedSegments) { // Try to align on sn so that we pick a better start fragment. // Do not perform this on playlists with delta updates as this is only to align levels on switch // and adjustSliding only adjusts fragments after skippedSegments. Object(_controller_level_helper__WEBPACK_IMPORTED_MODULE_2__["adjustSliding"])(lastLevel.details, details); } } /** * Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same * discontinuity sequence. * @param lastFrag - The last Fragment which shares the same discontinuity sequence * @param lastLevel - The details of the last loaded level * @param details - The details of the new level */ function alignDiscontinuities(lastFrag, details, lastLevel) { if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) { var referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details); if (referenceFrag && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(referenceFrag.start)) { _logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log("Adjusting PTS using last level due to CC increase within current level " + details.url); adjustSlidingStart(referenceFrag.start, details); } } } /** * Computes the PTS of a new level's fragments using the difference in Program Date Time from the last level. * @param details - The details of the new level * @param lastDetails - The details of the last loaded level */ function alignPDT(details, lastDetails) { // This check protects the unsafe "!" usage below for null program date time access. if (!lastDetails.fragments.length || !details.hasProgramDateTime || !lastDetails.hasProgramDateTime) { return; } // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM // and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM // then we can deduce that playlist B sliding is 1000+8 = 1008s var lastPDT = lastDetails.fragments[0].programDateTime; // hasProgramDateTime check above makes this safe. var newPDT = details.fragments[0].programDateTime; // date diff is in ms. frag.start is in seconds var sliding = (newPDT - lastPDT) / 1000 + lastDetails.fragments[0].start; if (sliding && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(sliding)) { _logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log("Adjusting PTS using programDateTime delta " + (newPDT - lastPDT) + "ms, sliding:" + sliding.toFixed(3) + " " + details.url + " "); adjustSlidingStart(sliding, details); } } /***/ }), /***/ "./src/utils/ewma-bandwidth-estimator.ts": /*!***********************************************!*\ !*** ./src/utils/ewma-bandwidth-estimator.ts ***! \***********************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _utils_ewma__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/ewma */ "./src/utils/ewma.ts"); /* * EWMA Bandwidth Estimator * - heavily inspired from shaka-player * Tracks bandwidth samples and estimates available bandwidth. * Based on the minimum of two exponentially-weighted moving averages with * different half-lives. */ var EwmaBandWidthEstimator = /*#__PURE__*/function () { function EwmaBandWidthEstimator(slow, fast, defaultEstimate) { this.defaultEstimate_ = void 0; this.minWeight_ = void 0; this.minDelayMs_ = void 0; this.slow_ = void 0; this.fast_ = void 0; this.defaultEstimate_ = defaultEstimate; this.minWeight_ = 0.001; this.minDelayMs_ = 50; this.slow_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](slow); this.fast_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](fast); } var _proto = EwmaBandWidthEstimator.prototype; _proto.update = function update(slow, fast) { var slow_ = this.slow_, fast_ = this.fast_; if (this.slow_.halfLife !== slow) { this.slow_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](slow, slow_.getEstimate(), slow_.getTotalWeight()); } if (this.fast_.halfLife !== fast) { this.fast_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](fast, fast_.getEstimate(), fast_.getTotalWeight()); } }; _proto.sample = function sample(durationMs, numBytes) { durationMs = Math.max(durationMs, this.minDelayMs_); var numBits = 8 * numBytes; // weight is duration in seconds var durationS = durationMs / 1000; // value is bandwidth in bits/s var bandwidthInBps = numBits / durationS; this.fast_.sample(durationS, bandwidthInBps); this.slow_.sample(durationS, bandwidthInBps); }; _proto.canEstimate = function canEstimate() { var fast = this.fast_; return fast && fast.getTotalWeight() >= this.minWeight_; }; _proto.getEstimate = function getEstimate() { if (this.canEstimate()) { // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate())); // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate())); // Take the minimum of these two estimates. This should have the effect of // adapting down quickly, but up more slowly. return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate()); } else { return this.defaultEstimate_; } }; _proto.destroy = function destroy() {}; return EwmaBandWidthEstimator; }(); /* harmony default export */ __webpack_exports__["default"] = (EwmaBandWidthEstimator); /***/ }), /***/ "./src/utils/ewma.ts": /*!***************************!*\ !*** ./src/utils/ewma.ts ***! \***************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* * compute an Exponential Weighted moving average * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average * - heavily inspired from shaka-player */ var EWMA = /*#__PURE__*/function () { // About half of the estimated value will be from the last |halfLife| samples by weight. function EWMA(halfLife, estimate, weight) { if (estimate === void 0) { estimate = 0; } if (weight === void 0) { weight = 0; } this.halfLife = void 0; this.alpha_ = void 0; this.estimate_ = void 0; this.totalWeight_ = void 0; this.halfLife = halfLife; // Larger values of alpha expire historical data more slowly. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0; this.estimate_ = estimate; this.totalWeight_ = weight; } var _proto = EWMA.prototype; _proto.sample = function sample(weight, value) { var adjAlpha = Math.pow(this.alpha_, weight); this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_; this.totalWeight_ += weight; }; _proto.getTotalWeight = function getTotalWeight() { return this.totalWeight_; }; _proto.getEstimate = function getEstimate() { if (this.alpha_) { var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_); if (zeroFactor) { return this.estimate_ / zeroFactor; } } return this.estimate_; }; return EWMA; }(); /* harmony default export */ __webpack_exports__["default"] = (EWMA); /***/ }), /***/ "./src/utils/fetch-loader.ts": /*!***********************************!*\ !*** ./src/utils/fetch-loader.ts ***! \***********************************/ /*! exports provided: fetchSupported, default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fetchSupported", function() { return fetchSupported; }); /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts"); /* harmony import */ var _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/load-stats */ "./src/loader/load-stats.ts"); /* harmony import */ var _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/chunk-cache */ "./src/demux/chunk-cache.ts"); function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function fetchSupported() { if ( // @ts-ignore self.fetch && self.AbortController && self.ReadableStream && self.Request) { try { new self.ReadableStream({}); // eslint-disable-line no-new return true; } catch (e) { /* noop */ } } return false; } var FetchLoader = /*#__PURE__*/function () { function FetchLoader(config /* HlsConfig */ ) { this.fetchSetup = void 0; this.requestTimeout = void 0; this.request = void 0; this.response = void 0; this.controller = void 0; this.context = void 0; this.config = null; this.callbacks = null; this.stats = void 0; this.loader = null; this.fetchSetup = config.fetchSetup || getRequest; this.controller = new self.AbortController(); this.stats = new _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__["LoadStats"](); } var _proto = FetchLoader.prototype; _proto.destroy = function destroy() { this.loader = this.callbacks = null; this.abortInternal(); }; _proto.abortInternal = function abortInternal() { var response = this.response; if (!response || !response.ok) { this.stats.aborted = true; this.controller.abort(); } }; _proto.abort = function abort() { var _this$callbacks; this.abortInternal(); if ((_this$callbacks = this.callbacks) !== null && _this$callbacks !== void 0 && _this$callbacks.onAbort) { this.callbacks.onAbort(this.stats, this.context, this.response); } }; _proto.load = function load(context, config, callbacks) { var _this = this; var stats = this.stats; if (stats.loading.start) { throw new Error('Loader can only be used once.'); } stats.loading.start = self.performance.now(); var initParams = getRequestParameters(context, this.controller.signal); var onProgress = callbacks.onProgress; var isArrayBuffer = context.responseType === 'arraybuffer'; var LENGTH = isArrayBuffer ? 'byteLength' : 'length'; this.context = context; this.config = config; this.callbacks = callbacks; this.request = this.fetchSetup(context, initParams); self.clearTimeout(this.requestTimeout); this.requestTimeout = self.setTimeout(function () { _this.abortInternal(); callbacks.onTimeout(stats, context, _this.response); }, config.timeout); self.fetch(this.request).then(function (response) { _this.response = _this.loader = response; if (!response.ok) { var status = response.status, statusText = response.statusText; throw new FetchError(statusText || 'fetch, bad network response', status, response); } stats.loading.first = Math.max(self.performance.now(), stats.loading.start); stats.total = parseInt(response.headers.get('Content-Length') || '0'); if (onProgress && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(config.highWaterMark)) { return _this.loadProgressively(response, stats, context, config.highWaterMark, onProgress); } if (isArrayBuffer) { return response.arrayBuffer(); } return response.text(); }).then(function (responseData) { var response = _this.response; self.clearTimeout(_this.requestTimeout); stats.loading.end = Math.max(self.performance.now(), stats.loading.first); stats.loaded = stats.total = responseData[LENGTH]; var loaderResponse = { url: response.url, data: responseData }; if (onProgress && !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(config.highWaterMark)) { onProgress(stats, context, responseData, response); } callbacks.onSuccess(loaderResponse, stats, context, response); }).catch(function (error) { self.clearTimeout(_this.requestTimeout); if (stats.aborted) { return; } // CORS errors result in an undefined code. Set it to 0 here to align with XHR's behavior var code = error.code || 0; callbacks.onError({ code: code, text: error.message }, context, error.details); }); }; _proto.getCacheAge = function getCacheAge() { var result = null; if (this.response) { var ageHeader = this.response.headers.get('age'); result = ageHeader ? parseFloat(ageHeader) : null; } return result; }; _proto.loadProgressively = function loadProgressively(response, stats, context, highWaterMark, onProgress) { if (highWaterMark === void 0) { highWaterMark = 0; } var chunkCache = new _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_2__["default"](); var reader = response.body.getReader(); var pump = function pump() { return reader.read().then(function (data) { if (data.done) { if (chunkCache.dataLength) { onProgress(stats, context, chunkCache.flush(), response); } return Promise.resolve(new ArrayBuffer(0)); } var chunk = data.value; var len = chunk.length; stats.loaded += len; if (len < highWaterMark || chunkCache.dataLength) { // The current chunk is too small to to be emitted or the cache already has data // Push it to the cache chunkCache.push(chunk); if (chunkCache.dataLength >= highWaterMark) { // flush in order to join the typed arrays onProgress(stats, context, chunkCache.flush(), response); } } else { // If there's nothing cached already, and the chache is large enough // just emit the progress event onProgress(stats, context, chunk, response); } return pump(); }).catch(function () { /* aborted */ return Promise.reject(); }); }; return pump(); }; return FetchLoader; }(); function getRequestParameters(context, signal) { var initParams = { method: 'GET', mode: 'cors', credentials: 'same-origin', signal: signal }; if (context.rangeEnd) { initParams.headers = new self.Headers({ Range: 'bytes=' + context.rangeStart + '-' + String(context.rangeEnd - 1) }); } return initParams; } function getRequest(context, initParams) { return new self.Request(context.url, initParams); } var FetchError = /*#__PURE__*/function (_Error) { _inheritsLoose(FetchError, _Error); function FetchError(message, code, details) { var _this2; _this2 = _Error.call(this, message) || this; _this2.code = void 0; _this2.details = void 0; _this2.code = code; _this2.details = details; return _this2; } return FetchError; }( /*#__PURE__*/_wrapNativeSuper(Error)); /* harmony default export */ __webpack_exports__["default"] = (FetchLoader); /***/ }), /***/ "./src/utils/logger.ts": /*!*****************************!*\ !*** ./src/utils/logger.ts ***! \*****************************/ /*! exports provided: enableLogs, logger */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableLogs", function() { return enableLogs; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logger", function() { return logger; }); var noop = function noop() {}; var fakeLogger = { trace: noop, debug: noop, log: noop, warn: noop, info: noop, error: noop }; var exportedLogger = fakeLogger; // let lastCallTime; // function formatMsgWithTimeInfo(type, msg) { // const now = Date.now(); // const diff = lastCallTime ? '+' + (now - lastCallTime) : '0'; // lastCallTime = now; // msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )'; // return msg; // } function consolePrintFn(type) { var func = self.console[type]; if (func) { return func.bind(self.console, "[" + type + "] >"); } return noop; } function exportLoggerFunctions(debugConfig) { for (var _len = arguments.length, functions = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { functions[_key - 1] = arguments[_key]; } functions.forEach(function (type) { exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type); }); } function enableLogs(debugConfig) { // check that console is available if (self.console && debugConfig === true || typeof debugConfig === 'object') { exportLoggerFunctions(debugConfig, // Remove out from list here to hard-disable a log-level // 'trace', 'debug', 'log', 'info', 'warn', 'error'); // Some browsers don't allow to use bind on console object anyway // fallback to default if needed try { exportedLogger.log(); } catch (e) { exportedLogger = fakeLogger; } } else { exportedLogger = fakeLogger; } } var logger = exportedLogger; /***/ }), /***/ "./src/utils/mediakeys-helper.ts": /*!***************************************!*\ !*** ./src/utils/mediakeys-helper.ts ***! \***************************************/ /*! exports provided: KeySystems, requestMediaKeySystemAccess */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeySystems", function() { return KeySystems; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "requestMediaKeySystemAccess", function() { return requestMediaKeySystemAccess; }); /** * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess */ var KeySystems; (function (KeySystems) { KeySystems["WIDEVINE"] = "com.widevine.alpha"; KeySystems["PLAYREADY"] = "com.microsoft.playready"; })(KeySystems || (KeySystems = {})); var requestMediaKeySystemAccess = function () { if (typeof self !== 'undefined' && self.navigator && self.navigator.requestMediaKeySystemAccess) { return self.navigator.requestMediaKeySystemAccess.bind(self.navigator); } else { return null; } }(); /***/ }), /***/ "./src/utils/mediasource-helper.ts": /*!*****************************************!*\ !*** ./src/utils/mediasource-helper.ts ***! \*****************************************/ /*! exports provided: getMediaSource */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getMediaSource", function() { return getMediaSource; }); /** * MediaSource helper */ function getMediaSource() { return self.MediaSource || self.WebKitMediaSource; } /***/ }), /***/ "./src/utils/mp4-tools.ts": /*!********************************!*\ !*** ./src/utils/mp4-tools.ts ***! \********************************/ /*! exports provided: bin2str, readUint16, readUint32, writeUint32, findBox, parseSegmentIndex, parseInitSegment, getStartDTS, getDuration, computeRawDurationFromSamples, offsetStartDTS, segmentValidRange, appendUint8Array */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bin2str", function() { return bin2str; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "readUint16", function() { return readUint16; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "readUint32", function() { return readUint32; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "writeUint32", function() { return writeUint32; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findBox", function() { return findBox; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseSegmentIndex", function() { return parseSegmentIndex; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseInitSegment", function() { return parseInitSegment; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getStartDTS", function() { return getStartDTS; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDuration", function() { return getDuration; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "computeRawDurationFromSamples", function() { return computeRawDurationFromSamples; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "offsetStartDTS", function() { return offsetStartDTS; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "segmentValidRange", function() { return segmentValidRange; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendUint8Array", function() { return appendUint8Array; }); /* harmony import */ var _typed_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./typed-array */ "./src/utils/typed-array.ts"); /* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts"); var UINT32_MAX = Math.pow(2, 32) - 1; var push = [].push; function bin2str(data) { return String.fromCharCode.apply(null, data); } function readUint16(buffer, offset) { if ('data' in buffer) { offset += buffer.start; buffer = buffer.data; } var val = buffer[offset] << 8 | buffer[offset + 1]; return val < 0 ? 65536 + val : val; } function readUint32(buffer, offset) { if ('data' in buffer) { offset += buffer.start; buffer = buffer.data; } var val = buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3]; return val < 0 ? 4294967296 + val : val; } function writeUint32(buffer, offset, value) { if ('data' in buffer) { offset += buffer.start; buffer = buffer.data; } buffer[offset] = value >> 24; buffer[offset + 1] = value >> 16 & 0xff; buffer[offset + 2] = value >> 8 & 0xff; buffer[offset + 3] = value & 0xff; } // Find the data for a box specified by its path function findBox(input, path) { var results = []; if (!path.length) { // short-circuit the search for empty paths return results; } var data; var start; var end; if ('data' in input) { data = input.data; start = input.start; end = input.end; } else { data = input; start = 0; end = data.byteLength; } for (var i = start; i < end;) { var size = readUint32(data, i); var type = bin2str(data.subarray(i + 4, i + 8)); var endbox = size > 1 ? i + size : end; if (type === path[0]) { if (path.length === 1) { // this is the end of the path and we've found the box we were // looking for results.push({ data: data, start: i + 8, end: endbox }); } else { // recursively search for the next box along the path var subresults = findBox({ data: data, start: i + 8, end: endbox }, path.slice(1)); if (subresults.length) { push.apply(results, subresults); } } } i = endbox; } // we've finished searching all of data return results; } function parseSegmentIndex(initSegment) { var moovBox = findBox(initSegment, ['moov']); var moov = moovBox[0]; var moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data var sidxBox = findBox(initSegment, ['sidx']); if (!sidxBox || !sidxBox[0]) { return null; } var references = []; var sidx = sidxBox[0]; var version = sidx.data[0]; // set initial offset, we skip the reference ID (not needed) var index = version === 0 ? 8 : 16; var timescale = readUint32(sidx, index); index += 4; // TODO: parse earliestPresentationTime and firstOffset // usually zero in our case var earliestPresentationTime = 0; var firstOffset = 0; if (version === 0) { index += 8; } else { index += 16; } // skip reserved index += 2; var startByte = sidx.end + firstOffset; var referencesCount = readUint16(sidx, index); index += 2; for (var i = 0; i < referencesCount; i++) { var referenceIndex = index; var referenceInfo = readUint32(sidx, referenceIndex); referenceIndex += 4; var referenceSize = referenceInfo & 0x7fffffff; var referenceType = (referenceInfo & 0x80000000) >>> 31; if (referenceType === 1) { // eslint-disable-next-line no-console console.warn('SIDX has hierarchical references (not supported)'); return null; } var subsegmentDuration = readUint32(sidx, referenceIndex); referenceIndex += 4; references.push({ referenceSize: referenceSize, subsegmentDuration: subsegmentDuration, // unscaled info: { duration: subsegmentDuration / timescale, start: startByte, end: startByte + referenceSize - 1 } }); startByte += referenceSize; // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits // for |sapDelta|. referenceIndex += 4; // skip to next ref index = referenceIndex; } return { earliestPresentationTime: earliestPresentationTime, timescale: timescale, version: version, referencesCount: referencesCount, references: references, moovEndOffset: moovEndOffset }; } /** * Parses an MP4 initialization segment and extracts stream type and * timescale values for any declared tracks. Timescale values indicate the * number of clock ticks per second to assume for time-based values * elsewhere in the MP4. * * To determine the start time of an MP4, you need two pieces of * information: the timescale unit and the earliest base media decode * time. Multiple timescales can be specified within an MP4 but the * base media decode time is always expressed in the timescale from * the media header box for the track: * ``` * moov > trak > mdia > mdhd.timescale * moov > trak > mdia > hdlr * ``` * @param initSegment {Uint8Array} the bytes of the init segment * @return {InitData} a hash of track type to timescale values or null if * the init segment is malformed. */ function parseInitSegment(initSegment) { var result = []; var traks = findBox(initSegment, ['moov', 'trak']); for (var i = 0; i < traks.length; i++) { var trak = traks[i]; var tkhd = findBox(trak, ['tkhd'])[0]; if (tkhd) { var version = tkhd.data[tkhd.start]; var _index = version === 0 ? 12 : 20; var trackId = readUint32(tkhd, _index); var mdhd = findBox(trak, ['mdia', 'mdhd'])[0]; if (mdhd) { version = mdhd.data[mdhd.start]; _index = version === 0 ? 12 : 20; var timescale = readUint32(mdhd, _index); var hdlr = findBox(trak, ['mdia', 'hdlr'])[0]; if (hdlr) { var hdlrType = bin2str(hdlr.data.subarray(hdlr.start + 8, hdlr.start + 12)); var type = { soun: _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].AUDIO, vide: _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].VIDEO }[hdlrType]; if (type) { // Parse codec details var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0]; var codec = void 0; if (stsd) { codec = bin2str(stsd.data.subarray(stsd.start + 12, stsd.start + 16)); // TODO: Parse codec details to be able to build MIME type. // stsd.start += 8; // const codecBox = findBox(stsd, [codec])[0]; // if (codecBox) { // TODO: Codec parsing support for avc1, mp4a, hevc, av01... // } } result[trackId] = { timescale: timescale, type: type }; result[type] = { timescale: timescale, id: trackId, codec: codec }; } } } } } var trex = findBox(initSegment, ['moov', 'mvex', 'trex']); trex.forEach(function (trex) { var trackId = readUint32(trex, 4); var track = result[trackId]; if (track) { track.default = { duration: readUint32(trex, 12), flags: readUint32(trex, 20) }; } }); return result; } /** * Determine the base media decode start time, in seconds, for an MP4 * fragment. If multiple fragments are specified, the earliest time is * returned. * * The base media decode time can be parsed from track fragment * metadata: * ``` * moof > traf > tfdt.baseMediaDecodeTime * ``` * It requires the timescale value from the mdhd to interpret. * * @param initData {InitData} a hash of track type to timescale values * @param fmp4 {Uint8Array} the bytes of the mp4 fragment * @return {number} the earliest base media decode start time for the * fragment, in seconds */ function getStartDTS(initData, fmp4) { // we need info from two children of each track fragment box return findBox(fmp4, ['moof', 'traf']).reduce(function (result, traf) { var tfdt = findBox(traf, ['tfdt'])[0]; var version = tfdt.data[tfdt.start]; var start = findBox(traf, ['tfhd']).reduce(function (result, tfhd) { // get the track id from the tfhd var id = readUint32(tfhd, 4); var track = initData[id]; if (track) { var baseTime = readUint32(tfdt, 4); if (version === 1) { baseTime *= Math.pow(2, 32); baseTime += readUint32(tfdt, 8); } // assume a 90kHz clock if no timescale was specified var scale = track.timescale || 90e3; // convert base time to seconds var startTime = baseTime / scale; if (isFinite(startTime) && (result === null || startTime < result)) { return startTime; } } return result; }, null); if (start !== null && isFinite(start) && (result === null || start < result)) { return start; } return result; }, null) || 0; } /* For Reference: aligned(8) class TrackFragmentHeaderBox extends FullBox(‘tfhd’, 0, tf_flags){ unsigned int(32) track_ID; // all the following are optional fields unsigned int(64) base_data_offset; unsigned int(32) sample_description_index; unsigned int(32) default_sample_duration; unsigned int(32) default_sample_size; unsigned int(32) default_sample_flags } */ function getDuration(data, initData) { var rawDuration = 0; var videoDuration = 0; var audioDuration = 0; var trafs = findBox(data, ['moof', 'traf']); for (var i = 0; i < trafs.length; i++) { var traf = trafs[i]; // There is only one tfhd & trun per traf // This is true for CMAF style content, and we should perhaps check the ftyp // and only look for a single trun then, but for ISOBMFF we should check // for multiple track runs. var tfhd = findBox(traf, ['tfhd'])[0]; // get the track id from the tfhd var id = readUint32(tfhd, 4); var track = initData[id]; if (!track) { continue; } var trackDefault = track.default; var tfhdFlags = readUint32(tfhd, 0) | (trackDefault === null || trackDefault === void 0 ? void 0 : trackDefault.flags); var sampleDuration = trackDefault === null || trackDefault === void 0 ? void 0 : trackDefault.duration; if (tfhdFlags & 0x000008) { // 0x000008 indicates the presence of the default_sample_duration field if (tfhdFlags & 0x000002) { // 0x000002 indicates the presence of the sample_description_index field, which precedes default_sample_duration // If present, the default_sample_duration exists at byte offset 12 sampleDuration = readUint32(tfhd, 12); } else { // Otherwise, the duration is at byte offset 8 sampleDuration = readUint32(tfhd, 8); } } // assume a 90kHz clock if no timescale was specified var timescale = track.timescale || 90e3; var truns = findBox(traf, ['trun']); for (var j = 0; j < truns.length; j++) { if (sampleDuration) { var sampleCount = readUint32(truns[j], 4); rawDuration = sampleDuration * sampleCount; } else { rawDuration = computeRawDurationFromSamples(truns[j]); } if (track.type === _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].VIDEO) { videoDuration += rawDuration / timescale; } else if (track.type === _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].AUDIO) { audioDuration += rawDuration / timescale; } } } if (videoDuration === 0 && audioDuration === 0) { // If duration samples are not available in the traf use sidx subsegment_duration var sidx = parseSegmentIndex(data); if (sidx !== null && sidx !== void 0 && sidx.references) { return sidx.references.reduce(function (dur, ref) { return dur + ref.info.duration || 0; }, 0); } } if (videoDuration) { return videoDuration; } return audioDuration; } /* For Reference: aligned(8) class TrackRunBox extends FullBox(‘trun’, version, tr_flags) { unsigned int(32) sample_count; // the following are optional fields signed int(32) data_offset; unsigned int(32) first_sample_flags; // all fields in the following array are optional { unsigned int(32) sample_duration; unsigned int(32) sample_size; unsigned int(32) sample_flags if (version == 0) { unsigned int(32) else { signed int(32) }[ sample_count ] } */ function computeRawDurationFromSamples(trun) { var flags = readUint32(trun, 0); // Flags are at offset 0, non-optional sample_count is at offset 4. Therefore we start 8 bytes in. // Each field is an int32, which is 4 bytes var offset = 8; // data-offset-present flag if (flags & 0x000001) { offset += 4; } // first-sample-flags-present flag if (flags & 0x000004) { offset += 4; } var duration = 0; var sampleCount = readUint32(trun, 4); for (var i = 0; i < sampleCount; i++) { // sample-duration-present flag if (flags & 0x000100) { var sampleDuration = readUint32(trun, offset); duration += sampleDuration; offset += 4; } // sample-size-present flag if (flags & 0x000200) { offset += 4; } // sample-flags-present flag if (flags & 0x000400) { offset += 4; } // sample-composition-time-offsets-present flag if (flags & 0x000800) { offset += 4; } } return duration; } function offsetStartDTS(initData, fmp4, timeOffset) { findBox(fmp4, ['moof', 'traf']).forEach(function (traf) { findBox(traf, ['tfhd']).forEach(function (tfhd) { // get the track id from the tfhd var id = readUint32(tfhd, 4); var track = initData[id]; if (!track) { return; } // assume a 90kHz clock if no timescale was specified var timescale = track.timescale || 90e3; // get the base media decode time from the tfdt findBox(traf, ['tfdt']).forEach(function (tfdt) { var version = tfdt.data[tfdt.start]; var baseMediaDecodeTime = readUint32(tfdt, 4); if (version === 0) { writeUint32(tfdt, 4, baseMediaDecodeTime - timeOffset * timescale); } else { baseMediaDecodeTime *= Math.pow(2, 32); baseMediaDecodeTime += readUint32(tfdt, 8); baseMediaDecodeTime -= timeOffset * timescale; baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0); var upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1)); var lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1)); writeUint32(tfdt, 4, upper); writeUint32(tfdt, 8, lower); } }); }); }); } // TODO: Check if the last moof+mdat pair is part of the valid range function segmentValidRange(data) { var segmentedRange = { valid: null, remainder: null }; var moofs = findBox(data, ['moof']); if (!moofs) { return segmentedRange; } else if (moofs.length < 2) { segmentedRange.remainder = data; return segmentedRange; } var last = moofs[moofs.length - 1]; // Offset by 8 bytes; findBox offsets the start by as much segmentedRange.valid = Object(_typed_array__WEBPACK_IMPORTED_MODULE_0__["sliceUint8"])(data, 0, last.start - 8); segmentedRange.remainder = Object(_typed_array__WEBPACK_IMPORTED_MODULE_0__["sliceUint8"])(data, last.start - 8); return segmentedRange; } function appendUint8Array(data1, data2) { var temp = new Uint8Array(data1.length + data2.length); temp.set(data1); temp.set(data2, data1.length); return temp; } /***/ }), /***/ "./src/utils/texttrack-utils.ts": /*!**************************************!*\ !*** ./src/utils/texttrack-utils.ts ***! \**************************************/ /*! exports provided: sendAddTrackEvent, addCueToTrack, clearCurrentCues, removeCuesInRange, getCuesInRange */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sendAddTrackEvent", function() { return sendAddTrackEvent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addCueToTrack", function() { return addCueToTrack; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearCurrentCues", function() { return clearCurrentCues; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeCuesInRange", function() { return removeCuesInRange; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getCuesInRange", function() { return getCuesInRange; }); /* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./logger */ "./src/utils/logger.ts"); function sendAddTrackEvent(track, videoEl) { var event; try { event = new Event('addtrack'); } catch (err) { // for IE11 event = document.createEvent('Event'); event.initEvent('addtrack', false, false); } event.track = track; videoEl.dispatchEvent(event); } function addCueToTrack(track, cue) { // Sometimes there are cue overlaps on segmented vtts so the same // cue can appear more than once in different vtt files. // This avoid showing duplicated cues with same timecode and text. var mode = track.mode; if (mode === 'disabled') { track.mode = 'hidden'; } if (track.cues && !track.cues.getCueById(cue.id)) { try { track.addCue(cue); if (!track.cues.getCueById(cue.id)) { throw new Error("addCue is failed for: " + cue); } } catch (err) { _logger__WEBPACK_IMPORTED_MODULE_0__["logger"].debug("[texttrack-utils]: " + err); var textTrackCue = new self.TextTrackCue(cue.startTime, cue.endTime, cue.text); textTrackCue.id = cue.id; track.addCue(textTrackCue); } } if (mode === 'disabled') { track.mode = mode; } } function clearCurrentCues(track) { // When track.mode is disabled, track.cues will be null. // To guarantee the removal of cues, we need to temporarily // change the mode to hidden var mode = track.mode; if (mode === 'disabled') { track.mode = 'hidden'; } if (track.cues) { for (var i = track.cues.length; i--;) { track.removeCue(track.cues[i]); } } if (mode === 'disabled') { track.mode = mode; } } function removeCuesInRange(track, start, end) { var mode = track.mode; if (mode === 'disabled') { track.mode = 'hidden'; } if (track.cues && track.cues.length > 0) { var cues = getCuesInRange(track.cues, start, end); for (var i = 0; i < cues.length; i++) { track.removeCue(cues[i]); } } if (mode === 'disabled') { track.mode = mode; } } // Find first cue starting after given time. // Modified version of binary search O(log(n)). function getFirstCueIndexAfterTime(cues, time) { // If first cue starts after time, start there if (time < cues[0].startTime) { return 0; } // If the last cue ends before time there is no overlap var len = cues.length - 1; if (time > cues[len].endTime) { return -1; } var left = 0; var right = len; while (left <= right) { var mid = Math.floor((right + left) / 2); if (time < cues[mid].startTime) { right = mid - 1; } else if (time > cues[mid].startTime && left < len) { left = mid + 1; } else { // If it's not lower or higher, it must be equal. return mid; } } // At this point, left and right have swapped. // No direct match was found, left or right element must be the closest. Check which one has the smallest diff. return cues[left].startTime - time < time - cues[right].startTime ? left : right; } function getCuesInRange(cues, start, end) { var cuesFound = []; var firstCueInRange = getFirstCueIndexAfterTime(cues, start); if (firstCueInRange > -1) { for (var i = firstCueInRange, len = cues.length; i < len; i++) { var cue = cues[i]; if (cue.startTime >= start && cue.endTime <= end) { cuesFound.push(cue); } else if (cue.startTime > end) { return cuesFound; } } } return cuesFound; } /***/ }), /***/ "./src/utils/time-ranges.ts": /*!**********************************!*\ !*** ./src/utils/time-ranges.ts ***! \**********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * TimeRanges to string helper */ var TimeRanges = { toString: function toString(r) { var log = ''; var len = r.length; for (var i = 0; i < len; i++) { log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']'; } return log; } }; /* harmony default export */ __webpack_exports__["default"] = (TimeRanges); /***/ }), /***/ "./src/utils/timescale-conversion.ts": /*!*******************************************!*\ !*** ./src/utils/timescale-conversion.ts ***! \*******************************************/ /*! exports provided: toTimescaleFromBase, toTimescaleFromScale, toMsFromMpegTsClock, toMpegTsClockFromTimescale */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toTimescaleFromBase", function() { return toTimescaleFromBase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toTimescaleFromScale", function() { return toTimescaleFromScale; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toMsFromMpegTsClock", function() { return toMsFromMpegTsClock; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toMpegTsClockFromTimescale", function() { return toMpegTsClockFromTimescale; }); var MPEG_TS_CLOCK_FREQ_HZ = 90000; function toTimescaleFromBase(value, destScale, srcBase, round) { if (srcBase === void 0) { srcBase = 1; } if (round === void 0) { round = false; } var result = value * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)` return round ? Math.round(result) : result; } function toTimescaleFromScale(value, destScale, srcScale, round) { if (srcScale === void 0) { srcScale = 1; } if (round === void 0) { round = false; } return toTimescaleFromBase(value, destScale, 1 / srcScale, round); } function toMsFromMpegTsClock(value, round) { if (round === void 0) { round = false; } return toTimescaleFromBase(value, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round); } function toMpegTsClockFromTimescale(value, srcScale) { if (srcScale === void 0) { srcScale = 1; } return toTimescaleFromBase(value, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale); } /***/ }), /***/ "./src/utils/typed-array.ts": /*!**********************************!*\ !*** ./src/utils/typed-array.ts ***! \**********************************/ /*! exports provided: sliceUint8 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sliceUint8", function() { return sliceUint8; }); function sliceUint8(array, start, end) { // @ts-expect-error This polyfills IE11 usage of Uint8Array slice. // It always exists in the TypeScript definition so fails, but it fails at runtime on IE11. return Uint8Array.prototype.slice ? array.slice(start, end) : new Uint8Array(Array.prototype.slice.call(array, start, end)); } /***/ }), /***/ "./src/utils/xhr-loader.ts": /*!*********************************!*\ !*** ./src/utils/xhr-loader.ts ***! \*********************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts"); /* harmony import */ var _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/load-stats */ "./src/loader/load-stats.ts"); var AGE_HEADER_LINE_REGEX = /^age:\s*[\d.]+\s*$/m; var XhrLoader = /*#__PURE__*/function () { function XhrLoader(config /* HlsConfig */ ) { this.xhrSetup = void 0; this.requestTimeout = void 0; this.retryTimeout = void 0; this.retryDelay = void 0; this.config = null; this.callbacks = null; this.context = void 0; this.loader = null; this.stats = void 0; this.xhrSetup = config ? config.xhrSetup : null; this.stats = new _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__["LoadStats"](); this.retryDelay = 0; } var _proto = XhrLoader.prototype; _proto.destroy = function destroy() { this.callbacks = null; this.abortInternal(); this.loader = null; this.config = null; }; _proto.abortInternal = function abortInternal() { var loader = this.loader; self.clearTimeout(this.requestTimeout); self.clearTimeout(this.retryTimeout); if (loader) { loader.onreadystatechange = null; loader.onprogress = null; if (loader.readyState !== 4) { this.stats.aborted = true; loader.abort(); } } }; _proto.abort = function abort() { var _this$callbacks; this.abortInternal(); if ((_this$callbacks = this.callbacks) !== null && _this$callbacks !== void 0 && _this$callbacks.onAbort) { this.callbacks.onAbort(this.stats, this.context, this.loader); } }; _proto.load = function load(context, config, callbacks) { if (this.stats.loading.start) { throw new Error('Loader can only be used once.'); } this.stats.loading.start = self.performance.now(); this.context = context; this.config = config; this.callbacks = callbacks; this.retryDelay = config.retryDelay; this.loadInternal(); }; _proto.loadInternal = function loadInternal() { var config = this.config, context = this.context; if (!config) { return; } var xhr = this.loader = new self.XMLHttpRequest(); var stats = this.stats; stats.loading.first = 0; stats.loaded = 0; var xhrSetup = this.xhrSetup; try { if (xhrSetup) { try { xhrSetup(xhr, context.url); } catch (e) { // fix xhrSetup: (xhr, url) => {xhr.setRequestHeader("Content-Language", "test");} // not working, as xhr.setRequestHeader expects xhr.readyState === OPEN xhr.open('GET', context.url, true); xhrSetup(xhr, context.url); } } if (!xhr.readyState) { xhr.open('GET', context.url, true); } } catch (e) { // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS this.callbacks.onError({ code: xhr.status, text: e.message }, context, xhr); return; } if (context.rangeEnd) { xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1)); } xhr.onreadystatechange = this.readystatechange.bind(this); xhr.onprogress = this.loadprogress.bind(this); xhr.responseType = context.responseType; // setup timeout before we perform request self.clearTimeout(this.requestTimeout); this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout); xhr.send(); }; _proto.readystatechange = function readystatechange() { var context = this.context, xhr = this.loader, stats = this.stats; if (!context || !xhr) { return; } var readyState = xhr.readyState; var config = this.config; // don't proceed if xhr has been aborted if (stats.aborted) { return; } // >= HEADERS_RECEIVED if (readyState >= 2) { // clear xhr timeout and rearm it if readyState less than 4 self.clearTimeout(this.requestTimeout); if (stats.loading.first === 0) { stats.loading.first = Math.max(self.performance.now(), stats.loading.start); } if (readyState === 4) { xhr.onreadystatechange = null; xhr.onprogress = null; var status = xhr.status; // http status between 200 to 299 are all successful if (status >= 200 && status < 300) { stats.loading.end = Math.max(self.performance.now(), stats.loading.first); var data; var len; if (context.responseType === 'arraybuffer') { data = xhr.response; len = data.byteLength; } else { data = xhr.responseText; len = data.length; } stats.loaded = stats.total = len; if (!this.callbacks) { return; } var onProgress = this.callbacks.onProgress; if (onProgress) { onProgress(stats, context, data, xhr); } if (!this.callbacks) { return; } var response = { url: xhr.responseURL, data: data }; this.callbacks.onSuccess(response, stats, context, xhr); } else { // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error if (stats.retry >= config.maxRetry || status >= 400 && status < 499) { _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].error(status + " while loading " + context.url); this.callbacks.onError({ code: status, text: xhr.statusText }, context, xhr); } else { // retry _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].warn(status + " while loading " + context.url + ", retrying in " + this.retryDelay + "..."); // abort and reset internal state this.abortInternal(); this.loader = null; // schedule retry self.clearTimeout(this.retryTimeout); this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay); // set exponential backoff this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay); stats.retry++; } } } else { // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet self.clearTimeout(this.requestTimeout); this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout); } } }; _proto.loadtimeout = function loadtimeout() { _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].warn("timeout while loading " + this.context.url); var callbacks = this.callbacks; if (callbacks) { this.abortInternal(); callbacks.onTimeout(this.stats, this.context, this.loader); } }; _proto.loadprogress = function loadprogress(event) { var stats = this.stats; stats.loaded = event.loaded; if (event.lengthComputable) { stats.total = event.total; } }; _proto.getCacheAge = function getCacheAge() { var result = null; if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) { var ageHeader = this.loader.getResponseHeader('age'); result = ageHeader ? parseFloat(ageHeader) : null; } return result; }; return XhrLoader; }(); /* harmony default export */ __webpack_exports__["default"] = (XhrLoader); /***/ }) /******/ })["default"]; }); //# sourceMappingURL=hls.light.js.map
import React from 'react'; import ReactShallowRenderer from 'react-test-renderer/shallow'; import SlideInChild from 'chamel/transition-groups/SlideInChild'; /** * Test rendering the SlideInChild */ describe("SlideInChild Component", () => { // Basic validation that render works in edit mode and returns children it("Should render", () => { const renderer = new ReactShallowRenderer(); const renderedDocument = renderer.render( <SlideInChild /> ); expect(renderedDocument.props.className).toBe('chamel-transition-slide-in-child'); }); });
/** * @license AngularJS v1.3.0-beta.13 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, document, undefined) {'use strict'; /** * @description * * This object provides a utility for producing rich Error messages within * Angular. It can be called as follows: * * var exampleMinErr = minErr('example'); * throw exampleMinErr('one', 'This {0} is {1}', foo, bar); * * The above creates an instance of minErr in the example namespace. The * resulting error will have a namespaced error code of example.one. The * resulting error will replace {0} with the value of foo, and {1} with the * value of bar. The object is not restricted in the number of arguments it can * take. * * If fewer arguments are specified than necessary for interpolation, the extra * interpolation markers will be preserved in the final string. * * Since data will be parsed statically during a build step, some restrictions * are applied with respect to how minErr instances are created and called. * Instances should have names of the form namespaceMinErr for a minErr created * using minErr('namespace') . Error codes, namespaces and template strings * should all be static strings, not variables or general expressions. * * @param {string} module The namespace to use for the new minErr instance. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance */ function minErr(module) { return function () { var code = arguments[0], prefix = '[' + (module ? module + ':' : '') + code + '] ', template = arguments[1], templateArgs = arguments, stringify = function (obj) { if (typeof obj === 'function') { return obj.toString().replace(/ \{[\s\S]*$/, ''); } else if (typeof obj === 'undefined') { return 'undefined'; } else if (typeof obj !== 'string') { return JSON.stringify(obj); } return obj; }, message, i; message = prefix + template.replace(/\{\d+\}/g, function (match) { var index = +match.slice(1, -1), arg; if (index + 2 < templateArgs.length) { arg = templateArgs[index + 2]; if (typeof arg === 'function') { return arg.toString().replace(/ ?\{[\s\S]*$/, ''); } else if (typeof arg === 'undefined') { return 'undefined'; } else if (typeof arg !== 'string') { return toJson(arg); } return arg; } return match; }); message = message + '\nhttp://errors.angularjs.org/1.3.0-beta.13/' + (module ? module + '/' : '') + code; for (i = 2; i < arguments.length; i++) { message = message + (i == 2 ? '?' : '&') + 'p' + (i-2) + '=' + encodeURIComponent(stringify(arguments[i])); } return new Error(message); }; } /* We need to tell jshint what variables are being exported */ /* global -angular, -msie, -jqLite, -jQuery, -slice, -push, -toString, -ngMinErr, -angularModule, -nodeName_, -uid, -REGEX_STRING_REGEXP, -lowercase, -uppercase, -manualLowercase, -manualUppercase, -nodeName_, -isArrayLike, -forEach, -sortedKeys, -forEachSorted, -reverseParams, -nextUid, -setHashKey, -extend, -int, -inherit, -noop, -identity, -valueFn, -isUndefined, -isDefined, -isObject, -isString, -isNumber, -isDate, -isArray, -isFunction, -isRegExp, -isWindow, -isScope, -isFile, -isBlob, -isBoolean, -trim, -isElement, -makeMap, -map, -size, -includes, -indexOf, -arrayRemove, -isLeafNode, -copy, -shallowCopy, -equals, -csp, -concat, -sliceArgs, -bind, -toJsonReplacer, -toJson, -fromJson, -toBoolean, -startingTag, -tryDecodeURIComponent, -parseKeyValue, -toKeyValue, -encodeUriSegment, -encodeUriQuery, -angularInit, -bootstrap, -snake_case, -bindJQuery, -assertArg, -assertArgFn, -assertNotHasOwnProperty, -getter, -getBlockElements, -hasOwnProperty, */ //////////////////////////////////// /** * @ngdoc module * @name ng * @module ng * @description * * # ng (core module) * The ng module is loaded by default when an AngularJS application is started. The module itself * contains the essential components for an AngularJS application to function. The table below * lists a high level breakdown of each of the services/factories, filters, directives and testing * components available within this core module. * * <div doc-module-components="ng"></div> */ var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/; /** * @ngdoc function * @name angular.lowercase * @module ng * @kind function * * @description Converts the specified string to lowercase. * @param {string} string String to be converted to lowercase. * @returns {string} Lowercased string. */ var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;}; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * @ngdoc function * @name angular.uppercase * @module ng * @kind function * * @description Converts the specified string to uppercase. * @param {string} string String to be converted to uppercase. * @returns {string} Uppercased string. */ var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;}; var manualLowercase = function(s) { /* jshint bitwise: false */ return isString(s) ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);}) : s; }; var manualUppercase = function(s) { /* jshint bitwise: false */ return isString(s) ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);}) : s; }; // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods // with correct but slower alternatives. if ('i' !== 'I'.toLowerCase()) { lowercase = manualLowercase; uppercase = manualUppercase; } var /** holds major version number for IE or NaN for real browsers */ msie, jqLite, // delay binding since jQuery could be loaded after us. jQuery, // delay binding slice = [].slice, push = [].push, toString = Object.prototype.toString, ngMinErr = minErr('ng'), /** @name angular */ angular = window.angular || (window.angular = {}), angularModule, nodeName_, uid = 0; /** * IE 11 changed the format of the UserAgent string. * See http://msdn.microsoft.com/en-us/library/ms537503.aspx */ msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]); if (isNaN(msie)) { msie = int((/trident\/.*; rv:(\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]); } /** * @private * @param {*} obj * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments, * String ...) */ function isArrayLike(obj) { if (obj == null || isWindow(obj)) { return false; } var length = obj.length; if (obj.nodeType === 1 && length) { return true; } return isString(obj) || isArray(obj) || length === 0 || typeof length === 'number' && length > 0 && (length - 1) in obj; } /** * @ngdoc function * @name angular.forEach * @module ng * @kind function * * @description * Invokes the `iterator` function once for each item in `obj` collection, which can be either an * object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value` * is the value of an object property or an array element and `key` is the object property key or * array element index. Specifying a `context` for the function is optional. * * It is worth noting that `.forEach` does not iterate over inherited properties because it filters * using the `hasOwnProperty` method. * ```js var values = {name: 'misko', gender: 'male'}; var log = []; angular.forEach(values, function(value, key) { this.push(key + ': ' + value); }, log); expect(log).toEqual(['name: misko', 'gender: male']); ``` * * @param {Object|Array} obj Object to iterate over. * @param {Function} iterator Iterator function. * @param {Object=} context Object to become context (`this`) for the iterator function. * @returns {Object|Array} Reference to `obj`. */ function forEach(obj, iterator, context) { var key, length; if (obj) { if (isFunction(obj)) { for (key in obj) { // Need to check if hasOwnProperty exists, // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) { iterator.call(context, obj[key], key); } } } else if (obj.forEach && obj.forEach !== forEach) { obj.forEach(iterator, context); } else if (isArrayLike(obj)) { for (key = 0, length = obj.length; key < length; key++) { iterator.call(context, obj[key], key); } } else { for (key in obj) { if (obj.hasOwnProperty(key)) { iterator.call(context, obj[key], key); } } } } return obj; } function sortedKeys(obj) { var keys = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { keys.push(key); } } return keys.sort(); } function forEachSorted(obj, iterator, context) { var keys = sortedKeys(obj); for ( var i = 0; i < keys.length; i++) { iterator.call(context, obj[keys[i]], keys[i]); } return keys; } /** * when using forEach the params are value, key, but it is often useful to have key, value. * @param {function(string, *)} iteratorFn * @returns {function(*, string)} */ function reverseParams(iteratorFn) { return function(value, key) { iteratorFn(key, value); }; } /** * A consistent way of creating unique IDs in angular. * * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before * we hit number precision issues in JavaScript. * * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M * * @returns {number} an unique alpha-numeric string */ function nextUid() { return ++uid; } /** * Set or clear the hashkey for an object. * @param obj object * @param h the hashkey (!truthy to delete the hashkey) */ function setHashKey(obj, h) { if (h) { obj.$$hashKey = h; } else { delete obj.$$hashKey; } } /** * @ngdoc function * @name angular.extend * @module ng * @kind function * * @description * Extends the destination object `dst` by copying all of the properties from the `src` object(s) * to `dst`. You can specify multiple `src` objects. * * @param {Object} dst Destination object. * @param {...Object} src Source object(s). * @returns {Object} Reference to `dst`. */ function extend(dst) { var h = dst.$$hashKey; forEach(arguments, function(obj) { if (obj !== dst) { forEach(obj, function(value, key) { dst[key] = value; }); } }); setHashKey(dst,h); return dst; } function int(str) { return parseInt(str, 10); } function inherit(parent, extra) { return extend(new (extend(function() {}, {prototype:parent}))(), extra); } /** * @ngdoc function * @name angular.noop * @module ng * @kind function * * @description * A function that performs no operations. This function can be useful when writing code in the * functional style. ```js function foo(callback) { var result = calculateResult(); (callback || angular.noop)(result); } ``` */ function noop() {} noop.$inject = []; /** * @ngdoc function * @name angular.identity * @module ng * @kind function * * @description * A function that returns its first argument. This function is useful when writing code in the * functional style. * ```js function transformer(transformationFn, value) { return (transformationFn || angular.identity)(value); }; ``` */ function identity($) {return $;} identity.$inject = []; function valueFn(value) {return function() {return value;};} /** * @ngdoc function * @name angular.isUndefined * @module ng * @kind function * * @description * Determines if a reference is undefined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is undefined. */ function isUndefined(value){return typeof value === 'undefined';} /** * @ngdoc function * @name angular.isDefined * @module ng * @kind function * * @description * Determines if a reference is defined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is defined. */ function isDefined(value){return typeof value !== 'undefined';} /** * @ngdoc function * @name angular.isObject * @module ng * @kind function * * @description * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not * considered to be objects. Note that JavaScript arrays are objects. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Object` but not `null`. */ function isObject(value){return value != null && typeof value === 'object';} /** * @ngdoc function * @name angular.isString * @module ng * @kind function * * @description * Determines if a reference is a `String`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `String`. */ function isString(value){return typeof value === 'string';} /** * @ngdoc function * @name angular.isNumber * @module ng * @kind function * * @description * Determines if a reference is a `Number`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Number`. */ function isNumber(value){return typeof value === 'number';} /** * @ngdoc function * @name angular.isDate * @module ng * @kind function * * @description * Determines if a value is a date. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Date`. */ function isDate(value) { return toString.call(value) === '[object Date]'; } /** * @ngdoc function * @name angular.isArray * @module ng * @kind function * * @description * Determines if a reference is an `Array`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Array`. */ var isArray = (function() { if (!isFunction(Array.isArray)) { return function(value) { return toString.call(value) === '[object Array]'; }; } return Array.isArray; })(); /** * @ngdoc function * @name angular.isFunction * @module ng * @kind function * * @description * Determines if a reference is a `Function`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Function`. */ function isFunction(value){return typeof value === 'function';} /** * Determines if a value is a regular expression object. * * @private * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `RegExp`. */ function isRegExp(value) { return toString.call(value) === '[object RegExp]'; } /** * Checks if `obj` is a window object. * * @private * @param {*} obj Object to check * @returns {boolean} True if `obj` is a window obj. */ function isWindow(obj) { return obj && obj.window === obj; } function isScope(obj) { return obj && obj.$evalAsync && obj.$watch; } function isFile(obj) { return toString.call(obj) === '[object File]'; } function isBlob(obj) { return toString.call(obj) === '[object Blob]'; } function isBoolean(value) { return typeof value === 'boolean'; } var trim = (function() { // native trim is way faster: http://jsperf.com/angular-trim-test // but IE doesn't have it... :-( // TODO: we should move this into IE/ES5 polyfill if (!String.prototype.trim) { return function(value) { return isString(value) ? value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : value; }; } return function(value) { return isString(value) ? value.trim() : value; }; })(); /** * @ngdoc function * @name angular.isElement * @module ng * @kind function * * @description * Determines if a reference is a DOM element (or wrapped jQuery element). * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element). */ function isElement(node) { return !!(node && (node.nodeName // we are a direct element || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API } /** * @param str 'key1,key2,...' * @returns {object} in the form of {key1:true, key2:true, ...} */ function makeMap(str) { var obj = {}, items = str.split(","), i; for ( i = 0; i < items.length; i++ ) obj[ items[i] ] = true; return obj; } if (msie < 9) { nodeName_ = function(element) { element = element.nodeName ? element : element[0]; return (element.scopeName && element.scopeName != 'HTML') ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName; }; } else { nodeName_ = function(element) { return element.nodeName ? element.nodeName : element[0].nodeName; }; } function map(obj, iterator, context) { var results = []; forEach(obj, function(value, index, list) { results.push(iterator.call(context, value, index, list)); }); return results; } /** * @description * Determines the number of elements in an array, the number of properties an object has, or * the length of a string. * * Note: This function is used to augment the Object type in Angular expressions. See * {@link angular.Object} for more information about Angular arrays. * * @param {Object|Array|string} obj Object, array, or string to inspect. * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array. */ function size(obj, ownPropsOnly) { var count = 0, key; if (isArray(obj) || isString(obj)) { return obj.length; } else if (isObject(obj)) { for (key in obj) if (!ownPropsOnly || obj.hasOwnProperty(key)) count++; } return count; } function includes(array, obj) { return indexOf(array, obj) != -1; } function indexOf(array, obj) { if (array.indexOf) return array.indexOf(obj); for (var i = 0; i < array.length; i++) { if (obj === array[i]) return i; } return -1; } function arrayRemove(array, value) { var index = indexOf(array, value); if (index >=0) array.splice(index, 1); return value; } function isLeafNode (node) { if (node) { switch (node.nodeName) { case "OPTION": case "PRE": case "TITLE": return true; } } return false; } /** * @ngdoc function * @name angular.copy * @module ng * @kind function * * @description * Creates a deep copy of `source`, which should be an object or an array. * * * If no destination is supplied, a copy of the object or array is created. * * If a destination is provided, all of its elements (for array) or properties (for objects) * are deleted and then all elements/properties from the source are copied to it. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned. * * If `source` is identical to 'destination' an exception will be thrown. * * @param {*} source The source that will be used to make a copy. * Can be any type, including primitives, `null`, and `undefined`. * @param {(Object|Array)=} destination Destination into which the source is copied. If * provided, must be of the same type as `source`. * @returns {*} The copy or updated `destination`, if `destination` was specified. * * @example <example> <file name="index.html"> <div ng-controller="Controller"> <form novalidate class="simple-form"> Name: <input type="text" ng-model="user.name" /><br /> E-mail: <input type="email" ng-model="user.email" /><br /> Gender: <input type="radio" ng-model="user.gender" value="male" />male <input type="radio" ng-model="user.gender" value="female" />female<br /> <button ng-click="reset()">RESET</button> <button ng-click="update(user)">SAVE</button> </form> <pre>form = {{user | json}}</pre> <pre>master = {{master | json}}</pre> </div> <script> function Controller($scope) { $scope.master= {}; $scope.update = function(user) { // Example with 1 argument $scope.master= angular.copy(user); }; $scope.reset = function() { // Example with 2 arguments angular.copy($scope.master, $scope.user); }; $scope.reset(); } </script> </file> </example> */ function copy(source, destination, stackSource, stackDest) { if (isWindow(source) || isScope(source)) { throw ngMinErr('cpws', "Can't copy! Making copies of Window or Scope instances is not supported."); } if (!destination) { destination = source; if (source) { if (isArray(source)) { destination = copy(source, [], stackSource, stackDest); } else if (isDate(source)) { destination = new Date(source.getTime()); } else if (isRegExp(source)) { destination = new RegExp(source.source); } else if (isObject(source)) { destination = copy(source, {}, stackSource, stackDest); } } } else { if (source === destination) throw ngMinErr('cpi', "Can't copy! Source and destination are identical."); stackSource = stackSource || []; stackDest = stackDest || []; if (isObject(source)) { var index = indexOf(stackSource, source); if (index !== -1) return stackDest[index]; stackSource.push(source); stackDest.push(destination); } var result; if (isArray(source)) { destination.length = 0; for ( var i = 0; i < source.length; i++) { result = copy(source[i], null, stackSource, stackDest); if (isObject(source[i])) { stackSource.push(source[i]); stackDest.push(result); } destination.push(result); } } else { var h = destination.$$hashKey; forEach(destination, function(value, key) { delete destination[key]; }); for ( var key in source) { result = copy(source[key], null, stackSource, stackDest); if (isObject(source[key])) { stackSource.push(source[key]); stackDest.push(result); } destination[key] = result; } setHashKey(destination,h); } } return destination; } /** * Creates a shallow copy of an object, an array or a primitive */ function shallowCopy(src, dst) { var i = 0; if (isArray(src)) { dst = dst || []; for (; i < src.length; i++) { dst[i] = src[i]; } } else if (isObject(src)) { dst = dst || {}; var keys = Object.keys(src); for (var l = keys.length; i < l; i++) { var key = keys[i]; if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) { dst[key] = src[key]; } } } return dst || src; } /** * @ngdoc function * @name angular.equals * @module ng * @kind function * * @description * Determines if two objects or two values are equivalent. Supports value types, regular * expressions, arrays and objects. * * Two objects or values are considered equivalent if at least one of the following is true: * * * Both objects or values pass `===` comparison. * * Both objects or values are of the same type and all of their properties are equal by * comparing them with `angular.equals`. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal) * * Both values represent the same regular expression (In JavaScript, * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual * representation matches). * * During a property comparison, properties of `function` type and properties with names * that begin with `$` are ignored. * * Scope and DOMWindow objects are being compared only by identify (`===`). * * @param {*} o1 Object or value to compare. * @param {*} o2 Object or value to compare. * @returns {boolean} True if arguments are equal. */ function equals(o1, o2) { if (o1 === o2) return true; if (o1 === null || o2 === null) return false; if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN var t1 = typeof o1, t2 = typeof o2, length, key, keySet; if (t1 == t2) { if (t1 == 'object') { if (isArray(o1)) { if (!isArray(o2)) return false; if ((length = o1.length) == o2.length) { for(key=0; key<length; key++) { if (!equals(o1[key], o2[key])) return false; } return true; } } else if (isDate(o1)) { return isDate(o2) && o1.getTime() == o2.getTime(); } else if (isRegExp(o1) && isRegExp(o2)) { return o1.toString() == o2.toString(); } else { if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || isArray(o2)) return false; keySet = {}; for(key in o1) { if (key.charAt(0) === '$' || isFunction(o1[key])) continue; if (!equals(o1[key], o2[key])) return false; keySet[key] = true; } for(key in o2) { if (!keySet.hasOwnProperty(key) && key.charAt(0) !== '$' && o2[key] !== undefined && !isFunction(o2[key])) return false; } return true; } } } return false; } function csp() { return (document.securityPolicy && document.securityPolicy.isActive) || (document.querySelector && !!(document.querySelector('[ng-csp]') || document.querySelector('[data-ng-csp]'))); } function concat(array1, array2, index) { return array1.concat(slice.call(array2, index)); } function sliceArgs(args, startIndex) { return slice.call(args, startIndex || 0); } /* jshint -W101 */ /** * @ngdoc function * @name angular.bind * @module ng * @kind function * * @description * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for * `fn`). You can supply optional `args` that are prebound to the function. This feature is also * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application). * * @param {Object} self Context which `fn` should be evaluated in. * @param {function()} fn Function to be bound. * @param {...*} args Optional arguments to be prebound to the `fn` function call. * @returns {function()} Function that wraps the `fn` with all the specified bindings. */ /* jshint +W101 */ function bind(self, fn) { var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : []; if (isFunction(fn) && !(fn instanceof RegExp)) { return curryArgs.length ? function() { return arguments.length ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0))) : fn.apply(self, curryArgs); } : function() { return arguments.length ? fn.apply(self, arguments) : fn.call(self); }; } else { // in IE, native methods are not functions so they cannot be bound (note: they don't need to be) return fn; } } function toJsonReplacer(key, value) { var val = value; if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') { val = undefined; } else if (isWindow(value)) { val = '$WINDOW'; } else if (value && document === value) { val = '$DOCUMENT'; } else if (isScope(value)) { val = '$SCOPE'; } return val; } /** * @ngdoc function * @name angular.toJson * @module ng * @kind function * * @description * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be * stripped since angular uses this notation internally. * * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace. * @returns {string|undefined} JSON-ified string representing `obj`. */ function toJson(obj, pretty) { if (typeof obj === 'undefined') return undefined; return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null); } /** * @ngdoc function * @name angular.fromJson * @module ng * @kind function * * @description * Deserializes a JSON string. * * @param {string} json JSON string to deserialize. * @returns {Object|Array|string|number} Deserialized thingy. */ function fromJson(json) { return isString(json) ? JSON.parse(json) : json; } function toBoolean(value) { if (typeof value === 'function') { value = true; } else if (value && value.length !== 0) { var v = lowercase("" + value); value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]'); } else { value = false; } return value; } /** * @returns {string} Returns the string representation of the element. */ function startingTag(element) { element = jqLite(element).clone(); try { // turns out IE does not let you set .html() on elements which // are not allowed to have children. So we just ignore it. element.empty(); } catch(e) {} // As Per DOM Standards var TEXT_NODE = 3; var elemHtml = jqLite('<div>').append(element).html(); try { return element[0].nodeType === TEXT_NODE ? lowercase(elemHtml) : elemHtml. match(/^(<[^>]+>)/)[1]. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); }); } catch(e) { return lowercase(elemHtml); } } ///////////////////////////////////////////////// /** * Tries to decode the URI component without throwing an exception. * * @private * @param str value potential URI component to check. * @returns {boolean} True if `value` can be decoded * with the decodeURIComponent function. */ function tryDecodeURIComponent(value) { try { return decodeURIComponent(value); } catch(e) { // Ignore any invalid uri component } } /** * Parses an escaped url query string into key-value pairs. * @returns {Object.<string,boolean|Array>} */ function parseKeyValue(/**string*/keyValue) { var obj = {}, key_value, key; forEach((keyValue || "").split('&'), function(keyValue) { if ( keyValue ) { key_value = keyValue.split('='); key = tryDecodeURIComponent(key_value[0]); if ( isDefined(key) ) { var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true; if (!obj[key]) { obj[key] = val; } else if(isArray(obj[key])) { obj[key].push(val); } else { obj[key] = [obj[key],val]; } } } }); return obj; } function toKeyValue(obj) { var parts = []; forEach(obj, function(value, key) { if (isArray(value)) { forEach(value, function(arrayValue) { parts.push(encodeUriQuery(key, true) + (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true))); }); } else { parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true))); } }); return parts.length ? parts.join('&') : ''; } /** * We need our custom method because encodeURIComponent is too aggressive and doesn't follow * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path * segments: * segment = *pchar * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * pct-encoded = "%" HEXDIG HEXDIG * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriSegment(val) { return encodeUriQuery(val, true). replace(/%26/gi, '&'). replace(/%3D/gi, '='). replace(/%2B/gi, '+'); } /** * This method is intended for encoding *key* or *value* parts of query component. We need a custom * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be * encoded per http://tools.ietf.org/html/rfc3986: * query = *( pchar / "/" / "?" ) * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * pct-encoded = "%" HEXDIG HEXDIG * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriQuery(val, pctEncodeSpaces) { return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); } var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-']; function getNgAttribute(element, ngAttr) { var attr, i, ii = ngAttrPrefixes.length, j, jj; element = jqLite(element); for (i=0; i<ii; ++i) { attr = ngAttrPrefixes[i] + ngAttr; if (isString(attr = element.attr(attr))) { return attr; } } return null; } /** * @ngdoc directive * @name ngApp * @module ng * * @element ANY * @param {angular.Module} ngApp an optional application * {@link angular.module module} name to load. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be * created in "strict-di" mode. This means that the application will fail to invoke functions which * do not use explicit function annotation (and are thus unsuitable for minification), as described * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in * tracking down the root of these bugs. * * @description * * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive * designates the **root element** of the application and is typically placed near the root element * of the page - e.g. on the `<body>` or `<html>` tags. * * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp` * found in the document will be used to define the root element to auto-bootstrap as an * application. To run multiple applications in an HTML document you must manually bootstrap them using * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other. * * You can specify an **AngularJS module** to be used as the root module for the application. This * module will be loaded into the {@link auto.$injector} when the application is bootstrapped and * should contain the application code needed or have dependencies on other modules that will * contain the code. See {@link angular.module} for more information. * * In the example below if the `ngApp` directive were not placed on the `html` element then the * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}` * would not be resolved to `3`. * * `ngApp` is the easiest, and most common, way to bootstrap an application. * <example module="ngAppDemo"> <file name="index.html"> <div ng-controller="ngAppDemoController"> I can add: {{a}} + {{b}} = {{ a+b }} </div> </file> <file name="script.js"> angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) { $scope.a = 1; $scope.b = 2; }); </file> </example> * * Using `ngStrictDi`, you would see something like this: * <example ng-app-included="true"> <file name="index.html"> <div ng-app="ngAppStrictDemo" ng-strict-di> <div ng-controller="GoodController1"> I can add: {{a}} + {{b}} = {{ a+b }} <p>This renders because the controller does not fail to instantiate, by using explicit annotation style (see script.js for details) </p> </div> <div ng-controller="GoodController2"> Name: <input ng-model="name"><br /> Hello, {{name}}! <p>This renders because the controller does not fail to instantiate, by using explicit annotation style (see script.js for details) </p> </div> <div ng-controller="BadController"> I can add: {{a}} + {{b}} = {{ a+b }} <p>The controller could not be instantiated, due to relying on automatic function annotations (which are disabled in strict mode). As such, the content of this section is not interpolated, and there should be an error in your web console. </p> </div> </div> </file> <file name="script.js"> angular.module('ngAppStrictDemo', []) // BadController will fail to instantiate, due to relying on automatic function annotation, // rather than an explicit annotation .controller('BadController', function($scope) { $scope.a = 1; $scope.b = 2; }) // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated, // due to using explicit annotations using the array style and $inject property, respectively. .controller('GoodController1', ['$scope', function($scope) { $scope.a = 1; $scope.b = 2; }]) .controller('GoodController2', GoodController2); function GoodController2($scope) { $scope.name = "World"; } GoodController2.$inject = ['$scope']; </file> <file name="style.css"> div[ng-controller] { margin-bottom: 1em; -webkit-border-radius: 4px; border-radius: 4px; border: 1px solid; padding: .5em; } div[ng-controller^=Good] { border-color: #d6e9c6; background-color: #dff0d8; color: #3c763d; } div[ng-controller^=Bad] { border-color: #ebccd1; background-color: #f2dede; color: #a94442; margin-bottom: 0; } </file> </example> */ function angularInit(element, bootstrap) { var elements = [element], appElement, module, config = {}, names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'], options = { 'boolean': ['strict-di'] }, NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/; function append(element) { element && elements.push(element); } forEach(names, function(name) { names[name] = true; append(document.getElementById(name)); name = name.replace(':', '\\:'); if (element.querySelectorAll) { forEach(element.querySelectorAll('.' + name), append); forEach(element.querySelectorAll('.' + name + '\\:'), append); forEach(element.querySelectorAll('[' + name + ']'), append); } }); forEach(elements, function(element) { if (!appElement) { var className = ' ' + element.className + ' '; var match = NG_APP_CLASS_REGEXP.exec(className); if (match) { appElement = element; module = (match[2] || '').replace(/\s+/g, ','); } else { forEach(element.attributes, function(attr) { if (!appElement && names[attr.name]) { appElement = element; module = attr.value; } }); } } }); if (appElement) { config.strictDi = getNgAttribute(appElement, "strict-di") !== null; bootstrap(appElement, module ? [module] : [], config); } } /** * @ngdoc function * @name angular.bootstrap * @module ng * @description * Use this function to manually start up angular application. * * See: {@link guide/bootstrap Bootstrap} * * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually. * They must use {@link ng.directive:ngApp ngApp}. * * Angular will detect if it has been loaded into the browser more than once and only allow the * first loaded script to be bootstrapped and will report a warning to the browser console for * each of the subsequent scripts. This prevents strange results in applications, where otherwise * multiple instances of Angular try to work on the DOM. * * ```html * <!doctype html> * <html> * <body> * <div ng-controller="WelcomeController"> * {{greeting}} * </div> * * <script src="angular.js"></script> * <script> * var app = angular.module('demo', []) * .controller('WelcomeController', function($scope) { * $scope.greeting = 'Welcome!'; * }); * angular.bootstrap(document, ['demo']); * </script> * </body> * </html> * ``` * * @param {DOMElement} element DOM element which is the root of angular application. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application. * Each item in the array should be the name of a predefined module or a (DI annotated) * function that will be invoked by the injector as a run block. * See: {@link angular.module modules} * @param {Object=} config an object for defining configuration options for the application. The * following keys are supported: * * - `strictDi`: disable automatic function annotation for the application. This is meant to * assist in finding bugs which break minified code. * * @returns {auto.$injector} Returns the newly created injector for this app. */ function bootstrap(element, modules, config) { if (!isObject(config)) config = {}; var defaultConfig = { strictDi: false }; config = extend(defaultConfig, config); var doBootstrap = function() { element = jqLite(element); if (element.injector()) { var tag = (element[0] === document) ? 'document' : startingTag(element); throw ngMinErr('btstrpd', "App Already Bootstrapped with this Element '{0}'", tag); } modules = modules || []; modules.unshift(['$provide', function($provide) { $provide.value('$rootElement', element); }]); modules.unshift('ng'); var injector = createInjector(modules, config.strictDi); injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', function(scope, element, compile, injector) { scope.$apply(function() { element.data('$injector', injector); compile(element)(scope); }); }] ); return injector; }; var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/; if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) { return doBootstrap(); } window.name = window.name.replace(NG_DEFER_BOOTSTRAP, ''); angular.resumeBootstrap = function(extraModules) { forEach(extraModules, function(module) { modules.push(module); }); doBootstrap(); }; } var SNAKE_CASE_REGEXP = /[A-Z]/g; function snake_case(name, separator) { separator = separator || '_'; return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) { return (pos ? separator : '') + letter.toLowerCase(); }); } function bindJQuery() { var originalCleanData; // bind to jQuery if present; jQuery = window.jQuery; // Use jQuery if it exists with proper functionality, otherwise default to us. // Angular 1.2+ requires jQuery 1.7.1+ for on()/off() support. if (jQuery && jQuery.fn.on) { jqLite = jQuery; extend(jQuery.fn, { scope: JQLitePrototype.scope, isolateScope: JQLitePrototype.isolateScope, controller: JQLitePrototype.controller, injector: JQLitePrototype.injector, inheritedData: JQLitePrototype.inheritedData }); originalCleanData = jQuery.cleanData; // Prevent double-proxying. originalCleanData = originalCleanData.$$original || originalCleanData; // All nodes removed from the DOM via various jQuery APIs like .remove() // are passed through jQuery.cleanData. Monkey-patch this method to fire // the $destroy event on all removed nodes. jQuery.cleanData = function(elems) { for (var i = 0, elem; (elem = elems[i]) != null; i++) { jQuery(elem).triggerHandler('$destroy'); } originalCleanData(elems); }; jQuery.cleanData.$$original = originalCleanData; } else { jqLite = JQLite; } angular.element = jqLite; } /** * throw error if the argument is falsy. */ function assertArg(arg, name, reason) { if (!arg) { throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required")); } return arg; } function assertArgFn(arg, name, acceptArrayAnnotation) { if (acceptArrayAnnotation && isArray(arg)) { arg = arg[arg.length - 1]; } assertArg(isFunction(arg), name, 'not a function, got ' + (arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg)); return arg; } /** * throw error if the name given is hasOwnProperty * @param {String} name the name to test * @param {String} context the context in which the name is used, such as module or directive */ function assertNotHasOwnProperty(name, context) { if (name === 'hasOwnProperty') { throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context); } } /** * Return the value accessible from the object by path. Any undefined traversals are ignored * @param {Object} obj starting object * @param {String} path path to traverse * @param {boolean} [bindFnToScope=true] * @returns {Object} value as accessible by path */ //TODO(misko): this function needs to be removed function getter(obj, path, bindFnToScope) { if (!path) return obj; var keys = path.split('.'); var key; var lastInstance = obj; var len = keys.length; for (var i = 0; i < len; i++) { key = keys[i]; if (obj) { obj = (lastInstance = obj)[key]; } } if (!bindFnToScope && isFunction(obj)) { return bind(lastInstance, obj); } return obj; } /** * Return the DOM siblings between the first and last node in the given array. * @param {Array} array like object * @returns {DOMElement} object containing the elements */ function getBlockElements(nodes) { var startNode = nodes[0], endNode = nodes[nodes.length - 1]; if (startNode === endNode) { return jqLite(startNode); } var element = startNode; var elements = [element]; do { element = element.nextSibling; if (!element) break; elements.push(element); } while (element !== endNode); return jqLite(elements); } /** * @ngdoc type * @name angular.Module * @module ng * @description * * Interface for configuring angular {@link angular.module modules}. */ function setupModuleLoader(window) { var $injectorMinErr = minErr('$injector'); var ngMinErr = minErr('ng'); function ensure(obj, name, factory) { return obj[name] || (obj[name] = factory()); } var angular = ensure(window, 'angular', Object); // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap angular.$$minErr = angular.$$minErr || minErr; return ensure(angular, 'module', function() { /** @type {Object.<string, angular.Module>} */ var modules = {}; /** * @ngdoc function * @name angular.module * @module ng * @description * * The `angular.module` is a global place for creating, registering and retrieving Angular * modules. * All modules (angular core or 3rd party) that should be available to an application must be * registered using this mechanism. * * When passed two or more arguments, a new module is created. If passed only one argument, an * existing module (the name passed as the first argument to `module`) is retrieved. * * * # Module * * A module is a collection of services, directives, controllers, filters, and configuration information. * `angular.module` is used to configure the {@link auto.$injector $injector}. * * ```js * // Create a new module * var myModule = angular.module('myModule', []); * * // register a new service * myModule.value('appName', 'MyCoolApp'); * * // configure existing services inside initialization blocks. * myModule.config(['$locationProvider', function($locationProvider) { * // Configure existing providers * $locationProvider.hashPrefix('!'); * }]); * ``` * * Then you can create an injector and load your modules like this: * * ```js * var injector = angular.injector(['ng', 'myModule']) * ``` * * However it's more likely that you'll just use * {@link ng.directive:ngApp ngApp} or * {@link angular.bootstrap} to simplify this process for you. * * @param {!string} name The name of the module to create or retrieve. * @param {!Array.<string>=} requires If specified then new module is being created. If * unspecified then the module is being retrieved for further configuration. * @param {Function=} configFn Optional configuration function for the module. Same as * {@link angular.Module#config Module#config()}. * @returns {module} new module with the {@link angular.Module} api. */ return function module(name, requires, configFn) { var assertNotHasOwnProperty = function(name, context) { if (name === 'hasOwnProperty') { throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); } }; assertNotHasOwnProperty(name, 'module'); if (requires && modules.hasOwnProperty(name)) { modules[name] = null; } return ensure(modules, name, function() { if (!requires) { throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " + "the module name or forgot to load it. If registering a module ensure that you " + "specify the dependencies as the second argument.", name); } /** @type {!Array.<Array.<*>>} */ var invokeQueue = []; /** @type {!Array.<Function>} */ var configBlocks = []; /** @type {!Array.<Function>} */ var runBlocks = []; var config = invokeLater('$injector', 'invoke', 'push', configBlocks); /** @type {angular.Module} */ var moduleInstance = { // Private state _invokeQueue: invokeQueue, _configBlocks: configBlocks, _runBlocks: runBlocks, /** * @ngdoc property * @name angular.Module#requires * @module ng * @returns {Array.<string>} List of module names which must be loaded before this module. * @description * Holds the list of modules which the injector will load before the current module is * loaded. */ requires: requires, /** * @ngdoc property * @name angular.Module#name * @module ng * @returns {string} Name of the module. * @description */ name: name, /** * @ngdoc method * @name angular.Module#provider * @module ng * @param {string} name service name * @param {Function} providerType Construction function for creating new instance of the * service. * @description * See {@link auto.$provide#provider $provide.provider()}. */ provider: invokeLater('$provide', 'provider'), /** * @ngdoc method * @name angular.Module#factory * @module ng * @param {string} name service name * @param {Function} providerFunction Function for creating new instance of the service. * @description * See {@link auto.$provide#factory $provide.factory()}. */ factory: invokeLater('$provide', 'factory'), /** * @ngdoc method * @name angular.Module#service * @module ng * @param {string} name service name * @param {Function} constructor A constructor function that will be instantiated. * @description * See {@link auto.$provide#service $provide.service()}. */ service: invokeLater('$provide', 'service'), /** * @ngdoc method * @name angular.Module#value * @module ng * @param {string} name service name * @param {*} object Service instance object. * @description * See {@link auto.$provide#value $provide.value()}. */ value: invokeLater('$provide', 'value'), /** * @ngdoc method * @name angular.Module#constant * @module ng * @param {string} name constant name * @param {*} object Constant value. * @description * Because the constant are fixed, they get applied before other provide methods. * See {@link auto.$provide#constant $provide.constant()}. */ constant: invokeLater('$provide', 'constant', 'unshift'), /** * @ngdoc method * @name angular.Module#animation * @module ng * @param {string} name animation name * @param {Function} animationFactory Factory function for creating new instance of an * animation. * @description * * **NOTE**: animations take effect only if the **ngAnimate** module is loaded. * * * Defines an animation hook that can be later used with * {@link ngAnimate.$animate $animate} service and directives that use this service. * * ```js * module.animation('.animation-name', function($inject1, $inject2) { * return { * eventName : function(element, done) { * //code to run the animation * //once complete, then run done() * return function cancellationFunction(element) { * //code to cancel the animation * } * } * } * }) * ``` * * See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and * {@link ngAnimate ngAnimate module} for more information. */ animation: invokeLater('$animateProvider', 'register'), /** * @ngdoc method * @name angular.Module#filter * @module ng * @param {string} name Filter name. * @param {Function} filterFactory Factory function for creating new instance of filter. * @description * See {@link ng.$filterProvider#register $filterProvider.register()}. */ filter: invokeLater('$filterProvider', 'register'), /** * @ngdoc method * @name angular.Module#controller * @module ng * @param {string|Object} name Controller name, or an object map of controllers where the * keys are the names and the values are the constructors. * @param {Function} constructor Controller constructor function. * @description * See {@link ng.$controllerProvider#register $controllerProvider.register()}. */ controller: invokeLater('$controllerProvider', 'register'), /** * @ngdoc method * @name angular.Module#directive * @module ng * @param {string|Object} name Directive name, or an object map of directives where the * keys are the names and the values are the factories. * @param {Function} directiveFactory Factory function for creating new instance of * directives. * @description * See {@link ng.$compileProvider#directive $compileProvider.directive()}. */ directive: invokeLater('$compileProvider', 'directive'), /** * @ngdoc method * @name angular.Module#config * @module ng * @param {Function} configFn Execute this function on module load. Useful for service * configuration. * @description * Use this method to register work which needs to be performed on module loading. * For more about how to configure services, see * {@link providers#providers_provider-recipe Provider Recipe}. */ config: config, /** * @ngdoc method * @name angular.Module#run * @module ng * @param {Function} initializationFn Execute this function after injector creation. * Useful for application initialization. * @description * Use this method to register work which should be performed when the injector is done * loading all modules. */ run: function(block) { runBlocks.push(block); return this; } }; if (configFn) { config(configFn); } return moduleInstance; /** * @param {string} provider * @param {string} method * @param {String=} insertMethod * @returns {angular.Module} */ function invokeLater(provider, method, insertMethod, queue) { if (!queue) queue = invokeQueue; return function() { queue[insertMethod || 'push']([provider, method, arguments]); return moduleInstance; }; } }); }; }); } /* global angularModule: true, version: true, $LocaleProvider, $CompileProvider, htmlAnchorDirective, inputDirective, inputDirective, formDirective, scriptDirective, selectDirective, styleDirective, optionDirective, ngBindDirective, ngBindHtmlDirective, ngBindTemplateDirective, ngClassDirective, ngClassEvenDirective, ngClassOddDirective, ngCspDirective, ngCloakDirective, ngControllerDirective, ngFormDirective, ngHideDirective, ngIfDirective, ngIncludeDirective, ngIncludeFillContentDirective, ngInitDirective, ngNonBindableDirective, ngPluralizeDirective, ngRepeatDirective, ngShowDirective, ngStyleDirective, ngSwitchDirective, ngSwitchWhenDirective, ngSwitchDefaultDirective, ngOptionsDirective, ngTranscludeDirective, ngModelDirective, ngListDirective, ngChangeDirective, patternDirective, patternDirective, requiredDirective, requiredDirective, minlengthDirective, minlengthDirective, maxlengthDirective, maxlengthDirective, ngValueDirective, ngModelOptionsDirective, ngAttributeAliasDirectives, ngEventDirectives, $AnchorScrollProvider, $AnimateProvider, $BrowserProvider, $CacheFactoryProvider, $ControllerProvider, $DocumentProvider, $ExceptionHandlerProvider, $FilterProvider, $InterpolateProvider, $IntervalProvider, $HttpProvider, $HttpBackendProvider, $LocationProvider, $LogProvider, $ParseProvider, $RootScopeProvider, $QProvider, $$SanitizeUriProvider, $SceProvider, $SceDelegateProvider, $SnifferProvider, $TemplateCacheProvider, $TimeoutProvider, $$RAFProvider, $$AsyncCallbackProvider, $WindowProvider */ /** * @ngdoc object * @name angular.version * @module ng * @description * An object that contains information about the current AngularJS version. This object has the * following properties: * * - `full` – `{string}` – Full version string, such as "0.9.18". * - `major` – `{number}` – Major version number, such as "0". * - `minor` – `{number}` – Minor version number, such as "9". * - `dot` – `{number}` – Dot version number, such as "18". * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat". */ var version = { full: '1.3.0-beta.13', // all of these placeholder strings will be replaced by grunt's major: 1, // package task minor: 3, dot: 0, codeName: 'idiosyncratic-numerification' }; function publishExternalAPI(angular){ extend(angular, { 'bootstrap': bootstrap, 'copy': copy, 'extend': extend, 'equals': equals, 'element': jqLite, 'forEach': forEach, 'injector': createInjector, 'noop':noop, 'bind':bind, 'toJson': toJson, 'fromJson': fromJson, 'identity':identity, 'isUndefined': isUndefined, 'isDefined': isDefined, 'isString': isString, 'isFunction': isFunction, 'isObject': isObject, 'isNumber': isNumber, 'isElement': isElement, 'isArray': isArray, 'version': version, 'isDate': isDate, 'lowercase': lowercase, 'uppercase': uppercase, 'callbacks': {counter: 0}, '$$minErr': minErr, '$$csp': csp }); angularModule = setupModuleLoader(window); try { angularModule('ngLocale'); } catch (e) { angularModule('ngLocale', []).provider('$locale', $LocaleProvider); } angularModule('ng', ['ngLocale'], ['$provide', function ngModule($provide) { // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it. $provide.provider({ $$sanitizeUri: $$SanitizeUriProvider }); $provide.provider('$compile', $CompileProvider). directive({ a: htmlAnchorDirective, input: inputDirective, textarea: inputDirective, form: formDirective, script: scriptDirective, select: selectDirective, style: styleDirective, option: optionDirective, ngBind: ngBindDirective, ngBindHtml: ngBindHtmlDirective, ngBindTemplate: ngBindTemplateDirective, ngClass: ngClassDirective, ngClassEven: ngClassEvenDirective, ngClassOdd: ngClassOddDirective, ngCloak: ngCloakDirective, ngController: ngControllerDirective, ngForm: ngFormDirective, ngHide: ngHideDirective, ngIf: ngIfDirective, ngInclude: ngIncludeDirective, ngInit: ngInitDirective, ngNonBindable: ngNonBindableDirective, ngPluralize: ngPluralizeDirective, ngRepeat: ngRepeatDirective, ngShow: ngShowDirective, ngStyle: ngStyleDirective, ngSwitch: ngSwitchDirective, ngSwitchWhen: ngSwitchWhenDirective, ngSwitchDefault: ngSwitchDefaultDirective, ngOptions: ngOptionsDirective, ngTransclude: ngTranscludeDirective, ngModel: ngModelDirective, ngList: ngListDirective, ngChange: ngChangeDirective, pattern: patternDirective, ngPattern: patternDirective, required: requiredDirective, ngRequired: requiredDirective, minlength: minlengthDirective, ngMinlength: minlengthDirective, maxlength: maxlengthDirective, ngMaxlength: maxlengthDirective, ngValue: ngValueDirective, ngModelOptions: ngModelOptionsDirective }). directive({ ngInclude: ngIncludeFillContentDirective }). directive(ngAttributeAliasDirectives). directive(ngEventDirectives); $provide.provider({ $anchorScroll: $AnchorScrollProvider, $animate: $AnimateProvider, $browser: $BrowserProvider, $cacheFactory: $CacheFactoryProvider, $controller: $ControllerProvider, $document: $DocumentProvider, $exceptionHandler: $ExceptionHandlerProvider, $filter: $FilterProvider, $interpolate: $InterpolateProvider, $interval: $IntervalProvider, $http: $HttpProvider, $httpBackend: $HttpBackendProvider, $location: $LocationProvider, $log: $LogProvider, $parse: $ParseProvider, $rootScope: $RootScopeProvider, $q: $QProvider, $sce: $SceProvider, $sceDelegate: $SceDelegateProvider, $sniffer: $SnifferProvider, $templateCache: $TemplateCacheProvider, $timeout: $TimeoutProvider, $window: $WindowProvider, $$rAF: $$RAFProvider, $$asyncCallback : $$AsyncCallbackProvider }); } ]); } /* global -JQLitePrototype, -addEventListenerFn, -removeEventListenerFn, -BOOLEAN_ATTR, -ALIASED_ATTR */ ////////////////////////////////// //JQLite ////////////////////////////////// /** * @ngdoc function * @name angular.element * @module ng * @kind function * * @description * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element. * * If jQuery is available, `angular.element` is an alias for the * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element` * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite." * * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most * commonly needed functionality with the goal of having a very small footprint.</div> * * To use jQuery, simply load it before `DOMContentLoaded` event fired. * * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or * jqLite; they are never raw DOM references.</div> * * ## Angular's jqLite * jqLite provides only the following jQuery methods: * * - [`addClass()`](http://api.jquery.com/addClass/) * - [`after()`](http://api.jquery.com/after/) * - [`append()`](http://api.jquery.com/append/) * - [`attr()`](http://api.jquery.com/attr/) * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData * - [`children()`](http://api.jquery.com/children/) - Does not support selectors * - [`clone()`](http://api.jquery.com/clone/) * - [`contents()`](http://api.jquery.com/contents/) * - [`css()`](http://api.jquery.com/css/) * - [`data()`](http://api.jquery.com/data/) * - [`empty()`](http://api.jquery.com/empty/) * - [`eq()`](http://api.jquery.com/eq/) * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name * - [`hasClass()`](http://api.jquery.com/hasClass/) * - [`html()`](http://api.jquery.com/html/) * - [`next()`](http://api.jquery.com/next/) - Does not support selectors * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors * - [`prepend()`](http://api.jquery.com/prepend/) * - [`prop()`](http://api.jquery.com/prop/) * - [`ready()`](http://api.jquery.com/ready/) * - [`remove()`](http://api.jquery.com/remove/) * - [`removeAttr()`](http://api.jquery.com/removeAttr/) * - [`removeClass()`](http://api.jquery.com/removeClass/) * - [`removeData()`](http://api.jquery.com/removeData/) * - [`replaceWith()`](http://api.jquery.com/replaceWith/) * - [`text()`](http://api.jquery.com/text/) * - [`toggleClass()`](http://api.jquery.com/toggleClass/) * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces * - [`val()`](http://api.jquery.com/val/) * - [`wrap()`](http://api.jquery.com/wrap/) * * ## jQuery/jqLite Extras * Angular also provides the following additional methods and events to both jQuery and jqLite: * * ### Events * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM * element before it is removed. * * ### Methods * - `controller(name)` - retrieves the controller of the current element or its parent. By default * retrieves controller associated with the `ngController` directive. If `name` is provided as * camelCase directive name, then the controller for this directive will be retrieved (e.g. * `'ngModel'`). * - `injector()` - retrieves the injector of the current element or its parent. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current * element or its parent. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the * current element. This getter should be used only on elements that contain a directive which starts a new isolate * scope. Calling `scope()` on this element always returns the original non-isolate scope. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top * parent element is reached. * * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery. * @returns {Object} jQuery object. */ JQLite.expando = 'ng339'; var jqCache = JQLite.cache = {}, jqId = 1, addEventListenerFn = (window.document.addEventListener ? function(element, type, fn) {element.addEventListener(type, fn, false);} : function(element, type, fn) {element.attachEvent('on' + type, fn);}), removeEventListenerFn = (window.document.removeEventListener ? function(element, type, fn) {element.removeEventListener(type, fn, false); } : function(element, type, fn) {element.detachEvent('on' + type, fn); }); /* * !!! This is an undocumented "private" function !!! */ var jqData = JQLite._data = function(node) { //jQuery always returns an object on cache miss return this.cache[node[this.expando]] || {}; }; function jqNextId() { return ++jqId; } var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g; var MOZ_HACK_REGEXP = /^moz([A-Z])/; var jqLiteMinErr = minErr('jqLite'); /** * Converts snake_case to camelCase. * Also there is special case for Moz prefix starting with upper case letter. * @param name Name to normalize */ function camelCase(name) { return name. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) { return offset ? letter.toUpperCase() : letter; }). replace(MOZ_HACK_REGEXP, 'Moz$1'); } var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/; var HTML_REGEXP = /<|&#?\w+;/; var TAG_NAME_REGEXP = /<([\w:]+)/; var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi; var wrapMap = { 'option': [1, '<select multiple="multiple">', '</select>'], 'thead': [1, '<table>', '</table>'], 'col': [2, '<table><colgroup>', '</colgroup></table>'], 'tr': [2, '<table><tbody>', '</tbody></table>'], 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'], '_default': [0, "", ""] }; wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function jqLiteIsTextNode(html) { return !HTML_REGEXP.test(html); } function jqLiteBuildFragment(html, context) { var elem, tmp, tag, wrap, fragment = context.createDocumentFragment(), nodes = [], i; if (jqLiteIsTextNode(html)) { // Convert non-html into a text node nodes.push(context.createTextNode(html)); } else { // Convert html into DOM nodes tmp = tmp || fragment.appendChild(context.createElement("div")); tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase(); wrap = wrapMap[tag] || wrapMap._default; tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2]; // Descend through wrappers to the right content i = wrap[0]; while (i--) { tmp = tmp.lastChild; } nodes = concat(nodes, tmp.childNodes); tmp = fragment.firstChild; tmp.textContent = ""; } // Remove wrapper from fragment fragment.textContent = ""; fragment.innerHTML = ""; // Clear inner HTML forEach(nodes, function(node) { fragment.appendChild(node); }); return fragment; } function jqLiteParseHTML(html, context) { context = context || document; var parsed; if ((parsed = SINGLE_TAG_REGEXP.exec(html))) { return [context.createElement(parsed[1])]; } if ((parsed = jqLiteBuildFragment(html, context))) { return parsed.childNodes; } return []; } ///////////////////////////////////////////// function JQLite(element) { if (element instanceof JQLite) { return element; } if (isString(element)) { element = trim(element); } if (!(this instanceof JQLite)) { if (isString(element) && element.charAt(0) != '<') { throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element'); } return new JQLite(element); } if (isString(element)) { jqLiteAddNodes(this, jqLiteParseHTML(element)); } else { jqLiteAddNodes(this, element); } } function jqLiteClone(element) { return element.cloneNode(true); } function jqLiteDealoc(element){ jqLiteRemoveData(element); var childElement; for ( var i = 0, children = element.children, l = (children && children.length) || 0; i < l; i++) { childElement = children[i]; jqLiteDealoc(childElement); } } function jqLiteOff(element, type, fn, unsupported) { if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument'); var events = jqLiteExpandoStore(element, 'events'), handle = jqLiteExpandoStore(element, 'handle'); if (!handle) return; //no listeners registered if (isUndefined(type)) { forEach(events, function(eventHandler, type) { removeEventListenerFn(element, type, eventHandler); delete events[type]; }); } else { forEach(type.split(' '), function(type) { if (isUndefined(fn)) { removeEventListenerFn(element, type, events[type]); delete events[type]; } else { arrayRemove(events[type] || [], fn); } }); } } function jqLiteRemoveData(element, name) { var expandoId = element.ng339, expandoStore = jqCache[expandoId]; if (expandoStore) { if (name) { delete jqCache[expandoId].data[name]; return; } if (expandoStore.handle) { expandoStore.events.$destroy && expandoStore.handle({}, '$destroy'); jqLiteOff(element); } delete jqCache[expandoId]; element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it } } function jqLiteExpandoStore(element, key, value) { var expandoId = element.ng339, expandoStore = jqCache[expandoId || -1]; if (isDefined(value)) { if (!expandoStore) { element.ng339 = expandoId = jqNextId(); expandoStore = jqCache[expandoId] = {}; } expandoStore[key] = value; } else { return expandoStore && expandoStore[key]; } } function jqLiteData(element, key, value) { var data = jqLiteExpandoStore(element, 'data'), isSetter = isDefined(value), keyDefined = !isSetter && isDefined(key), isSimpleGetter = keyDefined && !isObject(key); if (!data && !isSimpleGetter) { jqLiteExpandoStore(element, 'data', data = {}); } if (isSetter) { // set data only on Elements and Documents if (element.nodeType === 1 || element.nodeType === 9) { data[key] = value; } } else { if (keyDefined) { if (isSimpleGetter) { // don't create data in this case. return data && data[key]; } else { extend(data, key); } } else { return data; } } } function jqLiteHasClass(element, selector) { if (!element.getAttribute) return false; return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " "). indexOf( " " + selector + " " ) > -1); } function jqLiteRemoveClass(element, cssClasses) { if (cssClasses && element.setAttribute) { forEach(cssClasses.split(' '), function(cssClass) { element.setAttribute('class', trim( (" " + (element.getAttribute('class') || '') + " ") .replace(/[\n\t]/g, " ") .replace(" " + trim(cssClass) + " ", " ")) ); }); } } function jqLiteAddClass(element, cssClasses) { if (cssClasses && element.setAttribute) { var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ') .replace(/[\n\t]/g, " "); forEach(cssClasses.split(' '), function(cssClass) { cssClass = trim(cssClass); if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) { existingClasses += cssClass + ' '; } }); element.setAttribute('class', trim(existingClasses)); } } function jqLiteAddNodes(root, elements) { // THIS CODE IS VERY HOT. Don't make changes without benchmarking. if (elements) { // if a Node (the most common case) if (elements.nodeType) { root[root.length++] = elements; } else { var length = elements.length; // if an Array or NodeList and not a Window if (typeof length === 'number' && elements.window !== elements) { if (length) { push.apply(root, elements); } } else { root[root.length++] = elements; } } } } function jqLiteController(element, name) { return jqLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller'); } function jqLiteInheritedData(element, name, value) { element = jqLite(element); // if element is the document object work with the html element instead // this makes $(document).scope() possible if(element[0].nodeType == 9) { element = element.find('html'); } var names = isArray(name) ? name : [name]; while (element.length) { var node = element[0]; for (var i = 0, ii = names.length; i < ii; i++) { if ((value = element.data(names[i])) !== undefined) return value; } // If dealing with a document fragment node with a host element, and no parent, use the host // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM // to lookup parent controllers. element = jqLite(node.parentNode || (node.nodeType === 11 && node.host)); } } function jqLiteEmpty(element) { for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) { jqLiteDealoc(childNodes[i]); } while (element.firstChild) { element.removeChild(element.firstChild); } } ////////////////////////////////////////// // Functions which are declared directly. ////////////////////////////////////////// var JQLitePrototype = JQLite.prototype = { ready: function(fn) { var fired = false; function trigger() { if (fired) return; fired = true; fn(); } // check if document already is loaded if (document.readyState === 'complete'){ setTimeout(trigger); } else { this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9 // we can not use jqLite since we are not done loading and jQuery could be loaded later. // jshint -W064 JQLite(window).on('load', trigger); // fallback to window.onload for others // jshint +W064 } }, toString: function() { var value = []; forEach(this, function(e){ value.push('' + e);}); return '[' + value.join(', ') + ']'; }, eq: function(index) { return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]); }, length: 0, push: push, sort: [].sort, splice: [].splice }; ////////////////////////////////////////// // Functions iterating getter/setters. // these functions return self on setter and // value on get. ////////////////////////////////////////// var BOOLEAN_ATTR = {}; forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) { BOOLEAN_ATTR[lowercase(value)] = value; }); var BOOLEAN_ELEMENTS = {}; forEach('input,select,option,textarea,button,form,details'.split(','), function(value) { BOOLEAN_ELEMENTS[uppercase(value)] = true; }); var ALIASED_ATTR = { 'ngMinlength' : 'minlength', 'ngMaxlength' : 'maxlength', 'ngPattern' : 'pattern' }; function getBooleanAttrName(element, name) { // check dom last since we will most likely fail on name var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()]; // booleanAttr is here twice to minimize DOM access return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr; } function getAliasedAttrName(element, name) { var nodeName = element.nodeName; return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name]; } forEach({ data: jqLiteData, inheritedData: jqLiteInheritedData, scope: function(element) { // Can't use jqLiteData here directly so we stay compatible with jQuery! return jqLite(element).data('$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']); }, isolateScope: function(element) { // Can't use jqLiteData here directly so we stay compatible with jQuery! return jqLite(element).data('$isolateScope') || jqLite(element).data('$isolateScopeNoTemplate'); }, controller: jqLiteController, injector: function(element) { return jqLiteInheritedData(element, '$injector'); }, removeAttr: function(element,name) { element.removeAttribute(name); }, hasClass: jqLiteHasClass, css: function(element, name, value) { name = camelCase(name); if (isDefined(value)) { element.style[name] = value; } else { var val; if (msie <= 8) { // this is some IE specific weirdness that jQuery 1.6.4 does not sure why val = element.currentStyle && element.currentStyle[name]; if (val === '') val = 'auto'; } val = val || element.style[name]; if (msie <= 8) { // jquery weirdness :-/ val = (val === '') ? undefined : val; } return val; } }, attr: function(element, name, value){ var lowercasedName = lowercase(name); if (BOOLEAN_ATTR[lowercasedName]) { if (isDefined(value)) { if (!!value) { element[name] = true; element.setAttribute(name, lowercasedName); } else { element[name] = false; element.removeAttribute(lowercasedName); } } else { return (element[name] || (element.attributes.getNamedItem(name)|| noop).specified) ? lowercasedName : undefined; } } else if (isDefined(value)) { element.setAttribute(name, value); } else if (element.getAttribute) { // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code // some elements (e.g. Document) don't have get attribute, so return undefined var ret = element.getAttribute(name, 2); // normalize non-existing attributes to undefined (as jQuery) return ret === null ? undefined : ret; } }, prop: function(element, name, value) { if (isDefined(value)) { element[name] = value; } else { return element[name]; } }, text: (function() { getText.$dv = ''; return getText; function getText(element, value) { if (isUndefined(value)) { var nodeType = element.nodeType; return (nodeType === 1 || nodeType === 3) ? element.textContent : ''; } element.textContent = value; } })(), val: function(element, value) { if (isUndefined(value)) { if (nodeName_(element) === 'SELECT' && element.multiple) { var result = []; forEach(element.options, function (option) { if (option.selected) { result.push(option.value || option.text); } }); return result.length === 0 ? null : result; } return element.value; } element.value = value; }, html: function(element, value) { if (isUndefined(value)) { return element.innerHTML; } for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) { jqLiteDealoc(childNodes[i]); } element.innerHTML = value; }, empty: jqLiteEmpty }, function(fn, name){ /** * Properties: writes return selection, reads return first value */ JQLite.prototype[name] = function(arg1, arg2) { var i, key; var nodeCount = this.length; // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it // in a way that survives minification. // jqLiteEmpty takes no arguments but is a setter. if (fn !== jqLiteEmpty && (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) { if (isObject(arg1)) { // we are a write, but the object properties are the key/values for (i = 0; i < nodeCount; i++) { if (fn === jqLiteData) { // data() takes the whole object in jQuery fn(this[i], arg1); } else { for (key in arg1) { fn(this[i], key, arg1[key]); } } } // return self for chaining return this; } else { // we are a read, so read the first child. // TODO: do we still need this? var value = fn.$dv; // Only if we have $dv do we iterate over all, otherwise it is just the first element. var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount; for (var j = 0; j < jj; j++) { var nodeValue = fn(this[j], arg1, arg2); value = value ? value + nodeValue : nodeValue; } return value; } } else { // we are a write, so apply to all children for (i = 0; i < nodeCount; i++) { fn(this[i], arg1, arg2); } // return self for chaining return this; } }; }); function createEventHandler(element, events) { var eventHandler = function (event, type) { if (!event.preventDefault) { event.preventDefault = function() { event.returnValue = false; //ie }; } if (!event.stopPropagation) { event.stopPropagation = function() { event.cancelBubble = true; //ie }; } if (!event.target) { event.target = event.srcElement || document; } if (isUndefined(event.defaultPrevented)) { var prevent = event.preventDefault; event.preventDefault = function() { event.defaultPrevented = true; prevent.call(event); }; event.defaultPrevented = false; } event.isDefaultPrevented = function() { return event.defaultPrevented || event.returnValue === false; }; // Copy event handlers in case event handlers array is modified during execution. var eventHandlersCopy = shallowCopy(events[type || event.type] || []); forEach(eventHandlersCopy, function(fn) { fn.call(element, event); }); // Remove monkey-patched methods (IE), // as they would cause memory leaks in IE8. if (msie <= 8) { // IE7/8 does not allow to delete property on native object event.preventDefault = null; event.stopPropagation = null; event.isDefaultPrevented = null; } else { // It shouldn't affect normal browsers (native methods are defined on prototype). delete event.preventDefault; delete event.stopPropagation; delete event.isDefaultPrevented; } }; eventHandler.elem = element; return eventHandler; } ////////////////////////////////////////// // Functions iterating traversal. // These functions chain results into a single // selector. ////////////////////////////////////////// forEach({ removeData: jqLiteRemoveData, dealoc: jqLiteDealoc, on: function onFn(element, type, fn, unsupported){ if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters'); var events = jqLiteExpandoStore(element, 'events'), handle = jqLiteExpandoStore(element, 'handle'); if (!events) jqLiteExpandoStore(element, 'events', events = {}); if (!handle) jqLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events)); forEach(type.split(' '), function(type){ var eventFns = events[type]; if (!eventFns) { if (type == 'mouseenter' || type == 'mouseleave') { var contains = document.body.contains || document.body.compareDocumentPosition ? function( a, b ) { // jshint bitwise: false var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; events[type] = []; // Refer to jQuery's implementation of mouseenter & mouseleave // Read about mouseenter and mouseleave: // http://www.quirksmode.org/js/events_mouse.html#link8 var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"}; onFn(element, eventmap[type], function(event) { var target = this, related = event.relatedTarget; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !contains(target, related)) ){ handle(event, type); } }); } else { addEventListenerFn(element, type, handle); events[type] = []; } eventFns = events[type]; } eventFns.push(fn); }); }, off: jqLiteOff, one: function(element, type, fn) { element = jqLite(element); //add the listener twice so that when it is called //you can remove the original function and still be //able to call element.off(ev, fn) normally element.on(type, function onFn() { element.off(type, fn); element.off(type, onFn); }); element.on(type, fn); }, replaceWith: function(element, replaceNode) { var index, parent = element.parentNode; jqLiteDealoc(element); forEach(new JQLite(replaceNode), function(node){ if (index) { parent.insertBefore(node, index.nextSibling); } else { parent.replaceChild(node, element); } index = node; }); }, children: function(element) { var children = []; forEach(element.childNodes, function(element){ if (element.nodeType === 1) children.push(element); }); return children; }, contents: function(element) { return element.contentDocument || element.childNodes || []; }, append: function(element, node) { forEach(new JQLite(node), function(child){ if (element.nodeType === 1 || element.nodeType === 11) { element.appendChild(child); } }); }, prepend: function(element, node) { if (element.nodeType === 1) { var index = element.firstChild; forEach(new JQLite(node), function(child){ element.insertBefore(child, index); }); } }, wrap: function(element, wrapNode) { wrapNode = jqLite(wrapNode)[0]; var parent = element.parentNode; if (parent) { parent.replaceChild(wrapNode, element); } wrapNode.appendChild(element); }, remove: function(element) { jqLiteDealoc(element); var parent = element.parentNode; if (parent) parent.removeChild(element); }, after: function(element, newElement) { var index = element, parent = element.parentNode; forEach(new JQLite(newElement), function(node){ parent.insertBefore(node, index.nextSibling); index = node; }); }, addClass: jqLiteAddClass, removeClass: jqLiteRemoveClass, toggleClass: function(element, selector, condition) { if (selector) { forEach(selector.split(' '), function(className){ var classCondition = condition; if (isUndefined(classCondition)) { classCondition = !jqLiteHasClass(element, className); } (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className); }); } }, parent: function(element) { var parent = element.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, next: function(element) { if (element.nextElementSibling) { return element.nextElementSibling; } // IE8 doesn't have nextElementSibling var elm = element.nextSibling; while (elm != null && elm.nodeType !== 1) { elm = elm.nextSibling; } return elm; }, find: function(element, selector) { if (element.getElementsByTagName) { return element.getElementsByTagName(selector); } else { return []; } }, clone: jqLiteClone, triggerHandler: function(element, eventName, eventData) { var eventFns = (jqLiteExpandoStore(element, 'events') || {})[eventName]; eventData = eventData || []; var event = [{ preventDefault: noop, stopPropagation: noop }]; forEach(eventFns, function(fn) { fn.apply(element, event.concat(eventData)); }); } }, function(fn, name){ /** * chaining functions */ JQLite.prototype[name] = function(arg1, arg2, arg3) { var value; for(var i=0; i < this.length; i++) { if (isUndefined(value)) { value = fn(this[i], arg1, arg2, arg3); if (isDefined(value)) { // any function which returns a value needs to be wrapped value = jqLite(value); } } else { jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3)); } } return isDefined(value) ? value : this; }; // bind legacy bind/unbind to on/off JQLite.prototype.bind = JQLite.prototype.on; JQLite.prototype.unbind = JQLite.prototype.off; }); /** * Computes a hash of an 'obj'. * Hash of a: * string is string * number is number as string * object is either result of calling $$hashKey function on the object or uniquely generated id, * that is also assigned to the $$hashKey property of the object. * * @param obj * @returns {string} hash string such that the same input will have the same hash string. * The resulting string key is in 'type:hashKey' format. */ function hashKey(obj) { var objType = typeof obj, key; if (objType == 'object' && obj !== null) { if (typeof (key = obj.$$hashKey) == 'function') { // must invoke on object to keep the right this key = obj.$$hashKey(); } else if (key === undefined) { key = obj.$$hashKey = nextUid(); } } else { key = obj; } return objType + ':' + key; } /** * HashMap which can use objects as keys */ function HashMap(array){ forEach(array, this.put, this); } HashMap.prototype = { /** * Store key value pair * @param key key to store can be any type * @param value value to store can be any type */ put: function(key, value) { this[hashKey(key)] = value; }, /** * @param key * @returns {Object} the value for the key */ get: function(key) { return this[hashKey(key)]; }, /** * Remove the key/value pair * @param key */ remove: function(key) { var value = this[key = hashKey(key)]; delete this[key]; return value; } }; /** * @ngdoc function * @module ng * @name angular.injector * @kind function * * @description * Creates an injector function that can be used for retrieving services as well as for * dependency injection (see {@link guide/di dependency injection}). * * @param {Array.<string|Function>} modules A list of module functions or their aliases. See * {@link angular.module}. The `ng` module must be explicitly added. * @returns {function()} Injector function. See {@link auto.$injector $injector}. * * @example * Typical usage * ```js * // create an injector * var $injector = angular.injector(['ng']); * * // use the injector to kick off your application * // use the type inference to auto inject arguments, or use implicit injection * $injector.invoke(function($rootScope, $compile, $document){ * $compile($document)($rootScope); * $rootScope.$digest(); * }); * ``` * * Sometimes you want to get access to the injector of a currently running Angular app * from outside Angular. Perhaps, you want to inject and compile some markup after the * application has been bootstrapped. You can do this using the extra `injector()` added * to JQuery/jqLite elements. See {@link angular.element}. * * *This is fairly rare but could be the case if a third party library is injecting the * markup.* * * In the following example a new block of HTML containing a `ng-controller` * directive is added to the end of the document body by JQuery. We then compile and link * it into the current AngularJS scope. * * ```js * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>'); * $(document.body).append($div); * * angular.element(document).injector().invoke(function($compile) { * var scope = angular.element($div).scope(); * $compile($div)(scope); * }); * ``` */ /** * @ngdoc module * @name auto * @description * * Implicit module which gets automatically added to each {@link auto.$injector $injector}. */ var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; var $injectorMinErr = minErr('$injector'); function anonFn(fn) { // For anonymous functions, showing at the very least the function signature can help in // debugging. var fnText = fn.toString().replace(STRIP_COMMENTS, ''), args = fnText.match(FN_ARGS); if (args) { return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')'; } return 'fn'; } function annotate(fn, strictDi, name) { var $inject, fnText, argDecl, last; if (typeof fn == 'function') { if (!($inject = fn.$inject)) { $inject = []; if (fn.length) { if (strictDi) { if (!isString(name) || !name) { name = fn.name || anonFn(fn); } throw $injectorMinErr('strictdi', '{0} is not using explicit annotation and cannot be invoked in strict mode', name); } fnText = fn.toString().replace(STRIP_COMMENTS, ''); argDecl = fnText.match(FN_ARGS); forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){ arg.replace(FN_ARG, function(all, underscore, name){ $inject.push(name); }); }); } fn.$inject = $inject; } } else if (isArray(fn)) { last = fn.length - 1; assertArgFn(fn[last], 'fn'); $inject = fn.slice(0, last); } else { assertArgFn(fn, 'fn', true); } return $inject; } /////////////////////////////////////// /** * @ngdoc service * @name $injector * @kind function * * @description * * `$injector` is used to retrieve object instances as defined by * {@link auto.$provide provider}, instantiate types, invoke methods, * and load modules. * * The following always holds true: * * ```js * var $injector = angular.injector(); * expect($injector.get('$injector')).toBe($injector); * expect($injector.invoke(function($injector){ * return $injector; * }).toBe($injector); * ``` * * # Injection Function Annotation * * JavaScript does not have annotations, and annotations are needed for dependency injection. The * following are all valid ways of annotating function with injection arguments and are equivalent. * * ```js * // inferred (only works if code not minified/obfuscated) * $injector.invoke(function(serviceA){}); * * // annotated * function explicit(serviceA) {}; * explicit.$inject = ['serviceA']; * $injector.invoke(explicit); * * // inline * $injector.invoke(['serviceA', function(serviceA){}]); * ``` * * ## Inference * * In JavaScript calling `toString()` on a function returns the function definition. The definition * can then be parsed and the function arguments can be extracted. *NOTE:* This does not work with * minification, and obfuscation tools since these tools change the argument names. * * ## `$inject` Annotation * By adding an `$inject` property onto a function the injection parameters can be specified. * * ## Inline * As an array of injection names, where the last item in the array is the function to call. */ /** * @ngdoc method * @name $injector#get * * @description * Return an instance of the service. * * @param {string} name The name of the instance to retrieve. * @return {*} The instance. */ /** * @ngdoc method * @name $injector#invoke * * @description * Invoke the method and supply the method arguments from the `$injector`. * * @param {!Function} fn The function to invoke. Function parameters are injected according to the * {@link guide/di $inject Annotation} rules. * @param {Object=} self The `this` for the invoked method. * @param {Object=} locals Optional object. If preset then any argument names are read from this * object first, before the `$injector` is consulted. * @returns {*} the value returned by the invoked `fn` function. */ /** * @ngdoc method * @name $injector#has * * @description * Allows the user to query if the particular service exists. * * @param {string} Name of the service to query. * @returns {boolean} returns true if injector has given service. */ /** * @ngdoc method * @name $injector#instantiate * @description * Create a new instance of JS type. The method takes a constructor function, invokes the new * operator, and supplies all of the arguments to the constructor function as specified by the * constructor annotation. * * @param {Function} Type Annotated constructor function. * @param {Object=} locals Optional object. If preset then any argument names are read from this * object first, before the `$injector` is consulted. * @returns {Object} new instance of `Type`. */ /** * @ngdoc method * @name $injector#annotate * * @description * Returns an array of service names which the function is requesting for injection. This API is * used by the injector to determine which services need to be injected into the function when the * function is invoked. There are three ways in which the function can be annotated with the needed * dependencies. * * # Argument names * * The simplest form is to extract the dependencies from the arguments of the function. This is done * by converting the function into a string using `toString()` method and extracting the argument * names. * ```js * // Given * function MyController($scope, $route) { * // ... * } * * // Then * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * ``` * * This method does not work with code minification / obfuscation. For this reason the following * annotation strategies are supported. * * # The `$inject` property * * If a function has an `$inject` property and its value is an array of strings, then the strings * represent names of services to be injected into the function. * ```js * // Given * var MyController = function(obfuscatedScope, obfuscatedRoute) { * // ... * } * // Define function dependencies * MyController['$inject'] = ['$scope', '$route']; * * // Then * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * ``` * * # The array notation * * It is often desirable to inline Injected functions and that's when setting the `$inject` property * is very inconvenient. In these situations using the array notation to specify the dependencies in * a way that survives minification is a better choice: * * ```js * // We wish to write this (not minification / obfuscation safe) * injector.invoke(function($compile, $rootScope) { * // ... * }); * * // We are forced to write break inlining * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) { * // ... * }; * tmpFn.$inject = ['$compile', '$rootScope']; * injector.invoke(tmpFn); * * // To better support inline function the inline annotation is supported * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) { * // ... * }]); * * // Therefore * expect(injector.annotate( * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}]) * ).toEqual(['$compile', '$rootScope']); * ``` * * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to * be retrieved as described above. * * @returns {Array.<string>} The names of the services which the function requires. */ /** * @ngdoc object * @name $provide * * @description * * The {@link auto.$provide $provide} service has a number of methods for registering components * with the {@link auto.$injector $injector}. Many of these functions are also exposed on * {@link angular.Module}. * * An Angular **service** is a singleton object created by a **service factory**. These **service * factories** are functions which, in turn, are created by a **service provider**. * The **service providers** are constructor functions. When instantiated they must contain a * property called `$get`, which holds the **service factory** function. * * When you request a service, the {@link auto.$injector $injector} is responsible for finding the * correct **service provider**, instantiating it and then calling its `$get` **service factory** * function to get the instance of the **service**. * * Often services have no configuration options and there is no need to add methods to the service * provider. The provider will be no more than a constructor function with a `$get` property. For * these cases the {@link auto.$provide $provide} service has additional helper methods to register * services without specifying a provider. * * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the * {@link auto.$injector $injector} * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by * providers and services. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by * services, not providers. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`, * that will be wrapped in a **service provider** object, whose `$get` property will contain the * given factory function. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class` * that will be wrapped in a **service provider** object, whose `$get` property will instantiate * a new object using the given constructor function. * * See the individual methods for more information and examples. */ /** * @ngdoc method * @name $provide#provider * @description * * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions * are constructor functions, whose instances are responsible for "providing" a factory for a * service. * * Service provider names start with the name of the service they provide followed by `Provider`. * For example, the {@link ng.$log $log} service has a provider called * {@link ng.$logProvider $logProvider}. * * Service provider objects can have additional methods which allow configuration of the provider * and its service. Importantly, you can configure what kind of service is created by the `$get` * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a * method {@link ng.$logProvider#debugEnabled debugEnabled} * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the * console or not. * * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key. * @param {(Object|function())} provider If the provider is: * * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created. * - `Constructor`: a new instance of the provider will be created using * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`. * * @returns {Object} registered provider instance * @example * * The following example shows how to create a simple event tracking service and register it using * {@link auto.$provide#provider $provide.provider()}. * * ```js * // Define the eventTracker provider * function EventTrackerProvider() { * var trackingUrl = '/track'; * * // A provider method for configuring where the tracked events should been saved * this.setTrackingUrl = function(url) { * trackingUrl = url; * }; * * // The service factory function * this.$get = ['$http', function($http) { * var trackedEvents = {}; * return { * // Call this to track an event * event: function(event) { * var count = trackedEvents[event] || 0; * count += 1; * trackedEvents[event] = count; * return count; * }, * // Call this to save the tracked events to the trackingUrl * save: function() { * $http.post(trackingUrl, trackedEvents); * } * }; * }]; * } * * describe('eventTracker', function() { * var postSpy; * * beforeEach(module(function($provide) { * // Register the eventTracker provider * $provide.provider('eventTracker', EventTrackerProvider); * })); * * beforeEach(module(function(eventTrackerProvider) { * // Configure eventTracker provider * eventTrackerProvider.setTrackingUrl('/custom-track'); * })); * * it('tracks events', inject(function(eventTracker) { * expect(eventTracker.event('login')).toEqual(1); * expect(eventTracker.event('login')).toEqual(2); * })); * * it('saves to the tracking url', inject(function(eventTracker, $http) { * postSpy = spyOn($http, 'post'); * eventTracker.event('login'); * eventTracker.save(); * expect(postSpy).toHaveBeenCalled(); * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track'); * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track'); * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 }); * })); * }); * ``` */ /** * @ngdoc method * @name $provide#factory * @description * * Register a **service factory**, which will be called to return the service instance. * This is short for registering a service where its provider consists of only a `$get` property, * which is the given service factory function. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to * configure your service in a provider. * * @param {string} name The name of the instance. * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand * for `$provide.provider(name, {$get: $getFn})`. * @returns {Object} registered provider instance * * @example * Here is an example of registering a service * ```js * $provide.factory('ping', ['$http', function($http) { * return function ping() { * return $http.send('/ping'); * }; * }]); * ``` * You would then inject and use this service like this: * ```js * someModule.controller('Ctrl', ['ping', function(ping) { * ping(); * }]); * ``` */ /** * @ngdoc method * @name $provide#service * @description * * Register a **service constructor**, which will be invoked with `new` to create the service * instance. * This is short for registering a service where its provider's `$get` property is the service * constructor function that will be used to instantiate the service instance. * * You should use {@link auto.$provide#service $provide.service(class)} if you define your service * as a type/class. * * @param {string} name The name of the instance. * @param {Function} constructor A class (constructor function) that will be instantiated. * @returns {Object} registered provider instance * * @example * Here is an example of registering a service using * {@link auto.$provide#service $provide.service(class)}. * ```js * var Ping = function($http) { * this.$http = $http; * }; * * Ping.$inject = ['$http']; * * Ping.prototype.send = function() { * return this.$http.get('/ping'); * }; * $provide.service('ping', Ping); * ``` * You would then inject and use this service like this: * ```js * someModule.controller('Ctrl', ['ping', function(ping) { * ping.send(); * }]); * ``` */ /** * @ngdoc method * @name $provide#value * @description * * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a * number, an array, an object or a function. This is short for registering a service where its * provider's `$get` property is a factory function that takes no arguments and returns the **value * service**. * * Value services are similar to constant services, except that they cannot be injected into a * module configuration function (see {@link angular.Module#config}) but they can be overridden by * an Angular * {@link auto.$provide#decorator decorator}. * * @param {string} name The name of the instance. * @param {*} value The value. * @returns {Object} registered provider instance * * @example * Here are some examples of creating value services. * ```js * $provide.value('ADMIN_USER', 'admin'); * * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 }); * * $provide.value('halfOf', function(value) { * return value / 2; * }); * ``` */ /** * @ngdoc method * @name $provide#constant * @description * * Register a **constant service**, such as a string, a number, an array, an object or a function, * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be * injected into a module configuration function (see {@link angular.Module#config}) and it cannot * be overridden by an Angular {@link auto.$provide#decorator decorator}. * * @param {string} name The name of the constant. * @param {*} value The constant value. * @returns {Object} registered instance * * @example * Here a some examples of creating constants: * ```js * $provide.constant('SHARD_HEIGHT', 306); * * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']); * * $provide.constant('double', function(value) { * return value * 2; * }); * ``` */ /** * @ngdoc method * @name $provide#decorator * @description * * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator * intercepts the creation of a service, allowing it to override or modify the behaviour of the * service. The object returned by the decorator may be the original service, or a new service * object which replaces or wraps and delegates to the original service. * * @param {string} name The name of the service to decorate. * @param {function()} decorator This function will be invoked when the service needs to be * instantiated and should return the decorated service instance. The function is called using * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable. * Local injection arguments: * * * `$delegate` - The original service instance, which can be monkey patched, configured, * decorated or delegated to. * * @example * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting * calls to {@link ng.$log#error $log.warn()}. * ```js * $provide.decorator('$log', ['$delegate', function($delegate) { * $delegate.warn = $delegate.error; * return $delegate; * }]); * ``` */ function createInjector(modulesToLoad, strictDi) { strictDi = (strictDi === true); var INSTANTIATING = {}, providerSuffix = 'Provider', path = [], loadedModules = new HashMap(), providerCache = { $provide: { provider: supportObject(provider), factory: supportObject(factory), service: supportObject(service), value: supportObject(value), constant: supportObject(constant), decorator: decorator } }, providerInjector = (providerCache.$injector = createInternalInjector(providerCache, function() { throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- ')); }, strictDi)), instanceCache = {}, instanceInjector = (instanceCache.$injector = createInternalInjector(instanceCache, function(servicename) { var provider = providerInjector.get(servicename + providerSuffix); return instanceInjector.invoke(provider.$get, provider, undefined, servicename); }, strictDi)); forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); }); return instanceInjector; //////////////////////////////////// // $provider //////////////////////////////////// function supportObject(delegate) { return function(key, value) { if (isObject(key)) { forEach(key, reverseParams(delegate)); } else { return delegate(key, value); } }; } function provider(name, provider_) { assertNotHasOwnProperty(name, 'service'); if (isFunction(provider_) || isArray(provider_)) { provider_ = providerInjector.instantiate(provider_); } if (!provider_.$get) { throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name); } return providerCache[name + providerSuffix] = provider_; } function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); } function service(name, constructor) { return factory(name, ['$injector', function($injector) { return $injector.instantiate(constructor); }]); } function value(name, val) { return factory(name, valueFn(val)); } function constant(name, value) { assertNotHasOwnProperty(name, 'constant'); providerCache[name] = value; instanceCache[name] = value; } function decorator(serviceName, decorFn) { var origProvider = providerInjector.get(serviceName + providerSuffix), orig$get = origProvider.$get; origProvider.$get = function() { var origInstance = instanceInjector.invoke(orig$get, origProvider); return instanceInjector.invoke(decorFn, null, {$delegate: origInstance}); }; } //////////////////////////////////// // Module Loading //////////////////////////////////// function loadModules(modulesToLoad){ var runBlocks = [], moduleFn, invokeQueue; forEach(modulesToLoad, function(module) { if (loadedModules.get(module)) return; loadedModules.put(module, true); function runInvokeQueue(queue) { var i, ii; for(i = 0, ii = queue.length; i < ii; i++) { var invokeArgs = queue[i], provider = providerInjector.get(invokeArgs[0]); provider[invokeArgs[1]].apply(provider, invokeArgs[2]); } } try { if (isString(module)) { moduleFn = angularModule(module); runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); runInvokeQueue(moduleFn._invokeQueue); runInvokeQueue(moduleFn._configBlocks); } else if (isFunction(module)) { runBlocks.push(providerInjector.invoke(module)); } else if (isArray(module)) { runBlocks.push(providerInjector.invoke(module)); } else { assertArgFn(module, 'module'); } } catch (e) { if (isArray(module)) { module = module[module.length - 1]; } if (e.message && e.stack && e.stack.indexOf(e.message) == -1) { // Safari & FF's stack traces don't contain error.message content // unlike those of Chrome and IE // So if stack doesn't contain message, we create a new string that contains both. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here. /* jshint -W022 */ e = e.message + '\n' + e.stack; } throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}", module, e.stack || e.message || e); } }); return runBlocks; } //////////////////////////////////// // internal Injector //////////////////////////////////// function createInternalInjector(cache, factory) { function getService(serviceName) { if (cache.hasOwnProperty(serviceName)) { if (cache[serviceName] === INSTANTIATING) { throw $injectorMinErr('cdep', 'Circular dependency found: {0}', serviceName + ' <- ' + path.join(' <- ')); } return cache[serviceName]; } else { try { path.unshift(serviceName); cache[serviceName] = INSTANTIATING; return cache[serviceName] = factory(serviceName); } catch (err) { if (cache[serviceName] === INSTANTIATING) { delete cache[serviceName]; } throw err; } finally { path.shift(); } } } function invoke(fn, self, locals, serviceName){ if (typeof locals === 'string') { serviceName = locals; locals = null; } var args = [], $inject = annotate(fn, strictDi, serviceName), length, i, key; for(i = 0, length = $inject.length; i < length; i++) { key = $inject[i]; if (typeof key !== 'string') { throw $injectorMinErr('itkn', 'Incorrect injection token! Expected service name as string, got {0}', key); } args.push( locals && locals.hasOwnProperty(key) ? locals[key] : getService(key) ); } if (!fn.$inject) { // this means that we must be an array. fn = fn[length]; } // http://jsperf.com/angularjs-invoke-apply-vs-switch // #5388 return fn.apply(self, args); } function instantiate(Type, locals, serviceName) { var Constructor = function() {}, instance, returnedValue; // Check if Type is annotated and use just the given function at n-1 as parameter // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]); Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype; instance = new Constructor(); returnedValue = invoke(Type, instance, locals, serviceName); return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance; } return { invoke: invoke, instantiate: instantiate, get: getService, annotate: annotate, has: function(name) { return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name); } }; } } createInjector.$$annotate = annotate; /** * @ngdoc service * @name $anchorScroll * @kind function * @requires $window * @requires $location * @requires $rootScope * * @description * When called, it checks current value of `$location.hash()` and scrolls to the related element, * according to rules specified in * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document). * * It also watches the `$location.hash()` and scrolls whenever it changes to match any anchor. * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`. * * @example <example> <file name="index.html"> <div id="scrollArea" ng-controller="ScrollCtrl"> <a ng-click="gotoBottom()">Go to bottom</a> <a id="bottom"></a> You're at the bottom! </div> </file> <file name="script.js"> function ScrollCtrl($scope, $location, $anchorScroll) { $scope.gotoBottom = function (){ // set the location.hash to the id of // the element you wish to scroll to. $location.hash('bottom'); // call $anchorScroll() $anchorScroll(); }; } </file> <file name="style.css"> #scrollArea { height: 350px; overflow: auto; } #bottom { display: block; margin-top: 2000px; } </file> </example> */ function $AnchorScrollProvider() { var autoScrollingEnabled = true; this.disableAutoScrolling = function() { autoScrollingEnabled = false; }; this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) { var document = $window.document; // helper function to get first anchor from a NodeList // can't use filter.filter, as it accepts only instances of Array // and IE can't convert NodeList to an array using [].slice // TODO(vojta): use filter if we change it to accept lists as well function getFirstAnchor(list) { var result = null; forEach(list, function(element) { if (!result && lowercase(element.nodeName) === 'a') result = element; }); return result; } function scroll() { var hash = $location.hash(), elm; // empty hash, scroll to the top of the page if (!hash) $window.scrollTo(0, 0); // element with given id else if ((elm = document.getElementById(hash))) elm.scrollIntoView(); // first anchor with given name :-D else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView(); // no element and hash == 'top', scroll to the top of the page else if (hash === 'top') $window.scrollTo(0, 0); } // does not scroll when user clicks on anchor link that is currently on // (no url change, no $location.hash() change), browser native does scroll if (autoScrollingEnabled) { $rootScope.$watch(function autoScrollWatch() {return $location.hash();}, function autoScrollWatchAction() { $rootScope.$evalAsync(scroll); }); } return scroll; }]; } var $animateMinErr = minErr('$animate'); /** * @ngdoc provider * @name $animateProvider * * @description * Default implementation of $animate that doesn't perform any animations, instead just * synchronously performs DOM * updates and calls done() callbacks. * * In order to enable animations the ngAnimate module has to be loaded. * * To see the functional implementation check out src/ngAnimate/animate.js */ var $AnimateProvider = ['$provide', function($provide) { this.$$selectors = {}; /** * @ngdoc method * @name $animateProvider#register * * @description * Registers a new injectable animation factory function. The factory function produces the * animation object which contains callback functions for each event that is expected to be * animated. * * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction` * must be called once the element animation is complete. If a function is returned then the * animation service will use this function to cancel the animation whenever a cancel event is * triggered. * * * ```js * return { * eventFn : function(element, done) { * //code to run the animation * //once complete, then run done() * return function cancellationFunction() { * //code to cancel the animation * } * } * } * ``` * * @param {string} name The name of the animation. * @param {Function} factory The factory function that will be executed to return the animation * object. */ this.register = function(name, factory) { var key = name + '-animation'; if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name); this.$$selectors[name.substr(1)] = key; $provide.factory(key, factory); }; /** * @ngdoc method * @name $animateProvider#classNameFilter * * @description * Sets and/or returns the CSS class regular expression that is checked when performing * an animation. Upon bootstrap the classNameFilter value is not set at all and will * therefore enable $animate to attempt to perform an animation on any element. * When setting the classNameFilter value, animations will only be performed on elements * that successfully match the filter expression. This in turn can boost performance * for low-powered devices as well as applications containing a lot of structural operations. * @param {RegExp=} expression The className expression which will be checked against all animations * @return {RegExp} The current CSS className expression value. If null then there is no expression value */ this.classNameFilter = function(expression) { if(arguments.length === 1) { this.$$classNameFilter = (expression instanceof RegExp) ? expression : null; } return this.$$classNameFilter; }; this.$get = ['$timeout', '$$asyncCallback', function($timeout, $$asyncCallback) { function async(fn) { fn && $$asyncCallback(fn); } /** * * @ngdoc service * @name $animate * @description The $animate service provides rudimentary DOM manipulation functions to * insert, remove and move elements within the DOM, as well as adding and removing classes. * This service is the core service used by the ngAnimate $animator service which provides * high-level animation hooks for CSS and JavaScript. * * $animate is available in the AngularJS core, however, the ngAnimate module must be included * to enable full out animation support. Otherwise, $animate will only perform simple DOM * manipulation operations. * * To learn more about enabling animation support, click here to visit the {@link ngAnimate * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service * page}. */ return { /** * * @ngdoc method * @name $animate#enter * @kind function * @description Inserts the element into the DOM either after the `after` element or * as the first child within the `parent` element. Once complete, the done() callback * will be fired (if provided). * @param {DOMElement} element the element which will be inserted into the DOM * @param {DOMElement} parent the parent element which will append the element as * a child (if the after element is not present) * @param {DOMElement} after the sibling element which will append the element * after itself * @param {Function=} done callback function that will be called after the element has been * inserted into the DOM */ enter : function(element, parent, after, done) { after ? after.after(element) : parent.prepend(element); async(done); }, /** * * @ngdoc method * @name $animate#leave * @kind function * @description Removes the element from the DOM. Once complete, the done() callback will be * fired (if provided). * @param {DOMElement} element the element which will be removed from the DOM * @param {Function=} done callback function that will be called after the element has been * removed from the DOM */ leave : function(element, done) { element.remove(); async(done); }, /** * * @ngdoc method * @name $animate#move * @kind function * @description Moves the position of the provided element within the DOM to be placed * either after the `after` element or inside of the `parent` element. Once complete, the * done() callback will be fired (if provided). * * @param {DOMElement} element the element which will be moved around within the * DOM * @param {DOMElement} parent the parent element where the element will be * inserted into (if the after element is not present) * @param {DOMElement} after the sibling element where the element will be * positioned next to * @param {Function=} done the callback function (if provided) that will be fired after the * element has been moved to its new position */ move : function(element, parent, after, done) { // Do not remove element before insert. Removing will cause data associated with the // element to be dropped. Insert will implicitly do the remove. this.enter(element, parent, after, done); }, /** * * @ngdoc method * @name $animate#addClass * @kind function * @description Adds the provided className CSS class value to the provided element. Once * complete, the done() callback will be fired (if provided). * @param {DOMElement} element the element which will have the className value * added to it * @param {string} className the CSS class which will be added to the element * @param {Function=} done the callback function (if provided) that will be fired after the * className value has been added to the element */ addClass : function(element, className, done) { className = isString(className) ? className : isArray(className) ? className.join(' ') : ''; forEach(element, function (element) { jqLiteAddClass(element, className); }); async(done); }, /** * * @ngdoc method * @name $animate#removeClass * @kind function * @description Removes the provided className CSS class value from the provided element. * Once complete, the done() callback will be fired (if provided). * @param {DOMElement} element the element which will have the className value * removed from it * @param {string} className the CSS class which will be removed from the element * @param {Function=} done the callback function (if provided) that will be fired after the * className value has been removed from the element */ removeClass : function(element, className, done) { className = isString(className) ? className : isArray(className) ? className.join(' ') : ''; forEach(element, function (element) { jqLiteRemoveClass(element, className); }); async(done); }, /** * * @ngdoc method * @name $animate#setClass * @kind function * @description Adds and/or removes the given CSS classes to and from the element. * Once complete, the done() callback will be fired (if provided). * @param {DOMElement} element the element which will have its CSS classes changed * removed from it * @param {string} add the CSS classes which will be added to the element * @param {string} remove the CSS class which will be removed from the element * @param {Function=} done the callback function (if provided) that will be fired after the * CSS classes have been set on the element */ setClass : function(element, add, remove, done) { forEach(element, function (element) { jqLiteAddClass(element, add); jqLiteRemoveClass(element, remove); }); async(done); }, enabled : noop }; }]; }]; function $$AsyncCallbackProvider(){ this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) { return $$rAF.supported ? function(fn) { return $$rAF(fn); } : function(fn) { return $timeout(fn, 0, false); }; }]; } /** * ! This is a private undocumented service ! * * @name $browser * @requires $log * @description * This object has two goals: * * - hide all the global state in the browser caused by the window object * - abstract away all the browser specific features and inconsistencies * * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser` * service, which can be used for convenient testing of the application without the interaction with * the real browser apis. */ /** * @param {object} window The global window object. * @param {object} document jQuery wrapped document. * @param {function()} XHR XMLHttpRequest constructor. * @param {object} $log console.log or an object with the same interface. * @param {object} $sniffer $sniffer service */ function Browser(window, document, $log, $sniffer) { var self = this, rawDocument = document[0], location = window.location, history = window.history, setTimeout = window.setTimeout, clearTimeout = window.clearTimeout, pendingDeferIds = {}; self.isMock = false; var outstandingRequestCount = 0; var outstandingRequestCallbacks = []; // TODO(vojta): remove this temporary api self.$$completeOutstandingRequest = completeOutstandingRequest; self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; }; /** * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks` * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. */ function completeOutstandingRequest(fn) { try { fn.apply(null, sliceArgs(arguments, 1)); } finally { outstandingRequestCount--; if (outstandingRequestCount === 0) { while(outstandingRequestCallbacks.length) { try { outstandingRequestCallbacks.pop()(); } catch (e) { $log.error(e); } } } } } /** * @private * Note: this method is used only by scenario runner * TODO(vojta): prefix this method with $$ ? * @param {function()} callback Function that will be called when no outstanding request */ self.notifyWhenNoOutstandingRequests = function(callback) { // force browser to execute all pollFns - this is needed so that cookies and other pollers fire // at some deterministic time in respect to the test runner's actions. Leaving things up to the // regular poller would result in flaky tests. forEach(pollFns, function(pollFn){ pollFn(); }); if (outstandingRequestCount === 0) { callback(); } else { outstandingRequestCallbacks.push(callback); } }; ////////////////////////////////////////////////////////////// // Poll Watcher API ////////////////////////////////////////////////////////////// var pollFns = [], pollTimeout; /** * @name $browser#addPollFn * * @param {function()} fn Poll function to add * * @description * Adds a function to the list of functions that poller periodically executes, * and starts polling if not started yet. * * @returns {function()} the added function */ self.addPollFn = function(fn) { if (isUndefined(pollTimeout)) startPoller(100, setTimeout); pollFns.push(fn); return fn; }; /** * @param {number} interval How often should browser call poll functions (ms) * @param {function()} setTimeout Reference to a real or fake `setTimeout` function. * * @description * Configures the poller to run in the specified intervals, using the specified * setTimeout fn and kicks it off. */ function startPoller(interval, setTimeout) { (function check() { forEach(pollFns, function(pollFn){ pollFn(); }); pollTimeout = setTimeout(check, interval); })(); } ////////////////////////////////////////////////////////////// // URL API ////////////////////////////////////////////////////////////// var lastBrowserUrl = location.href, baseElement = document.find('base'), newLocation = null; /** * @name $browser#url * * @description * GETTER: * Without any argument, this method just returns current value of location.href. * * SETTER: * With at least one argument, this method sets url to new value. * If html5 history api supported, pushState/replaceState is used, otherwise * location.href/location.replace is used. * Returns its own instance to allow chaining * * NOTE: this api is intended for use only by the $location service. Please use the * {@link ng.$location $location service} to change url. * * @param {string} url New url (when used as setter) * @param {boolean=} replace Should new url replace current history record ? */ self.url = function(url, replace) { // Android Browser BFCache causes location, history reference to become stale. if (location !== window.location) location = window.location; if (history !== window.history) history = window.history; // setter if (url) { if (lastBrowserUrl == url) return; lastBrowserUrl = url; if ($sniffer.history) { if (replace) history.replaceState(null, '', url); else { history.pushState(null, '', url); // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462 baseElement.attr('href', baseElement.attr('href')); } } else { newLocation = url; if (replace) { location.replace(url); } else { location.href = url; } } return self; // getter } else { // - newLocation is a workaround for an IE7-9 issue with location.replace and location.href // methods not updating location.href synchronously. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 return newLocation || location.href.replace(/%27/g,"'"); } }; var urlChangeListeners = [], urlChangeInit = false; function fireUrlChange() { newLocation = null; if (lastBrowserUrl == self.url()) return; lastBrowserUrl = self.url(); forEach(urlChangeListeners, function(listener) { listener(self.url()); }); } /** * @name $browser#onUrlChange * * @description * Register callback function that will be called, when url changes. * * It's only called when the url is changed from outside of angular: * - user types different url into address bar * - user clicks on history (forward/back) button * - user clicks on a link * * It's not called when url is changed by $browser.url() method * * The listener gets called with new url as parameter. * * NOTE: this api is intended for use only by the $location service. Please use the * {@link ng.$location $location service} to monitor url changes in angular apps. * * @param {function(string)} listener Listener function to be called when url changes. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous. */ self.onUrlChange = function(callback) { // TODO(vojta): refactor to use node's syntax for events if (!urlChangeInit) { // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera) // don't fire popstate when user change the address bar and don't fire hashchange when url // changed by push/replaceState // html5 history api - popstate event if ($sniffer.history) jqLite(window).on('popstate', fireUrlChange); // hashchange event if ($sniffer.hashchange) jqLite(window).on('hashchange', fireUrlChange); // polling else self.addPollFn(fireUrlChange); urlChangeInit = true; } urlChangeListeners.push(callback); return callback; }; ////////////////////////////////////////////////////////////// // Misc API ////////////////////////////////////////////////////////////// /** * @name $browser#baseHref * * @description * Returns current <base href> * (always relative - without domain) * * @returns {string} The current base href */ self.baseHref = function() { var href = baseElement.attr('href'); return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : ''; }; ////////////////////////////////////////////////////////////// // Cookies API ////////////////////////////////////////////////////////////// var lastCookies = {}; var lastCookieString = ''; var cookiePath = self.baseHref(); /** * @name $browser#cookies * * @param {string=} name Cookie name * @param {string=} value Cookie value * * @description * The cookies method provides a 'private' low level access to browser cookies. * It is not meant to be used directly, use the $cookie service instead. * * The return values vary depending on the arguments that the method was called with as follows: * * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify * it * - cookies(name, value) -> set name to value, if value is undefined delete the cookie * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that * way) * * @returns {Object} Hash of all cookies (if called without any parameter) */ self.cookies = function(name, value) { /* global escape: false, unescape: false */ var cookieLength, cookieArray, cookie, i, index; if (name) { if (value === undefined) { rawDocument.cookie = escape(name) + "=;path=" + cookiePath + ";expires=Thu, 01 Jan 1970 00:00:00 GMT"; } else { if (isString(value)) { cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) + ';path=' + cookiePath).length + 1; // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum: // - 300 cookies // - 20 cookies per unique domain // - 4096 bytes per cookie if (cookieLength > 4096) { $log.warn("Cookie '"+ name + "' possibly not set or overflowed because it was too large ("+ cookieLength + " > 4096 bytes)!"); } } } } else { if (rawDocument.cookie !== lastCookieString) { lastCookieString = rawDocument.cookie; cookieArray = lastCookieString.split("; "); lastCookies = {}; for (i = 0; i < cookieArray.length; i++) { cookie = cookieArray[i]; index = cookie.indexOf('='); if (index > 0) { //ignore nameless cookies name = unescape(cookie.substring(0, index)); // the first value that is seen for a cookie is the most // specific one. values for the same cookie name that // follow are for less specific paths. if (lastCookies[name] === undefined) { lastCookies[name] = unescape(cookie.substring(index + 1)); } } } } return lastCookies; } }; /** * @name $browser#defer * @param {function()} fn A function, who's execution should be deferred. * @param {number=} [delay=0] of milliseconds to defer the function execution. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`. * * @description * Executes a fn asynchronously via `setTimeout(fn, delay)`. * * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed * via `$browser.defer.flush()`. * */ self.defer = function(fn, delay) { var timeoutId; outstandingRequestCount++; timeoutId = setTimeout(function() { delete pendingDeferIds[timeoutId]; completeOutstandingRequest(fn); }, delay || 0); pendingDeferIds[timeoutId] = true; return timeoutId; }; /** * @name $browser#defer.cancel * * @description * Cancels a deferred task identified with `deferId`. * * @param {*} deferId Token returned by the `$browser.defer` function. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully * canceled. */ self.defer.cancel = function(deferId) { if (pendingDeferIds[deferId]) { delete pendingDeferIds[deferId]; clearTimeout(deferId); completeOutstandingRequest(noop); return true; } return false; }; } function $BrowserProvider(){ this.$get = ['$window', '$log', '$sniffer', '$document', function( $window, $log, $sniffer, $document){ return new Browser($window, $document, $log, $sniffer); }]; } /** * @ngdoc service * @name $cacheFactory * * @description * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to * them. * * ```js * * var cache = $cacheFactory('cacheId'); * expect($cacheFactory.get('cacheId')).toBe(cache); * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined(); * * cache.put("key", "value"); * cache.put("another key", "another value"); * * // We've specified no options on creation * expect(cache.info()).toEqual({id: 'cacheId', size: 2}); * * ``` * * * @param {string} cacheId Name or id of the newly created cache. * @param {object=} options Options object that specifies the cache behavior. Properties: * * - `{number=}` `capacity` — turns the cache into LRU cache. * * @returns {object} Newly created cache object with the following set of methods: * * - `{object}` `info()` — Returns id, size, and options of cache. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns * it. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache. * - `{void}` `removeAll()` — Removes all cached values. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory. * * @example <example module="cacheExampleApp"> <file name="index.html"> <div ng-controller="CacheController"> <input ng-model="newCacheKey" placeholder="Key"> <input ng-model="newCacheValue" placeholder="Value"> <button ng-click="put(newCacheKey, newCacheValue)">Cache</button> <p ng-if="keys.length">Cached Values</p> <div ng-repeat="key in keys"> <span ng-bind="key"></span> <span>: </span> <b ng-bind="cache.get(key)"></b> </div> <p>Cache Info</p> <div ng-repeat="(key, value) in cache.info()"> <span ng-bind="key"></span> <span>: </span> <b ng-bind="value"></b> </div> </div> </file> <file name="script.js"> angular.module('cacheExampleApp', []). controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) { $scope.keys = []; $scope.cache = $cacheFactory('cacheId'); $scope.put = function(key, value) { $scope.cache.put(key, value); $scope.keys.push(key); }; }]); </file> <file name="style.css"> p { margin: 10px 0 3px; } </file> </example> */ function $CacheFactoryProvider() { this.$get = function() { var caches = {}; function cacheFactory(cacheId, options) { if (cacheId in caches) { throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId); } var size = 0, stats = extend({}, options, {id: cacheId}), data = {}, capacity = (options && options.capacity) || Number.MAX_VALUE, lruHash = {}, freshEnd = null, staleEnd = null; /** * @ngdoc type * @name $cacheFactory.Cache * * @description * A cache object used to store and retrieve data, primarily used by * {@link $http $http} and the {@link ng.directive:script script} directive to cache * templates and other data. * * ```js * angular.module('superCache') * .factory('superCache', ['$cacheFactory', function($cacheFactory) { * return $cacheFactory('super-cache'); * }]); * ``` * * Example test: * * ```js * it('should behave like a cache', inject(function(superCache) { * superCache.put('key', 'value'); * superCache.put('another key', 'another value'); * * expect(superCache.info()).toEqual({ * id: 'super-cache', * size: 2 * }); * * superCache.remove('another key'); * expect(superCache.get('another key')).toBeUndefined(); * * superCache.removeAll(); * expect(superCache.info()).toEqual({ * id: 'super-cache', * size: 0 * }); * })); * ``` */ return caches[cacheId] = { /** * @ngdoc method * @name $cacheFactory.Cache#put * @kind function * * @description * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be * retrieved later, and incrementing the size of the cache if the key was not already * present in the cache. If behaving like an LRU cache, it will also remove stale * entries from the set. * * It will not insert undefined values into the cache. * * @param {string} key the key under which the cached data is stored. * @param {*} value the value to store alongside the key. If it is undefined, the key * will not be stored. * @returns {*} the value stored. */ put: function(key, value) { if (capacity < Number.MAX_VALUE) { var lruEntry = lruHash[key] || (lruHash[key] = {key: key}); refresh(lruEntry); } if (isUndefined(value)) return; if (!(key in data)) size++; data[key] = value; if (size > capacity) { this.remove(staleEnd.key); } return value; }, /** * @ngdoc method * @name $cacheFactory.Cache#get * @kind function * * @description * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object. * * @param {string} key the key of the data to be retrieved * @returns {*} the value stored. */ get: function(key) { if (capacity < Number.MAX_VALUE) { var lruEntry = lruHash[key]; if (!lruEntry) return; refresh(lruEntry); } return data[key]; }, /** * @ngdoc method * @name $cacheFactory.Cache#remove * @kind function * * @description * Removes an entry from the {@link $cacheFactory.Cache Cache} object. * * @param {string} key the key of the entry to be removed */ remove: function(key) { if (capacity < Number.MAX_VALUE) { var lruEntry = lruHash[key]; if (!lruEntry) return; if (lruEntry == freshEnd) freshEnd = lruEntry.p; if (lruEntry == staleEnd) staleEnd = lruEntry.n; link(lruEntry.n,lruEntry.p); delete lruHash[key]; } delete data[key]; size--; }, /** * @ngdoc method * @name $cacheFactory.Cache#removeAll * @kind function * * @description * Clears the cache object of any entries. */ removeAll: function() { data = {}; size = 0; lruHash = {}; freshEnd = staleEnd = null; }, /** * @ngdoc method * @name $cacheFactory.Cache#destroy * @kind function * * @description * Destroys the {@link $cacheFactory.Cache Cache} object entirely, * removing it from the {@link $cacheFactory $cacheFactory} set. */ destroy: function() { data = null; stats = null; lruHash = null; delete caches[cacheId]; }, /** * @ngdoc method * @name $cacheFactory.Cache#info * @kind function * * @description * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}. * * @returns {object} an object with the following properties: * <ul> * <li>**id**: the id of the cache instance</li> * <li>**size**: the number of entries kept in the cache instance</li> * <li>**...**: any additional properties from the options object when creating the * cache.</li> * </ul> */ info: function() { return extend({}, stats, {size: size}); } }; /** * makes the `entry` the freshEnd of the LRU linked list */ function refresh(entry) { if (entry != freshEnd) { if (!staleEnd) { staleEnd = entry; } else if (staleEnd == entry) { staleEnd = entry.n; } link(entry.n, entry.p); link(entry, freshEnd); freshEnd = entry; freshEnd.n = null; } } /** * bidirectionally links two entries of the LRU linked list */ function link(nextEntry, prevEntry) { if (nextEntry != prevEntry) { if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify } } } /** * @ngdoc method * @name $cacheFactory#info * * @description * Get information about all the caches that have been created * * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info` */ cacheFactory.info = function() { var info = {}; forEach(caches, function(cache, cacheId) { info[cacheId] = cache.info(); }); return info; }; /** * @ngdoc method * @name $cacheFactory#get * * @description * Get access to a cache object by the `cacheId` used when it was created. * * @param {string} cacheId Name or id of a cache to access. * @returns {object} Cache object identified by the cacheId or undefined if no such cache. */ cacheFactory.get = function(cacheId) { return caches[cacheId]; }; return cacheFactory; }; } /** * @ngdoc service * @name $templateCache * * @description * The first time a template is used, it is loaded in the template cache for quick retrieval. You * can load templates directly into the cache in a `script` tag, or by consuming the * `$templateCache` service directly. * * Adding via the `script` tag: * * ```html * <script type="text/ng-template" id="templateId.html"> * <p>This is the content of the template</p> * </script> * ``` * * **Note:** the `script` tag containing the template does not need to be included in the `head` of * the document, but it must be below the `ng-app` definition. * * Adding via the $templateCache service: * * ```js * var myApp = angular.module('myApp', []); * myApp.run(function($templateCache) { * $templateCache.put('templateId.html', 'This is the content of the template'); * }); * ``` * * To retrieve the template later, simply use it in your HTML: * ```html * <div ng-include=" 'templateId.html' "></div> * ``` * * or get it via Javascript: * ```js * $templateCache.get('templateId.html') * ``` * * See {@link ng.$cacheFactory $cacheFactory}. * */ function $TemplateCacheProvider() { this.$get = ['$cacheFactory', function($cacheFactory) { return $cacheFactory('templates'); }]; } /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE! * * DOM-related variables: * * - "node" - DOM Node * - "element" - DOM Element or Node * - "$node" or "$element" - jqLite-wrapped node or element * * * Compiler related stuff: * * - "linkFn" - linking fn of a single directive * - "nodeLinkFn" - function that aggregates all linking fns for a particular node * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList) */ /** * @ngdoc service * @name $compile * @kind function * * @description * Compiles an HTML string or DOM into a template and produces a template function, which * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together. * * The compilation is a process of walking the DOM tree and matching DOM elements to * {@link ng.$compileProvider#directive directives}. * * <div class="alert alert-warning"> * **Note:** This document is an in-depth reference of all directive options. * For a gentle introduction to directives with examples of common use cases, * see the {@link guide/directive directive guide}. * </div> * * ## Comprehensive Directive API * * There are many different options for a directive. * * The difference resides in the return value of the factory function. * You can either return a "Directive Definition Object" (see below) that defines the directive properties, * or just the `postLink` function (all other properties will have the default values). * * <div class="alert alert-success"> * **Best Practice:** It's recommended to use the "directive definition object" form. * </div> * * Here's an example directive declared with a Directive Definition Object: * * ```js * var myModule = angular.module(...); * * myModule.directive('directiveName', function factory(injectables) { * var directiveDefinitionObject = { * priority: 0, * template: '<div></div>', // or // function(tElement, tAttrs) { ... }, * // or * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... }, * transclude: false, * restrict: 'A', * scope: false, * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... }, * controllerAs: 'stringAlias', * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'], * compile: function compile(tElement, tAttrs, transclude) { * return { * pre: function preLink(scope, iElement, iAttrs, controller) { ... }, * post: function postLink(scope, iElement, iAttrs, controller) { ... } * } * // or * // return function postLink( ... ) { ... } * }, * // or * // link: { * // pre: function preLink(scope, iElement, iAttrs, controller) { ... }, * // post: function postLink(scope, iElement, iAttrs, controller) { ... } * // } * // or * // link: function postLink( ... ) { ... } * }; * return directiveDefinitionObject; * }); * ``` * * <div class="alert alert-warning"> * **Note:** Any unspecified options will use the default value. You can see the default values below. * </div> * * Therefore the above can be simplified as: * * ```js * var myModule = angular.module(...); * * myModule.directive('directiveName', function factory(injectables) { * var directiveDefinitionObject = { * link: function postLink(scope, iElement, iAttrs) { ... } * }; * return directiveDefinitionObject; * // or * // return function postLink(scope, iElement, iAttrs) { ... } * }); * ``` * * * * ### Directive Definition Object * * The directive definition object provides instructions to the {@link ng.$compile * compiler}. The attributes are: * * #### `priority` * When there are multiple directives defined on a single DOM element, sometimes it * is necessary to specify the order in which the directives are applied. The `priority` is used * to sort the directives before their `compile` functions get called. Priority is defined as a * number. Directives with greater numerical `priority` are compiled first. Pre-link functions * are also run in priority order, but post-link functions are run in reverse order. The order * of directives with the same priority is undefined. The default priority is `0`. * * #### `terminal` * If set to true then the current `priority` will be the last set of directives * which will execute (any directives at the current priority will still execute * as the order of execution on same `priority` is undefined). * * #### `scope` * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the * same element request a new scope, only one new scope is created. The new scope rule does not * apply for the root of the template since the root of the template always gets a new scope. * * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from * normal scope in that it does not prototypically inherit from the parent scope. This is useful * when creating reusable components, which should not accidentally read or modify data in the * parent scope. * * The 'isolate' scope takes an object hash which defines a set of local scope properties * derived from the parent scope. These local properties are useful for aliasing values for * templates. Locals definition is a hash of local scope property to its source: * * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is * always a string since DOM attributes are strings. If no `attr` name is specified then the * attribute name is assumed to be the same as the local name. * Given `<widget my-attr="hello {{name}}">` and widget definition * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the * `localName` property on the widget scope. The `name` is read from the parent scope (not * component scope). * * * `=` or `=attr` - set up bi-directional binding between a local scope property and the * parent scope property of name defined via the value of the `attr` attribute. If no `attr` * name is specified then the attribute name is assumed to be the same as the local name. * Given `<widget my-attr="parentModel">` and widget definition of * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. * * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. * If no `attr` name is specified then the attribute name is assumed to be the same as the * local name. Given `<widget my-attr="count = count + value">` and widget definition of * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to * a function wrapper for the `count = count + value` expression. Often it's desirable to * pass data from the isolated scope via an expression and to the parent scope, this can be * done by passing a map of local variable names and values into the expression wrapper fn. * For example, if the expression is `increment(amount)` then we can specify the amount value * by calling the `localFn` as `localFn({amount: 22})`. * * * * #### `controller` * Controller constructor function. The controller is instantiated before the * pre-linking phase and it is shared with other directives (see * `require` attribute). This allows the directives to communicate with each other and augment * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals: * * * `$scope` - Current scope associated with the element * * `$element` - Current element * * `$attrs` - Current attributes object for the element * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope. * The scope can be overridden by an optional first argument. * `function([scope], cloneLinkingFn)`. * * * #### `require` * Require another directive and inject its controller as the fourth argument to the linking function. The * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the * injected argument will be an array in corresponding order. If no such directive can be * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with: * * * (no prefix) - Locate the required controller on the current element. Throw an error if not found. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found. * * `^` - Locate the required controller by searching the element's parents. Throw an error if not found. * * `?^` - Attempt to locate the required controller by searching the element's parents or pass `null` to the * `link` fn if not found. * * * #### `controllerAs` * Controller alias at the directive scope. An alias for the controller so it * can be referenced at the directive template. The directive needs to define a scope for this * configuration to be used. Useful in the case when directive is used as component. * * * #### `restrict` * String of subset of `EACM` which restricts the directive to a specific directive * declaration style. If omitted, the default (attributes only) is used. * * * `E` - Element name: `<my-directive></my-directive>` * * `A` - Attribute (default): `<div my-directive="exp"></div>` * * `C` - Class: `<div class="my-directive: exp;"></div>` * * `M` - Comment: `<!-- directive: my-directive exp -->` * * * #### `type` * String representing the document type used by the markup. This is useful for templates where the root * node is non-HTML content (such as SVG or MathML). The default value is "html". * * * `html` - All root template nodes are HTML, and don't need to be wrapped. Root nodes may also be * top-level elements such as `<svg>` or `<math>`. * * `svg` - The template contains only SVG content, and must be wrapped in an `<svg>` node prior to * processing. * * `math` - The template contains only MathML content, and must be wrapped in an `<math>` node prior to * processing. * * If no `type` is specified, then the type is considered to be html. * * #### `template` * replace the current element with the contents of the HTML. The replacement process * migrates all of the attributes / classes from the old element to the new one. See the * {@link guide/directive#creating-custom-directives_creating-directives_template-expanding-directive * Directives Guide} for an example. * * You can specify `template` as a string representing the template or as a function which takes * two arguments `tElement` and `tAttrs` (described in the `compile` function api below) and * returns a string value representing the template. * * * #### `templateUrl` * Same as `template` but the template is loaded from the specified URL. Because * the template loading is asynchronous the compilation/linking is suspended until the template * is loaded. * * You can specify `templateUrl` as a string representing the URL or as a function which takes two * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns * a string value representing the url. In either case, the template URL is passed through {@link * api/ng.$sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}. * * * #### `replace` ([*DEPRECATED*!], will be removed in next major release) * specify where the template should be inserted. Defaults to `false`. * * * `true` - the template will replace the current element. * * `false` - the template will replace the contents of the current element. * * * #### `transclude` * compile the content of the element and make it available to the directive. * Typically used with {@link ng.directive:ngTransclude * ngTransclude}. The advantage of transclusion is that the linking function receives a * transclusion function which is pre-bound to the correct scope. In a typical setup the widget * creates an `isolate` scope, but the transclusion is not a child, but a sibling of the `isolate` * scope. This makes it possible for the widget to have private state, and the transclusion to * be bound to the parent (pre-`isolate`) scope. * * * `true` - transclude the content of the directive. * * `'element'` - transclude the whole element including any directives defined at lower priority. * * * #### `compile` * * ```js * function compile(tElement, tAttrs, transclude) { ... } * ``` * * The compile function deals with transforming the template DOM. Since most directives do not do * template transformation, it is not used often. The compile function takes the following arguments: * * * `tElement` - template element - The element where the directive has been declared. It is * safe to do template transformation on the element and child elements only. * * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared * between all directive compile functions. * * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)` * * <div class="alert alert-warning"> * **Note:** The template instance and the link instance may be different objects if the template has * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration * should be done in a linking function rather than in a compile function. * </div> * <div class="alert alert-warning"> * **Note:** The compile function cannot handle directives that recursively use themselves in their * own templates or compile functions. Compiling these directives results in an infinite loop and a * stack overflow errors. * * This can be avoided by manually using $compile in the postLink function to imperatively compile * a directive's template instead of relying on automatic template compilation via `template` or * `templateUrl` declaration or manual compilation inside the compile function. * </div> * * <div class="alert alert-error"> * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it * e.g. does not know about the right outer scope. Please use the transclude function that is passed * to the link function instead. * </div> * A compile function can have a return value which can be either a function or an object. * * * returning a (post-link) function - is equivalent to registering the linking function via the * `link` property of the config object when the compile function is empty. * * * returning an object with function(s) registered via `pre` and `post` properties - allows you to * control when a linking function should be called during the linking phase. See info about * pre-linking and post-linking functions below. * * * #### `link` * This property is used only if the `compile` property is not defined. * * ```js * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... } * ``` * * The link function is responsible for registering DOM listeners as well as updating the DOM. It is * executed after the template has been cloned. This is where most of the directive logic will be * put. * * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the * directive for registering {@link ng.$rootScope.Scope#$watch watches}. * * * `iElement` - instance element - The element where the directive is to be used. It is safe to * manipulate the children of the element only in `postLink` function since the children have * already been linked. * * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared * between all directive linking functions. * * * `controller` - a controller instance - A controller instance if at least one directive on the * element defines a controller. The controller is shared among all the directives, which allows * the directives to use the controllers as a communication channel. * * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope. * The scope can be overridden by an optional first argument. This is the same as the `$transclude` * parameter of directive controllers. * `function([scope], cloneLinkingFn)`. * * * #### Pre-linking function * * Executed before the child elements are linked. Not safe to do DOM transformation since the * compiler linking function will fail to locate the correct elements for linking. * * #### Post-linking function * * Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function. * * <a name="Attributes"></a> * ### Attributes * * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the * `link()` or `compile()` functions. It has a variety of uses. * * accessing *Normalized attribute names:* * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. * the attributes object allows for normalized access to * the attributes. * * * *Directive inter-communication:* All directives share the same instance of the attributes * object which allows the directives to use the attributes object as inter directive * communication. * * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object * allowing other directives to read the interpolated value. * * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also * the only way to easily get the actual value because during the linking phase the interpolation * hasn't been evaluated yet and so the value is at this time set to `undefined`. * * ```js * function linkingFn(scope, elm, attrs, ctrl) { * // get the attribute value * console.log(attrs.ngModel); * * // change the attribute * attrs.$set('ngModel', 'new value'); * * // observe changes to interpolated attribute * attrs.$observe('ngModel', function(value) { * console.log('ngModel has changed value to ' + value); * }); * } * ``` * * Below is an example using `$compileProvider`. * * <div class="alert alert-warning"> * **Note**: Typically directives are registered with `module.directive`. The example below is * to illustrate how `$compile` works. * </div> * <example module="compile"> <file name="index.html"> <script> angular.module('compile', [], function($compileProvider) { // configure new 'compile' directive by passing a directive // factory function. The factory function injects the '$compile' $compileProvider.directive('compile', function($compile) { // directive factory creates a link function return function(scope, element, attrs) { scope.$watch( function(scope) { // watch the 'compile' expression for changes return scope.$eval(attrs.compile); }, function(value) { // when the 'compile' expression changes // assign it into the current DOM element.html(value); // compile the new DOM and link it to the current // scope. // NOTE: we only compile .childNodes so that // we don't get into infinite loop compiling ourselves $compile(element.contents())(scope); } ); }; }) }); function Ctrl($scope) { $scope.name = 'Angular'; $scope.html = 'Hello {{name}}'; } </script> <div ng-controller="Ctrl"> <input ng-model="name"> <br> <textarea ng-model="html"></textarea> <br> <div compile="html"></div> </div> </file> <file name="protractor.js" type="protractor"> it('should auto compile', function() { var textarea = $('textarea'); var output = $('div[compile]'); // The initial state reads 'Hello Angular'. expect(output.getText()).toBe('Hello Angular'); textarea.clear(); textarea.sendKeys('{{name}}!'); expect(output.getText()).toBe('Angular!'); }); </file> </example> * * * @param {string|DOMElement} element Element or HTML string to compile into a template function. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives. * @param {number} maxPriority only apply directives lower than given priority (Only effects the * root element(s), not their children) * @returns {function(scope, cloneAttachFn=)} a link function which is used to bind template * (a DOM element/tree) to a scope. Where: * * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the * `template` and call the `cloneAttachFn` function allowing the caller to attach the * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is * called as: <br> `cloneAttachFn(clonedElement, scope)` where: * * * `clonedElement` - is a clone of the original `element` passed into the compiler. * * `scope` - is the current scope with which the linking function is working with. * * Calling the linking function returns the element of the template. It is either the original * element passed in, or the clone of the element if the `cloneAttachFn` is provided. * * After linking the view is not updated until after a call to $digest which typically is done by * Angular automatically. * * If you need access to the bound view, there are two ways to do it: * * - If you are not asking the linking function to clone the template, create the DOM element(s) * before you send them to the compiler and keep this reference around. * ```js * var element = $compile('<p>{{total}}</p>')(scope); * ``` * * - if on the other hand, you need the element to be cloned, the view reference from the original * example would not point to the clone, but rather to the original template that was cloned. In * this case, you can access the clone via the cloneAttachFn: * ```js * var templateElement = angular.element('<p>{{total}}</p>'), * scope = ....; * * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) { * //attach the clone to DOM document at the right place * }); * * //now we have reference to the cloned DOM via `clonedElement` * ``` * * * For information on how the compiler works, see the * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide. */ var $compileMinErr = minErr('$compile'); /** * @ngdoc provider * @name $compileProvider * @kind function * * @description */ $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider']; function $CompileProvider($provide, $$sanitizeUriProvider) { var hasDirectives = {}, Suffix = 'Directive', COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w_\-]+)\s+(.*)$/, CLASS_DIRECTIVE_REGEXP = /(([\d\w_\-]+)(?:\:([^;]+))?;?)/, ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'); // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes // The assumption is that future DOM event attribute names will begin with // 'on' and be composed of only English letters. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/; /** * @ngdoc method * @name $compileProvider#directive * @kind function * * @description * Register a new directive with the compiler. * * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which * will match as <code>ng-bind</code>), or an object map of directives where the keys are the * names and the values are the factories. * @param {Function|Array} directiveFactory An injectable directive factory function. See * {@link guide/directive} for more info. * @returns {ng.$compileProvider} Self for chaining. */ this.directive = function registerDirective(name, directiveFactory) { assertNotHasOwnProperty(name, 'directive'); if (isString(name)) { assertArg(directiveFactory, 'directiveFactory'); if (!hasDirectives.hasOwnProperty(name)) { hasDirectives[name] = []; $provide.factory(name + Suffix, ['$injector', '$exceptionHandler', function($injector, $exceptionHandler) { var directives = []; forEach(hasDirectives[name], function(directiveFactory, index) { try { var directive = $injector.invoke(directiveFactory); if (isFunction(directive)) { directive = { compile: valueFn(directive) }; } else if (!directive.compile && directive.link) { directive.compile = valueFn(directive.link); } directive.priority = directive.priority || 0; directive.index = index; directive.name = directive.name || name; directive.require = directive.require || (directive.controller && directive.name); directive.restrict = directive.restrict || 'A'; directives.push(directive); } catch (e) { $exceptionHandler(e); } }); return directives; }]); } hasDirectives[name].push(directiveFactory); } else { forEach(name, reverseParams(registerDirective)); } return this; }; /** * @ngdoc method * @name $compileProvider#aHrefSanitizationWhitelist * @kind function * * @description * Retrieves or overrides the default regular expression that is used for whitelisting of safe * urls during a[href] sanitization. * * The sanitization is a security measure aimed at prevent XSS attacks via html links. * * Any url about to be assigned to a[href] via data-binding is first normalized and turned into * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` * regular expression. If a match is found, the original url is written into the dom. Otherwise, * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. * * @param {RegExp=} regexp New regexp to whitelist urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ this.aHrefSanitizationWhitelist = function(regexp) { if (isDefined(regexp)) { $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp); return this; } else { return $$sanitizeUriProvider.aHrefSanitizationWhitelist(); } }; /** * @ngdoc method * @name $compileProvider#imgSrcSanitizationWhitelist * @kind function * * @description * Retrieves or overrides the default regular expression that is used for whitelisting of safe * urls during img[src] sanitization. * * The sanitization is a security measure aimed at prevent XSS attacks via html links. * * Any url about to be assigned to img[src] via data-binding is first normalized and turned into * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` * regular expression. If a match is found, the original url is written into the dom. Otherwise, * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. * * @param {RegExp=} regexp New regexp to whitelist urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ this.imgSrcSanitizationWhitelist = function(regexp) { if (isDefined(regexp)) { $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp); return this; } else { return $$sanitizeUriProvider.imgSrcSanitizationWhitelist(); } }; this.$get = [ '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse', '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri', function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse, $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) { var Attributes = function(element, attr) { this.$$element = element; this.$attr = attr || {}; }; Attributes.prototype = { $normalize: directiveNormalize, /** * @ngdoc method * @name $compile.directive.Attributes#$addClass * @kind function * * @description * Adds the CSS class value specified by the classVal parameter to the element. If animations * are enabled then an animation will be triggered for the class addition. * * @param {string} classVal The className value that will be added to the element */ $addClass : function(classVal) { if(classVal && classVal.length > 0) { $animate.addClass(this.$$element, classVal); } }, /** * @ngdoc method * @name $compile.directive.Attributes#$removeClass * @kind function * * @description * Removes the CSS class value specified by the classVal parameter from the element. If * animations are enabled then an animation will be triggered for the class removal. * * @param {string} classVal The className value that will be removed from the element */ $removeClass : function(classVal) { if(classVal && classVal.length > 0) { $animate.removeClass(this.$$element, classVal); } }, /** * @ngdoc method * @name $compile.directive.Attributes#$updateClass * @kind function * * @description * Adds and removes the appropriate CSS class values to the element based on the difference * between the new and old CSS class values (specified as newClasses and oldClasses). * * @param {string} newClasses The current CSS className value * @param {string} oldClasses The former CSS className value */ $updateClass : function(newClasses, oldClasses) { var toAdd = tokenDifference(newClasses, oldClasses); var toRemove = tokenDifference(oldClasses, newClasses); if(toAdd.length === 0) { $animate.removeClass(this.$$element, toRemove); } else if(toRemove.length === 0) { $animate.addClass(this.$$element, toAdd); } else { $animate.setClass(this.$$element, toAdd, toRemove); } }, /** * Set a normalized attribute on the element in a way such that all directives * can share the attribute. This function properly handles boolean attributes. * @param {string} key Normalized key. (ie ngAttribute) * @param {string|boolean} value The value to set. If `null` attribute will be deleted. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute. * Defaults to true. * @param {string=} attrName Optional none normalized name. Defaults to key. */ $set: function(key, value, writeAttr, attrName) { // TODO: decide whether or not to throw an error if "class" //is set through this function since it may cause $updateClass to //become unstable. var node = this.$$element[0], booleanKey = getBooleanAttrName(node, key), aliasedKey = getAliasedAttrName(node, key), observer = key, normalizedVal, nodeName; if (booleanKey) { this.$$element.prop(key, value); attrName = booleanKey; } else if(aliasedKey) { this[aliasedKey] = value; observer = aliasedKey; } this[key] = value; // translate normalized key to actual key if (attrName) { this.$attr[key] = attrName; } else { attrName = this.$attr[key]; if (!attrName) { this.$attr[key] = attrName = snake_case(key, '-'); } } nodeName = nodeName_(this.$$element); // sanitize a[href] and img[src] values if ((nodeName === 'A' && key === 'href') || (nodeName === 'IMG' && key === 'src')) { this[key] = value = $$sanitizeUri(value, key === 'src'); } if (writeAttr !== false) { if (value === null || value === undefined) { this.$$element.removeAttr(attrName); } else { this.$$element.attr(attrName, value); } } // fire observers var $$observers = this.$$observers; $$observers && forEach($$observers[observer], function(fn) { try { fn(value); } catch (e) { $exceptionHandler(e); } }); }, /** * @ngdoc method * @name $compile.directive.Attributes#$observe * @kind function * * @description * Observes an interpolated attribute. * * The observer function will be invoked once during the next `$digest` following * compilation. The observer is then invoked whenever the interpolated value * changes. * * @param {string} key Normalized key. (ie ngAttribute) . * @param {function(interpolatedValue)} fn Function that will be called whenever the interpolated value of the attribute changes. * See the {@link guide/directive#Attributes Directives} guide for more info. * @returns {function()} Returns a deregistration function for this observer. */ $observe: function(key, fn) { var attrs = this, $$observers = (attrs.$$observers || (attrs.$$observers = {})), listeners = ($$observers[key] || ($$observers[key] = [])); listeners.push(fn); $rootScope.$evalAsync(function() { if (!listeners.$$inter) { // no one registered attribute interpolation function, so lets call it manually fn(attrs[key]); } }); return function() { arrayRemove(listeners, fn); }; } }; var startSymbol = $interpolate.startSymbol(), endSymbol = $interpolate.endSymbol(), denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}') ? identity : function denormalizeTemplate(template) { return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol); }, NG_ATTR_BINDING = /^ngAttr[A-Z]/; return compile; //================================ function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) { if (!($compileNodes instanceof jqLite)) { // jquery always rewraps, whereas we need to preserve the original selector so that we can // modify it. $compileNodes = jqLite($compileNodes); } // We can not compile top level text elements since text nodes can be merged and we will // not be able to attach scope data to them, so we will wrap them in <span> forEach($compileNodes, function(node, index){ if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) { $compileNodes[index] = node = jqLite(node).wrap('<span></span>').parent()[0]; } }); var compositeLinkFn = compileNodes($compileNodes, transcludeFn, $compileNodes, maxPriority, ignoreDirective, previousCompileContext); safeAddClass($compileNodes, 'ng-scope'); return function publicLinkFn(scope, cloneConnectFn, transcludeControllers, parentBoundTranscludeFn){ assertArg(scope, 'scope'); // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart // and sometimes changes the structure of the DOM. var $linkNode = cloneConnectFn ? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!! : $compileNodes; forEach(transcludeControllers, function(instance, name) { $linkNode.data('$' + name + 'Controller', instance); }); // Attach scope only to non-text nodes. for(var i = 0, ii = $linkNode.length; i<ii; i++) { var node = $linkNode[i], nodeType = node.nodeType; if (nodeType === 1 /* element */ || nodeType === 9 /* document */) { $linkNode.eq(i).data('$scope', scope); } } if (cloneConnectFn) cloneConnectFn($linkNode, scope); if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn); return $linkNode; }; } function safeAddClass($element, className) { try { $element.addClass(className); } catch(e) { // ignore, since it means that we are trying to set class on // SVG element, where class name is read-only. } } /** * Compile function matches each node in nodeList against the directives. Once all directives * for a particular node are collected their compile functions are executed. The compile * functions return values - the linking functions - are combined into a composite linking * function, which is the a linking function for the node. * * @param {NodeList} nodeList an array of nodes or NodeList to compile * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the * scope argument is auto-generated to the new child of the transcluded parent scope. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then * the rootElement must be set the jqLite collection of the compile root. This is * needed so that the jqLite collection items can be replaced with widgets. * @param {number=} maxPriority Max directive priority. * @returns {Function} A composite linking function of all of the matched directives or null. */ function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective, previousCompileContext) { var linkFns = [], attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound; for (var i = 0; i < nodeList.length; i++) { attrs = new Attributes(); // we must always refer to nodeList[i] since the nodes can be replaced underneath us. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined, ignoreDirective); nodeLinkFn = (directives.length) ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement, null, [], [], previousCompileContext) : null; if (nodeLinkFn && nodeLinkFn.scope) { safeAddClass(jqLite(nodeList[i]), 'ng-scope'); } childLinkFn = (nodeLinkFn && nodeLinkFn.terminal || !(childNodes = nodeList[i].childNodes) || !childNodes.length) ? null : compileNodes(childNodes, nodeLinkFn ? ( (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement) && nodeLinkFn.transclude) : transcludeFn); linkFns.push(nodeLinkFn, childLinkFn); linkFnFound = linkFnFound || nodeLinkFn || childLinkFn; //use the previous context only for the first element in the virtual group previousCompileContext = null; } // return a linking function if we have found anything, null otherwise return linkFnFound ? compositeLinkFn : null; function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) { var nodeLinkFn, childLinkFn, node, $node, childScope, i, ii, n, childBoundTranscludeFn; // copy nodeList so that linking doesn't break due to live list updates. var nodeListLength = nodeList.length, stableNodeList = new Array(nodeListLength); for (i = 0; i < nodeListLength; i++) { stableNodeList[i] = nodeList[i]; } for(i = 0, n = 0, ii = linkFns.length; i < ii; n++) { node = stableNodeList[n]; nodeLinkFn = linkFns[i++]; childLinkFn = linkFns[i++]; $node = jqLite(node); if (nodeLinkFn) { if (nodeLinkFn.scope) { childScope = scope.$new(); $node.data('$scope', childScope); } else { childScope = scope; } if ( nodeLinkFn.transcludeOnThisElement ) { childBoundTranscludeFn = createBoundTranscludeFn(scope, nodeLinkFn.transclude, parentBoundTranscludeFn); } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) { childBoundTranscludeFn = parentBoundTranscludeFn; } else if (!parentBoundTranscludeFn && transcludeFn) { childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn); } else { childBoundTranscludeFn = null; } nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn); } else if (childLinkFn) { childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn); } } } } function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) { var boundTranscludeFn = function(transcludedScope, cloneFn, controllers) { var scopeCreated = false; if (!transcludedScope) { transcludedScope = scope.$new(); transcludedScope.$$transcluded = true; scopeCreated = true; } var clone = transcludeFn(transcludedScope, cloneFn, controllers, previousBoundTranscludeFn); if (scopeCreated) { clone.on('$destroy', function() { transcludedScope.$destroy(); }); } return clone; }; return boundTranscludeFn; } /** * Looks for directives on the given node and adds them to the directive collection which is * sorted. * * @param node Node to search. * @param directives An array to which the directives are added to. This array is sorted before * the function returns. * @param attrs The shared attrs object which is used to populate the normalized attributes. * @param {number=} maxPriority Max directive priority. */ function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) { var nodeType = node.nodeType, attrsMap = attrs.$attr, match, className; switch(nodeType) { case 1: /* Element */ // use the node name: <directive> addDirective(directives, directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority, ignoreDirective); // iterate over the attributes for (var attr, name, nName, ngAttrName, value, nAttrs = node.attributes, j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) { var attrStartName = false; var attrEndName = false; attr = nAttrs[j]; if (!msie || msie >= 8 || attr.specified) { name = attr.name; // support ngAttr attribute binding ngAttrName = directiveNormalize(name); if (NG_ATTR_BINDING.test(ngAttrName)) { name = snake_case(ngAttrName.substr(6), '-'); } var directiveNName = ngAttrName.replace(/(Start|End)$/, ''); if (ngAttrName === directiveNName + 'Start') { attrStartName = name; attrEndName = name.substr(0, name.length - 5) + 'end'; name = name.substr(0, name.length - 6); } nName = directiveNormalize(name.toLowerCase()); attrsMap[nName] = name; attrs[nName] = value = trim(attr.value); if (getBooleanAttrName(node, nName)) { attrs[nName] = true; // presence means true } addAttrInterpolateDirective(node, directives, value, nName); addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName, attrEndName); } } // use class as directive className = node.className; if (isString(className) && className !== '') { while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) { nName = directiveNormalize(match[2]); if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) { attrs[nName] = trim(match[3]); } className = className.substr(match.index + match[0].length); } } break; case 3: /* Text Node */ addTextInterpolateDirective(directives, node.nodeValue); break; case 8: /* Comment */ try { match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue); if (match) { nName = directiveNormalize(match[1]); if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) { attrs[nName] = trim(match[2]); } } } catch (e) { // turns out that under some circumstances IE9 throws errors when one attempts to read // comment's node value. // Just ignore it and continue. (Can't seem to reproduce in test case.) } break; } directives.sort(byPriority); return directives; } /** * Given a node with an directive-start it collects all of the siblings until it finds * directive-end. * @param node * @param attrStart * @param attrEnd * @returns {*} */ function groupScan(node, attrStart, attrEnd) { var nodes = []; var depth = 0; if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) { var startNode = node; do { if (!node) { throw $compileMinErr('uterdir', "Unterminated attribute, found '{0}' but no matching '{1}' found.", attrStart, attrEnd); } if (node.nodeType == 1 /** Element **/) { if (node.hasAttribute(attrStart)) depth++; if (node.hasAttribute(attrEnd)) depth--; } nodes.push(node); node = node.nextSibling; } while (depth > 0); } else { nodes.push(node); } return jqLite(nodes); } /** * Wrapper for linking function which converts normal linking function into a grouped * linking function. * @param linkFn * @param attrStart * @param attrEnd * @returns {Function} */ function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) { return function(scope, element, attrs, controllers, transcludeFn) { element = groupScan(element[0], attrStart, attrEnd); return linkFn(scope, element, attrs, controllers, transcludeFn); }; } /** * Once the directives have been collected, their compile functions are executed. This method * is responsible for inlining directive templates as well as terminating the application * of the directives if the terminal directive has been reached. * * @param {Array} directives Array of collected directives to execute their compile function. * this needs to be pre-sorted by priority order. * @param {Node} compileNode The raw DOM node to apply the compile functions to * @param {Object} templateAttrs The shared attribute function * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the * scope argument is auto-generated to the new * child of the transcluded parent scope. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this * argument has the root jqLite array so that we can replace nodes * on it. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when * compiling the transclusion. * @param {Array.<Function>} preLinkFns * @param {Array.<Function>} postLinkFns * @param {Object} previousCompileContext Context used for previous compilation of the current * node * @returns {Function} linkFn */ function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, jqCollection, originalReplaceDirective, preLinkFns, postLinkFns, previousCompileContext) { previousCompileContext = previousCompileContext || {}; var terminalPriority = -Number.MAX_VALUE, newScopeDirective, controllerDirectives = previousCompileContext.controllerDirectives, newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective, templateDirective = previousCompileContext.templateDirective, nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective, hasTranscludeDirective = false, hasTemplate = false, hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective, $compileNode = templateAttrs.$$element = jqLite(compileNode), directive, directiveName, $template, replaceDirective = originalReplaceDirective, childTranscludeFn = transcludeFn, linkFn, directiveValue; // executes all directives on the current element for(var i = 0, ii = directives.length; i < ii; i++) { directive = directives[i]; var attrStart = directive.$$start; var attrEnd = directive.$$end; // collect multiblock sections if (attrStart) { $compileNode = groupScan(compileNode, attrStart, attrEnd); } $template = undefined; if (terminalPriority > directive.priority) { break; // prevent further processing of directives } if (directiveValue = directive.scope) { // skip the check for directives with async templates, we'll check the derived sync // directive when the template arrives if (!directive.templateUrl) { if (isObject(directiveValue)) { // This directive is trying to add an isolated scope. // Check that there is no scope of any kind already assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective, directive, $compileNode); newIsolateScopeDirective = directive; } else { // This directive is trying to add a child scope. // Check that there is no isolated scope already assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive, $compileNode); } } newScopeDirective = newScopeDirective || directive; } directiveName = directive.name; if (!directive.templateUrl && directive.controller) { directiveValue = directive.controller; controllerDirectives = controllerDirectives || {}; assertNoDuplicate("'" + directiveName + "' controller", controllerDirectives[directiveName], directive, $compileNode); controllerDirectives[directiveName] = directive; } if (directiveValue = directive.transclude) { hasTranscludeDirective = true; // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion. // This option should only be used by directives that know how to safely handle element transclusion, // where the transcluded nodes are added or replaced after linking. if (!directive.$$tlb) { assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode); nonTlbTranscludeDirective = directive; } if (directiveValue == 'element') { hasElementTranscludeDirective = true; terminalPriority = directive.priority; $template = groupScan(compileNode, attrStart, attrEnd); $compileNode = templateAttrs.$$element = jqLite(document.createComment(' ' + directiveName + ': ' + templateAttrs[directiveName] + ' ')); compileNode = $compileNode[0]; replaceWith(jqCollection, jqLite(sliceArgs($template)), compileNode); childTranscludeFn = compile($template, transcludeFn, terminalPriority, replaceDirective && replaceDirective.name, { // Don't pass in: // - controllerDirectives - otherwise we'll create duplicates controllers // - newIsolateScopeDirective or templateDirective - combining templates with // element transclusion doesn't make sense. // // We need only nonTlbTranscludeDirective so that we prevent putting transclusion // on the same element more than once. nonTlbTranscludeDirective: nonTlbTranscludeDirective }); } else { $template = jqLite(jqLiteClone(compileNode)).contents(); $compileNode.empty(); // clear contents childTranscludeFn = compile($template, transcludeFn); } } if (directive.template) { hasTemplate = true; assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; directiveValue = (isFunction(directive.template)) ? directive.template($compileNode, templateAttrs) : directive.template; directiveValue = denormalizeTemplate(directiveValue); if (directive.replace) { replaceDirective = directive; if (jqLiteIsTextNode(directiveValue)) { $template = []; } else { $template = jqLite(wrapTemplate(directive.type, trim(directiveValue))); } compileNode = $template[0]; if ($template.length != 1 || compileNode.nodeType !== 1) { throw $compileMinErr('tplrt', "Template for directive '{0}' must have exactly one root element. {1}", directiveName, ''); } replaceWith(jqCollection, $compileNode, compileNode); var newTemplateAttrs = {$attr: {}}; // combine directives from the original node and from the template: // - take the array of directives for this element // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed) // - collect directives from the template and sort them by priority // - combine directives as: processed + template + unprocessed var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs); var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1)); if (newIsolateScopeDirective) { markDirectivesAsIsolate(templateDirectives); } directives = directives.concat(templateDirectives).concat(unprocessedDirectives); mergeTemplateAttributes(templateAttrs, newTemplateAttrs); ii = directives.length; } else { $compileNode.html(directiveValue); } } if (directive.templateUrl) { hasTemplate = true; assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; if (directive.replace) { replaceDirective = directive; } nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode, templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, { controllerDirectives: controllerDirectives, newIsolateScopeDirective: newIsolateScopeDirective, templateDirective: templateDirective, nonTlbTranscludeDirective: nonTlbTranscludeDirective }); ii = directives.length; } else if (directive.compile) { try { linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn); if (isFunction(linkFn)) { addLinkFns(null, linkFn, attrStart, attrEnd); } else if (linkFn) { addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd); } } catch (e) { $exceptionHandler(e, startingTag($compileNode)); } } if (directive.terminal) { nodeLinkFn.terminal = true; terminalPriority = Math.max(terminalPriority, directive.priority); } } nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true; nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective; nodeLinkFn.templateOnThisElement = hasTemplate; nodeLinkFn.transclude = childTranscludeFn; previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective; // might be normal or delayed nodeLinkFn depending on if templateUrl is present return nodeLinkFn; //////////////////// function addLinkFns(pre, post, attrStart, attrEnd) { if (pre) { if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd); pre.require = directive.require; pre.directiveName = directiveName; if (newIsolateScopeDirective === directive || directive.$$isolateScope) { pre = cloneAndAnnotateFn(pre, {isolateScope: true}); } preLinkFns.push(pre); } if (post) { if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd); post.require = directive.require; post.directiveName = directiveName; if (newIsolateScopeDirective === directive || directive.$$isolateScope) { post = cloneAndAnnotateFn(post, {isolateScope: true}); } postLinkFns.push(post); } } function getControllers(directiveName, require, $element, elementControllers) { var value, retrievalMethod = 'data', optional = false; if (isString(require)) { while((value = require.charAt(0)) == '^' || value == '?') { require = require.substr(1); if (value == '^') { retrievalMethod = 'inheritedData'; } optional = optional || value == '?'; } value = null; if (elementControllers && retrievalMethod === 'data') { value = elementControllers[require]; } value = value || $element[retrievalMethod]('$' + require + 'Controller'); if (!value && !optional) { throw $compileMinErr('ctreq', "Controller '{0}', required by directive '{1}', can't be found!", require, directiveName); } return value; } else if (isArray(require)) { value = []; forEach(require, function(require) { value.push(getControllers(directiveName, require, $element, elementControllers)); }); } return value; } function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) { var attrs, $element, i, ii, linkFn, controller, isolateScope, elementControllers = {}, transcludeFn; if (compileNode === linkNode) { attrs = templateAttrs; } else { attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr)); } $element = attrs.$$element; if (newIsolateScopeDirective) { var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/; var $linkNode = jqLite(linkNode); isolateScope = scope.$new(true); if (templateDirective && (templateDirective === newIsolateScopeDirective || templateDirective === newIsolateScopeDirective.$$originalDirective)) { $linkNode.data('$isolateScope', isolateScope) ; } else { $linkNode.data('$isolateScopeNoTemplate', isolateScope); } safeAddClass($linkNode, 'ng-isolate-scope'); forEach(newIsolateScopeDirective.scope, function(definition, scopeName) { var match = definition.match(LOCAL_REGEXP) || [], attrName = match[3] || scopeName, optional = (match[2] == '?'), mode = match[1], // @, =, or & lastValue, parentGet, parentSet, compare; isolateScope.$$isolateBindings[scopeName] = mode + attrName; switch (mode) { case '@': attrs.$observe(attrName, function(value) { isolateScope[scopeName] = value; }); attrs.$$observers[attrName].$$scope = scope; if( attrs[attrName] ) { // If the attribute has been provided then we trigger an interpolation to ensure // the value is there for use in the link fn isolateScope[scopeName] = $interpolate(attrs[attrName])(scope); } break; case '=': if (optional && !attrs[attrName]) { return; } parentGet = $parse(attrs[attrName]); if (parentGet.literal) { compare = equals; } else { compare = function(a,b) { return a === b; }; } parentSet = parentGet.assign || function() { // reset the change, or we will throw this exception on every $digest lastValue = isolateScope[scopeName] = parentGet(scope); throw $compileMinErr('nonassign', "Expression '{0}' used with directive '{1}' is non-assignable!", attrs[attrName], newIsolateScopeDirective.name); }; lastValue = isolateScope[scopeName] = parentGet(scope); isolateScope.$watch(function parentValueWatch() { var parentValue = parentGet(scope); if (!compare(parentValue, isolateScope[scopeName])) { // we are out of sync and need to copy if (!compare(parentValue, lastValue)) { // parent changed and it has precedence isolateScope[scopeName] = parentValue; } else { // if the parent can be assigned then do so parentSet(scope, parentValue = isolateScope[scopeName]); } } parentValueWatch.$$unwatch = parentGet.$$unwatch; return lastValue = parentValue; }, null, parentGet.literal); break; case '&': parentGet = $parse(attrs[attrName]); isolateScope[scopeName] = function(locals) { return parentGet(scope, locals); }; break; default: throw $compileMinErr('iscp', "Invalid isolate scope definition for directive '{0}'." + " Definition: {... {1}: '{2}' ...}", newIsolateScopeDirective.name, scopeName, definition); } }); } transcludeFn = boundTranscludeFn && controllersBoundTransclude; if (controllerDirectives) { forEach(controllerDirectives, function(directive) { var locals = { $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope, $element: $element, $attrs: attrs, $transclude: transcludeFn }, controllerInstance; controller = directive.controller; if (controller == '@') { controller = attrs[directive.name]; } controllerInstance = $controller(controller, locals); // For directives with element transclusion the element is a comment, // but jQuery .data doesn't support attaching data to comment nodes as it's hard to // clean up (http://bugs.jquery.com/ticket/8335). // Instead, we save the controllers for the element in a local hash and attach to .data // later, once we have the actual element. elementControllers[directive.name] = controllerInstance; if (!hasElementTranscludeDirective) { $element.data('$' + directive.name + 'Controller', controllerInstance); } if (directive.controllerAs) { locals.$scope[directive.controllerAs] = controllerInstance; } }); } // PRELINKING for(i = 0, ii = preLinkFns.length; i < ii; i++) { try { linkFn = preLinkFns[i]; linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs, linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), transcludeFn); } catch (e) { $exceptionHandler(e, startingTag($element)); } } // RECURSION // We only pass the isolate scope, if the isolate directive has a template, // otherwise the child elements do not belong to the isolate directive. var scopeToChild = scope; if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) { scopeToChild = isolateScope; } childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn); // POSTLINKING for(i = postLinkFns.length - 1; i >= 0; i--) { try { linkFn = postLinkFns[i]; linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs, linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), transcludeFn); } catch (e) { $exceptionHandler(e, startingTag($element)); } } // This is the function that is injected as `$transclude`. function controllersBoundTransclude(scope, cloneAttachFn) { var transcludeControllers; // no scope passed if (arguments.length < 2) { cloneAttachFn = scope; scope = undefined; } if (hasElementTranscludeDirective) { transcludeControllers = elementControllers; } return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers); } } } function markDirectivesAsIsolate(directives) { // mark all directives as needing isolate scope. for (var j = 0, jj = directives.length; j < jj; j++) { directives[j] = inherit(directives[j], {$$isolateScope: true}); } } /** * looks up the directive and decorates it with exception handling and proper parameters. We * call this the boundDirective. * * @param {string} name name of the directive to look up. * @param {string} location The directive must be found in specific format. * String containing any of theses characters: * * * `E`: element name * * `A': attribute * * `C`: class * * `M`: comment * @returns {boolean} true if directive was added. */ function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName, endAttrName) { if (name === ignoreDirective) return null; var match = null; if (hasDirectives.hasOwnProperty(name)) { for(var directive, directives = $injector.get(name + Suffix), i = 0, ii = directives.length; i<ii; i++) { try { directive = directives[i]; if ( (maxPriority === undefined || maxPriority > directive.priority) && directive.restrict.indexOf(location) != -1) { if (startAttrName) { directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName}); } tDirectives.push(directive); match = directive; } } catch(e) { $exceptionHandler(e); } } } return match; } /** * When the element is replaced with HTML template then the new attributes * on the template need to be merged with the existing attributes in the DOM. * The desired effect is to have both of the attributes present. * * @param {object} dst destination attributes (original DOM) * @param {object} src source attributes (from the directive template) */ function mergeTemplateAttributes(dst, src) { var srcAttr = src.$attr, dstAttr = dst.$attr, $element = dst.$$element; // reapply the old attributes to the new element forEach(dst, function(value, key) { if (key.charAt(0) != '$') { if (src[key] && src[key] !== value) { value += (key === 'style' ? ';' : ' ') + src[key]; } dst.$set(key, value, true, srcAttr[key]); } }); // copy the new attributes on the old attrs object forEach(src, function(value, key) { if (key == 'class') { safeAddClass($element, value); dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value; } else if (key == 'style') { $element.attr('style', $element.attr('style') + ';' + value); dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value; // `dst` will never contain hasOwnProperty as DOM parser won't let it. // You will get an "InvalidCharacterError: DOM Exception 5" error if you // have an attribute like "has-own-property" or "data-has-own-property", etc. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) { dst[key] = value; dstAttr[key] = srcAttr[key]; } }); } function compileTemplateUrl(directives, $compileNode, tAttrs, $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) { var linkQueue = [], afterTemplateNodeLinkFn, afterTemplateChildLinkFn, beforeTemplateCompileNode = $compileNode[0], origAsyncDirective = directives.shift(), // The fact that we have to copy and patch the directive seems wrong! derivedSyncDirective = extend({}, origAsyncDirective, { templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective }), templateUrl = (isFunction(origAsyncDirective.templateUrl)) ? origAsyncDirective.templateUrl($compileNode, tAttrs) : origAsyncDirective.templateUrl, type = origAsyncDirective.type; $compileNode.empty(); $http.get($sce.getTrustedResourceUrl(templateUrl), {cache: $templateCache}). success(function(content) { var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn; content = denormalizeTemplate(content); if (origAsyncDirective.replace) { if (jqLiteIsTextNode(content)) { $template = []; } else { $template = jqLite(wrapTemplate(type, trim(content))); } compileNode = $template[0]; if ($template.length != 1 || compileNode.nodeType !== 1) { throw $compileMinErr('tplrt', "Template for directive '{0}' must have exactly one root element. {1}", origAsyncDirective.name, templateUrl); } tempTemplateAttrs = {$attr: {}}; replaceWith($rootElement, $compileNode, compileNode); var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs); if (isObject(origAsyncDirective.scope)) { markDirectivesAsIsolate(templateDirectives); } directives = templateDirectives.concat(directives); mergeTemplateAttributes(tAttrs, tempTemplateAttrs); } else { compileNode = beforeTemplateCompileNode; $compileNode.html(content); } directives.unshift(derivedSyncDirective); afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs, childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns, previousCompileContext); forEach($rootElement, function(node, i) { if (node == compileNode) { $rootElement[i] = $compileNode[0]; } }); afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn); while(linkQueue.length) { var scope = linkQueue.shift(), beforeTemplateLinkNode = linkQueue.shift(), linkRootElement = linkQueue.shift(), boundTranscludeFn = linkQueue.shift(), linkNode = $compileNode[0]; if (beforeTemplateLinkNode !== beforeTemplateCompileNode) { var oldClasses = beforeTemplateLinkNode.className; if (!(previousCompileContext.hasElementTranscludeDirective && origAsyncDirective.replace)) { // it was cloned therefore we have to clone as well. linkNode = jqLiteClone(compileNode); } replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode); // Copy in CSS classes from original node safeAddClass(jqLite(linkNode), oldClasses); } if (afterTemplateNodeLinkFn.transcludeOnThisElement) { childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn); } else { childBoundTranscludeFn = boundTranscludeFn; } afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, childBoundTranscludeFn); } linkQueue = null; }). error(function(response, code, headers, config) { throw $compileMinErr('tpload', 'Failed to load template: {0}', config.url); }); return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) { var childBoundTranscludeFn = boundTranscludeFn; if (linkQueue) { linkQueue.push(scope); linkQueue.push(node); linkQueue.push(rootElement); linkQueue.push(childBoundTranscludeFn); } else { if (afterTemplateNodeLinkFn.transcludeOnThisElement) { childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn); } afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn); } }; } /** * Sorting function for bound directives. */ function byPriority(a, b) { var diff = b.priority - a.priority; if (diff !== 0) return diff; if (a.name !== b.name) return (a.name < b.name) ? -1 : 1; return a.index - b.index; } function assertNoDuplicate(what, previousDirective, directive, element) { if (previousDirective) { throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}', previousDirective.name, directive.name, what, startingTag(element)); } } function addTextInterpolateDirective(directives, text) { var interpolateFn = $interpolate(text, true); if (interpolateFn) { directives.push({ priority: 0, compile: function textInterpolateCompileFn(templateNode) { // when transcluding a template that has bindings in the root // then we don't have a parent and should do this in the linkFn var parent = templateNode.parent(), hasCompileParent = parent.length; if (hasCompileParent) safeAddClass(templateNode.parent(), 'ng-binding'); return function textInterpolateLinkFn(scope, node) { var parent = node.parent(), bindings = parent.data('$binding') || []; // Need to interpolate again in case this is using one-time bindings in multiple clones // of transcluded templates. interpolateFn = $interpolate(text); bindings.push(interpolateFn); parent.data('$binding', bindings); if (!hasCompileParent) safeAddClass(parent, 'ng-binding'); scope.$watch(interpolateFn, function interpolateFnWatchAction(value) { node[0].nodeValue = value; }); }; } }); } } function wrapTemplate(type, template) { type = lowercase(type || 'html'); switch(type) { case 'svg': case 'math': var wrapper = document.createElement('div'); wrapper.innerHTML = '<'+type+'>'+template+'</'+type+'>'; return wrapper.childNodes[0].childNodes; default: return template; } } function getTrustedContext(node, attrNormalizedName) { if (attrNormalizedName == "srcdoc") { return $sce.HTML; } var tag = nodeName_(node); // maction[xlink:href] can source SVG. It's not limited to <maction>. if (attrNormalizedName == "xlinkHref" || (tag == "FORM" && attrNormalizedName == "action") || (tag != "IMG" && (attrNormalizedName == "src" || attrNormalizedName == "ngSrc"))) { return $sce.RESOURCE_URL; } } function addAttrInterpolateDirective(node, directives, value, name) { var interpolateFn = $interpolate(value, true); // no interpolation found -> ignore if (!interpolateFn) return; if (name === "multiple" && nodeName_(node) === "SELECT") { throw $compileMinErr("selmulti", "Binding to the 'multiple' attribute is not supported. Element: {0}", startingTag(node)); } directives.push({ priority: 100, compile: function() { return { pre: function attrInterpolatePreLinkFn(scope, element, attr) { var $$observers = (attr.$$observers || (attr.$$observers = {})); if (EVENT_HANDLER_ATTR_REGEXP.test(name)) { throw $compileMinErr('nodomevents', "Interpolations for HTML DOM event attributes are disallowed. Please use the " + "ng- versions (such as ng-click instead of onclick) instead."); } // we need to interpolate again, in case the attribute value has been updated // (e.g. by another directive's compile function) interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name), ALL_OR_NOTHING_ATTRS[name]); // if attribute was updated so that there is no interpolation going on we don't want to // register any observers if (!interpolateFn) return; // initialize attr object so that it's ready in case we need the value for isolate // scope initialization, otherwise the value would not be available from isolate // directive's linking fn during linking phase attr[name] = interpolateFn(scope); ($$observers[name] || ($$observers[name] = [])).$$inter = true; (attr.$$observers && attr.$$observers[name].$$scope || scope). $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) { //special case for class attribute addition + removal //so that class changes can tap into the animation //hooks provided by the $animate service. Be sure to //skip animations when the first digest occurs (when //both the new and the old values are the same) since //the CSS classes are the non-interpolated values if(name === 'class' && newValue != oldValue) { attr.$updateClass(newValue, oldValue); } else { attr.$set(name, newValue); } }); } }; } }); } /** * This is a special jqLite.replaceWith, which can replace items which * have no parents, provided that the containing jqLite collection is provided. * * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes * in the root of the tree. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep * the shell, but replace its DOM node reference. * @param {Node} newNode The new DOM node. */ function replaceWith($rootElement, elementsToRemove, newNode) { var firstElementToRemove = elementsToRemove[0], removeCount = elementsToRemove.length, parent = firstElementToRemove.parentNode, i, ii; if ($rootElement) { for(i = 0, ii = $rootElement.length; i < ii; i++) { if ($rootElement[i] == firstElementToRemove) { $rootElement[i++] = newNode; for (var j = i, j2 = j + removeCount - 1, jj = $rootElement.length; j < jj; j++, j2++) { if (j2 < jj) { $rootElement[j] = $rootElement[j2]; } else { delete $rootElement[j]; } } $rootElement.length -= removeCount - 1; break; } } } if (parent) { parent.replaceChild(newNode, firstElementToRemove); } var fragment = document.createDocumentFragment(); fragment.appendChild(firstElementToRemove); newNode[jqLite.expando] = firstElementToRemove[jqLite.expando]; for (var k = 1, kk = elementsToRemove.length; k < kk; k++) { var element = elementsToRemove[k]; jqLite(element).remove(); // must do this way to clean up expando fragment.appendChild(element); delete elementsToRemove[k]; } elementsToRemove[0] = newNode; elementsToRemove.length = 1; } function cloneAndAnnotateFn(fn, annotation) { return extend(function() { return fn.apply(null, arguments); }, fn, annotation); } }]; } var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i; /** * Converts all accepted directives format into proper directive name. * All of these will become 'myDirective': * my:Directive * my-directive * x-my-directive * data-my:directive * * Also there is special case for Moz prefix starting with upper case letter. * @param name Name to normalize */ function directiveNormalize(name) { return camelCase(name.replace(PREFIX_REGEXP, '')); } /** * @ngdoc type * @name $compile.directive.Attributes * * @description * A shared object between directive compile / linking functions which contains normalized DOM * element attributes. The values reflect current binding state `{{ }}`. The normalization is * needed since all of these are treated as equivalent in Angular: * * ``` * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a"> * ``` */ /** * @ngdoc property * @name $compile.directive.Attributes#$attr * @returns {object} A map of DOM element attribute names to the normalized name. This is * needed to do reverse lookup from normalized name back to actual name. */ /** * @ngdoc method * @name $compile.directive.Attributes#$set * @kind function * * @description * Set DOM element attribute value. * * * @param {string} name Normalized element attribute name of the property to modify. The name is * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr} * property to the original name. * @param {string} value Value to set the attribute to. The value can be an interpolated string. */ /** * Closure compiler type information */ function nodesetLinkingFn( /* angular.Scope */ scope, /* NodeList */ nodeList, /* Element */ rootElement, /* function(Function) */ boundTranscludeFn ){} function directiveLinkingFn( /* nodesetLinkingFn */ nodesetLinkingFn, /* angular.Scope */ scope, /* Node */ node, /* Element */ rootElement, /* function(Function) */ boundTranscludeFn ){} function tokenDifference(str1, str2) { var values = '', tokens1 = str1.split(/\s+/), tokens2 = str2.split(/\s+/); outer: for(var i = 0; i < tokens1.length; i++) { var token = tokens1[i]; for(var j = 0; j < tokens2.length; j++) { if(token == tokens2[j]) continue outer; } values += (values.length > 0 ? ' ' : '') + token; } return values; } /** * @ngdoc provider * @name $controllerProvider * @description * The {@link ng.$controller $controller service} is used by Angular to create new * controllers. * * This provider allows controller registration via the * {@link ng.$controllerProvider#register register} method. */ function $ControllerProvider() { var controllers = {}, CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/; /** * @ngdoc method * @name $controllerProvider#register * @param {string|Object} name Controller name, or an object map of controllers where the keys are * the names and the values are the constructors. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI * annotations in the array notation). */ this.register = function(name, constructor) { assertNotHasOwnProperty(name, 'controller'); if (isObject(name)) { extend(controllers, name); } else { controllers[name] = constructor; } }; this.$get = ['$injector', '$window', function($injector, $window) { /** * @ngdoc service * @name $controller * @requires $injector * * @param {Function|string} constructor If called with a function then it's considered to be the * controller constructor function. Otherwise it's considered to be a string which is used * to retrieve the controller constructor using the following steps: * * * check if a controller with given name is registered via `$controllerProvider` * * check if evaluating the string on the current scope returns a constructor * * check `window[constructor]` on the global `window` object * * @param {Object} locals Injection locals for Controller. * @return {Object} Instance of given controller. * * @description * `$controller` service is responsible for instantiating controllers. * * It's just a simple call to {@link auto.$injector $injector}, but extracted into * a service, so that one can override this service with [BC version](https://gist.github.com/1649788). */ return function(expression, locals) { var instance, match, constructor, identifier; if(isString(expression)) { match = expression.match(CNTRL_REG), constructor = match[1], identifier = match[3]; expression = controllers.hasOwnProperty(constructor) ? controllers[constructor] : getter(locals.$scope, constructor, true) || getter($window, constructor, true); assertArgFn(expression, constructor, true); } instance = $injector.instantiate(expression, locals, constructor); if (identifier) { if (!(locals && typeof locals.$scope == 'object')) { throw minErr('$controller')('noscp', "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.", constructor || expression.name, identifier); } locals.$scope[identifier] = instance; } return instance; }; }]; } /** * @ngdoc service * @name $document * @requires $window * * @description * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object. * * @example <example> <file name="index.html"> <div ng-controller="MainCtrl"> <p>$document title: <b ng-bind="title"></b></p> <p>window.document title: <b ng-bind="windowTitle"></b></p> </div> </file> <file name="script.js"> function MainCtrl($scope, $document) { $scope.title = $document[0].title; $scope.windowTitle = angular.element(window.document)[0].title; } </file> </example> */ function $DocumentProvider(){ this.$get = ['$window', function(window){ return jqLite(window.document); }]; } /** * @ngdoc service * @name $exceptionHandler * @requires ng.$log * * @description * Any uncaught exception in angular expressions is delegated to this service. * The default implementation simply delegates to `$log.error` which logs it into * the browser console. * * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing. * * ## Example: * * ```js * angular.module('exceptionOverride', []).factory('$exceptionHandler', function () { * return function (exception, cause) { * exception.message += ' (caused by "' + cause + '")'; * throw exception; * }; * }); * ``` * * This example will override the normal action of `$exceptionHandler`, to make angular * exceptions fail hard when they happen, instead of just logging to the console. * * @param {Error} exception Exception associated with the error. * @param {string=} cause optional information about the context in which * the error was thrown. * */ function $ExceptionHandlerProvider() { this.$get = ['$log', function($log) { return function(exception, cause) { $log.error.apply($log, arguments); }; }]; } /** * Parse headers into key value object * * @param {string} headers Raw headers as a string * @returns {Object} Parsed headers as key value object */ function parseHeaders(headers) { var parsed = {}, key, val, i; if (!headers) return parsed; forEach(headers.split('\n'), function(line) { i = line.indexOf(':'); key = lowercase(trim(line.substr(0, i))); val = trim(line.substr(i + 1)); if (key) { if (parsed[key]) { parsed[key] += ', ' + val; } else { parsed[key] = val; } } }); return parsed; } /** * Returns a function that provides access to parsed headers. * * Headers are lazy parsed when first requested. * @see parseHeaders * * @param {(string|Object)} headers Headers to provide access to. * @returns {function(string=)} Returns a getter function which if called with: * * - if called with single an argument returns a single header value or null * - if called with no arguments returns an object containing all headers. */ function headersGetter(headers) { var headersObj = isObject(headers) ? headers : undefined; return function(name) { if (!headersObj) headersObj = parseHeaders(headers); if (name) { return headersObj[lowercase(name)] || null; } return headersObj; }; } /** * Chain all given functions * * This function is used for both request and response transforming * * @param {*} data Data to transform. * @param {function(string=)} headers Http headers getter fn. * @param {(Function|Array.<Function>)} fns Function or an array of functions. * @returns {*} Transformed data. */ function transformData(data, headers, fns) { if (isFunction(fns)) return fns(data, headers); forEach(fns, function(fn) { data = fn(data, headers); }); return data; } function isSuccess(status) { return 200 <= status && status < 300; } function $HttpProvider() { var JSON_START = /^\s*(\[|\{[^\{])/, JSON_END = /[\}\]]\s*$/, PROTECTION_PREFIX = /^\)\]\}',?\n/, CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'}; var defaults = this.defaults = { // transform incoming response data transformResponse: [function(data) { if (isString(data)) { // strip json vulnerability protection prefix data = data.replace(PROTECTION_PREFIX, ''); if (JSON_START.test(data) && JSON_END.test(data)) data = fromJson(data); } return data; }], // transform outgoing request data transformRequest: [function(d) { return isObject(d) && !isFile(d) && !isBlob(d) ? toJson(d) : d; }], // default headers headers: { common: { 'Accept': 'application/json, text/plain, */*' }, post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON) }, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN' }; /** * Are ordered by request, i.e. they are applied in the same order as the * array, on request, but reverse order, on response. */ var interceptorFactories = this.interceptors = []; this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector', function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) { var defaultCache = $cacheFactory('$http'); /** * Interceptors stored in reverse order. Inner interceptors before outer interceptors. * The reversal is needed so that we can build up the interception chain around the * server request. */ var reversedInterceptors = []; forEach(interceptorFactories, function(interceptorFactory) { reversedInterceptors.unshift(isString(interceptorFactory) ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory)); }); /** * @ngdoc service * @kind function * @name $http * @requires ng.$httpBackend * @requires $cacheFactory * @requires $rootScope * @requires $q * @requires $injector * * @description * The `$http` service is a core Angular service that facilitates communication with the remote * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest) * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP). * * For unit testing applications that use `$http` service, see * {@link ngMock.$httpBackend $httpBackend mock}. * * For a higher level of abstraction, please check out the {@link ngResource.$resource * $resource} service. * * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage * it is important to familiarize yourself with these APIs and the guarantees they provide. * * * # General usage * The `$http` service is a function which takes a single argument — a configuration object — * that is used to generate an HTTP request and returns a {@link ng.$q promise} * with two $http specific methods: `success` and `error`. * * ```js * $http({method: 'GET', url: '/someUrl'}). * success(function(data, status, headers, config) { * // this callback will be called asynchronously * // when the response is available * }). * error(function(data, status, headers, config) { * // called asynchronously if an error occurs * // or server returns response with an error status. * }); * ``` * * Since the returned value of calling the $http function is a `promise`, you can also use * the `then` method to register callbacks, and these callbacks will receive a single argument – * an object representing the response. See the API signature and type info below for more * details. * * A response status code between 200 and 299 is considered a success status and * will result in the success callback being called. Note that if the response is a redirect, * XMLHttpRequest will transparently follow it, meaning that the error callback will not be * called for such responses. * * # Writing Unit Tests that use $http * When unit testing (using {@link ngMock ngMock}), it is necessary to call * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending * request using trained responses. * * ``` * $httpBackend.expectGET(...); * $http.get(...); * $httpBackend.flush(); * ``` * * # Shortcut methods * * Shortcut methods are also available. All shortcut methods require passing in the URL, and * request data must be passed in for POST/PUT requests. * * ```js * $http.get('/someUrl').success(successCallback); * $http.post('/someUrl', data).success(successCallback); * ``` * * Complete list of shortcut methods: * * - {@link ng.$http#get $http.get} * - {@link ng.$http#head $http.head} * - {@link ng.$http#post $http.post} * - {@link ng.$http#put $http.put} * - {@link ng.$http#delete $http.delete} * - {@link ng.$http#jsonp $http.jsonp} * * * # Setting HTTP Headers * * The $http service will automatically add certain HTTP headers to all requests. These defaults * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration * object, which currently contains this default configuration: * * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): * - `Accept: application/json, text/plain, * / *` * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests) * - `Content-Type: application/json` * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests) * - `Content-Type: application/json` * * To add or overwrite these defaults, simply add or remove a property from these configuration * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object * with the lowercased HTTP method name as the key, e.g. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }. * * The defaults can also be set at runtime via the `$http.defaults` object in the same * fashion. For example: * * ``` * module.run(function($http) { * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w' * }); * ``` * * In addition, you can supply a `headers` property in the config object passed when * calling `$http(config)`, which overrides the defaults without changing them globally. * * * # Transforming Requests and Responses * * Both requests and responses can be transformed using transform functions. By default, Angular * applies these transformations: * * Request transformations: * * - If the `data` property of the request configuration object contains an object, serialize it * into JSON format. * * Response transformations: * * - If XSRF prefix is detected, strip it (see Security Considerations section below). * - If JSON response is detected, deserialize it using a JSON parser. * * To globally augment or override the default transforms, modify the * `$httpProvider.defaults.transformRequest` and `$httpProvider.defaults.transformResponse` * properties. These properties are by default an array of transform functions, which allows you * to `push` or `unshift` a new transformation function into the transformation chain. You can * also decide to completely override any default transformations by assigning your * transformation functions to these properties directly without the array wrapper. These defaults * are again available on the $http factory at run-time, which may be useful if you have run-time * services you wish to be involved in your transformations. * * Similarly, to locally override the request/response transforms, augment the * `transformRequest` and/or `transformResponse` properties of the configuration object passed * into `$http`. * * * # Caching * * To enable caching, set the request configuration `cache` property to `true` (to use default * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}). * When the cache is enabled, `$http` stores the response from the server in the specified * cache. The next time the same request is made, the response is served from the cache without * sending a request to the server. * * Note that even if the response is served from cache, delivery of the data is asynchronous in * the same way that real requests are. * * If there are multiple GET requests for the same URL that should be cached using the same * cache, but the cache is not populated yet, only one request to the server will be made and * the remaining requests will be fulfilled using the response from the first request. * * You can change the default cache to a new object (built with * {@link ng.$cacheFactory `$cacheFactory`}) by updating the * {@link ng.$http#properties_defaults `$http.defaults.cache`} property. All requests who set * their `cache` property to `true` will now use this cache object. * * If you set the default cache to `false` then only requests that specify their own custom * cache object will be cached. * * # Interceptors * * Before you start creating interceptors, be sure to understand the * {@link ng.$q $q and deferred/promise APIs}. * * For purposes of global error handling, authentication, or any kind of synchronous or * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be * able to intercept requests before they are handed to the server and * responses before they are handed over to the application code that * initiated these requests. The interceptors leverage the {@link ng.$q * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing. * * The interceptors are service factories that are registered with the `$httpProvider` by * adding them to the `$httpProvider.interceptors` array. The factory is called and * injected with dependencies (if specified) and returns the interceptor. * * There are two kinds of interceptors (and two kinds of rejection interceptors): * * * `request`: interceptors get called with a http `config` object. The function is free to * modify the `config` object or create a new one. The function needs to return the `config` * object directly, or a promise containing the `config` or a new `config` object. * * `requestError`: interceptor gets called when a previous interceptor threw an error or * resolved with a rejection. * * `response`: interceptors get called with http `response` object. The function is free to * modify the `response` object or create a new one. The function needs to return the `response` * object directly, or as a promise containing the `response` or a new `response` object. * * `responseError`: interceptor gets called when a previous interceptor threw an error or * resolved with a rejection. * * * ```js * // register the interceptor as a service * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { * return { * // optional method * 'request': function(config) { * // do something on success * return config; * }, * * // optional method * 'requestError': function(rejection) { * // do something on error * if (canRecover(rejection)) { * return responseOrNewPromise * } * return $q.reject(rejection); * }, * * * * // optional method * 'response': function(response) { * // do something on success * return response; * }, * * // optional method * 'responseError': function(rejection) { * // do something on error * if (canRecover(rejection)) { * return responseOrNewPromise * } * return $q.reject(rejection); * } * }; * }); * * $httpProvider.interceptors.push('myHttpInterceptor'); * * * // alternatively, register the interceptor via an anonymous factory * $httpProvider.interceptors.push(function($q, dependency1, dependency2) { * return { * 'request': function(config) { * // same as above * }, * * 'response': function(response) { * // same as above * } * }; * }); * ``` * * # Security Considerations * * When designing web applications, consider security threats from: * * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx) * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) * * Both server and the client must cooperate in order to eliminate these threats. Angular comes * pre-configured with strategies that address these issues, but for this to work backend server * cooperation is required. * * ## JSON Vulnerability Protection * * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx) * allows third party website to turn your JSON resource URL into * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To * counter this your server can prefix all JSON requests with following string `")]}',\n"`. * Angular will automatically strip the prefix before processing it as JSON. * * For example if your server needs to return: * ```js * ['one','two'] * ``` * * which is vulnerable to attack, your server can return: * ```js * )]}', * ['one','two'] * ``` * * Angular will strip the prefix, before processing the JSON. * * * ## Cross Site Request Forgery (XSRF) Protection * * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which * an unauthorized site can gain your user's private data. Angular provides a mechanism * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only * JavaScript that runs on your domain could read the cookie, your server can be assured that * the XHR came from JavaScript running on your domain. The header will not be set for * cross-domain requests. * * To take advantage of this, your server needs to set a token in a JavaScript readable session * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure * that only JavaScript running on your domain could have sent the request. The token must be * unique for each user and must be verifiable by the server (to prevent the JavaScript from * making up its own tokens). We recommend that the token is a digest of your site's * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography)) * for added security. * * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time, * or the per-request config object. * * * @param {object} config Object describing the request to be made and how it should be * processed. The object has following properties: * * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be * JSONified. * - **data** – `{string|Object}` – Data to be sent as the request message data. * - **headers** – `{Object}` – Map of strings or functions which return strings representing * HTTP headers to send to the server. If the return value of a function is null, the * header will not be sent. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token. * - **transformRequest** – * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – * transform function or an array of such functions. The transform function takes the http * request body and headers and returns its transformed (typically serialized) version. * - **transformResponse** – * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – * transform function or an array of such functions. The transform function takes the http * response body and headers and returns its transformed (typically deserialized) version. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the * GET request, otherwise if a cache instance built with * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for * caching. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} * that should abort the request when resolved. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the * XHR object. See [requests with credentials]https://developer.mozilla.org/en/http_access_control#section_5 * for more information. * - **responseType** - `{string}` - see * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType). * * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the * standard `then` method and two http specific methods: `success` and `error`. The `then` * method takes two arguments a success and an error callback which will be called with a * response object. The `success` and `error` methods take a single argument - a function that * will be called when the request succeeds or fails respectively. The arguments passed into * these functions are destructured representation of the response object passed into the * `then` method. The response object has these properties: * * - **data** – `{string|Object}` – The response body transformed with the transform * functions. * - **status** – `{number}` – HTTP status code of the response. * - **headers** – `{function([headerName])}` – Header getter function. * - **config** – `{Object}` – The configuration object that was used to generate the request. * - **statusText** – `{string}` – HTTP status text of the response. * * @property {Array.<Object>} pendingRequests Array of config objects for currently pending * requests. This is primarily meant to be used for debugging purposes. * * * @example <example> <file name="index.html"> <div ng-controller="FetchCtrl"> <select ng-model="method"> <option>GET</option> <option>JSONP</option> </select> <input type="text" ng-model="url" size="80"/> <button id="fetchbtn" ng-click="fetch()">fetch</button><br> <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button> <button id="samplejsonpbtn" ng-click="updateModel('JSONP', 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')"> Sample JSONP </button> <button id="invalidjsonpbtn" ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')"> Invalid JSONP </button> <pre>http status code: {{status}}</pre> <pre>http response data: {{data}}</pre> </div> </file> <file name="script.js"> function FetchCtrl($scope, $http, $templateCache) { $scope.method = 'GET'; $scope.url = 'http-hello.html'; $scope.fetch = function() { $scope.code = null; $scope.response = null; $http({method: $scope.method, url: $scope.url, cache: $templateCache}). success(function(data, status) { $scope.status = status; $scope.data = data; }). error(function(data, status) { $scope.data = data || "Request failed"; $scope.status = status; }); }; $scope.updateModel = function(method, url) { $scope.method = method; $scope.url = url; }; } </file> <file name="http-hello.html"> Hello, $http! </file> <file name="protractor.js" type="protractor"> var status = element(by.binding('status')); var data = element(by.binding('data')); var fetchBtn = element(by.id('fetchbtn')); var sampleGetBtn = element(by.id('samplegetbtn')); var sampleJsonpBtn = element(by.id('samplejsonpbtn')); var invalidJsonpBtn = element(by.id('invalidjsonpbtn')); it('should make an xhr GET request', function() { sampleGetBtn.click(); fetchBtn.click(); expect(status.getText()).toMatch('200'); expect(data.getText()).toMatch(/Hello, \$http!/); }); it('should make a JSONP request to angularjs.org', function() { sampleJsonpBtn.click(); fetchBtn.click(); expect(status.getText()).toMatch('200'); expect(data.getText()).toMatch(/Super Hero!/); }); it('should make JSONP request to invalid URL and invoke the error handler', function() { invalidJsonpBtn.click(); fetchBtn.click(); expect(status.getText()).toMatch('0'); expect(data.getText()).toMatch('Request failed'); }); </file> </example> */ function $http(requestConfig) { var config = { method: 'get', transformRequest: defaults.transformRequest, transformResponse: defaults.transformResponse }; var headers = mergeHeaders(requestConfig); extend(config, requestConfig); config.headers = headers; config.method = uppercase(config.method); var serverRequest = function(config) { headers = config.headers; var reqData = transformData(config.data, headersGetter(headers), config.transformRequest); // strip content-type if data is undefined if (isUndefined(config.data)) { forEach(headers, function(value, header) { if (lowercase(header) === 'content-type') { delete headers[header]; } }); } if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) { config.withCredentials = defaults.withCredentials; } // send request return sendReq(config, reqData, headers).then(transformResponse, transformResponse); }; var chain = [serverRequest, undefined]; var promise = $q.when(config); // apply interceptors forEach(reversedInterceptors, function(interceptor) { if (interceptor.request || interceptor.requestError) { chain.unshift(interceptor.request, interceptor.requestError); } if (interceptor.response || interceptor.responseError) { chain.push(interceptor.response, interceptor.responseError); } }); while(chain.length) { var thenFn = chain.shift(); var rejectFn = chain.shift(); promise = promise.then(thenFn, rejectFn); } promise.success = function(fn) { promise.then(function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; promise.error = function(fn) { promise.then(null, function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; return promise; function transformResponse(response) { // make a copy since the response must be cacheable var resp = extend({}, response, { data: transformData(response.data, response.headers, config.transformResponse) }); return (isSuccess(response.status)) ? resp : $q.reject(resp); } function mergeHeaders(config) { var defHeaders = defaults.headers, reqHeaders = extend({}, config.headers), defHeaderName, lowercaseDefHeaderName, reqHeaderName; defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]); // execute if header value is function execHeaders(defHeaders); execHeaders(reqHeaders); // using for-in instead of forEach to avoid unecessary iteration after header has been found defaultHeadersIteration: for (defHeaderName in defHeaders) { lowercaseDefHeaderName = lowercase(defHeaderName); for (reqHeaderName in reqHeaders) { if (lowercase(reqHeaderName) === lowercaseDefHeaderName) { continue defaultHeadersIteration; } } reqHeaders[defHeaderName] = defHeaders[defHeaderName]; } return reqHeaders; function execHeaders(headers) { var headerContent; forEach(headers, function(headerFn, header) { if (isFunction(headerFn)) { headerContent = headerFn(); if (headerContent != null) { headers[header] = headerContent; } else { delete headers[header]; } } }); } } } $http.pendingRequests = []; /** * @ngdoc method * @name $http#get * * @description * Shortcut method to perform `GET` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name $http#delete * * @description * Shortcut method to perform `DELETE` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name $http#head * * @description * Shortcut method to perform `HEAD` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name $http#jsonp * * @description * Shortcut method to perform `JSONP` request. * * @param {string} url Relative or absolute URL specifying the destination of the request. * Should contain `JSON_CALLBACK` string. * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ createShortMethods('get', 'delete', 'head', 'jsonp'); /** * @ngdoc method * @name $http#post * * @description * Shortcut method to perform `POST` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name $http#put * * @description * Shortcut method to perform `PUT` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ createShortMethodsWithData('post', 'put'); /** * @ngdoc property * @name $http#defaults * * @description * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of * default headers, withCredentials as well as request and response transformations. * * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above. */ $http.defaults = defaults; return $http; function createShortMethods(names) { forEach(arguments, function(name) { $http[name] = function(url, config) { return $http(extend(config || {}, { method: name, url: url })); }; }); } function createShortMethodsWithData(name) { forEach(arguments, function(name) { $http[name] = function(url, data, config) { return $http(extend(config || {}, { method: name, url: url, data: data })); }; }); } /** * Makes the request. * * !!! ACCESSES CLOSURE VARS: * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests */ function sendReq(config, reqData, reqHeaders) { var deferred = $q.defer(), promise = deferred.promise, cache, cachedResp, url = buildUrl(config.url, config.params); $http.pendingRequests.push(config); promise.then(removePendingReq, removePendingReq); if ((config.cache || defaults.cache) && config.cache !== false && config.method == 'GET') { cache = isObject(config.cache) ? config.cache : isObject(defaults.cache) ? defaults.cache : defaultCache; } if (cache) { cachedResp = cache.get(url); if (isDefined(cachedResp)) { if (cachedResp.then) { // cached request has already been sent, but there is no response yet cachedResp.then(removePendingReq, removePendingReq); return cachedResp; } else { // serving from cache if (isArray(cachedResp)) { resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]); } else { resolvePromise(cachedResp, 200, {}, 'OK'); } } } else { // put the promise for the non-transformed response into cache as a placeholder cache.put(url, promise); } } // if we won't have the response in cache, set the xsrf headers and // send the request to the backend if (isUndefined(cachedResp)) { var xsrfValue = urlIsSameOrigin(config.url) ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName] : undefined; if (xsrfValue) { reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue; } $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, config.withCredentials, config.responseType); } return promise; /** * Callback registered to $httpBackend(): * - caches the response if desired * - resolves the raw $http promise * - calls $apply */ function done(status, response, headersString, statusText) { if (cache) { if (isSuccess(status)) { cache.put(url, [status, response, parseHeaders(headersString), statusText]); } else { // remove promise from the cache cache.remove(url); } } resolvePromise(response, status, headersString, statusText); if (!$rootScope.$$phase) $rootScope.$apply(); } /** * Resolves the raw $http promise. */ function resolvePromise(response, status, headers, statusText) { // normalize internal statuses to 0 status = Math.max(status, 0); (isSuccess(status) ? deferred.resolve : deferred.reject)({ data: response, status: status, headers: headersGetter(headers), config: config, statusText : statusText }); } function removePendingReq() { var idx = indexOf($http.pendingRequests, config); if (idx !== -1) $http.pendingRequests.splice(idx, 1); } } function buildUrl(url, params) { if (!params) return url; var parts = []; forEachSorted(params, function(value, key) { if (value === null || isUndefined(value)) return; if (!isArray(value)) value = [value]; forEach(value, function(v) { if (isObject(v)) { v = toJson(v); } parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(v)); }); }); if(parts.length > 0) { url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); } return url; } }]; } function createXhr(method) { //if IE and the method is not RFC2616 compliant, or if XMLHttpRequest //is not available, try getting an ActiveXObject. Otherwise, use XMLHttpRequest //if it is available if (msie <= 8 && (!method.match(/^(get|post|head|put|delete|options)$/i) || !window.XMLHttpRequest)) { return new window.ActiveXObject("Microsoft.XMLHTTP"); } else if (window.XMLHttpRequest) { return new window.XMLHttpRequest(); } throw minErr('$httpBackend')('noxhr', "This browser does not support XMLHttpRequest."); } /** * @ngdoc service * @name $httpBackend * @requires $window * @requires $document * * @description * HTTP backend used by the {@link ng.$http service} that delegates to * XMLHttpRequest object or JSONP and deals with browser incompatibilities. * * You should never need to use this service directly, instead use the higher-level abstractions: * {@link ng.$http $http} or {@link ngResource.$resource $resource}. * * During testing this implementation is swapped with {@link ngMock.$httpBackend mock * $httpBackend} which can be trained with responses. */ function $HttpBackendProvider() { this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) { return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]); }]; } function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) { var ABORTED = -1; // TODO(vojta): fix the signature return function(method, url, post, callback, headers, timeout, withCredentials, responseType) { var status; $browser.$$incOutstandingRequestCount(); url = url || $browser.url(); if (lowercase(method) == 'jsonp') { var callbackId = '_' + (callbacks.counter++).toString(36); callbacks[callbackId] = function(data) { callbacks[callbackId].data = data; callbacks[callbackId].called = true; }; var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), callbackId, function(status, text) { completeRequest(callback, status, callbacks[callbackId].data, "", text); callbacks[callbackId] = noop; }); } else { var xhr = createXhr(method); xhr.open(method, url, true); forEach(headers, function(value, key) { if (isDefined(value)) { xhr.setRequestHeader(key, value); } }); // In IE6 and 7, this might be called synchronously when xhr.send below is called and the // response is in the cache. the promise api will ensure that to the app code the api is // always async xhr.onreadystatechange = function() { // onreadystatechange might get called multiple times with readyState === 4 on mobile webkit caused by // xhrs that are resolved while the app is in the background (see #5426). // since calling completeRequest sets the `xhr` variable to null, we just check if it's not null before // continuing // // we can't set xhr.onreadystatechange to undefined or delete it because that breaks IE8 (method=PATCH) and // Safari respectively. if (xhr && xhr.readyState == 4) { var responseHeaders = null, response = null; if(status !== ABORTED) { responseHeaders = xhr.getAllResponseHeaders(); // responseText is the old-school way of retrieving response (supported by IE8 & 9) // response/responseType properties were introduced in XHR Level2 spec (supported by IE10) response = ('response' in xhr) ? xhr.response : xhr.responseText; } completeRequest(callback, status || xhr.status, response, responseHeaders, xhr.statusText || ''); } }; if (withCredentials) { xhr.withCredentials = true; } if (responseType) { try { xhr.responseType = responseType; } catch (e) { // WebKit added support for the json responseType value on 09/03/2013 // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are // known to throw when setting the value "json" as the response type. Other older // browsers implementing the responseType // // The json response type can be ignored if not supported, because JSON payloads are // parsed on the client-side regardless. if (responseType !== 'json') { throw e; } } } xhr.send(post || null); } if (timeout > 0) { var timeoutId = $browserDefer(timeoutRequest, timeout); } else if (timeout && timeout.then) { timeout.then(timeoutRequest); } function timeoutRequest() { status = ABORTED; jsonpDone && jsonpDone(); xhr && xhr.abort(); } function completeRequest(callback, status, response, headersString, statusText) { // cancel timeout and subsequent timeout promise resolution timeoutId && $browserDefer.cancel(timeoutId); jsonpDone = xhr = null; // fix status code when it is 0 (0 status is undocumented). // Occurs when accessing file resources or on Android 4.1 stock browser // while retrieving files from application cache. if (status === 0) { status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0; } // normalize IE bug (http://bugs.jquery.com/ticket/1450) status = status === 1223 ? 204 : status; statusText = statusText || ''; callback(status, response, headersString, statusText); $browser.$$completeOutstandingRequest(noop); } }; function jsonpReq(url, callbackId, done) { // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: // - fetches local scripts via XHR and evals them // - adds and immediately removes script elements from the document var script = rawDocument.createElement('script'), callback = null; script.type = "text/javascript"; script.src = url; script.async = true; callback = function(event) { removeEventListenerFn(script, "load", callback); removeEventListenerFn(script, "error", callback); rawDocument.body.removeChild(script); script = null; var status = -1; var text = "unknown"; if (event) { if (event.type === "load" && !callbacks[callbackId].called) { event = { type: "error" }; } text = event.type; status = event.type === "error" ? 404 : 200; } if (done) { done(status, text); } }; addEventListenerFn(script, "load", callback); addEventListenerFn(script, "error", callback); rawDocument.body.appendChild(script); return callback; } } var $interpolateMinErr = minErr('$interpolate'); /** * @ngdoc provider * @name $interpolateProvider * @kind function * * @description * * Used for configuring the interpolation markup. Defaults to `{{` and `}}`. * * @example <example module="customInterpolationApp"> <file name="index.html"> <script> var customInterpolationApp = angular.module('customInterpolationApp', []); customInterpolationApp.config(function($interpolateProvider) { $interpolateProvider.startSymbol('//'); $interpolateProvider.endSymbol('//'); }); customInterpolationApp.controller('DemoController', function() { this.label = "This binding is brought you by // interpolation symbols."; }); </script> <div ng-app="App" ng-controller="DemoController as demo"> //demo.label// </div> </file> <file name="protractor.js" type="protractor"> it('should interpolate binding with custom symbols', function() { expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.'); }); </file> </example> */ function $InterpolateProvider() { var startSymbol = '{{'; var endSymbol = '}}'; /** * @ngdoc method * @name $interpolateProvider#startSymbol * @description * Symbol to denote start of expression in the interpolated string. Defaults to `{{`. * * @param {string=} value new value to set the starting symbol to. * @returns {string|self} Returns the symbol when used as getter and self if used as setter. */ this.startSymbol = function(value){ if (value) { startSymbol = value; return this; } else { return startSymbol; } }; /** * @ngdoc method * @name $interpolateProvider#endSymbol * @description * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. * * @param {string=} value new value to set the ending symbol to. * @returns {string|self} Returns the symbol when used as getter and self if used as setter. */ this.endSymbol = function(value){ if (value) { endSymbol = value; return this; } else { return endSymbol; } }; this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) { var startSymbolLength = startSymbol.length, endSymbolLength = endSymbol.length, escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'), escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g'); function escape(ch) { return '\\\\\\' + ch; } /** * @ngdoc service * @name $interpolate * @kind function * * @requires $parse * @requires $sce * * @description * * Compiles a string with markup into an interpolation function. This service is used by the * HTML {@link ng.$compile $compile} service for data binding. See * {@link ng.$interpolateProvider $interpolateProvider} for configuring the * interpolation markup. * * * ```js * var $interpolate = ...; // injected * var exp = $interpolate('Hello {{name | uppercase}}!'); * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!'); * ``` * * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is * `true`, the interpolation function will return `undefined` unless all embedded expressions * evaluate to a value other than `undefined`. * * ```js * var $interpolate = ...; // injected * var context = {greeting: 'Hello', name: undefined }; * * // default "forgiving" mode * var exp = $interpolate('{{greeting}} {{name}}!'); * expect(exp(context)).toEqual('Hello !'); * * // "allOrNothing" mode * exp = $interpolate('{{greeting}} {{name}}!', false, null, true); * expect(exp(context, true)).toBeUndefined(); * context.name = 'Angular'; * expect(exp(context, true)).toEqual('Hello Angular!'); * ``` * * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior. * * ####Escaped Interpolation * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash). * It will be rendered as a regular start/end marker, and will not be interpreted as an expression * or binding. * * This enables web-servers to prevent script injection attacks and defacing attacks, to some * degree, while also enabling code examples to work without relying on the * {@link ng.directive:ngNonBindable ngNonBindable} directive. * * **For security purposes, it is strongly encouraged that web servers escape user-supplied data, * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all * interpolation start/end markers with their escaped counterparts.** * * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered * output when the $interpolate service processes the text. So, for HTML elements interpolated * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such, * this is typically useful only when user-data is used in rendering a template from the server, or * when otherwise untrusted data is used by a directive. * * <example> * <file name="index.html"> * <div ng-init="username='A user'"> * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\} * </p> * <p><strong>{{username}}</strong> attempts to inject code which will deface the * application, but fails to accomplish their task, because the server has correctly * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash) * characters.</p> * <p>Instead, the result of the attempted script injection is visible, and can be removed * from the database by an administrator.</p> * </div> * </file> * </example> * * @param {string} text The text with markup to interpolate. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have * embedded expression in order to return an interpolation function. Strings with no * embedded expression will return null for the interpolation function. * @param {string=} trustedContext when provided, the returned function passes the interpolated * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult, * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that * provides Strict Contextual Escaping for details. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined * unless all embedded expressions evaluate to a value other than `undefined`. * @returns {function(context)} an interpolation function which is used to compute the * interpolated string. The function has these parameters: * * - `context`: evaluation context for all expressions embedded in the interpolated text */ function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) { allOrNothing = !!allOrNothing; var startIndex, endIndex, index = 0, separators = [], expressions = [], parseFns = [], textLength = text.length, hasInterpolation = false, hasText = false, exp, concat = [], lastValuesCache = { values: {}, results: {}}; while(index < textLength) { if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) && ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) { if (index !== startIndex) hasText = true; separators.push(text.substring(index, startIndex)); exp = text.substring(startIndex + startSymbolLength, endIndex); expressions.push(exp); parseFns.push($parse(exp)); index = endIndex + endSymbolLength; hasInterpolation = true; } else { // we did not find an interpolation, so we have to add the remainder to the separators array if (index !== textLength) { hasText = true; separators.push(text.substring(index)); } break; } } forEach(separators, function(key, i) { separators[i] = separators[i]. replace(escapedStartRegexp, startSymbol). replace(escapedEndRegexp, endSymbol); }); if (separators.length === expressions.length) { separators.push(''); } // Concatenating expressions makes it hard to reason about whether some combination of // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a // single expression be used for iframe[src], object[src], etc., we ensure that the value // that's used is assigned or constructed by some JS code somewhere that is more testable or // make it obvious that you bound the value to some user controlled value. This helps reduce // the load when auditing for XSS issues. if (trustedContext && hasInterpolation && (hasText || expressions.length > 1)) { throw $interpolateMinErr('noconcat', "Error while interpolating: {0}\nStrict Contextual Escaping disallows " + "interpolations that concatenate multiple expressions when a trusted value is " + "required. See http://docs.angularjs.org/api/ng.$sce", text); } if (!mustHaveExpression || hasInterpolation) { concat.length = separators.length + expressions.length; var compute = function(values) { for(var i = 0, ii = expressions.length; i < ii; i++) { concat[2*i] = separators[i]; concat[(2*i)+1] = values[i]; } concat[2*ii] = separators[ii]; return concat.join(''); }; var getValue = function (value) { if (trustedContext) { value = $sce.getTrusted(trustedContext, value); } else { value = $sce.valueOf(value); } return value; }; var stringify = function (value) { if (value == null) { // null || undefined return ''; } switch (typeof value) { case 'string': { break; } case 'number': { value = '' + value; break; } default: { value = toJson(value); } } return value; }; return extend(function interpolationFn(context) { var scopeId = (context && context.$id) || 'notAScope'; var lastValues = lastValuesCache.values[scopeId]; var lastResult = lastValuesCache.results[scopeId]; var i = 0; var ii = expressions.length; var values = new Array(ii); var val; var inputsChanged = lastResult === undefined ? true: false; // if we haven't seen this context before, initialize the cache and try to setup // a cleanup routine that purges the cache when the scope goes away. if (!lastValues) { lastValues = []; inputsChanged = true; if (context && context.$on) { context.$on('$destroy', function() { lastValuesCache.values[scopeId] = null; lastValuesCache.results[scopeId] = null; }); } } try { interpolationFn.$$unwatch = true; for (; i < ii; i++) { val = getValue(parseFns[i](context)); if (allOrNothing && isUndefined(val)) { interpolationFn.$$unwatch = undefined; return; } val = stringify(val); if (val !== lastValues[i]) { inputsChanged = true; } values[i] = val; interpolationFn.$$unwatch = interpolationFn.$$unwatch && parseFns[i].$$unwatch; } if (inputsChanged) { lastValuesCache.values[scopeId] = values; lastValuesCache.results[scopeId] = lastResult = compute(values); } } catch(err) { var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString()); $exceptionHandler(newErr); } return lastResult; }, { // all of these properties are undocumented for now exp: text, //just for compatibility with regular watchers created via $watch separators: separators, expressions: expressions }); } } /** * @ngdoc method * @name $interpolate#startSymbol * @description * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`. * * Use {@link ng.$interpolateProvider#startSymbol $interpolateProvider#startSymbol} to change * the symbol. * * @returns {string} start symbol. */ $interpolate.startSymbol = function() { return startSymbol; }; /** * @ngdoc method * @name $interpolate#endSymbol * @description * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. * * Use {@link ng.$interpolateProvider#endSymbol $interpolateProvider#endSymbol} to change * the symbol. * * @returns {string} end symbol. */ $interpolate.endSymbol = function() { return endSymbol; }; return $interpolate; }]; } function $IntervalProvider() { this.$get = ['$rootScope', '$window', '$q', function($rootScope, $window, $q) { var intervals = {}; /** * @ngdoc service * @name $interval * * @description * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay` * milliseconds. * * The return value of registering an interval function is a promise. This promise will be * notified upon each tick of the interval, and will be resolved after `count` iterations, or * run indefinitely if `count` is not defined. The value of the notification will be the * number of iterations that have run. * To cancel an interval, call `$interval.cancel(promise)`. * * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to * move forward by `millis` milliseconds and trigger any functions scheduled to run in that * time. * * <div class="alert alert-warning"> * **Note**: Intervals created by this service must be explicitly destroyed when you are finished * with them. In particular they are not automatically destroyed when a controller's scope or a * directive's element are destroyed. * You should take this into consideration and make sure to always cancel the interval at the * appropriate moment. See the example below for more details on how and when to do this. * </div> * * @param {function()} fn A function that should be called repeatedly. * @param {number} delay Number of milliseconds between each function call. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat * indefinitely. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. * @returns {promise} A promise which will be notified on each iteration. * * @example * <example module="time"> * <file name="index.html"> * <script> * function Ctrl2($scope,$interval) { * $scope.format = 'M/d/yy h:mm:ss a'; * $scope.blood_1 = 100; * $scope.blood_2 = 120; * * var stop; * $scope.fight = function() { * // Don't start a new fight if we are already fighting * if ( angular.isDefined(stop) ) return; * * stop = $interval(function() { * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) { * $scope.blood_1 = $scope.blood_1 - 3; * $scope.blood_2 = $scope.blood_2 - 4; * } else { * $scope.stopFight(); * } * }, 100); * }; * * $scope.stopFight = function() { * if (angular.isDefined(stop)) { * $interval.cancel(stop); * stop = undefined; * } * }; * * $scope.resetFight = function() { * $scope.blood_1 = 100; * $scope.blood_2 = 120; * } * * $scope.$on('$destroy', function() { * // Make sure that the interval is destroyed too * $scope.stopFight(); * }); * } * * angular.module('time', []) * // Register the 'myCurrentTime' directive factory method. * // We inject $interval and dateFilter service since the factory method is DI. * .directive('myCurrentTime', function($interval, dateFilter) { * // return the directive link function. (compile function not needed) * return function(scope, element, attrs) { * var format, // date format * stopTime; // so that we can cancel the time updates * * // used to update the UI * function updateTime() { * element.text(dateFilter(new Date(), format)); * } * * // watch the expression, and update the UI on change. * scope.$watch(attrs.myCurrentTime, function(value) { * format = value; * updateTime(); * }); * * stopTime = $interval(updateTime, 1000); * * // listen on DOM destroy (removal) event, and cancel the next UI update * // to prevent updating time ofter the DOM element was removed. * element.on('$destroy', function() { * $interval.cancel(stopTime); * }); * } * }); * </script> * * <div> * <div ng-controller="Ctrl2"> * Date format: <input ng-model="format"> <hr/> * Current time is: <span my-current-time="format"></span> * <hr/> * Blood 1 : <font color='red'>{{blood_1}}</font> * Blood 2 : <font color='red'>{{blood_2}}</font> * <button type="button" data-ng-click="fight()">Fight</button> * <button type="button" data-ng-click="stopFight()">StopFight</button> * <button type="button" data-ng-click="resetFight()">resetFight</button> * </div> * </div> * * </file> * </example> */ function interval(fn, delay, count, invokeApply) { var setInterval = $window.setInterval, clearInterval = $window.clearInterval, deferred = $q.defer(), promise = deferred.promise, iteration = 0, skipApply = (isDefined(invokeApply) && !invokeApply); count = isDefined(count) ? count : 0; promise.then(null, null, fn); promise.$$intervalId = setInterval(function tick() { deferred.notify(iteration++); if (count > 0 && iteration >= count) { deferred.resolve(iteration); clearInterval(promise.$$intervalId); delete intervals[promise.$$intervalId]; } if (!skipApply) $rootScope.$apply(); }, delay); intervals[promise.$$intervalId] = deferred; return promise; } /** * @ngdoc method * @name $interval#cancel * * @description * Cancels a task associated with the `promise`. * * @param {promise} promise returned by the `$interval` function. * @returns {boolean} Returns `true` if the task was successfully canceled. */ interval.cancel = function(promise) { if (promise && promise.$$intervalId in intervals) { intervals[promise.$$intervalId].reject('canceled'); clearInterval(promise.$$intervalId); delete intervals[promise.$$intervalId]; return true; } return false; }; return interval; }]; } /** * @ngdoc service * @name $locale * * @description * $locale service provides localization rules for various Angular components. As of right now the * only public api is: * * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) */ function $LocaleProvider(){ this.$get = function() { return { id: 'en-us', NUMBER_FORMATS: { DECIMAL_SEP: '.', GROUP_SEP: ',', PATTERNS: [ { // Decimal Pattern minInt: 1, minFrac: 0, maxFrac: 3, posPre: '', posSuf: '', negPre: '-', negSuf: '', gSize: 3, lgSize: 3 },{ //Currency Pattern minInt: 1, minFrac: 2, maxFrac: 2, posPre: '\u00A4', posSuf: '', negPre: '(\u00A4', negSuf: ')', gSize: 3, lgSize: 3 } ], CURRENCY_SYM: '$' }, DATETIME_FORMATS: { MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December' .split(','), SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','), AMPMS: ['AM','PM'], medium: 'MMM d, y h:mm:ss a', short: 'M/d/yy h:mm a', fullDate: 'EEEE, MMMM d, y', longDate: 'MMMM d, y', mediumDate: 'MMM d, y', shortDate: 'M/d/yy', mediumTime: 'h:mm:ss a', shortTime: 'h:mm a' }, pluralCat: function(num) { if (num === 1) { return 'one'; } return 'other'; } }; }; } var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/, DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21}; var $locationMinErr = minErr('$location'); /** * Encode path using encodeUriSegment, ignoring forward slashes * * @param {string} path Path to encode * @returns {string} */ function encodePath(path) { var segments = path.split('/'), i = segments.length; while (i--) { segments[i] = encodeUriSegment(segments[i]); } return segments.join('/'); } function parseAbsoluteUrl(absoluteUrl, locationObj, appBase) { var parsedUrl = urlResolve(absoluteUrl, appBase); locationObj.$$protocol = parsedUrl.protocol; locationObj.$$host = parsedUrl.hostname; locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null; } function parseAppUrl(relativeUrl, locationObj, appBase) { var prefixed = (relativeUrl.charAt(0) !== '/'); if (prefixed) { relativeUrl = '/' + relativeUrl; } var match = urlResolve(relativeUrl, appBase); locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ? match.pathname.substring(1) : match.pathname); locationObj.$$search = parseKeyValue(match.search); locationObj.$$hash = decodeURIComponent(match.hash); // make sure path starts with '/'; if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') { locationObj.$$path = '/' + locationObj.$$path; } } /** * * @param {string} begin * @param {string} whole * @returns {string} returns text from whole after begin or undefined if it does not begin with * expected string. */ function beginsWith(begin, whole) { if (whole.indexOf(begin) === 0) { return whole.substr(begin.length); } } function stripHash(url) { var index = url.indexOf('#'); return index == -1 ? url : url.substr(0, index); } function stripFile(url) { return url.substr(0, stripHash(url).lastIndexOf('/') + 1); } /* return the server only (scheme://host:port) */ function serverBase(url) { return url.substring(0, url.indexOf('/', url.indexOf('//') + 2)); } /** * LocationHtml5Url represents an url * This object is exposed as $location service when HTML5 mode is enabled and supported * * @constructor * @param {string} appBase application base URL * @param {string} basePrefix url path prefix */ function LocationHtml5Url(appBase, basePrefix) { this.$$html5 = true; basePrefix = basePrefix || ''; var appBaseNoFile = stripFile(appBase); parseAbsoluteUrl(appBase, this, appBase); /** * Parse given html5 (regular) url string into properties * @param {string} newAbsoluteUrl HTML5 url * @private */ this.$$parse = function(url) { var pathUrl = beginsWith(appBaseNoFile, url); if (!isString(pathUrl)) { throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url, appBaseNoFile); } parseAppUrl(pathUrl, this, appBase); if (!this.$$path) { this.$$path = '/'; } this.$$compose(); }; /** * Compose url and update `absUrl` property * @private */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/' }; this.$$rewrite = function(url) { var appUrl, prevAppUrl; if ( (appUrl = beginsWith(appBase, url)) !== undefined ) { prevAppUrl = appUrl; if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) { return appBaseNoFile + (beginsWith('/', appUrl) || appUrl); } else { return appBase + prevAppUrl; } } else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) { return appBaseNoFile + appUrl; } else if (appBaseNoFile == url + '/') { return appBaseNoFile; } }; } /** * LocationHashbangUrl represents url * This object is exposed as $location service when developer doesn't opt into html5 mode. * It also serves as the base class for html5 mode fallback on legacy browsers. * * @constructor * @param {string} appBase application base URL * @param {string} hashPrefix hashbang prefix */ function LocationHashbangUrl(appBase, hashPrefix) { var appBaseNoFile = stripFile(appBase); parseAbsoluteUrl(appBase, this, appBase); /** * Parse given hashbang url into properties * @param {string} url Hashbang url * @private */ this.$$parse = function(url) { var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url); var withoutHashUrl = withoutBaseUrl.charAt(0) == '#' ? beginsWith(hashPrefix, withoutBaseUrl) : (this.$$html5) ? withoutBaseUrl : ''; if (!isString(withoutHashUrl)) { throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url, hashPrefix); } parseAppUrl(withoutHashUrl, this, appBase); this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase); this.$$compose(); /* * In Windows, on an anchor node on documents loaded from * the filesystem, the browser will return a pathname * prefixed with the drive name ('/C:/path') when a * pathname without a drive is set: * * a.setAttribute('href', '/foo') * * a.pathname === '/C:/foo' //true * * Inside of Angular, we're always using pathnames that * do not include drive names for routing. */ function removeWindowsDriveName (path, url, base) { /* Matches paths for file protocol on windows, such as /C:/foo/bar, and captures only /foo/bar. */ var windowsFilePathExp = /^\/[A-Z]:(\/.*)/; var firstPathSegmentMatch; //Get the relative path from the input URL. if (url.indexOf(base) === 0) { url = url.replace(base, ''); } // The input URL intentionally contains a first path segment that ends with a colon. if (windowsFilePathExp.exec(url)) { return path; } firstPathSegmentMatch = windowsFilePathExp.exec(path); return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path; } }; /** * Compose hashbang url and update `absUrl` property * @private */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : ''); }; this.$$rewrite = function(url) { if(stripHash(appBase) == stripHash(url)) { return url; } }; } /** * LocationHashbangUrl represents url * This object is exposed as $location service when html5 history api is enabled but the browser * does not support it. * * @constructor * @param {string} appBase application base URL * @param {string} hashPrefix hashbang prefix */ function LocationHashbangInHtml5Url(appBase, hashPrefix) { this.$$html5 = true; LocationHashbangUrl.apply(this, arguments); var appBaseNoFile = stripFile(appBase); this.$$rewrite = function(url) { var appUrl; if ( appBase == stripHash(url) ) { return url; } else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) { return appBase + hashPrefix + appUrl; } else if ( appBaseNoFile === url + '/') { return appBaseNoFile; } }; this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#' this.$$absUrl = appBase + hashPrefix + this.$$url; }; } LocationHashbangInHtml5Url.prototype = LocationHashbangUrl.prototype = LocationHtml5Url.prototype = { /** * Are we in html5 mode? * @private */ $$html5: false, /** * Has any change been replacing ? * @private */ $$replace: false, /** * @ngdoc method * @name $location#absUrl * * @description * This method is getter only. * * Return full url representation with all segments encoded according to rules specified in * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt). * * @return {string} full url */ absUrl: locationGetter('$$absUrl'), /** * @ngdoc method * @name $location#url * * @description * This method is getter / setter. * * Return url (e.g. `/path?a=b#hash`) when called without any parameter. * * Change path, search and hash, when called with parameter and return `$location`. * * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`) * @param {string=} replace The path that will be changed * @return {string} url */ url: function(url, replace) { if (isUndefined(url)) return this.$$url; var match = PATH_MATCH.exec(url); if (match[1]) this.path(decodeURIComponent(match[1])); if (match[2] || match[1]) this.search(match[3] || ''); this.hash(match[5] || '', replace); return this; }, /** * @ngdoc method * @name $location#protocol * * @description * This method is getter only. * * Return protocol of current url. * * @return {string} protocol of current url */ protocol: locationGetter('$$protocol'), /** * @ngdoc method * @name $location#host * * @description * This method is getter only. * * Return host of current url. * * @return {string} host of current url. */ host: locationGetter('$$host'), /** * @ngdoc method * @name $location#port * * @description * This method is getter only. * * Return port of current url. * * @return {Number} port */ port: locationGetter('$$port'), /** * @ngdoc method * @name $location#path * * @description * This method is getter / setter. * * Return path of current url when called without any parameter. * * Change path when called with parameter and return `$location`. * * Note: Path should always begin with forward slash (/), this method will add the forward slash * if it is missing. * * @param {string=} path New path * @return {string} path */ path: locationGetterSetter('$$path', function(path) { return path.charAt(0) == '/' ? path : '/' + path; }), /** * @ngdoc method * @name $location#search * * @description * This method is getter / setter. * * Return search part (as object) of current url when called without any parameter. * * Change search part when called with parameter and return `$location`. * * * ```js * // given url http://example.com/#/some/path?foo=bar&baz=xoxo * var searchObject = $location.search(); * // => {foo: 'bar', baz: 'xoxo'} * * * // set foo to 'yipee' * $location.search('foo', 'yipee'); * // => $location * ``` * * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or * hash object. * * When called with a single argument the method acts as a setter, setting the `search` component * of `$location` to the specified value. * * If the argument is a hash object containing an array of values, these values will be encoded * as duplicate search parameters in the url. * * @param {(string|Array<string>)=} paramValue If `search` is a string, then `paramValue` will * override only a single search property. * * If `paramValue` is an array, it will override the property of the `search` component of * `$location` specified via the first argument. * * If `paramValue` is `null`, the property specified via the first argument will be deleted. * * @return {Object} If called with no arguments returns the parsed `search` object. If called with * one or more arguments returns `$location` object itself. */ search: function(search, paramValue) { switch (arguments.length) { case 0: return this.$$search; case 1: if (isString(search)) { this.$$search = parseKeyValue(search); } else if (isObject(search)) { this.$$search = search; } else { throw $locationMinErr('isrcharg', 'The first argument of the `$location#search()` call must be a string or an object.'); } break; default: if (isUndefined(paramValue) || paramValue === null) { delete this.$$search[search]; } else { this.$$search[search] = paramValue; } } this.$$compose(); return this; }, /** * @ngdoc method * @name $location#hash * * @description * This method is getter / setter. * * Return hash fragment when called without any parameter. * * Change hash fragment when called with parameter and return `$location`. * * @param {string=} hash New hash fragment * @return {string} hash */ hash: locationGetterSetter('$$hash', identity), /** * @ngdoc method * @name $location#replace * * @description * If called, all changes to $location during current `$digest` will be replacing current history * record, instead of adding new one. */ replace: function() { this.$$replace = true; return this; } }; function locationGetter(property) { return function() { return this[property]; }; } function locationGetterSetter(property, preprocess) { return function(value) { if (isUndefined(value)) return this[property]; this[property] = preprocess(value); this.$$compose(); return this; }; } /** * @ngdoc service * @name $location * * @requires $rootElement * * @description * The $location service parses the URL in the browser address bar (based on the * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL * available to your application. Changes to the URL in the address bar are reflected into * $location service and changes to $location are reflected into the browser address bar. * * **The $location service:** * * - Exposes the current URL in the browser address bar, so you can * - Watch and observe the URL. * - Change the URL. * - Synchronizes the URL with the browser when the user * - Changes the address bar. * - Clicks the back or forward button (or clicks a History link). * - Clicks on a link. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash). * * For more information see {@link guide/$location Developer Guide: Using $location} */ /** * @ngdoc provider * @name $locationProvider * @description * Use the `$locationProvider` to configure how the application deep linking paths are stored. */ function $LocationProvider(){ var hashPrefix = '', html5Mode = false; /** * @ngdoc property * @name $locationProvider#hashPrefix * @description * @param {string=} prefix Prefix for hash part (containing path and search) * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.hashPrefix = function(prefix) { if (isDefined(prefix)) { hashPrefix = prefix; return this; } else { return hashPrefix; } }; /** * @ngdoc property * @name $locationProvider#html5Mode * @description * @param {boolean=} mode Use HTML5 strategy if available. * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.html5Mode = function(mode) { if (isDefined(mode)) { html5Mode = mode; return this; } else { return html5Mode; } }; /** * @ngdoc event * @name $location#$locationChangeStart * @eventType broadcast on root scope * @description * Broadcasted before a URL will change. This change can be prevented by calling * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more * details about event object. Upon successful change * {@link ng.$location#events_$locationChangeSuccess $locationChangeSuccess} is fired. * * @param {Object} angularEvent Synthetic event object. * @param {string} newUrl New URL * @param {string=} oldUrl URL that was before it was changed. */ /** * @ngdoc event * @name $location#$locationChangeSuccess * @eventType broadcast on root scope * @description * Broadcasted after a URL was changed. * * @param {Object} angularEvent Synthetic event object. * @param {string} newUrl New URL * @param {string=} oldUrl URL that was before it was changed. */ this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', function( $rootScope, $browser, $sniffer, $rootElement) { var $location, LocationMode, baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to '' initialUrl = $browser.url(), appBase; if (html5Mode) { appBase = serverBase(initialUrl) + (baseHref || '/'); LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url; } else { appBase = stripHash(initialUrl); LocationMode = LocationHashbangUrl; } $location = new LocationMode(appBase, '#' + hashPrefix); $location.$$parse($location.$$rewrite(initialUrl)); $rootElement.on('click', function(event) { // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser) // currently we open nice url link and redirect then if (event.ctrlKey || event.metaKey || event.which == 2) return; var elm = jqLite(event.target); // traverse the DOM up to find first A tag while (lowercase(elm[0].nodeName) !== 'a') { // ignore rewriting if no A tag (reached root element, or no parent - removed from document) if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return; } var absHref = elm.prop('href'); if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') { // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during // an animation. absHref = urlResolve(absHref.animVal).href; } // Make relative links work in HTML5 mode for legacy browsers (or at least IE8 & 9) // The href should be a regular url e.g. /link/somewhere or link/somewhere or ../somewhere or // somewhere#anchor or http://example.com/somewhere if (LocationMode === LocationHashbangInHtml5Url) { // get the actual href attribute - see // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx var href = elm.attr('href') || elm.attr('xlink:href'); if (href.indexOf('://') < 0) { // Ignore absolute URLs var prefix = '#' + hashPrefix; if (href[0] == '/') { // absolute path - replace old path absHref = appBase + prefix + href; } else if (href[0] == '#') { // local anchor absHref = appBase + prefix + ($location.path() || '/') + href; } else { // relative path - join with current path var stack = $location.path().split("/"), parts = href.split("/"); for (var i=0; i<parts.length; i++) { if (parts[i] == ".") continue; else if (parts[i] == "..") stack.pop(); else if (parts[i].length) stack.push(parts[i]); } absHref = appBase + prefix + stack.join('/'); } } } var rewrittenUrl = $location.$$rewrite(absHref); if (absHref && !elm.attr('target') && rewrittenUrl && !event.isDefaultPrevented()) { event.preventDefault(); if (rewrittenUrl != $browser.url()) { // update location manually $location.$$parse(rewrittenUrl); $rootScope.$apply(); // hack to work around FF6 bug 684208 when scenario runner clicks on links window.angular['ff-684208-preventDefault'] = true; } } }); // rewrite hashbang url <> html5 url if ($location.absUrl() != initialUrl) { $browser.url($location.absUrl(), true); } // update $location when $browser url changes $browser.onUrlChange(function(newUrl) { if ($location.absUrl() != newUrl) { $rootScope.$evalAsync(function() { var oldUrl = $location.absUrl(); $location.$$parse(newUrl); if ($rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl).defaultPrevented) { $location.$$parse(oldUrl); $browser.url(oldUrl); } else { afterLocationChange(oldUrl); } }); if (!$rootScope.$$phase) $rootScope.$digest(); } }); // update browser var changeCounter = 0; $rootScope.$watch(function $locationWatch() { var oldUrl = $browser.url(); var currentReplace = $location.$$replace; if (!changeCounter || oldUrl != $location.absUrl()) { changeCounter++; $rootScope.$evalAsync(function() { if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl). defaultPrevented) { $location.$$parse(oldUrl); } else { $browser.url($location.absUrl(), currentReplace); afterLocationChange(oldUrl); } }); } $location.$$replace = false; return changeCounter; }); return $location; function afterLocationChange(oldUrl) { $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl); } }]; } /** * @ngdoc service * @name $log * @requires $window * * @description * Simple service for logging. Default implementation safely writes the message * into the browser's console (if present). * * The main purpose of this service is to simplify debugging and troubleshooting. * * The default is to log `debug` messages. You can use * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this. * * @example <example> <file name="script.js"> function LogCtrl($scope, $log) { $scope.$log = $log; $scope.message = 'Hello World!'; } </file> <file name="index.html"> <div ng-controller="LogCtrl"> <p>Reload this page with open console, enter text and hit the log button...</p> Message: <input type="text" ng-model="message"/> <button ng-click="$log.log(message)">log</button> <button ng-click="$log.warn(message)">warn</button> <button ng-click="$log.info(message)">info</button> <button ng-click="$log.error(message)">error</button> </div> </file> </example> */ /** * @ngdoc provider * @name $logProvider * @description * Use the `$logProvider` to configure how the application logs messages */ function $LogProvider(){ var debug = true, self = this; /** * @ngdoc property * @name $logProvider#debugEnabled * @description * @param {boolean=} flag enable or disable debug level messages * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.debugEnabled = function(flag) { if (isDefined(flag)) { debug = flag; return this; } else { return debug; } }; this.$get = ['$window', function($window){ return { /** * @ngdoc method * @name $log#log * * @description * Write a log message */ log: consoleLog('log'), /** * @ngdoc method * @name $log#info * * @description * Write an information message */ info: consoleLog('info'), /** * @ngdoc method * @name $log#warn * * @description * Write a warning message */ warn: consoleLog('warn'), /** * @ngdoc method * @name $log#error * * @description * Write an error message */ error: consoleLog('error'), /** * @ngdoc method * @name $log#debug * * @description * Write a debug message */ debug: (function () { var fn = consoleLog('debug'); return function() { if (debug) { fn.apply(self, arguments); } }; }()) }; function formatError(arg) { if (arg instanceof Error) { if (arg.stack) { arg = (arg.message && arg.stack.indexOf(arg.message) === -1) ? 'Error: ' + arg.message + '\n' + arg.stack : arg.stack; } else if (arg.sourceURL) { arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; } } return arg; } function consoleLog(type) { var console = $window.console || {}, logFn = console[type] || console.log || noop, hasApply = false; // Note: reading logFn.apply throws an error in IE11 in IE8 document mode. // The reason behind this is that console.log has type "object" in IE8... try { hasApply = !!logFn.apply; } catch (e) {} if (hasApply) { return function() { var args = []; forEach(arguments, function(arg) { args.push(formatError(arg)); }); return logFn.apply(console, args); }; } // we are IE which either doesn't have window.console => this is noop and we do nothing, // or we are IE where console.log doesn't have apply so we log at least first 2 args return function(arg1, arg2) { logFn(arg1, arg2 == null ? '' : arg2); }; } }]; } var $parseMinErr = minErr('$parse'); // Sandboxing Angular Expressions // ------------------------------ // Angular expressions are generally considered safe because these expressions only have direct // access to $scope and locals. However, one can obtain the ability to execute arbitrary JS code by // obtaining a reference to native JS functions such as the Function constructor. // // As an example, consider the following Angular expression: // // {}.toString.constructor(alert("evil JS code")) // // We want to prevent this type of access. For the sake of performance, during the lexing phase we // disallow any "dotted" access to any member named "constructor". // // For reflective calls (a[b]) we check that the value of the lookup is not the Function constructor // while evaluating the expression, which is a stronger but more expensive test. Since reflective // calls are expensive anyway, this is not such a big deal compared to static dereferencing. // // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits // against the expression language, but not to prevent exploits that were enabled by exposing // sensitive JavaScript or browser apis on Scope. Exposing such objects on a Scope is never a good // practice and therefore we are not even trying to protect against interaction with an object // explicitly exposed in this way. // // A developer could foil the name check by aliasing the Function constructor under a different // name on the scope. // // In general, it is not possible to access a Window object from an angular expression unless a // window or some DOM object that has a reference to window is published onto a Scope. function ensureSafeMemberName(name, fullExpression) { if (name === "constructor") { throw $parseMinErr('isecfld', 'Referencing "constructor" field in Angular expressions is disallowed! Expression: {0}', fullExpression); } return name; } function ensureSafeObject(obj, fullExpression) { // nifty check if obj is Function that is fast and works across iframes and other contexts if (obj) { if (obj.constructor === obj) { throw $parseMinErr('isecfn', 'Referencing Function in Angular expressions is disallowed! Expression: {0}', fullExpression); } else if (// isWindow(obj) obj.document && obj.location && obj.alert && obj.setInterval) { throw $parseMinErr('isecwindow', 'Referencing the Window in Angular expressions is disallowed! Expression: {0}', fullExpression); } else if (// isElement(obj) obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) { throw $parseMinErr('isecdom', 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}', fullExpression); } } return obj; } var OPERATORS = { /* jshint bitwise : false */ 'null':function(){return null;}, 'true':function(){return true;}, 'false':function(){return false;}, undefined:noop, '+':function(self, locals, a,b){ a=a(self, locals); b=b(self, locals); if (isDefined(a)) { if (isDefined(b)) { return a + b; } return a; } return isDefined(b)?b:undefined;}, '-':function(self, locals, a,b){ a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)-(isDefined(b)?b:0); }, '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);}, '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);}, '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);}, '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);}, '=':noop, '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);}, '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);}, '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);}, '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);}, '<':function(self, locals, a,b){return a(self, locals)<b(self, locals);}, '>':function(self, locals, a,b){return a(self, locals)>b(self, locals);}, '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);}, '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);}, '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);}, '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);}, '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);}, // '|':function(self, locals, a,b){return a|b;}, '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));}, '!':function(self, locals, a){return !a(self, locals);} }; /* jshint bitwise: true */ var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; ///////////////////////////////////////// /** * @constructor */ var Lexer = function (options) { this.options = options; }; Lexer.prototype = { constructor: Lexer, lex: function (text) { this.text = text; this.index = 0; this.ch = undefined; this.tokens = []; while (this.index < this.text.length) { this.ch = this.text.charAt(this.index); if (this.is('"\'')) { this.readString(this.ch); } else if (this.isNumber(this.ch) || this.is('.') && this.isNumber(this.peek())) { this.readNumber(); } else if (this.isIdent(this.ch)) { this.readIdent(); } else if (this.is('(){}[].,;:?')) { this.tokens.push({ index: this.index, text: this.ch }); this.index++; } else if (this.isWhitespace(this.ch)) { this.index++; } else { var ch2 = this.ch + this.peek(); var ch3 = ch2 + this.peek(2); var fn = OPERATORS[this.ch]; var fn2 = OPERATORS[ch2]; var fn3 = OPERATORS[ch3]; if (fn3) { this.tokens.push({index: this.index, text: ch3, fn: fn3}); this.index += 3; } else if (fn2) { this.tokens.push({index: this.index, text: ch2, fn: fn2}); this.index += 2; } else if (fn) { this.tokens.push({ index: this.index, text: this.ch, fn: fn }); this.index += 1; } else { this.throwError('Unexpected next character ', this.index, this.index + 1); } } } return this.tokens; }, is: function(chars) { return chars.indexOf(this.ch) !== -1; }, peek: function(i) { var num = i || 1; return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false; }, isNumber: function(ch) { return ('0' <= ch && ch <= '9'); }, isWhitespace: function(ch) { // IE treats non-breaking space as \u00A0 return (ch === ' ' || ch === '\r' || ch === '\t' || ch === '\n' || ch === '\v' || ch === '\u00A0'); }, isIdent: function(ch) { return ('a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || '_' === ch || ch === '$'); }, isExpOperator: function(ch) { return (ch === '-' || ch === '+' || this.isNumber(ch)); }, throwError: function(error, start, end) { end = end || this.index; var colStr = (isDefined(start) ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']' : ' ' + end); throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].', error, colStr, this.text); }, readNumber: function() { var number = ''; var start = this.index; while (this.index < this.text.length) { var ch = lowercase(this.text.charAt(this.index)); if (ch == '.' || this.isNumber(ch)) { number += ch; } else { var peekCh = this.peek(); if (ch == 'e' && this.isExpOperator(peekCh)) { number += ch; } else if (this.isExpOperator(ch) && peekCh && this.isNumber(peekCh) && number.charAt(number.length - 1) == 'e') { number += ch; } else if (this.isExpOperator(ch) && (!peekCh || !this.isNumber(peekCh)) && number.charAt(number.length - 1) == 'e') { this.throwError('Invalid exponent'); } else { break; } } this.index++; } number = 1 * number; this.tokens.push({ index: start, text: number, constant: true, fn: function() { return number; } }); }, readIdent: function() { var parser = this; var ident = ''; var start = this.index; var lastDot, peekIndex, methodName, ch; while (this.index < this.text.length) { ch = this.text.charAt(this.index); if (ch === '.' || this.isIdent(ch) || this.isNumber(ch)) { if (ch === '.') lastDot = this.index; ident += ch; } else { break; } this.index++; } //check if this is not a method invocation and if it is back out to last dot if (lastDot) { peekIndex = this.index; while (peekIndex < this.text.length) { ch = this.text.charAt(peekIndex); if (ch === '(') { methodName = ident.substr(lastDot - start + 1); ident = ident.substr(0, lastDot - start); this.index = peekIndex; break; } if (this.isWhitespace(ch)) { peekIndex++; } else { break; } } } var token = { index: start, text: ident }; // OPERATORS is our own object so we don't need to use special hasOwnPropertyFn if (OPERATORS.hasOwnProperty(ident)) { token.fn = OPERATORS[ident]; token.constant = true; } else { var getter = getterFn(ident, this.options, this.text); token.fn = extend(function(self, locals) { return (getter(self, locals)); }, { assign: function(self, value) { return setter(self, ident, value, parser.text); } }); } this.tokens.push(token); if (methodName) { this.tokens.push({ index: lastDot, text: '.' }); this.tokens.push({ index: lastDot + 1, text: methodName }); } }, readString: function(quote) { var start = this.index; this.index++; var string = ''; var rawString = quote; var escape = false; while (this.index < this.text.length) { var ch = this.text.charAt(this.index); rawString += ch; if (escape) { if (ch === 'u') { var hex = this.text.substring(this.index + 1, this.index + 5); if (!hex.match(/[\da-f]{4}/i)) this.throwError('Invalid unicode escape [\\u' + hex + ']'); this.index += 4; string += String.fromCharCode(parseInt(hex, 16)); } else { var rep = ESCAPE[ch]; if (rep) { string += rep; } else { string += ch; } } escape = false; } else if (ch === '\\') { escape = true; } else if (ch === quote) { this.index++; this.tokens.push({ index: start, text: rawString, string: string, constant: true, fn: function() { return string; } }); return; } else { string += ch; } this.index++; } this.throwError('Unterminated quote', start); } }; /** * @constructor */ var Parser = function (lexer, $filter, options) { this.lexer = lexer; this.$filter = $filter; this.options = options; }; Parser.ZERO = extend(function () { return 0; }, { constant: true }); Parser.prototype = { constructor: Parser, parse: function (text) { this.text = text; this.tokens = this.lexer.lex(text); var value = this.statements(); if (this.tokens.length !== 0) { this.throwError('is an unexpected token', this.tokens[0]); } value.literal = !!value.literal; value.constant = !!value.constant; return value; }, primary: function () { var primary; if (this.expect('(')) { primary = this.filterChain(); this.consume(')'); } else if (this.expect('[')) { primary = this.arrayDeclaration(); } else if (this.expect('{')) { primary = this.object(); } else { var token = this.expect(); primary = token.fn; if (!primary) { this.throwError('not a primary expression', token); } if (token.constant) { primary.constant = true; primary.literal = true; } } var next, context; while ((next = this.expect('(', '[', '.'))) { if (next.text === '(') { primary = this.functionCall(primary, context); context = null; } else if (next.text === '[') { context = primary; primary = this.objectIndex(primary); } else if (next.text === '.') { context = primary; primary = this.fieldAccess(primary); } else { this.throwError('IMPOSSIBLE'); } } return primary; }, throwError: function(msg, token) { throw $parseMinErr('syntax', 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].', token.text, msg, (token.index + 1), this.text, this.text.substring(token.index)); }, peekToken: function() { if (this.tokens.length === 0) throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text); return this.tokens[0]; }, peek: function(e1, e2, e3, e4) { if (this.tokens.length > 0) { var token = this.tokens[0]; var t = token.text; if (t === e1 || t === e2 || t === e3 || t === e4 || (!e1 && !e2 && !e3 && !e4)) { return token; } } return false; }, expect: function(e1, e2, e3, e4){ var token = this.peek(e1, e2, e3, e4); if (token) { this.tokens.shift(); return token; } return false; }, consume: function(e1){ if (!this.expect(e1)) { this.throwError('is unexpected, expecting [' + e1 + ']', this.peek()); } }, unaryFn: function(fn, right) { return extend(function(self, locals) { return fn(self, locals, right); }, { constant:right.constant }); }, ternaryFn: function(left, middle, right){ return extend(function(self, locals){ return left(self, locals) ? middle(self, locals) : right(self, locals); }, { constant: left.constant && middle.constant && right.constant }); }, binaryFn: function(left, fn, right) { return extend(function(self, locals) { return fn(self, locals, left, right); }, { constant:left.constant && right.constant }); }, statements: function() { var statements = []; while (true) { if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']')) statements.push(this.filterChain()); if (!this.expect(';')) { // optimize for the common case where there is only one statement. // TODO(size): maybe we should not support multiple statements? return (statements.length === 1) ? statements[0] : function(self, locals) { var value; for (var i = 0; i < statements.length; i++) { var statement = statements[i]; if (statement) { value = statement(self, locals); } } return value; }; } } }, filterChain: function() { var left = this.expression(); var token; while (true) { if ((token = this.expect('|'))) { left = this.binaryFn(left, token.fn, this.filter()); } else { return left; } } }, filter: function() { var token = this.expect(); var fn = this.$filter(token.text); var argsFn = []; while(this.expect(':')) { argsFn.push(this.expression()); } return valueFn(fnInvoke); function fnInvoke(self, locals, input) { var args = [input]; for (var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self, locals)); } return fn.apply(self, args); } }, expression: function() { return this.assignment(); }, assignment: function() { var left = this.ternary(); var right; var token; if ((token = this.expect('='))) { if (!left.assign) { this.throwError('implies assignment but [' + this.text.substring(0, token.index) + '] can not be assigned to', token); } right = this.ternary(); return function(scope, locals) { return left.assign(scope, right(scope, locals), locals); }; } return left; }, ternary: function() { var left = this.logicalOR(); var middle; var token; if ((token = this.expect('?'))) { middle = this.ternary(); if ((token = this.expect(':'))) { return this.ternaryFn(left, middle, this.ternary()); } else { this.throwError('expected :', token); } } else { return left; } }, logicalOR: function() { var left = this.logicalAND(); var token; while (true) { if ((token = this.expect('||'))) { left = this.binaryFn(left, token.fn, this.logicalAND()); } else { return left; } } }, logicalAND: function() { var left = this.equality(); var token; if ((token = this.expect('&&'))) { left = this.binaryFn(left, token.fn, this.logicalAND()); } return left; }, equality: function() { var left = this.relational(); var token; if ((token = this.expect('==','!=','===','!=='))) { left = this.binaryFn(left, token.fn, this.equality()); } return left; }, relational: function() { var left = this.additive(); var token; if ((token = this.expect('<', '>', '<=', '>='))) { left = this.binaryFn(left, token.fn, this.relational()); } return left; }, additive: function() { var left = this.multiplicative(); var token; while ((token = this.expect('+','-'))) { left = this.binaryFn(left, token.fn, this.multiplicative()); } return left; }, multiplicative: function() { var left = this.unary(); var token; while ((token = this.expect('*','/','%'))) { left = this.binaryFn(left, token.fn, this.unary()); } return left; }, unary: function() { var token; if (this.expect('+')) { return this.primary(); } else if ((token = this.expect('-'))) { return this.binaryFn(Parser.ZERO, token.fn, this.unary()); } else if ((token = this.expect('!'))) { return this.unaryFn(token.fn, this.unary()); } else { return this.primary(); } }, fieldAccess: function(object) { var parser = this; var field = this.expect().text; var getter = getterFn(field, this.options, this.text); return extend(function(scope, locals, self) { return getter(self || object(scope, locals)); }, { assign: function(scope, value, locals) { return setter(object(scope, locals), field, value, parser.text); } }); }, objectIndex: function(obj) { var parser = this; var indexFn = this.expression(); this.consume(']'); return extend(function(self, locals) { var o = obj(self, locals), i = indexFn(self, locals), v; if (!o) return undefined; v = ensureSafeObject(o[i], parser.text); return v; }, { assign: function(self, value, locals) { var key = indexFn(self, locals); // prevent overwriting of Function.constructor which would break ensureSafeObject check var safe = ensureSafeObject(obj(self, locals), parser.text); return safe[key] = value; } }); }, functionCall: function(fn, contextGetter) { var argsFn = []; if (this.peekToken().text !== ')') { do { argsFn.push(this.expression()); } while (this.expect(',')); } this.consume(')'); var parser = this; return function(scope, locals) { var args = []; var context = contextGetter ? contextGetter(scope, locals) : scope; for (var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](scope, locals)); } var fnPtr = fn(scope, locals, context) || noop; ensureSafeObject(context, parser.text); ensureSafeObject(fnPtr, parser.text); // IE stupidity! (IE doesn't have apply for some native functions) var v = fnPtr.apply ? fnPtr.apply(context, args) : fnPtr(args[0], args[1], args[2], args[3], args[4]); return ensureSafeObject(v, parser.text); }; }, // This is used with json array declaration arrayDeclaration: function () { var elementFns = []; var allConstant = true; if (this.peekToken().text !== ']') { do { if (this.peek(']')) { // Support trailing commas per ES5.1. break; } var elementFn = this.expression(); elementFns.push(elementFn); if (!elementFn.constant) { allConstant = false; } } while (this.expect(',')); } this.consume(']'); return extend(function(self, locals) { var array = []; for (var i = 0; i < elementFns.length; i++) { array.push(elementFns[i](self, locals)); } return array; }, { literal: true, constant: allConstant }); }, object: function () { var keyValues = []; var allConstant = true; if (this.peekToken().text !== '}') { do { if (this.peek('}')) { // Support trailing commas per ES5.1. break; } var token = this.expect(), key = token.string || token.text; this.consume(':'); var value = this.expression(); keyValues.push({key: key, value: value}); if (!value.constant) { allConstant = false; } } while (this.expect(',')); } this.consume('}'); return extend(function(self, locals) { var object = {}; for (var i = 0; i < keyValues.length; i++) { var keyValue = keyValues[i]; object[keyValue.key] = keyValue.value(self, locals); } return object; }, { literal: true, constant: allConstant }); } }; ////////////////////////////////////////////////// // Parser helper functions ////////////////////////////////////////////////// function setter(obj, path, setValue, fullExp) { var element = path.split('.'), key; for (var i = 0; element.length > 1; i++) { key = ensureSafeMemberName(element.shift(), fullExp); var propertyObj = obj[key]; if (!propertyObj) { propertyObj = {}; obj[key] = propertyObj; } obj = propertyObj; } key = ensureSafeMemberName(element.shift(), fullExp); obj[key] = setValue; return setValue; } var getterFnCache = {}; /** * Implementation of the "Black Hole" variant from: * - http://jsperf.com/angularjs-parse-getter/4 * - http://jsperf.com/path-evaluation-simplified/7 */ function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp) { ensureSafeMemberName(key0, fullExp); ensureSafeMemberName(key1, fullExp); ensureSafeMemberName(key2, fullExp); ensureSafeMemberName(key3, fullExp); ensureSafeMemberName(key4, fullExp); return function cspSafeGetter(scope, locals) { var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope; if (pathVal == null) return pathVal; pathVal = pathVal[key0]; if (!key1) return pathVal; if (pathVal == null) return undefined; pathVal = pathVal[key1]; if (!key2) return pathVal; if (pathVal == null) return undefined; pathVal = pathVal[key2]; if (!key3) return pathVal; if (pathVal == null) return undefined; pathVal = pathVal[key3]; if (!key4) return pathVal; if (pathVal == null) return undefined; pathVal = pathVal[key4]; return pathVal; }; } function simpleGetterFn1(key0, fullExp) { ensureSafeMemberName(key0, fullExp); return function simpleGetterFn1(scope, locals) { if (scope == null) return undefined; return ((locals && locals.hasOwnProperty(key0)) ? locals : scope)[key0]; }; } function simpleGetterFn2(key0, key1, fullExp) { ensureSafeMemberName(key0, fullExp); ensureSafeMemberName(key1, fullExp); return function simpleGetterFn2(scope, locals) { if (scope == null) return undefined; scope = ((locals && locals.hasOwnProperty(key0)) ? locals : scope)[key0]; return scope == null ? undefined : scope[key1]; }; } function getterFn(path, options, fullExp) { // Check whether the cache has this getter already. // We can use hasOwnProperty directly on the cache because we ensure, // see below, that the cache never stores a path called 'hasOwnProperty' if (getterFnCache.hasOwnProperty(path)) { return getterFnCache[path]; } var pathKeys = path.split('.'), pathKeysLength = pathKeys.length, fn; // When we have only 1 or 2 tokens, use optimized special case closures. // http://jsperf.com/angularjs-parse-getter/6 if (pathKeysLength === 1) { fn = simpleGetterFn1(pathKeys[0], fullExp); } else if (pathKeysLength === 2) { fn = simpleGetterFn2(pathKeys[0], pathKeys[1], fullExp); } else if (options.csp) { if (pathKeysLength < 6) { fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp); } else { fn = function(scope, locals) { var i = 0, val; do { val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], fullExp)(scope, locals); locals = undefined; // clear after first iteration scope = val; } while (i < pathKeysLength); return val; }; } } else { var code = 'var p;\n'; forEach(pathKeys, function(key, index) { ensureSafeMemberName(key, fullExp); code += 'if(s == null) return undefined;\n' + 's='+ (index // we simply dereference 's' on any .dot notation ? 's' // but if we are first then we check locals first, and if so read it first : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n'; }); code += 'return s;'; /* jshint -W054 */ var evaledFnGetter = new Function('s', 'k', code); // s=scope, k=locals /* jshint +W054 */ evaledFnGetter.toString = valueFn(code); fn = evaledFnGetter; } // Only cache the value if it's not going to mess up the cache object // This is more performant that using Object.prototype.hasOwnProperty.call if (path !== 'hasOwnProperty') { getterFnCache[path] = fn; } return fn; } /////////////////////////////////// /** * @ngdoc service * @name $parse * @kind function * * @description * * Converts Angular {@link guide/expression expression} into a function. * * ```js * var getter = $parse('user.name'); * var setter = getter.assign; * var context = {user:{name:'angular'}}; * var locals = {user:{name:'local'}}; * * expect(getter(context)).toEqual('angular'); * setter(context, 'newValue'); * expect(context.user.name).toEqual('newValue'); * expect(getter(context, locals)).toEqual('local'); * ``` * * * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings * are evaluated against (typically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. * * The returned function also has the following properties: * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript * literal. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript * constant literals. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be * set to a function to change its value on the given context. * */ /** * @ngdoc provider * @name $parseProvider * @kind function * * @description * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse} * service. */ function $ParseProvider() { var cache = {}; var $parseOptions = { csp: false }; this.$get = ['$filter', '$sniffer', function($filter, $sniffer) { $parseOptions.csp = $sniffer.csp; return function(exp) { var parsedExpression, oneTime; switch (typeof exp) { case 'string': exp = trim(exp); if (exp.charAt(0) === ':' && exp.charAt(1) === ':') { oneTime = true; exp = exp.substring(2); } if (cache.hasOwnProperty(exp)) { return oneTime ? oneTimeWrapper(cache[exp]) : cache[exp]; } var lexer = new Lexer($parseOptions); var parser = new Parser(lexer, $filter, $parseOptions); parsedExpression = parser.parse(exp); if (exp !== 'hasOwnProperty') { // Only cache the value if it's not going to mess up the cache object // This is more performant that using Object.prototype.hasOwnProperty.call cache[exp] = parsedExpression; } if (parsedExpression.constant) { parsedExpression.$$unwatch = true; } return oneTime ? oneTimeWrapper(parsedExpression) : parsedExpression; case 'function': return exp; default: return noop; } function oneTimeWrapper(expression) { var stable = false, lastValue; oneTimeParseFn.literal = expression.literal; oneTimeParseFn.constant = expression.constant; oneTimeParseFn.assign = expression.assign; return oneTimeParseFn; function oneTimeParseFn(self, locals) { if (!stable) { lastValue = expression(self, locals); oneTimeParseFn.$$unwatch = isDefined(lastValue); if (oneTimeParseFn.$$unwatch && self && self.$$postDigestQueue) { self.$$postDigestQueue.push(function () { // create a copy if the value is defined and it is not a $sce value if ((stable = isDefined(lastValue)) && (lastValue === null || !lastValue.$$unwrapTrustedValue)) { lastValue = copy(lastValue, null); } }); } } return lastValue; } } }; }]; } /** * @ngdoc service * @name $q * @requires $rootScope * * @description * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q). * * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an * interface for interacting with an object that represents the result of an action that is * performed asynchronously, and may or may not be finished at any given point in time. * * From the perspective of dealing with error handling, deferred and promise APIs are to * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming. * * ```js * // for the purpose of this example let's assume that variables `$q`, `scope` and `okToGreet` * // are available in the current lexical scope (they could have been injected or passed in). * * function asyncGreet(name) { * var deferred = $q.defer(); * * setTimeout(function() { * // since this fn executes async in a future turn of the event loop, we need to wrap * // our code into an $apply call so that the model changes are properly observed. * scope.$apply(function() { * deferred.notify('About to greet ' + name + '.'); * * if (okToGreet(name)) { * deferred.resolve('Hello, ' + name + '!'); * } else { * deferred.reject('Greeting ' + name + ' is not allowed.'); * } * }); * }, 1000); * * return deferred.promise; * } * * var promise = asyncGreet('Robin Hood'); * promise.then(function(greeting) { * alert('Success: ' + greeting); * }, function(reason) { * alert('Failed: ' + reason); * }, function(update) { * alert('Got notification: ' + update); * }); * ``` * * At first it might not be obvious why this extra complexity is worth the trouble. The payoff * comes in the way of guarantees that promise and deferred APIs make, see * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md. * * Additionally the promise api allows for composition that is very hard to do with the * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the * section on serial or parallel joining of promises. * * * # The Deferred API * * A new instance of deferred is constructed by calling `$q.defer()`. * * The purpose of the deferred object is to expose the associated Promise instance as well as APIs * that can be used for signaling the successful or unsuccessful completion, as well as the status * of the task. * * **Methods** * * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection * constructed via `$q.reject`, the promise will be rejected instead. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to * resolving it with a rejection constructed via `$q.reject`. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called * multiple times before the promise is either resolved or rejected. * * **Properties** * * - promise – `{Promise}` – promise object associated with this deferred. * * * # The Promise API * * A new promise instance is created when a deferred instance is created and can be retrieved by * calling `deferred.promise`. * * The purpose of the promise object is to allow for interested parties to get access to the result * of the deferred task when it completes. * * **Methods** * * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously * as soon as the result is available. The callbacks are called with a single argument: the result * or rejection reason. Additionally, the notify callback may be called zero or more times to * provide a progress indication, before the promise is resolved or rejected. * * This method *returns a new promise* which is resolved or rejected via the return value of the * `successCallback`, `errorCallback`. It also notifies via the return value of the * `notifyCallback` method. The promise can not be resolved or rejected from the notifyCallback * method. * * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)` * * - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise, * but to do so without modifying the final value. This is useful to release resources or do some * clean-up that needs to be done whether the promise was rejected or resolved. See the [full * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for * more information. * * Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as * property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to * make your code IE8 and Android 2.x compatible. * * # Chaining promises * * Because calling the `then` method of a promise returns a new derived promise, it is easily * possible to create a chain of promises: * * ```js * promiseB = promiseA.then(function(result) { * return result + 1; * }); * * // promiseB will be resolved immediately after promiseA is resolved and its value * // will be the result of promiseA incremented by 1 * ``` * * It is possible to create chains of any length and since a promise can be resolved with another * promise (which will defer its resolution further), it is possible to pause/defer resolution of * the promises at any point in the chain. This makes it possible to implement powerful APIs like * $http's response interceptors. * * * # Differences between Kris Kowal's Q and $q * * There are two main differences: * * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation * mechanism in angular, which means faster propagation of resolution or rejection into your * models and avoiding unnecessary browser repaints, which would result in flickering UI. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains * all the important functionality needed for common async tasks. * * # Testing * * ```js * it('should simulate promise', inject(function($q, $rootScope) { * var deferred = $q.defer(); * var promise = deferred.promise; * var resolvedValue; * * promise.then(function(value) { resolvedValue = value; }); * expect(resolvedValue).toBeUndefined(); * * // Simulate resolving of promise * deferred.resolve(123); * // Note that the 'then' function does not get called synchronously. * // This is because we want the promise API to always be async, whether or not * // it got called synchronously or asynchronously. * expect(resolvedValue).toBeUndefined(); * * // Propagate promise resolution to 'then' functions using $apply(). * $rootScope.$apply(); * expect(resolvedValue).toEqual(123); * })); * ``` */ function $QProvider() { this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) { return qFactory(function(callback) { $rootScope.$evalAsync(callback); }, $exceptionHandler); }]; } /** * Constructs a promise manager. * * @param {function(Function)} nextTick Function for executing functions in the next turn. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for * debugging purposes. * @returns {object} Promise manager. */ function qFactory(nextTick, exceptionHandler) { /** * @ngdoc method * @name $q#defer * @kind function * * @description * Creates a `Deferred` object which represents a task which will finish in the future. * * @returns {Deferred} Returns a new instance of deferred. */ var defer = function() { var pending = [], value, deferred; deferred = { resolve: function(val) { if (pending) { var callbacks = pending; pending = undefined; value = ref(val); if (callbacks.length) { nextTick(function() { var callback; for (var i = 0, ii = callbacks.length; i < ii; i++) { callback = callbacks[i]; value.then(callback[0], callback[1], callback[2]); } }); } } }, reject: function(reason) { deferred.resolve(createInternalRejectedPromise(reason)); }, notify: function(progress) { if (pending) { var callbacks = pending; if (pending.length) { nextTick(function() { var callback; for (var i = 0, ii = callbacks.length; i < ii; i++) { callback = callbacks[i]; callback[2](progress); } }); } } }, promise: { then: function(callback, errback, progressback) { var result = defer(); var wrappedCallback = function(value) { try { result.resolve((isFunction(callback) ? callback : defaultCallback)(value)); } catch(e) { result.reject(e); exceptionHandler(e); } }; var wrappedErrback = function(reason) { try { result.resolve((isFunction(errback) ? errback : defaultErrback)(reason)); } catch(e) { result.reject(e); exceptionHandler(e); } }; var wrappedProgressback = function(progress) { try { result.notify((isFunction(progressback) ? progressback : defaultCallback)(progress)); } catch(e) { exceptionHandler(e); } }; if (pending) { pending.push([wrappedCallback, wrappedErrback, wrappedProgressback]); } else { value.then(wrappedCallback, wrappedErrback, wrappedProgressback); } return result.promise; }, "catch": function(callback) { return this.then(null, callback); }, "finally": function(callback) { function makePromise(value, resolved) { var result = defer(); if (resolved) { result.resolve(value); } else { result.reject(value); } return result.promise; } function handleCallback(value, isResolved) { var callbackOutput = null; try { callbackOutput = (callback ||defaultCallback)(); } catch(e) { return makePromise(e, false); } if (callbackOutput && isFunction(callbackOutput.then)) { return callbackOutput.then(function() { return makePromise(value, isResolved); }, function(error) { return makePromise(error, false); }); } else { return makePromise(value, isResolved); } } return this.then(function(value) { return handleCallback(value, true); }, function(error) { return handleCallback(error, false); }); } } }; return deferred; }; var ref = function(value) { if (value && isFunction(value.then)) return value; return { then: function(callback) { var result = defer(); nextTick(function() { result.resolve(callback(value)); }); return result.promise; } }; }; /** * @ngdoc method * @name $q#reject * @kind function * * @description * Creates a promise that is resolved as rejected with the specified `reason`. This api should be * used to forward rejection in a chain of promises. If you are dealing with the last promise in * a promise chain, you don't need to worry about it. * * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via * a promise error callback and you want to forward the error to the promise derived from the * current promise, you have to "rethrow" the error by returning a rejection constructed via * `reject`. * * ```js * promiseB = promiseA.then(function(result) { * // success: do something and resolve promiseB * // with the old or a new result * return result; * }, function(reason) { * // error: handle the error if possible and * // resolve promiseB with newPromiseOrValue, * // otherwise forward the rejection to promiseB * if (canHandle(reason)) { * // handle the error and recover * return newPromiseOrValue; * } * return $q.reject(reason); * }); * ``` * * @param {*} reason Constant, message, exception or an object representing the rejection reason. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`. */ var reject = function(reason) { var result = defer(); result.reject(reason); return result.promise; }; var createInternalRejectedPromise = function(reason) { return { then: function(callback, errback) { var result = defer(); nextTick(function() { try { result.resolve((isFunction(errback) ? errback : defaultErrback)(reason)); } catch(e) { result.reject(e); exceptionHandler(e); } }); return result.promise; } }; }; /** * @ngdoc method * @name $q#when * @kind function * * @description * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. * This is useful when you are dealing with an object that might or might not be a promise, or if * the promise comes from a source that can't be trusted. * * @param {*} value Value or a promise * @returns {Promise} Returns a promise of the passed value or promise */ var when = function(value, callback, errback, progressback) { var result = defer(), done; var wrappedCallback = function(value) { try { return (isFunction(callback) ? callback : defaultCallback)(value); } catch (e) { exceptionHandler(e); return reject(e); } }; var wrappedErrback = function(reason) { try { return (isFunction(errback) ? errback : defaultErrback)(reason); } catch (e) { exceptionHandler(e); return reject(e); } }; var wrappedProgressback = function(progress) { try { return (isFunction(progressback) ? progressback : defaultCallback)(progress); } catch (e) { exceptionHandler(e); } }; nextTick(function() { ref(value).then(function(value) { if (done) return; done = true; result.resolve(ref(value).then(wrappedCallback, wrappedErrback, wrappedProgressback)); }, function(reason) { if (done) return; done = true; result.resolve(wrappedErrback(reason)); }, function(progress) { if (done) return; result.notify(wrappedProgressback(progress)); }); }); return result.promise; }; function defaultCallback(value) { return value; } function defaultErrback(reason) { return reject(reason); } /** * @ngdoc method * @name $q#all * @kind function * * @description * Combines multiple promises into a single promise that is resolved when all of the input * promises are resolved. * * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values, * each value corresponding to the promise at the same index/key in the `promises` array/hash. * If any of the promises is resolved with a rejection, this resulting promise will be rejected * with the same rejection value. */ function all(promises) { var deferred = defer(), counter = 0, results = isArray(promises) ? [] : {}; forEach(promises, function(promise, key) { counter++; ref(promise).then(function(value) { if (results.hasOwnProperty(key)) return; results[key] = value; if (!(--counter)) deferred.resolve(results); }, function(reason) { if (results.hasOwnProperty(key)) return; deferred.reject(reason); }); }); if (counter === 0) { deferred.resolve(results); } return deferred.promise; } return { defer: defer, reject: reject, when: when, all: all }; } function $$RAFProvider(){ //rAF this.$get = ['$window', '$timeout', function($window, $timeout) { var requestAnimationFrame = $window.requestAnimationFrame || $window.webkitRequestAnimationFrame || $window.mozRequestAnimationFrame; var cancelAnimationFrame = $window.cancelAnimationFrame || $window.webkitCancelAnimationFrame || $window.mozCancelAnimationFrame || $window.webkitCancelRequestAnimationFrame; var rafSupported = !!requestAnimationFrame; var raf = rafSupported ? function(fn) { var id = requestAnimationFrame(fn); return function() { cancelAnimationFrame(id); }; } : function(fn) { var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666 return function() { $timeout.cancel(timer); }; }; raf.supported = rafSupported; return raf; }]; } /** * DESIGN NOTES * * The design decisions behind the scope are heavily favored for speed and memory consumption. * * The typical use of scope is to watch the expressions, which most of the time return the same * value as last time so we optimize the operation. * * Closures construction is expensive in terms of speed as well as memory: * - No closures, instead use prototypical inheritance for API * - Internal state needs to be stored on scope directly, which means that private state is * exposed as $$____ properties * * Loop operations are optimized by using while(count--) { ... } * - this means that in order to keep the same order of execution as addition we have to add * items to the array at the beginning (unshift) instead of at the end (push) * * Child scopes are created and removed often * - Using an array would be slow since inserts in middle are expensive so we use linked list * * There are few watches then a lot of observers. This is why you don't want the observer to be * implemented in the same way as watch. Watch requires return of initialization function which * are expensive to construct. */ /** * @ngdoc provider * @name $rootScopeProvider * @description * * Provider for the $rootScope service. */ /** * @ngdoc method * @name $rootScopeProvider#digestTtl * @description * * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and * assuming that the model is unstable. * * The current default is 10 iterations. * * In complex applications it's possible that the dependencies between `$watch`s will result in * several digest iterations. However if an application needs more than the default 10 digest * iterations for its model to stabilize then you should investigate what is causing the model to * continuously change during the digest. * * Increasing the TTL could have performance implications, so you should not change it without * proper justification. * * @param {number} limit The number of digest iterations. */ /** * @ngdoc service * @name $rootScope * @description * * Every application has a single root {@link ng.$rootScope.Scope scope}. * All other scopes are descendant scopes of the root scope. Scopes provide separation * between the model and the view, via a mechanism for watching the model for changes. * They also provide an event emission/broadcast and subscription facility. See the * {@link guide/scope developer guide on scopes}. */ function $RootScopeProvider(){ var TTL = 10; var $rootScopeMinErr = minErr('$rootScope'); var lastDirtyWatch = null; this.digestTtl = function(value) { if (arguments.length) { TTL = value; } return TTL; }; this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser', function( $injector, $exceptionHandler, $parse, $browser) { /** * @ngdoc type * @name $rootScope.Scope * * @description * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the * {@link auto.$injector $injector}. Child scopes are created using the * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when * compiled HTML template is executed.) * * Here is a simple scope snippet to show how you can interact with the scope. * ```html * <file src="./test/ng/rootScopeSpec.js" tag="docs1" /> * ``` * * # Inheritance * A scope can inherit from a parent scope, as in this example: * ```js var parent = $rootScope; var child = parent.$new(); parent.salutation = "Hello"; child.name = "World"; expect(child.salutation).toEqual('Hello'); child.salutation = "Welcome"; expect(child.salutation).toEqual('Welcome'); expect(parent.salutation).toEqual('Hello'); * ``` * * * @param {Object.<string, function()>=} providers Map of service factory which need to be * provided for the current scope. Defaults to {@link ng}. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should * append/override services provided by `providers`. This is handy * when unit-testing and having the need to override a default * service. * @returns {Object} Newly created scope. * */ function Scope() { this.$id = nextUid(); this.$$phase = this.$parent = this.$$watchers = this.$$nextSibling = this.$$prevSibling = this.$$childHead = this.$$childTail = null; this['this'] = this.$root = this; this.$$destroyed = false; this.$$asyncQueue = []; this.$$postDigestQueue = []; this.$$listeners = {}; this.$$listenerCount = {}; this.$$isolateBindings = {}; } /** * @ngdoc property * @name $rootScope.Scope#$id * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for * debugging. */ Scope.prototype = { constructor: Scope, /** * @ngdoc method * @name $rootScope.Scope#$new * @kind function * * @description * Creates a new child {@link ng.$rootScope.Scope scope}. * * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and * {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the * scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}. * * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is * desired for the scope and its child scopes to be permanently detached from the parent and * thus stop participating in model change detection and listener notification by invoking. * * @param {boolean} isolate If true, then the scope does not prototypically inherit from the * parent scope. The scope is isolated, as it can not see parent scope properties. * When creating widgets, it is useful for the widget to not accidentally read parent * state. * * @returns {Object} The newly created child scope. * */ $new: function(isolate) { var ChildScope, child; if (isolate) { child = new Scope(); child.$root = this.$root; // ensure that there is just one async queue per $rootScope and its children child.$$asyncQueue = this.$$asyncQueue; child.$$postDigestQueue = this.$$postDigestQueue; } else { // Only create a child scope class if somebody asks for one, // but cache it to allow the VM to optimize lookups. if (!this.$$childScopeClass) { this.$$childScopeClass = function() { this.$$watchers = this.$$nextSibling = this.$$childHead = this.$$childTail = null; this.$$listeners = {}; this.$$listenerCount = {}; this.$id = nextUid(); this.$$childScopeClass = null; }; this.$$childScopeClass.prototype = this; } child = new this.$$childScopeClass(); } child['this'] = child; child.$parent = this; child.$$prevSibling = this.$$childTail; if (this.$$childHead) { this.$$childTail.$$nextSibling = child; this.$$childTail = child; } else { this.$$childHead = this.$$childTail = child; } return child; }, /** * @ngdoc method * @name $rootScope.Scope#$watch * @kind function * * @description * Registers a `listener` callback to be executed whenever the `watchExpression` changes. * * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest * $digest()} and should return the value that will be watched. (Since * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the * `watchExpression` can execute multiple times per * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.) * - The `listener` is called only when the value from the current `watchExpression` and the * previous call to `watchExpression` are not equal (with the exception of the initial run, * see below). Inequality is determined according to reference inequality, * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators) * via the `!==` Javascript operator, unless `objectEquality == true` * (see next point) * - When `objectEquality == true`, inequality of the `watchExpression` is determined * according to the {@link angular.equals} function. To save the value of the object for * later comparison, the {@link angular.copy} function is used. This therefore means that * watching complex objects will have adverse memory and performance implications. * - The watch `listener` may change the model, which may trigger other `listener`s to fire. * This is achieved by rerunning the watchers until no changes are detected. The rerun * iteration limit is 10 to prevent an infinite loop deadlock. * * * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called, * you can register a `watchExpression` function with no `listener`. (Since `watchExpression` * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a * change is detected, be prepared for multiple calls to your listener.) * * After a watcher is registered with the scope, the `listener` fn is called asynchronously * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the * watcher. In rare cases, this is undesirable because the listener is called when the result * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the * listener was called due to initialization. * * The example below contains an illustration of using a function as your $watch listener * * * # Example * ```js // let's assume that scope was dependency injected as the $rootScope var scope = $rootScope; scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // the listener is always called during the first $digest loop after it was registered expect(scope.counter).toEqual(1); scope.$digest(); // but now it will not be called unless the value changes expect(scope.counter).toEqual(1); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(2); // Using a listener function var food; scope.foodCounter = 0; expect(scope.foodCounter).toEqual(0); scope.$watch( // This is the listener function function() { return food; }, // This is the change handler function(newValue, oldValue) { if ( newValue !== oldValue ) { // Only increment the counter if the value changed scope.foodCounter = scope.foodCounter + 1; } } ); // No digest has been run so the counter will be zero expect(scope.foodCounter).toEqual(0); // Run the digest but since food has not changed count will still be zero scope.$digest(); expect(scope.foodCounter).toEqual(0); // Update food and run digest. Now the counter will increment food = 'cheeseburger'; scope.$digest(); expect(scope.foodCounter).toEqual(1); * ``` * * * * @param {(function()|string)} watchExpression Expression that is evaluated on each * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers * a call to the `listener`. * * - `string`: Evaluated as {@link guide/expression expression} * - `function(scope)`: called with current `scope` as a parameter. * @param {(function()|string)=} listener Callback called whenever the return value of * the `watchExpression` changes. * * - `string`: Evaluated as {@link guide/expression expression} * - `function(newValue, oldValue, scope)`: called with current and previous values as * parameters. * * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of * comparing for reference equality. * @returns {function()} Returns a deregistration function for this listener. */ $watch: function(watchExp, listener, objectEquality) { var scope = this, get = compileToFn(watchExp, 'watch'), array = scope.$$watchers, watcher = { fn: listener, last: initWatchVal, get: get, exp: watchExp, eq: !!objectEquality }; lastDirtyWatch = null; // in the case user pass string, we need to compile it, do we really need this ? if (!isFunction(listener)) { var listenFn = compileToFn(listener || noop, 'listener'); watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);}; } if (!array) { array = scope.$$watchers = []; } // we use unshift since we use a while loop in $digest for speed. // the while loop reads in reverse order. array.unshift(watcher); return function deregisterWatch() { arrayRemove(array, watcher); lastDirtyWatch = null; }; }, /** * @ngdoc method * @name $rootScope.Scope#$watchGroup * @kind function * * @description * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`. * If any one expression in the collection changes the `listener` is executed. * * - The items in the `watchCollection` array are observed via standard $watch operation and are examined on every * call to $digest() to see if any items changes. * - The `listener` is called whenever any expression in the `watchExpressions` array changes. * * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually * watched using {@link ng.$rootScope.Scope#$watch $watch()} * * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any * expression in `watchExpressions` changes * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching * those of `watchExpression` * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching * those of `watchExpression` * The `scope` refers to the current scope. * * @returns {function()} Returns a de-registration function for all listeners. */ $watchGroup: function(watchExpressions, listener) { var oldValues = new Array(watchExpressions.length); var newValues = new Array(watchExpressions.length); var deregisterFns = []; var changeCount = 0; var self = this; var unwatchFlags = new Array(watchExpressions.length); var unwatchCount = watchExpressions.length; forEach(watchExpressions, function (expr, i) { var exprFn = $parse(expr); deregisterFns.push(self.$watch(exprFn, function (value, oldValue) { newValues[i] = value; oldValues[i] = oldValue; changeCount++; if (unwatchFlags[i] && !exprFn.$$unwatch) unwatchCount++; if (!unwatchFlags[i] && exprFn.$$unwatch) unwatchCount--; unwatchFlags[i] = exprFn.$$unwatch; })); }, this); deregisterFns.push(self.$watch(watchGroupFn, function () { listener(newValues, oldValues, self); if (unwatchCount === 0) { watchGroupFn.$$unwatch = true; } else { watchGroupFn.$$unwatch = false; } })); return function deregisterWatchGroup() { forEach(deregisterFns, function (fn) { fn(); }); }; function watchGroupFn() {return changeCount;} }, /** * @ngdoc method * @name $rootScope.Scope#$watchCollection * @kind function * * @description * Shallow watches the properties of an object and fires whenever any of the properties change * (for arrays, this implies watching the array items; for object maps, this implies watching * the properties). If a change is detected, the `listener` callback is fired. * * - The `obj` collection is observed via standard $watch operation and is examined on every * call to $digest() to see if any items have been added, removed, or moved. * - The `listener` is called whenever anything within the `obj` has changed. Examples include * adding, removing, and moving items belonging to an object or array. * * * # Example * ```js $scope.names = ['igor', 'matias', 'misko', 'james']; $scope.dataCount = 4; $scope.$watchCollection('names', function(newNames, oldNames) { $scope.dataCount = newNames.length; }); expect($scope.dataCount).toEqual(4); $scope.$digest(); //still at 4 ... no changes expect($scope.dataCount).toEqual(4); $scope.names.pop(); $scope.$digest(); //now there's been a change expect($scope.dataCount).toEqual(3); * ``` * * * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The * expression value should evaluate to an object or an array which is observed on each * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the * collection will trigger a call to the `listener`. * * @param {function(newCollection, oldCollection, scope)} listener a callback function called * when a change is detected. * - The `newCollection` object is the newly modified data obtained from the `obj` expression * - The `oldCollection` object is a copy of the former collection data. * Due to performance considerations, the`oldCollection` value is computed only if the * `listener` function declares two or more arguments. * - The `scope` argument refers to the current scope. * * @returns {function()} Returns a de-registration function for this listener. When the * de-registration function is executed, the internal watch operation is terminated. */ $watchCollection: function(obj, listener) { var self = this; // the current value, updated on each dirty-check run var newValue; // a shallow copy of the newValue from the last dirty-check run, // updated to match newValue during dirty-check run var oldValue; // a shallow copy of the newValue from when the last change happened var veryOldValue; // only track veryOldValue if the listener is asking for it var trackVeryOldValue = (listener.length > 1); var changeDetected = 0; var objGetter = $parse(obj); var internalArray = []; var internalObject = {}; var initRun = true; var oldLength = 0; function $watchCollectionWatch() { newValue = objGetter(self); var newLength, key; if (!isObject(newValue)) { // if primitive if (oldValue !== newValue) { oldValue = newValue; changeDetected++; } } else if (isArrayLike(newValue)) { if (oldValue !== internalArray) { // we are transitioning from something which was not an array into array. oldValue = internalArray; oldLength = oldValue.length = 0; changeDetected++; } newLength = newValue.length; if (oldLength !== newLength) { // if lengths do not match we need to trigger change notification changeDetected++; oldValue.length = oldLength = newLength; } // copy the items to oldValue and look for changes. for (var i = 0; i < newLength; i++) { var bothNaN = (oldValue[i] !== oldValue[i]) && (newValue[i] !== newValue[i]); if (!bothNaN && (oldValue[i] !== newValue[i])) { changeDetected++; oldValue[i] = newValue[i]; } } } else { if (oldValue !== internalObject) { // we are transitioning from something which was not an object into object. oldValue = internalObject = {}; oldLength = 0; changeDetected++; } // copy the items to oldValue and look for changes. newLength = 0; for (key in newValue) { if (newValue.hasOwnProperty(key)) { newLength++; if (oldValue.hasOwnProperty(key)) { if (oldValue[key] !== newValue[key]) { changeDetected++; oldValue[key] = newValue[key]; } } else { oldLength++; oldValue[key] = newValue[key]; changeDetected++; } } } if (oldLength > newLength) { // we used to have more keys, need to find them and destroy them. changeDetected++; for(key in oldValue) { if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) { oldLength--; delete oldValue[key]; } } } } $watchCollectionWatch.$$unwatch = objGetter.$$unwatch; return changeDetected; } function $watchCollectionAction() { if (initRun) { initRun = false; listener(newValue, newValue, self); } else { listener(newValue, veryOldValue, self); } // make a copy for the next time a collection is changed if (trackVeryOldValue) { if (!isObject(newValue)) { //primitive veryOldValue = newValue; } else if (isArrayLike(newValue)) { veryOldValue = new Array(newValue.length); for (var i = 0; i < newValue.length; i++) { veryOldValue[i] = newValue[i]; } } else { // if object veryOldValue = {}; for (var key in newValue) { if (hasOwnProperty.call(newValue, key)) { veryOldValue[key] = newValue[key]; } } } } } return this.$watch($watchCollectionWatch, $watchCollectionAction); }, /** * @ngdoc method * @name $rootScope.Scope#$digest * @kind function * * @description * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} * until no more listeners are firing. This means that it is possible to get into an infinite * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of * iterations exceeds 10. * * Usually, you don't call `$digest()` directly in * {@link ng.directive:ngController controllers} or in * {@link ng.$compileProvider#directive directives}. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`. * * If you want to be notified whenever `$digest()` is called, * you can register a `watchExpression` function with * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`. * * In unit tests, you may need to call `$digest()` to simulate the scope life cycle. * * # Example * ```js var scope = ...; scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // the listener is always called during the first $digest loop after it was registered expect(scope.counter).toEqual(1); scope.$digest(); // but now it will not be called unless the value changes expect(scope.counter).toEqual(1); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(2); * ``` * */ $digest: function() { var watch, value, last, watchers, asyncQueue = this.$$asyncQueue, postDigestQueue = this.$$postDigestQueue, length, dirty, ttl = TTL, next, current, target = this, watchLog = [], stableWatchesCandidates = [], logIdx, logMsg, asyncTask; beginPhase('$digest'); lastDirtyWatch = null; do { // "while dirty" loop dirty = false; current = target; while(asyncQueue.length) { try { asyncTask = asyncQueue.shift(); asyncTask.scope.$eval(asyncTask.expression); } catch (e) { clearPhase(); $exceptionHandler(e); } lastDirtyWatch = null; } traverseScopesLoop: do { // "traverse the scopes" loop if ((watchers = current.$$watchers)) { // process our watches length = watchers.length; while (length--) { try { watch = watchers[length]; // Most common watches are on primitives, in which case we can short // circuit it with === operator, only when === fails do we use .equals if (watch) { if ((value = watch.get(current)) !== (last = watch.last) && !(watch.eq ? equals(value, last) : (typeof value == 'number' && typeof last == 'number' && isNaN(value) && isNaN(last)))) { dirty = true; lastDirtyWatch = watch; watch.last = watch.eq ? copy(value, null) : value; watch.fn(value, ((last === initWatchVal) ? value : last), current); if (ttl < 5) { logIdx = 4 - ttl; if (!watchLog[logIdx]) watchLog[logIdx] = []; logMsg = (isFunction(watch.exp)) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp; logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last); watchLog[logIdx].push(logMsg); } if (watch.get.$$unwatch) stableWatchesCandidates.push({watch: watch, array: watchers}); } else if (watch === lastDirtyWatch) { // If the most recently dirty watcher is now clean, short circuit since the remaining watchers // have already been tested. dirty = false; break traverseScopesLoop; } } } catch (e) { clearPhase(); $exceptionHandler(e); } } } // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $broadcast if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { while(current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } while ((current = next)); // `break traverseScopesLoop;` takes us to here if((dirty || asyncQueue.length) && !(ttl--)) { clearPhase(); throw $rootScopeMinErr('infdig', '{0} $digest() iterations reached. Aborting!\n' + 'Watchers fired in the last 5 iterations: {1}', TTL, toJson(watchLog)); } } while (dirty || asyncQueue.length); clearPhase(); while(postDigestQueue.length) { try { postDigestQueue.shift()(); } catch (e) { $exceptionHandler(e); } } for (length = stableWatchesCandidates.length - 1; length >= 0; --length) { var candidate = stableWatchesCandidates[length]; if (candidate.watch.get.$$unwatch) { arrayRemove(candidate.array, candidate.watch); } } }, /** * @ngdoc event * @name $rootScope.Scope#$destroy * @eventType broadcast on scope being destroyed * * @description * Broadcasted when a scope and its children are being destroyed. * * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to * clean up DOM bindings before an element is removed from the DOM. */ /** * @ngdoc method * @name $rootScope.Scope#$destroy * @kind function * * @description * Removes the current scope (and all of its children) from the parent scope. Removal implies * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer * propagate to the current scope and its children. Removal also implies that the current * scope is eligible for garbage collection. * * The `$destroy()` is usually used by directives such as * {@link ng.directive:ngRepeat ngRepeat} for managing the * unrolling of the loop. * * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope. * Application code can register a `$destroy` event handler that will give it a chance to * perform any necessary cleanup. * * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to * clean up DOM bindings before an element is removed from the DOM. */ $destroy: function() { // we can't destroy the root scope or a scope that has been already destroyed if (this.$$destroyed) return; var parent = this.$parent; this.$broadcast('$destroy'); this.$$destroyed = true; if (this === $rootScope) return; forEach(this.$$listenerCount, bind(null, decrementListenerCount, this)); // sever all the references to parent scopes (after this cleanup, the current scope should // not be retained by any of our references and should be eligible for garbage collection) if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling; if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling; if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; // All of the code below is bogus code that works around V8's memory leak via optimized code // and inline caches. // // see: // - https://code.google.com/p/v8/issues/detail?id=2073#c26 // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909 // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451 this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead = this.$$childTail = this.$root = null; // don't reset these to null in case some async task tries to register a listener/watch/task this.$$listeners = {}; this.$$watchers = this.$$asyncQueue = this.$$postDigestQueue = []; // prevent NPEs since these methods have references to properties we nulled out this.$destroy = this.$digest = this.$apply = noop; this.$on = this.$watch = this.$watchGroup = function() { return noop; }; }, /** * @ngdoc method * @name $rootScope.Scope#$eval * @kind function * * @description * Executes the `expression` on the current scope and returns the result. Any exceptions in * the expression are propagated (uncaught). This is useful when evaluating Angular * expressions. * * # Example * ```js var scope = ng.$rootScope.Scope(); scope.a = 1; scope.b = 2; expect(scope.$eval('a+b')).toEqual(3); expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3); * ``` * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * * @param {(object)=} locals Local variables object, useful for overriding values in scope. * @returns {*} The result of evaluating the expression. */ $eval: function(expr, locals) { return $parse(expr)(this, locals); }, /** * @ngdoc method * @name $rootScope.Scope#$evalAsync * @kind function * * @description * Executes the expression on the current scope at a later point in time. * * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only * that: * * - it will execute after the function that scheduled the evaluation (preferably before DOM * rendering). * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after * `expression` execution. * * Any exceptions from the execution of the expression are forwarded to the * {@link ng.$exceptionHandler $exceptionHandler} service. * * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle * will be scheduled. However, it is encouraged to always call code that changes the model * from within an `$apply` call. That includes code evaluated via `$evalAsync`. * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * */ $evalAsync: function(expr) { // if we are outside of an $digest loop and this is the first time we are scheduling async // task also schedule async auto-flush if (!$rootScope.$$phase && !$rootScope.$$asyncQueue.length) { $browser.defer(function() { if ($rootScope.$$asyncQueue.length) { $rootScope.$digest(); } }); } this.$$asyncQueue.push({scope: this, expression: expr}); }, $$postDigest : function(fn) { this.$$postDigestQueue.push(fn); }, /** * @ngdoc method * @name $rootScope.Scope#$apply * @kind function * * @description * `$apply()` is used to execute an expression in angular from outside of the angular * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). * Because we are calling into the angular framework we need to perform proper scope life * cycle of {@link ng.$exceptionHandler exception handling}, * {@link ng.$rootScope.Scope#$digest executing watches}. * * ## Life cycle * * # Pseudo-Code of `$apply()` * ```js function $apply(expr) { try { return $eval(expr); } catch (e) { $exceptionHandler(e); } finally { $root.$digest(); } } * ``` * * * Scope's `$apply()` method transitions through the following stages: * * 1. The {@link guide/expression expression} is executed using the * {@link ng.$rootScope.Scope#$eval $eval()} method. * 2. Any exceptions from the execution of the expression are forwarded to the * {@link ng.$exceptionHandler $exceptionHandler} service. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method. * * * @param {(string|function())=} exp An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with current `scope` parameter. * * @returns {*} The result of evaluating the expression. */ $apply: function(expr) { try { beginPhase('$apply'); return this.$eval(expr); } catch (e) { $exceptionHandler(e); } finally { clearPhase(); try { $rootScope.$digest(); } catch (e) { $exceptionHandler(e); throw e; } } }, /** * @ngdoc method * @name $rootScope.Scope#$on * @kind function * * @description * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for * discussion of event life cycle. * * The event listener function format is: `function(event, args...)`. The `event` object * passed into the listener has the following attributes: * * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or * `$broadcast`-ed. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the * event propagates through the scope hierarchy, this property is set to null. * - `name` - `{string}`: name of the event. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel * further event propagation (available only for events that were `$emit`-ed). * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag * to true. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called. * * @param {string} name Event name to listen on. * @param {function(event, ...args)} listener Function to call when the event is emitted. * @returns {function()} Returns a deregistration function for this listener. */ $on: function(name, listener) { var namedListeners = this.$$listeners[name]; if (!namedListeners) { this.$$listeners[name] = namedListeners = []; } namedListeners.push(listener); var current = this; do { if (!current.$$listenerCount[name]) { current.$$listenerCount[name] = 0; } current.$$listenerCount[name]++; } while ((current = current.$parent)); var self = this; return function() { namedListeners[indexOf(namedListeners, listener)] = null; decrementListenerCount(self, 1, name); }; }, /** * @ngdoc method * @name $rootScope.Scope#$emit * @kind function * * @description * Dispatches an event `name` upwards through the scope hierarchy notifying the * registered {@link ng.$rootScope.Scope#$on} listeners. * * The event life cycle starts at the scope on which `$emit` was called. All * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get * notified. Afterwards, the event traverses upwards toward the root scope and calls all * registered listeners along the way. The event will stop propagating if one of the listeners * cancels it. * * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed * onto the {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to emit. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}). */ $emit: function(name, args) { var empty = [], namedListeners, scope = this, stopPropagation = false, event = { name: name, targetScope: scope, stopPropagation: function() {stopPropagation = true;}, preventDefault: function() { event.defaultPrevented = true; }, defaultPrevented: false }, listenerArgs = concat([event], arguments, 1), i, length; do { namedListeners = scope.$$listeners[name] || empty; event.currentScope = scope; for (i=0, length=namedListeners.length; i<length; i++) { // if listeners were deregistered, defragment the array if (!namedListeners[i]) { namedListeners.splice(i, 1); i--; length--; continue; } try { //allow all listeners attached to the current scope to run namedListeners[i].apply(null, listenerArgs); } catch (e) { $exceptionHandler(e); } } //if any listener on the current scope stops propagation, prevent bubbling if (stopPropagation) { event.currentScope = null; return event; } //traverse upwards scope = scope.$parent; } while (scope); event.currentScope = null; return event; }, /** * @ngdoc method * @name $rootScope.Scope#$broadcast * @kind function * * @description * Dispatches an event `name` downwards to all child scopes (and their children) notifying the * registered {@link ng.$rootScope.Scope#$on} listeners. * * The event life cycle starts at the scope on which `$broadcast` was called. All * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get * notified. Afterwards, the event propagates to all direct and indirect scopes of the current * scope and calls all registered listeners along the way. The event cannot be canceled. * * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed * onto the {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to broadcast. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} */ $broadcast: function(name, args) { var target = this, current = target, next = target, event = { name: name, targetScope: target, preventDefault: function() { event.defaultPrevented = true; }, defaultPrevented: false }, listenerArgs = concat([event], arguments, 1), listeners, i, length; //down while you can, then up and next sibling or up and next sibling until back at root while ((current = next)) { event.currentScope = current; listeners = current.$$listeners[name] || []; for (i=0, length = listeners.length; i<length; i++) { // if listeners were deregistered, defragment the array if (!listeners[i]) { listeners.splice(i, 1); i--; length--; continue; } try { listeners[i].apply(null, listenerArgs); } catch(e) { $exceptionHandler(e); } } // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $digest // (though it differs due to having the extra check for $$listenerCount) if (!(next = ((current.$$listenerCount[name] && current.$$childHead) || (current !== target && current.$$nextSibling)))) { while(current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } event.currentScope = null; return event; } }; var $rootScope = new Scope(); return $rootScope; function beginPhase(phase) { if ($rootScope.$$phase) { throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase); } $rootScope.$$phase = phase; } function clearPhase() { $rootScope.$$phase = null; } function compileToFn(exp, name) { var fn = $parse(exp); assertArgFn(fn, name); return fn; } function decrementListenerCount(current, count, name) { do { current.$$listenerCount[name] -= count; if (current.$$listenerCount[name] === 0) { delete current.$$listenerCount[name]; } } while ((current = current.$parent)); } /** * function used as an initial value for watchers. * because it's unique we can easily tell it apart from other values */ function initWatchVal() {} }]; } /** * @description * Private service to sanitize uris for links and images. Used by $compile and $sanitize. */ function $$SanitizeUriProvider() { var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/, imgSrcSanitizationWhitelist = /^\s*(https?|ftp|file|blob):|data:image\//; /** * @description * Retrieves or overrides the default regular expression that is used for whitelisting of safe * urls during a[href] sanitization. * * The sanitization is a security measure aimed at prevent XSS attacks via html links. * * Any url about to be assigned to a[href] via data-binding is first normalized and turned into * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` * regular expression. If a match is found, the original url is written into the dom. Otherwise, * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. * * @param {RegExp=} regexp New regexp to whitelist urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ this.aHrefSanitizationWhitelist = function(regexp) { if (isDefined(regexp)) { aHrefSanitizationWhitelist = regexp; return this; } return aHrefSanitizationWhitelist; }; /** * @description * Retrieves or overrides the default regular expression that is used for whitelisting of safe * urls during img[src] sanitization. * * The sanitization is a security measure aimed at prevent XSS attacks via html links. * * Any url about to be assigned to img[src] via data-binding is first normalized and turned into * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` * regular expression. If a match is found, the original url is written into the dom. Otherwise, * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. * * @param {RegExp=} regexp New regexp to whitelist urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ this.imgSrcSanitizationWhitelist = function(regexp) { if (isDefined(regexp)) { imgSrcSanitizationWhitelist = regexp; return this; } return imgSrcSanitizationWhitelist; }; this.$get = function() { return function sanitizeUri(uri, isImage) { var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist; var normalizedVal; // NOTE: urlResolve() doesn't support IE < 8 so we don't sanitize for that case. if (!msie || msie >= 8 ) { normalizedVal = urlResolve(uri).href; if (normalizedVal !== '' && !normalizedVal.match(regex)) { return 'unsafe:'+normalizedVal; } } return uri; }; }; } var $sceMinErr = minErr('$sce'); var SCE_CONTEXTS = { HTML: 'html', CSS: 'css', URL: 'url', // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a // url. (e.g. ng-include, script src, templateUrl) RESOURCE_URL: 'resourceUrl', JS: 'js' }; // Helper functions follow. // Copied from: // http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962 // Prereq: s is a string. function escapeForRegexp(s) { return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1'). replace(/\x08/g, '\\x08'); } function adjustMatcher(matcher) { if (matcher === 'self') { return matcher; } else if (isString(matcher)) { // Strings match exactly except for 2 wildcards - '*' and '**'. // '*' matches any character except those from the set ':/.?&'. // '**' matches any character (like .* in a RegExp). // More than 2 *'s raises an error as it's ill defined. if (matcher.indexOf('***') > -1) { throw $sceMinErr('iwcard', 'Illegal sequence *** in string matcher. String: {0}', matcher); } matcher = escapeForRegexp(matcher). replace('\\*\\*', '.*'). replace('\\*', '[^:/.?&;]*'); return new RegExp('^' + matcher + '$'); } else if (isRegExp(matcher)) { // The only other type of matcher allowed is a Regexp. // Match entire URL / disallow partial matches. // Flags are reset (i.e. no global, ignoreCase or multiline) return new RegExp('^' + matcher.source + '$'); } else { throw $sceMinErr('imatcher', 'Matchers may only be "self", string patterns or RegExp objects'); } } function adjustMatchers(matchers) { var adjustedMatchers = []; if (isDefined(matchers)) { forEach(matchers, function(matcher) { adjustedMatchers.push(adjustMatcher(matcher)); }); } return adjustedMatchers; } /** * @ngdoc service * @name $sceDelegate * @kind function * * @description * * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict * Contextual Escaping (SCE)} services to AngularJS. * * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things * work because `$sce` delegates to `$sceDelegate` for these operations. * * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service. * * The default instance of `$sceDelegate` should work out of the box with little pain. While you * can override it completely to change the behavior of `$sce`, the common case would * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist * $sceDelegateProvider.resourceUrlWhitelist} and {@link * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist} */ /** * @ngdoc provider * @name $sceDelegateProvider * @description * * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure * that the URLs used for sourcing Angular templates are safe. Refer {@link * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist} * * For the general details about this service in Angular, read the main page for {@link ng.$sce * Strict Contextual Escaping (SCE)}. * * **Example**: Consider the following case. <a name="example"></a> * * - your app is hosted at url `http://myapp.example.com/` * - but some of your templates are hosted on other domains you control such as * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`. * * Here is what a secure configuration for this scenario might look like: * * <pre class="prettyprint"> * angular.module('myApp', []).config(function($sceDelegateProvider) { * $sceDelegateProvider.resourceUrlWhitelist([ * // Allow same origin resource loads. * 'self', * // Allow loading from our assets domain. Notice the difference between * and **. * 'http://srv*.assets.example.com/**']); * * // The blacklist overrides the whitelist so the open redirect here is blocked. * $sceDelegateProvider.resourceUrlBlacklist([ * 'http://myapp.example.com/clickThru**']); * }); * </pre> */ function $SceDelegateProvider() { this.SCE_CONTEXTS = SCE_CONTEXTS; // Resource URLs can also be trusted by policy. var resourceUrlWhitelist = ['self'], resourceUrlBlacklist = []; /** * @ngdoc method * @name $sceDelegateProvider#resourceUrlWhitelist * @kind function * * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value * provided. This must be an array or null. A snapshot of this array is used so further * changes to the array are ignored. * * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items * allowed in this array. * * Note: **an empty whitelist array will block all URLs**! * * @return {Array} the currently set whitelist array. * * The **default value** when no whitelist has been explicitly set is `['self']` allowing only * same origin resource requests. * * @description * Sets/Gets the whitelist of trusted resource URLs. */ this.resourceUrlWhitelist = function (value) { if (arguments.length) { resourceUrlWhitelist = adjustMatchers(value); } return resourceUrlWhitelist; }; /** * @ngdoc method * @name $sceDelegateProvider#resourceUrlBlacklist * @kind function * * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value * provided. This must be an array or null. A snapshot of this array is used so further * changes to the array are ignored. * * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items * allowed in this array. * * The typical usage for the blacklist is to **block * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as * these would otherwise be trusted but actually return content from the redirected domain. * * Finally, **the blacklist overrides the whitelist** and has the final say. * * @return {Array} the currently set blacklist array. * * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there * is no blacklist.) * * @description * Sets/Gets the blacklist of trusted resource URLs. */ this.resourceUrlBlacklist = function (value) { if (arguments.length) { resourceUrlBlacklist = adjustMatchers(value); } return resourceUrlBlacklist; }; this.$get = ['$injector', function($injector) { var htmlSanitizer = function htmlSanitizer(html) { throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); }; if ($injector.has('$sanitize')) { htmlSanitizer = $injector.get('$sanitize'); } function matchUrl(matcher, parsedUrl) { if (matcher === 'self') { return urlIsSameOrigin(parsedUrl); } else { // definitely a regex. See adjustMatchers() return !!matcher.exec(parsedUrl.href); } } function isResourceUrlAllowedByPolicy(url) { var parsedUrl = urlResolve(url.toString()); var i, n, allowed = false; // Ensure that at least one item from the whitelist allows this url. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) { if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) { allowed = true; break; } } if (allowed) { // Ensure that no item from the blacklist blocked this url. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) { if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) { allowed = false; break; } } } return allowed; } function generateHolderType(Base) { var holderType = function TrustedValueHolderType(trustedValue) { this.$$unwrapTrustedValue = function() { return trustedValue; }; }; if (Base) { holderType.prototype = new Base(); } holderType.prototype.valueOf = function sceValueOf() { return this.$$unwrapTrustedValue(); }; holderType.prototype.toString = function sceToString() { return this.$$unwrapTrustedValue().toString(); }; return holderType; } var trustedValueHolderBase = generateHolderType(), byType = {}; byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase); byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase); byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase); byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase); byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]); /** * @ngdoc method * @name $sceDelegate#trustAs * * @description * Returns an object that is trusted by angular for use in specified strict * contextual escaping contexts (such as ng-bind-html, ng-include, any src * attribute interpolation, any dom event binding attribute interpolation * such as for onclick, etc.) that uses the provided value. * See {@link ng.$sce $sce} for enabling strict contextual escaping. * * @param {string} type The kind of context in which this value is safe for use. e.g. url, * resourceUrl, html, js and css. * @param {*} value The value that that should be considered trusted/safe. * @returns {*} A value that can be used to stand in for the provided `value` in places * where Angular expects a $sce.trustAs() return value. */ function trustAs(type, trustedValue) { var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null); if (!Constructor) { throw $sceMinErr('icontext', 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}', type, trustedValue); } if (trustedValue === null || trustedValue === undefined || trustedValue === '') { return trustedValue; } // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting // mutable objects, we ensure here that the value passed in is actually a string. if (typeof trustedValue !== 'string') { throw $sceMinErr('itype', 'Attempted to trust a non-string value in a content requiring a string: Context: {0}', type); } return new Constructor(trustedValue); } /** * @ngdoc method * @name $sceDelegate#valueOf * * @description * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. * * If the passed parameter is not a value that had been returned by {@link * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is. * * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} * call or anything else. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns * `value` unchanged. */ function valueOf(maybeTrusted) { if (maybeTrusted instanceof trustedValueHolderBase) { return maybeTrusted.$$unwrapTrustedValue(); } else { return maybeTrusted; } } /** * @ngdoc method * @name $sceDelegate#getTrusted * * @description * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and * returns the originally supplied value if the queried context type is a supertype of the * created type. If this condition isn't satisfied, throws an exception. * * @param {string} type The kind of context in which this value is to be used. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs * `$sceDelegate.trustAs`} call. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception. */ function getTrusted(type, maybeTrusted) { if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') { return maybeTrusted; } var constructor = (byType.hasOwnProperty(type) ? byType[type] : null); if (constructor && maybeTrusted instanceof constructor) { return maybeTrusted.$$unwrapTrustedValue(); } // If we get here, then we may only take one of two actions. // 1. sanitize the value for the requested type, or // 2. throw an exception. if (type === SCE_CONTEXTS.RESOURCE_URL) { if (isResourceUrlAllowedByPolicy(maybeTrusted)) { return maybeTrusted; } else { throw $sceMinErr('insecurl', 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}', maybeTrusted.toString()); } } else if (type === SCE_CONTEXTS.HTML) { return htmlSanitizer(maybeTrusted); } throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); } return { trustAs: trustAs, getTrusted: getTrusted, valueOf: valueOf }; }]; } /** * @ngdoc provider * @name $sceProvider * @description * * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service. * - enable/disable Strict Contextual Escaping (SCE) in a module * - override the default implementation with a custom delegate * * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}. */ /* jshint maxlen: false*/ /** * @ngdoc service * @name $sce * @kind function * * @description * * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS. * * # Strict Contextual Escaping * * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain * contexts to result in a value that is marked as safe to use for that context. One example of * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer * to these contexts as privileged or SCE contexts. * * As of version 1.2, Angular ships with SCE enabled by default. * * Note: When enabled (the default), IE8 in quirks mode is not supported. In this mode, IE8 allows * one to execute arbitrary javascript by the use of the expression() syntax. Refer * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>` * to the top of your HTML document. * * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for * security vulnerabilities such as XSS, clickjacking, etc. a lot easier. * * Here's an example of a binding in a privileged context: * * <pre class="prettyprint"> * <input ng-model="userHtml"> * <div ng-bind-html="userHtml"> * </pre> * * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE * disabled, this application allows the user to render arbitrary HTML into the DIV. * In a more realistic example, one may be rendering user comments, blog articles, etc. via * bindings. (HTML is just one example of a context where rendering user controlled input creates * security vulnerabilities.) * * For the case of HTML, you might use a library, either on the client side, or on the server side, * to sanitize unsafe HTML before binding to the value and rendering it in the document. * * How would you ensure that every place that used these types of bindings was bound to a value that * was sanitized by your library (or returned as safe for rendering by your server?) How can you * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some * properties/fields and forgot to update the binding to the sanitized value? * * To be secure by default, you want to ensure that any such bindings are disallowed unless you can * determine that something explicitly says it's safe to use a value for binding in that * context. You can then audit your code (a simple grep would do) to ensure that this is only done * for those values that you can easily tell are safe - because they were received from your server, * sanitized by your library, etc. You can organize your codebase to help with this - perhaps * allowing only the files in a specific directory to do this. Ensuring that the internal API * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task. * * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs} * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to * obtain values that will be accepted by SCE / privileged contexts. * * * ## How does it work? * * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link * ng.$sce#parse $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals. * * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly * simplified): * * <pre class="prettyprint"> * var ngBindHtmlDirective = ['$sce', function($sce) { * return function(scope, element, attr) { * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) { * element.html(value || ''); * }); * }; * }]; * </pre> * * ## Impact on loading templates * * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as * `templateUrl`'s specified by {@link guide/directive directives}. * * By default, Angular only loads templates from the same domain and protocol as the application * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value. * * *Please note*: * The browser's * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest) * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/) * policy apply in addition to this and may further restrict whether the template is successfully * loaded. This means that without the right CORS policy, loading templates from a different domain * won't work on all browsers. Also, loading templates from `file://` URL does not work on some * browsers. * * ## This feels like too much overhead * * It's important to remember that SCE only applies to interpolation expressions. * * If your expressions are constant literals, they're automatically trusted and you don't need to * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works. * * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here. * * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load * templates in `ng-include` from your application's domain without having to even know about SCE. * It blocks loading templates from other domains or loading templates over http from an https * served document. You can change these by setting your own custom {@link * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs. * * This significantly reduces the overhead. It is far easier to pay the small overhead and have an * application that's secure and can be audited to verify that with much more ease than bolting * security onto an application later. * * <a name="contexts"></a> * ## What trusted context types are supported? * * | Context | Notes | * |---------------------|----------------| * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. | * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. | * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=` and `<img src=` sanitize their urls and don't constitute an SCE context. | * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. | * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. | * * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a> * * Each element in these arrays must be one of the following: * * - **'self'** * - The special **string**, `'self'`, can be used to match against all URLs of the **same * domain** as the application document using the **same protocol**. * - **String** (except the special value `'self'`) * - The string is matched against the full *normalized / absolute URL* of the resource * being tested (substring matches are not good enough.) * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters * match themselves. * - `*`: matches zero or more occurrences of any character other than one of the following 6 * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use * in a whitelist. * - `**`: matches zero or more occurrences of *any* character. As such, it's not * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might * not have been the intention.) Its usage at the very end of the path is ok. (e.g. * http://foo.example.com/templates/**). * - **RegExp** (*see caveat below*) * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to * accidentally introduce a bug when one updates a complex expression (imho, all regexes should * have good test coverage.). For instance, the use of `.` in the regex is correct only in a * small number of cases. A `.` character in the regex used when matching the scheme or a * subdomain could be matched against a `:` or literal `.` that was likely not intended. It * is highly recommended to use the string patterns and only fall back to regular expressions * if they as a last resort. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is * matched against the **entire** *normalized / absolute URL* of the resource being tested * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags * present on the RegExp (such as multiline, global, ignoreCase) are ignored. * - If you are generating your JavaScript from some other templating engine (not * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)), * remember to escape your regular expression (and be aware that you might need more than * one level of escaping depending on your templating engine and the way you interpolated * the value.) Do make use of your platform's escaping mechanism as it might be good * enough before coding your own. e.g. Ruby has * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape) * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape). * Javascript lacks a similar built in function for escaping. Take a look at Google * Closure library's [goog.string.regExpEscape(s)]( * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962). * * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example. * * ## Show me an example using SCE. * * @example <example module="mySceApp" deps="angular-sanitize.js"> <file name="index.html"> <div ng-controller="myAppController as myCtrl"> <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br> <b>User comments</b><br> By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when $sanitize is available. If $sanitize isn't available, this results in an error instead of an exploit. <div class="well"> <div ng-repeat="userComment in myCtrl.userComments"> <b>{{userComment.name}}</b>: <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span> <br> </div> </div> </div> </file> <file name="script.js"> var mySceApp = angular.module('mySceApp', ['ngSanitize']); mySceApp.controller("myAppController", function myAppController($http, $templateCache, $sce) { var self = this; $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) { self.userComments = userComments; }); self.explicitlyTrustedHtml = $sce.trustAsHtml( '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' + 'sanitization.&quot;">Hover over this text.</span>'); }); </file> <file name="test_data.json"> [ { "name": "Alice", "htmlComment": "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>" }, { "name": "Bob", "htmlComment": "<i>Yes!</i> Am I the only other one?" } ] </file> <file name="protractor.js" type="protractor"> describe('SCE doc demo', function() { it('should sanitize untrusted values', function() { expect(element(by.css('.htmlComment')).getInnerHtml()) .toBe('<span>Is <i>anyone</i> reading this?</span>'); }); it('should NOT sanitize explicitly trusted values', function() { expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe( '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' + 'sanitization.&quot;">Hover over this text.</span>'); }); }); </file> </example> * * * * ## Can I disable SCE completely? * * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits * for little coding overhead. It will be much harder to take an SCE disabled application and * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE * for cases where you have a lot of existing code that was written before SCE was introduced and * you're migrating them a module at a time. * * That said, here's how you can completely disable SCE: * * <pre class="prettyprint"> * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) { * // Completely disable SCE. For demonstration purposes only! * // Do not use in new projects. * $sceProvider.enabled(false); * }); * </pre> * */ /* jshint maxlen: 100 */ function $SceProvider() { var enabled = true; /** * @ngdoc method * @name $sceProvider#enabled * @kind function * * @param {boolean=} value If provided, then enables/disables SCE. * @return {boolean} true if SCE is enabled, false otherwise. * * @description * Enables/disables SCE and returns the current value. */ this.enabled = function (value) { if (arguments.length) { enabled = !!value; } return enabled; }; /* Design notes on the default implementation for SCE. * * The API contract for the SCE delegate * ------------------------------------- * The SCE delegate object must provide the following 3 methods: * * - trustAs(contextEnum, value) * This method is used to tell the SCE service that the provided value is OK to use in the * contexts specified by contextEnum. It must return an object that will be accepted by * getTrusted() for a compatible contextEnum and return this value. * * - valueOf(value) * For values that were not produced by trustAs(), return them as is. For values that were * produced by trustAs(), return the corresponding input value to trustAs. Basically, if * trustAs is wrapping the given values into some type, this operation unwraps it when given * such a value. * * - getTrusted(contextEnum, value) * This function should return the a value that is safe to use in the context specified by * contextEnum or throw and exception otherwise. * * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be * opaque or wrapped in some holder object. That happens to be an implementation detail. For * instance, an implementation could maintain a registry of all trusted objects by context. In * such a case, trustAs() would return the same object that was passed in. getTrusted() would * return the same object passed in if it was found in the registry under a compatible context or * throw an exception otherwise. An implementation might only wrap values some of the time based * on some criteria. getTrusted() might return a value and not throw an exception for special * constants or objects even if not wrapped. All such implementations fulfill this contract. * * * A note on the inheritance model for SCE contexts * ------------------------------------------------ * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This * is purely an implementation details. * * The contract is simply this: * * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value) * will also succeed. * * Inheritance happens to capture this in a natural way. In some future, we * may not use inheritance anymore. That is OK because no code outside of * sce.js and sceSpecs.js would need to be aware of this detail. */ this.$get = ['$parse', '$sniffer', '$sceDelegate', function( $parse, $sniffer, $sceDelegate) { // Prereq: Ensure that we're not running in IE8 quirks mode. In that mode, IE allows // the "expression(javascript expression)" syntax which is insecure. if (enabled && $sniffer.msie && $sniffer.msieDocumentMode < 8) { throw $sceMinErr('iequirks', 'Strict Contextual Escaping does not support Internet Explorer version < 9 in quirks ' + 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' + 'document. See http://docs.angularjs.org/api/ng.$sce for more information.'); } var sce = shallowCopy(SCE_CONTEXTS); /** * @ngdoc method * @name $sce#isEnabled * @kind function * * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you * have to do it at module config time on {@link ng.$sceProvider $sceProvider}. * * @description * Returns a boolean indicating if SCE is enabled. */ sce.isEnabled = function () { return enabled; }; sce.trustAs = $sceDelegate.trustAs; sce.getTrusted = $sceDelegate.getTrusted; sce.valueOf = $sceDelegate.valueOf; if (!enabled) { sce.trustAs = sce.getTrusted = function(type, value) { return value; }; sce.valueOf = identity; } /** * @ngdoc method * @name $sce#parse * * @description * Converts Angular {@link guide/expression expression} into a function. This is like {@link * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*, * *result*)} * * @param {string} type The kind of SCE context in which this result will be used. * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings * are evaluated against (typically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. */ sce.parseAs = function sceParseAs(type, expr) { var parsed = $parse(expr); if (parsed.literal && parsed.constant) { return parsed; } else { return function sceParseAsTrusted(self, locals) { var result = sce.getTrusted(type, parsed(self, locals)); sceParseAsTrusted.$$unwatch = parsed.$$unwatch; return result; }; } }; /** * @ngdoc method * @name $sce#trustAs * * @description * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such, * returns an object that is trusted by angular for use in specified strict contextual * escaping contexts (such as ng-bind-html, ng-include, any src attribute * interpolation, any dom event binding attribute interpolation such as for onclick, etc.) * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual * escaping. * * @param {string} type The kind of context in which this value is safe for use. e.g. url, * resource_url, html, js and css. * @param {*} value The value that that should be considered trusted/safe. * @returns {*} A value that can be used to stand in for the provided `value` in places * where Angular expects a $sce.trustAs() return value. */ /** * @ngdoc method * @name $sce#trustAsHtml * * @description * Shorthand method. `$sce.trustAsHtml(value)` → * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`} * * @param {*} value The value to trustAs. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives * only accept expressions that are either literal constants or are the * return value of {@link ng.$sce#trustAs $sce.trustAs}.) */ /** * @ngdoc method * @name $sce#trustAsUrl * * @description * Shorthand method. `$sce.trustAsUrl(value)` → * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`} * * @param {*} value The value to trustAs. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives * only accept expressions that are either literal constants or are the * return value of {@link ng.$sce#trustAs $sce.trustAs}.) */ /** * @ngdoc method * @name $sce#trustAsResourceUrl * * @description * Shorthand method. `$sce.trustAsResourceUrl(value)` → * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`} * * @param {*} value The value to trustAs. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives * only accept expressions that are either literal constants or are the return * value of {@link ng.$sce#trustAs $sce.trustAs}.) */ /** * @ngdoc method * @name $sce#trustAsJs * * @description * Shorthand method. `$sce.trustAsJs(value)` → * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`} * * @param {*} value The value to trustAs. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives * only accept expressions that are either literal constants or are the * return value of {@link ng.$sce#trustAs $sce.trustAs}.) */ /** * @ngdoc method * @name $sce#getTrusted * * @description * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such, * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the * originally supplied value if the queried context type is a supertype of the created type. * If this condition isn't satisfied, throws an exception. * * @param {string} type The kind of context in which this value is to be used. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`} * call. * @returns {*} The value the was originally provided to * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context. * Otherwise, throws an exception. */ /** * @ngdoc method * @name $sce#getTrustedHtml * * @description * Shorthand method. `$sce.getTrustedHtml(value)` → * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`} * * @param {*} value The value to pass to `$sce.getTrusted`. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)` */ /** * @ngdoc method * @name $sce#getTrustedCss * * @description * Shorthand method. `$sce.getTrustedCss(value)` → * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`} * * @param {*} value The value to pass to `$sce.getTrusted`. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)` */ /** * @ngdoc method * @name $sce#getTrustedUrl * * @description * Shorthand method. `$sce.getTrustedUrl(value)` → * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`} * * @param {*} value The value to pass to `$sce.getTrusted`. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)` */ /** * @ngdoc method * @name $sce#getTrustedResourceUrl * * @description * Shorthand method. `$sce.getTrustedResourceUrl(value)` → * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`} * * @param {*} value The value to pass to `$sceDelegate.getTrusted`. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)` */ /** * @ngdoc method * @name $sce#getTrustedJs * * @description * Shorthand method. `$sce.getTrustedJs(value)` → * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`} * * @param {*} value The value to pass to `$sce.getTrusted`. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)` */ /** * @ngdoc method * @name $sce#parseAsHtml * * @description * Shorthand method. `$sce.parseAsHtml(expression string)` → * {@link ng.$sce#parse `$sce.parseAs($sce.HTML, value)`} * * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings * are evaluated against (typically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. */ /** * @ngdoc method * @name $sce#parseAsCss * * @description * Shorthand method. `$sce.parseAsCss(value)` → * {@link ng.$sce#parse `$sce.parseAs($sce.CSS, value)`} * * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings * are evaluated against (typically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. */ /** * @ngdoc method * @name $sce#parseAsUrl * * @description * Shorthand method. `$sce.parseAsUrl(value)` → * {@link ng.$sce#parse `$sce.parseAs($sce.URL, value)`} * * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings * are evaluated against (typically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. */ /** * @ngdoc method * @name $sce#parseAsResourceUrl * * @description * Shorthand method. `$sce.parseAsResourceUrl(value)` → * {@link ng.$sce#parse `$sce.parseAs($sce.RESOURCE_URL, value)`} * * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings * are evaluated against (typically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. */ /** * @ngdoc method * @name $sce#parseAsJs * * @description * Shorthand method. `$sce.parseAsJs(value)` → * {@link ng.$sce#parse `$sce.parseAs($sce.JS, value)`} * * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings * are evaluated against (typically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. */ // Shorthand delegations. var parse = sce.parseAs, getTrusted = sce.getTrusted, trustAs = sce.trustAs; forEach(SCE_CONTEXTS, function (enumValue, name) { var lName = lowercase(name); sce[camelCase("parse_as_" + lName)] = function (expr) { return parse(enumValue, expr); }; sce[camelCase("get_trusted_" + lName)] = function (value) { return getTrusted(enumValue, value); }; sce[camelCase("trust_as_" + lName)] = function (value) { return trustAs(enumValue, value); }; }); return sce; }]; } /** * !!! This is an undocumented "private" service !!! * * @name $sniffer * @requires $window * @requires $document * * @property {boolean} history Does the browser support html5 history api ? * @property {boolean} hashchange Does the browser support hashchange event ? * @property {boolean} transitions Does the browser support CSS transition events ? * @property {boolean} animations Does the browser support CSS animation events ? * * @description * This is very simple implementation of testing browser's features. */ function $SnifferProvider() { this.$get = ['$window', '$document', function($window, $document) { var eventSupport = {}, android = int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]), boxee = /Boxee/i.test(($window.navigator || {}).userAgent), document = $document[0] || {}, documentMode = document.documentMode, vendorPrefix, vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/, bodyStyle = document.body && document.body.style, transitions = false, animations = false, match; if (bodyStyle) { for(var prop in bodyStyle) { if(match = vendorRegex.exec(prop)) { vendorPrefix = match[0]; vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1); break; } } if(!vendorPrefix) { vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit'; } transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle)); animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle)); if (android && (!transitions||!animations)) { transitions = isString(document.body.style.webkitTransition); animations = isString(document.body.style.webkitAnimation); } } return { // Android has history.pushState, but it does not update location correctly // so let's not use the history API at all. // http://code.google.com/p/android/issues/detail?id=17471 // https://github.com/angular/angular.js/issues/904 // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has // so let's not use the history API also // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined // jshint -W018 history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee), // jshint +W018 hashchange: 'onhashchange' in $window && // IE8 compatible mode lies (!documentMode || documentMode > 7), hasEvent: function(event) { // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have // it. In particular the event is not fired when backspace or delete key are pressed or // when cut operation is performed. if (event == 'input' && msie == 9) return false; if (isUndefined(eventSupport[event])) { var divElm = document.createElement('div'); eventSupport[event] = 'on' + event in divElm; } return eventSupport[event]; }, csp: csp(), vendorPrefix: vendorPrefix, transitions : transitions, animations : animations, android: android, msie : msie, msieDocumentMode: documentMode }; }]; } function $TimeoutProvider() { this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler', function($rootScope, $browser, $q, $exceptionHandler) { var deferreds = {}; /** * @ngdoc service * @name $timeout * * @description * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch * block and delegates any exceptions to * {@link ng.$exceptionHandler $exceptionHandler} service. * * The return value of registering a timeout function is a promise, which will be resolved when * the timeout is reached and the timeout function is executed. * * To cancel a timeout request, call `$timeout.cancel(promise)`. * * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to * synchronously flush the queue of deferred functions. * * @param {function()} fn A function, whose execution should be delayed. * @param {number=} [delay=0] Delay in milliseconds. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this * promise will be resolved with is the return value of the `fn` function. * */ function timeout(fn, delay, invokeApply) { var deferred = $q.defer(), promise = deferred.promise, skipApply = (isDefined(invokeApply) && !invokeApply), timeoutId; timeoutId = $browser.defer(function() { try { deferred.resolve(fn()); } catch(e) { deferred.reject(e); $exceptionHandler(e); } finally { delete deferreds[promise.$$timeoutId]; } if (!skipApply) $rootScope.$apply(); }, delay); promise.$$timeoutId = timeoutId; deferreds[timeoutId] = deferred; return promise; } /** * @ngdoc method * @name $timeout#cancel * * @description * Cancels a task associated with the `promise`. As a result of this, the promise will be * resolved with a rejection. * * @param {Promise=} promise Promise returned by the `$timeout` function. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully * canceled. */ timeout.cancel = function(promise) { if (promise && promise.$$timeoutId in deferreds) { deferreds[promise.$$timeoutId].reject('canceled'); delete deferreds[promise.$$timeoutId]; return $browser.defer.cancel(promise.$$timeoutId); } return false; }; return timeout; }]; } // NOTE: The usage of window and document instead of $window and $document here is // deliberate. This service depends on the specific behavior of anchor nodes created by the // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and // cause us to break tests. In addition, when the browser resolves a URL for XHR, it // doesn't know about mocked locations and resolves URLs to the real document - which is // exactly the behavior needed here. There is little value is mocking these out for this // service. var urlParsingNode = document.createElement("a"); var originUrl = urlResolve(window.location.href, true); /** * * Implementation Notes for non-IE browsers * ---------------------------------------- * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM, * results both in the normalizing and parsing of the URL. Normalizing means that a relative * URL will be resolved into an absolute URL in the context of the application document. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related * properties are all populated to reflect the normalized URL. This approach has wide * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html * * Implementation Notes for IE * --------------------------- * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other * browsers. However, the parsed components will not be set if the URL assigned did not specify * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We * work around that by performing the parsing in a 2nd step by taking a previously normalized * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the * properties such as protocol, hostname, port, etc. * * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one * uses the inner HTML approach to assign the URL as part of an HTML snippet - * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL. * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception. * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that * method and IE < 8 is unsupported. * * References: * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html * http://url.spec.whatwg.org/#urlutils * https://github.com/angular/angular.js/pull/2902 * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/ * * @kind function * @param {string} url The URL to be parsed. * @description Normalizes and parses a URL. * @returns {object} Returns the normalized URL as a dictionary. * * | member name | Description | * |---------------|----------------| * | href | A normalized version of the provided URL if it was not an absolute URL | * | protocol | The protocol including the trailing colon | * | host | The host and port (if the port is non-default) of the normalizedUrl | * | search | The search params, minus the question mark | * | hash | The hash string, minus the hash symbol * | hostname | The hostname * | port | The port, without ":" * | pathname | The pathname, beginning with "/" * */ function urlResolve(url, base) { var href = url; if (msie) { // Normalize before parse. Refer Implementation Notes on why this is // done in two steps on IE. urlParsingNode.setAttribute("href", href); href = urlParsingNode.href; } urlParsingNode.setAttribute('href', href); // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils return { href: urlParsingNode.href, protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', host: urlParsingNode.host, search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', hostname: urlParsingNode.hostname, port: urlParsingNode.port, pathname: (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname : '/' + urlParsingNode.pathname }; } /** * Parse a request URL and determine whether this is a same-origin request as the application document. * * @param {string|object} requestUrl The url of the request as a string that will be resolved * or a parsed URL object. * @returns {boolean} Whether the request is for the same origin as the application document. */ function urlIsSameOrigin(requestUrl) { var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl; return (parsed.protocol === originUrl.protocol && parsed.host === originUrl.host); } /** * @ngdoc service * @name $window * * @description * A reference to the browser's `window` object. While `window` * is globally available in JavaScript, it causes testability problems, because * it is a global variable. In angular we always refer to it through the * `$window` service, so it may be overridden, removed or mocked for testing. * * Expressions, like the one defined for the `ngClick` directive in the example * below, are evaluated with respect to the current scope. Therefore, there is * no risk of inadvertently coding in a dependency on a global value in such an * expression. * * @example <example> <file name="index.html"> <script> function Ctrl($scope, $window) { $scope.greeting = 'Hello, World!'; $scope.doGreeting = function(greeting) { $window.alert(greeting); }; } </script> <div ng-controller="Ctrl"> <input type="text" ng-model="greeting" /> <button ng-click="doGreeting(greeting)">ALERT</button> </div> </file> <file name="protractor.js" type="protractor"> it('should display the greeting in the input box', function() { element(by.model('greeting')).sendKeys('Hello, E2E Tests'); // If we click the button it will block the test runner // element(':button').click(); }); </file> </example> */ function $WindowProvider(){ this.$get = valueFn(window); } /** * @ngdoc provider * @name $filterProvider * @description * * Filters are just functions which transform input to an output. However filters need to be * Dependency Injected. To achieve this a filter definition consists of a factory function which is * annotated with dependencies and is responsible for creating a filter function. * * ```js * // Filter registration * function MyModule($provide, $filterProvider) { * // create a service to demonstrate injection (not always needed) * $provide.value('greet', function(name){ * return 'Hello ' + name + '!'; * }); * * // register a filter factory which uses the * // greet service to demonstrate DI. * $filterProvider.register('greet', function(greet){ * // return the filter function which uses the greet service * // to generate salutation * return function(text) { * // filters need to be forgiving so check input validity * return text && greet(text) || text; * }; * }); * } * ``` * * The filter function is registered with the `$injector` under the filter name suffix with * `Filter`. * * ```js * it('should be the same instance', inject( * function($filterProvider) { * $filterProvider.register('reverse', function(){ * return ...; * }); * }, * function($filter, reverseFilter) { * expect($filter('reverse')).toBe(reverseFilter); * }); * ``` * * * For more information about how angular filters work, and how to create your own filters, see * {@link guide/filter Filters} in the Angular Developer Guide. */ /** * @ngdoc method * @name $filterProvider#register * @description * Register filter factory function. * * @param {String} name Name of the filter. * @param {Function} fn The filter factory function which is injectable. */ /** * @ngdoc service * @name $filter * @kind function * @description * Filters are used for formatting data displayed to the user. * * The general syntax in templates is as follows: * * {{ expression [| filter_name[:parameter_value] ... ] }} * * @param {String} name Name of the filter function to retrieve * @return {Function} the filter function * @example <example name="$filter" module="filterExample"> <file name="index.html"> <div ng-controller="MainCtrl"> <h3>{{ originalText }}</h3> <h3>{{ filteredText }}</h3> </div> </file> <file name="script.js"> angular.module('filterExample', []) .controller('MainCtrl', function($scope, $filter) { $scope.originalText = 'hello'; $scope.filteredText = $filter('uppercase')($scope.originalText); }); </file> </example> */ $FilterProvider.$inject = ['$provide']; function $FilterProvider($provide) { var suffix = 'Filter'; /** * @ngdoc method * @name $controllerProvider#register * @param {string|Object} name Name of the filter function, or an object map of filters where * the keys are the filter names and the values are the filter factories. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map * of the registered filter instances. */ function register(name, factory) { if(isObject(name)) { var filters = {}; forEach(name, function(filter, key) { filters[key] = register(key, filter); }); return filters; } else { return $provide.factory(name + suffix, factory); } } this.register = register; this.$get = ['$injector', function($injector) { return function(name) { return $injector.get(name + suffix); }; }]; //////////////////////////////////////// /* global currencyFilter: false, dateFilter: false, filterFilter: false, jsonFilter: false, limitToFilter: false, lowercaseFilter: false, numberFilter: false, orderByFilter: false, uppercaseFilter: false, */ register('currency', currencyFilter); register('date', dateFilter); register('filter', filterFilter); register('json', jsonFilter); register('limitTo', limitToFilter); register('lowercase', lowercaseFilter); register('number', numberFilter); register('orderBy', orderByFilter); register('uppercase', uppercaseFilter); } /** * @ngdoc filter * @name filter * @kind function * * @description * Selects a subset of items from `array` and returns it as a new array. * * @param {Array} array The source array. * @param {string|Object|function()} expression The predicate to be used for selecting items from * `array`. * * Can be one of: * * - `string`: The string is evaluated as an expression and the resulting value is used for substring match against * the contents of the `array`. All strings or objects with string properties in `array` that contain this string * will be returned. The predicate can be negated by prefixing the string with `!`. * * - `Object`: A pattern object can be used to filter specific properties on objects contained * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items * which have property `name` containing "M" and property `phone` containing "1". A special * property name `$` can be used (as in `{$:"text"}`) to accept a match against any * property of the object. That's equivalent to the simple substring match with a `string` * as described above. * * - `function(value)`: A predicate function can be used to write arbitrary filters. The function is * called for each element of `array`. The final result is an array of those elements that * the predicate returned true for. * * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in * determining if the expected value (from the filter expression) and actual value (from * the object in the array) should be considered a match. * * Can be one of: * * - `function(actual, expected)`: * The function will be given the object value and the predicate value to compare and * should return true if the item should be included in filtered result. * * - `true`: A shorthand for `function(actual, expected) { return angular.equals(expected, actual)}`. * this is essentially strict comparison of expected and actual. * * - `false|undefined`: A short hand for a function which will look for a substring match in case * insensitive way. * * @example <example> <file name="index.html"> <div ng-init="friends = [{name:'John', phone:'555-1276'}, {name:'Mary', phone:'800-BIG-MARY'}, {name:'Mike', phone:'555-4321'}, {name:'Adam', phone:'555-5678'}, {name:'Julie', phone:'555-8765'}, {name:'Juliette', phone:'555-5678'}]"></div> Search: <input ng-model="searchText"> <table id="searchTextResults"> <tr><th>Name</th><th>Phone</th></tr> <tr ng-repeat="friend in friends | filter:searchText"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> </tr> </table> <hr> Any: <input ng-model="search.$"> <br> Name only <input ng-model="search.name"><br> Phone only <input ng-model="search.phone"><br> Equality <input type="checkbox" ng-model="strict"><br> <table id="searchObjResults"> <tr><th>Name</th><th>Phone</th></tr> <tr ng-repeat="friendObj in friends | filter:search:strict"> <td>{{friendObj.name}}</td> <td>{{friendObj.phone}}</td> </tr> </table> </file> <file name="protractor.js" type="protractor"> var expectFriendNames = function(expectedNames, key) { element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) { arr.forEach(function(wd, i) { expect(wd.getText()).toMatch(expectedNames[i]); }); }); }; it('should search across all fields when filtering with a string', function() { var searchText = element(by.model('searchText')); searchText.clear(); searchText.sendKeys('m'); expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend'); searchText.clear(); searchText.sendKeys('76'); expectFriendNames(['John', 'Julie'], 'friend'); }); it('should search in specific fields when filtering with a predicate object', function() { var searchAny = element(by.model('search.$')); searchAny.clear(); searchAny.sendKeys('i'); expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj'); }); it('should use a equal comparison when comparator is true', function() { var searchName = element(by.model('search.name')); var strict = element(by.model('strict')); searchName.clear(); searchName.sendKeys('Julie'); strict.click(); expectFriendNames(['Julie'], 'friendObj'); }); </file> </example> */ function filterFilter() { return function(array, expression, comparator) { if (!isArray(array)) return array; var comparatorType = typeof(comparator), predicates = []; predicates.check = function(value) { for (var j = 0; j < predicates.length; j++) { if(!predicates[j](value)) { return false; } } return true; }; if (comparatorType !== 'function') { if (comparatorType === 'boolean' && comparator) { comparator = function(obj, text) { return angular.equals(obj, text); }; } else { comparator = function(obj, text) { if (obj && text && typeof obj === 'object' && typeof text === 'object') { for (var objKey in obj) { if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) && comparator(obj[objKey], text[objKey])) { return true; } } return false; } text = (''+text).toLowerCase(); return (''+obj).toLowerCase().indexOf(text) > -1; }; } } var search = function(obj, text){ if (typeof text == 'string' && text.charAt(0) === '!') { return !search(obj, text.substr(1)); } switch (typeof obj) { case "boolean": case "number": case "string": return comparator(obj, text); case "object": switch (typeof text) { case "object": return comparator(obj, text); default: for ( var objKey in obj) { if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { return true; } } break; } return false; case "array": for ( var i = 0; i < obj.length; i++) { if (search(obj[i], text)) { return true; } } return false; default: return false; } }; switch (typeof expression) { case "boolean": case "number": case "string": // Set up expression object and fall through expression = {$:expression}; // jshint -W086 case "object": // jshint +W086 for (var key in expression) { (function(path) { if (typeof expression[path] == 'undefined') return; predicates.push(function(value) { return search(path == '$' ? value : (value && value[path]), expression[path]); }); })(key); } break; case 'function': predicates.push(expression); break; default: return array; } var filtered = []; for ( var j = 0; j < array.length; j++) { var value = array[j]; if (predicates.check(value)) { filtered.push(value); } } return filtered; }; } /** * @ngdoc filter * @name currency * @kind function * * @description * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default * symbol for current locale is used. * * @param {number} amount Input to filter. * @param {string=} symbol Currency symbol or identifier to be displayed. * @returns {string} Formatted number. * * * @example <example> <file name="index.html"> <script> function Ctrl($scope) { $scope.amount = 1234.56; } </script> <div ng-controller="Ctrl"> <input type="number" ng-model="amount"> <br> default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br> custom currency identifier (USD$): <span>{{amount | currency:"USD$"}}</span> </div> </file> <file name="protractor.js" type="protractor"> it('should init with 1234.56', function() { expect(element(by.id('currency-default')).getText()).toBe('$1,234.56'); expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('USD$1,234.56'); }); it('should update', function() { if (browser.params.browser == 'safari') { // Safari does not understand the minus key. See // https://github.com/angular/protractor/issues/481 return; } element(by.model('amount')).clear(); element(by.model('amount')).sendKeys('-1234'); expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)'); expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('(USD$1,234.00)'); }); </file> </example> */ currencyFilter.$inject = ['$locale']; function currencyFilter($locale) { var formats = $locale.NUMBER_FORMATS; return function(amount, currencySymbol){ if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM; return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2). replace(/\u00A4/g, currencySymbol); }; } /** * @ngdoc filter * @name number * @kind function * * @description * Formats a number as text. * * If the input is not a number an empty string is returned. * * @param {number|string} number Number to format. * @param {(number|string)=} fractionSize Number of decimal places to round the number to. * If this is not provided then the fraction size is computed from the current locale's number * formatting pattern. In the case of the default locale, it will be 3. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit. * * @example <example> <file name="index.html"> <script> function Ctrl($scope) { $scope.val = 1234.56789; } </script> <div ng-controller="Ctrl"> Enter number: <input ng-model='val'><br> Default formatting: <span id='number-default'>{{val | number}}</span><br> No fractions: <span>{{val | number:0}}</span><br> Negative number: <span>{{-val | number:4}}</span> </div> </file> <file name="protractor.js" type="protractor"> it('should format numbers', function() { expect(element(by.id('number-default')).getText()).toBe('1,234.568'); expect(element(by.binding('val | number:0')).getText()).toBe('1,235'); expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679'); }); it('should update', function() { element(by.model('val')).clear(); element(by.model('val')).sendKeys('3374.333'); expect(element(by.id('number-default')).getText()).toBe('3,374.333'); expect(element(by.binding('val | number:0')).getText()).toBe('3,374'); expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330'); }); </file> </example> */ numberFilter.$inject = ['$locale']; function numberFilter($locale) { var formats = $locale.NUMBER_FORMATS; return function(number, fractionSize) { return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize); }; } var DECIMAL_SEP = '.'; function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { if (number == null || !isFinite(number) || isObject(number)) return ''; var isNegative = number < 0; number = Math.abs(number); var numStr = number + '', formatedText = '', parts = []; var hasExponent = false; if (numStr.indexOf('e') !== -1) { var match = numStr.match(/([\d\.]+)e(-?)(\d+)/); if (match && match[2] == '-' && match[3] > fractionSize + 1) { numStr = '0'; } else { formatedText = numStr; hasExponent = true; } } if (!hasExponent) { var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length; // determine fractionSize if it is not specified if (isUndefined(fractionSize)) { fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac); } var pow = Math.pow(10, fractionSize + 1); number = Math.floor(number * pow + 5) / pow; var fraction = ('' + number).split(DECIMAL_SEP); var whole = fraction[0]; fraction = fraction[1] || ''; var i, pos = 0, lgroup = pattern.lgSize, group = pattern.gSize; if (whole.length >= (lgroup + group)) { pos = whole.length - lgroup; for (i = 0; i < pos; i++) { if ((pos - i)%group === 0 && i !== 0) { formatedText += groupSep; } formatedText += whole.charAt(i); } } for (i = pos; i < whole.length; i++) { if ((whole.length - i)%lgroup === 0 && i !== 0) { formatedText += groupSep; } formatedText += whole.charAt(i); } // format fraction part. while(fraction.length < fractionSize) { fraction += '0'; } if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize); } else { if (fractionSize > 0 && number > -1 && number < 1) { formatedText = number.toFixed(fractionSize); } } parts.push(isNegative ? pattern.negPre : pattern.posPre); parts.push(formatedText); parts.push(isNegative ? pattern.negSuf : pattern.posSuf); return parts.join(''); } function padNumber(num, digits, trim) { var neg = ''; if (num < 0) { neg = '-'; num = -num; } num = '' + num; while(num.length < digits) num = '0' + num; if (trim) num = num.substr(num.length - digits); return neg + num; } function dateGetter(name, size, offset, trim) { offset = offset || 0; return function(date) { var value = date['get' + name](); if (offset > 0 || value > -offset) value += offset; if (value === 0 && offset == -12 ) value = 12; return padNumber(value, size, trim); }; } function dateStrGetter(name, shortForm) { return function(date, formats) { var value = date['get' + name](); var get = uppercase(shortForm ? ('SHORT' + name) : name); return formats[get][value]; }; } function timeZoneGetter(date) { var zone = -1 * date.getTimezoneOffset(); var paddedZone = (zone >= 0) ? "+" : ""; paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) + padNumber(Math.abs(zone % 60), 2); return paddedZone; } function getFirstThursdayOfYear(year) { // 0 = index of January var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay(); // 4 = index of Thursday (+1 to account for 1st = 5) // 11 = index of *next* Thursday (+1 account for 1st = 12) return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst); } function getThursdayThisWeek(datetime) { return new Date(datetime.getFullYear(), datetime.getMonth(), // 4 = index of Thursday datetime.getDate() + (4 - datetime.getDay())); } function weekGetter(size) { return function(date) { var firstThurs = getFirstThursdayOfYear(date.getFullYear()), thisThurs = getThursdayThisWeek(date); var diff = +thisThurs - +firstThurs, result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week return padNumber(result, size); }; } function ampmGetter(date, formats) { return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]; } var DATE_FORMATS = { yyyy: dateGetter('FullYear', 4), yy: dateGetter('FullYear', 2, 0, true), y: dateGetter('FullYear', 1), MMMM: dateStrGetter('Month'), MMM: dateStrGetter('Month', true), MM: dateGetter('Month', 2, 1), M: dateGetter('Month', 1, 1), dd: dateGetter('Date', 2), d: dateGetter('Date', 1), HH: dateGetter('Hours', 2), H: dateGetter('Hours', 1), hh: dateGetter('Hours', 2, -12), h: dateGetter('Hours', 1, -12), mm: dateGetter('Minutes', 2), m: dateGetter('Minutes', 1), ss: dateGetter('Seconds', 2), s: dateGetter('Seconds', 1), // while ISO 8601 requires fractions to be prefixed with `.` or `,` // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions sss: dateGetter('Milliseconds', 3), EEEE: dateStrGetter('Day'), EEE: dateStrGetter('Day', true), a: ampmGetter, Z: timeZoneGetter, ww: weekGetter(2), w: weekGetter(1) }; var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEw']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|w+))(.*)/, NUMBER_STRING = /^\-?\d+$/; /** * @ngdoc filter * @name date * @kind function * * @description * Formats `date` to a string based on the requested `format`. * * `format` string can be composed of the following elements: * * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) * * `'MMMM'`: Month in year (January-December) * * `'MMM'`: Month in year (Jan-Dec) * * `'MM'`: Month in year, padded (01-12) * * `'M'`: Month in year (1-12) * * `'dd'`: Day in month, padded (01-31) * * `'d'`: Day in month (1-31) * * `'EEEE'`: Day in Week,(Sunday-Saturday) * * `'EEE'`: Day in Week, (Sun-Sat) * * `'HH'`: Hour in day, padded (00-23) * * `'H'`: Hour in day (0-23) * * `'hh'`: Hour in am/pm, padded (01-12) * * `'h'`: Hour in am/pm, (1-12) * * `'mm'`: Minute in hour, padded (00-59) * * `'m'`: Minute in hour (0-59) * * `'ss'`: Second in minute, padded (00-59) * * `'s'`: Second in minute (0-59) * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999) * * `'a'`: am/pm marker * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200) * * `'ww'`: ISO-8601 week of year (00-53) * * `'w'`: ISO-8601 week of year (0-53) * * `format` string can also be one of the following predefined * {@link guide/i18n localizable formats}: * * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale * (e.g. Sep 3, 2010 12:05:08 pm) * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm) * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale * (e.g. Friday, September 3, 2010) * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010) * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm) * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm) * * `format` string can contain literal values. These need to be quoted with single quotes (e.g. * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence * (e.g. `"h 'o''clock'"`). * * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is * specified in the string input, the time is considered to be in the local timezone. * @param {string=} format Formatting rules (see Description). If not specified, * `mediumDate` is used. * @returns {string} Formatted string or the input if input is not recognized as date/millis. * * @example <example> <file name="index.html"> <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>: <span>{{1288323623006 | date:'medium'}}</span><br> <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>: <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br> <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>: <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br> </file> <file name="protractor.js" type="protractor"> it('should format date', function() { expect(element(by.binding("1288323623006 | date:'medium'")).getText()). toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/); expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()). toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/); expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()). toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/); }); </file> </example> */ dateFilter.$inject = ['$locale']; function dateFilter($locale) { var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; // 1 2 3 4 5 6 7 8 9 10 11 function jsonStringToDate(string) { var match; if (match = string.match(R_ISO8601_STR)) { var date = new Date(0), tzHour = 0, tzMin = 0, dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear, timeSetter = match[8] ? date.setUTCHours : date.setHours; if (match[9]) { tzHour = int(match[9] + match[10]); tzMin = int(match[9] + match[11]); } dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3])); var h = int(match[4]||0) - tzHour; var m = int(match[5]||0) - tzMin; var s = int(match[6]||0); var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000); timeSetter.call(date, h, m, s, ms); return date; } return string; } return function(date, format) { var text = '', parts = [], fn, match; format = format || 'mediumDate'; format = $locale.DATETIME_FORMATS[format] || format; if (isString(date)) { if (NUMBER_STRING.test(date)) { date = int(date); } else { date = jsonStringToDate(date); } } if (isNumber(date)) { date = new Date(date); } if (!isDate(date)) { return date; } while(format) { match = DATE_FORMATS_SPLIT.exec(format); if (match) { parts = concat(parts, match, 1); format = parts.pop(); } else { parts.push(format); format = null; } } forEach(parts, function(value){ fn = DATE_FORMATS[value]; text += fn ? fn(date, $locale.DATETIME_FORMATS) : value.replace(/(^'|'$)/g, '').replace(/''/g, "'"); }); return text; }; } /** * @ngdoc filter * @name json * @kind function * * @description * Allows you to convert a JavaScript object into JSON string. * * This filter is mostly useful for debugging. When using the double curly {{value}} notation * the binding is automatically converted to JSON. * * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. * @returns {string} JSON string. * * * @example <example> <file name="index.html"> <pre>{{ {'name':'value'} | json }}</pre> </file> <file name="protractor.js" type="protractor"> it('should jsonify filtered objects', function() { expect(element(by.binding("{'name':'value'}")).getText()).toMatch(/\{\n "name": ?"value"\n}/); }); </file> </example> * */ function jsonFilter() { return function(object) { return toJson(object, true); }; } /** * @ngdoc filter * @name lowercase * @kind function * @description * Converts string to lowercase. * @see angular.lowercase */ var lowercaseFilter = valueFn(lowercase); /** * @ngdoc filter * @name uppercase * @kind function * @description * Converts string to uppercase. * @see angular.uppercase */ var uppercaseFilter = valueFn(uppercase); /** * @ngdoc filter * @name limitTo * @kind function * * @description * Creates a new array or string containing only a specified number of elements. The elements * are taken from either the beginning or the end of the source array or string, as specified by * the value and sign (positive or negative) of `limit`. * * @param {Array|string} input Source array or string to be limited. * @param {string|number} limit The length of the returned array or string. If the `limit` number * is positive, `limit` number of items from the beginning of the source array/string are copied. * If the number is negative, `limit` number of items from the end of the source array/string * are copied. The `limit` will be trimmed if it exceeds `array.length` * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array * had less than `limit` elements. * * @example <example> <file name="index.html"> <script> function Ctrl($scope) { $scope.numbers = [1,2,3,4,5,6,7,8,9]; $scope.letters = "abcdefghi"; $scope.numLimit = 3; $scope.letterLimit = 3; } </script> <div ng-controller="Ctrl"> Limit {{numbers}} to: <input type="integer" ng-model="numLimit"> <p>Output numbers: {{ numbers | limitTo:numLimit }}</p> Limit {{letters}} to: <input type="integer" ng-model="letterLimit"> <p>Output letters: {{ letters | limitTo:letterLimit }}</p> </div> </file> <file name="protractor.js" type="protractor"> var numLimitInput = element(by.model('numLimit')); var letterLimitInput = element(by.model('letterLimit')); var limitedNumbers = element(by.binding('numbers | limitTo:numLimit')); var limitedLetters = element(by.binding('letters | limitTo:letterLimit')); it('should limit the number array to first three items', function() { expect(numLimitInput.getAttribute('value')).toBe('3'); expect(letterLimitInput.getAttribute('value')).toBe('3'); expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]'); expect(limitedLetters.getText()).toEqual('Output letters: abc'); }); it('should update the output when -3 is entered', function() { numLimitInput.clear(); numLimitInput.sendKeys('-3'); letterLimitInput.clear(); letterLimitInput.sendKeys('-3'); expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]'); expect(limitedLetters.getText()).toEqual('Output letters: ghi'); }); it('should not exceed the maximum size of input array', function() { numLimitInput.clear(); numLimitInput.sendKeys('100'); letterLimitInput.clear(); letterLimitInput.sendKeys('100'); expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]'); expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi'); }); </file> </example> */ function limitToFilter(){ return function(input, limit) { if (!isArray(input) && !isString(input)) return input; if (Math.abs(Number(limit)) === Infinity) { limit = Number(limit); } else { limit = int(limit); } if (isString(input)) { //NaN check on limit if (limit) { return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length); } else { return ""; } } var out = [], i, n; // if abs(limit) exceeds maximum length, trim it if (limit > input.length) limit = input.length; else if (limit < -input.length) limit = -input.length; if (limit > 0) { i = 0; n = limit; } else { i = input.length + limit; n = input.length; } for (; i<n; i++) { out.push(input[i]); } return out; }; } /** * @ngdoc filter * @name orderBy * @kind function * * @description * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically * for strings and numerically for numbers. Note: if you notice numbers are not being sorted * correctly, make sure they are actually being saved as numbers and not strings. * * @param {Array} array The array to sort. * @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be * used by the comparator to determine the order of elements. * * Can be one of: * * - `function`: Getter function. The result of this function will be sorted using the * `<`, `=`, `>` operator. * - `string`: An Angular expression which evaluates to an object to order by, such as 'name' * to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control * ascending or descending sort order (for example, +name or -name). * - `Array`: An array of function or string predicates. The first predicate in the array * is used for sorting, but when two items are equivalent, the next predicate is used. * * @param {boolean=} reverse Reverse the order of the array. * @returns {Array} Sorted copy of the source array. * * @example <example> <file name="index.html"> <script> function Ctrl($scope) { $scope.friends = [{name:'John', phone:'555-1212', age:10}, {name:'Mary', phone:'555-9876', age:19}, {name:'Mike', phone:'555-4321', age:21}, {name:'Adam', phone:'555-5678', age:35}, {name:'Julie', phone:'555-8765', age:29}] $scope.predicate = '-age'; } </script> <div ng-controller="Ctrl"> <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre> <hr/> [ <a href="" ng-click="predicate=''">unsorted</a> ] <table class="friend"> <tr> <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a> (<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th> <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th> <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th> </tr> <tr ng-repeat="friend in friends | orderBy:predicate:reverse"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <td>{{friend.age}}</td> </tr> </table> </div> </file> </example> * * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the * desired parameters. * * Example: * * @example <example> <file name="index.html"> <div ng-controller="Ctrl"> <table class="friend"> <tr> <th><a href="" ng-click="reverse=false;order('name', false)">Name</a> (<a href="" ng-click="order('-name',false)">^</a>)</th> <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th> <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th> </tr> <tr ng-repeat="friend in friends"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <td>{{friend.age}}</td> </tr> </table> </div> </file> <file name="script.js"> function Ctrl($scope, $filter) { var orderBy = $filter('orderBy'); $scope.friends = [ { name: 'John', phone: '555-1212', age: 10 }, { name: 'Mary', phone: '555-9876', age: 19 }, { name: 'Mike', phone: '555-4321', age: 21 }, { name: 'Adam', phone: '555-5678', age: 35 }, { name: 'Julie', phone: '555-8765', age: 29 } ]; $scope.order = function(predicate, reverse) { $scope.friends = orderBy($scope.friends, predicate, reverse); }; $scope.order('-age',false); } </file> </example> */ orderByFilter.$inject = ['$parse']; function orderByFilter($parse){ return function(array, sortPredicate, reverseOrder) { if (!isArray(array)) return array; if (!sortPredicate) return array; sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate]; sortPredicate = map(sortPredicate, function(predicate){ var descending = false, get = predicate || identity; if (isString(predicate)) { if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) { descending = predicate.charAt(0) == '-'; predicate = predicate.substring(1); } get = $parse(predicate); if (get.constant) { var key = get(); return reverseComparator(function(a,b) { return compare(a[key], b[key]); }, descending); } } return reverseComparator(function(a,b){ return compare(get(a),get(b)); }, descending); }); var arrayCopy = []; for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); } return arrayCopy.sort(reverseComparator(comparator, reverseOrder)); function comparator(o1, o2){ for ( var i = 0; i < sortPredicate.length; i++) { var comp = sortPredicate[i](o1, o2); if (comp !== 0) return comp; } return 0; } function reverseComparator(comp, descending) { return toBoolean(descending) ? function(a,b){return comp(b,a);} : comp; } function compare(v1, v2){ var t1 = typeof v1; var t2 = typeof v2; if (t1 == t2) { if (t1 == "string") { v1 = v1.toLowerCase(); v2 = v2.toLowerCase(); } if (v1 === v2) return 0; return v1 < v2 ? -1 : 1; } else { return t1 < t2 ? -1 : 1; } } }; } function ngDirective(directive) { if (isFunction(directive)) { directive = { link: directive }; } directive.restrict = directive.restrict || 'AC'; return valueFn(directive); } /** * @ngdoc directive * @name a * @restrict E * * @description * Modifies the default behavior of the html A tag so that the default action is prevented when * the href attribute is empty. * * This change permits the easy creation of action links with the `ngClick` directive * without changing the location or causing page reloads, e.g.: * `<a href="" ng-click="list.addItem()">Add Item</a>` */ var htmlAnchorDirective = valueFn({ restrict: 'E', compile: function(element, attr) { if (msie <= 8) { // turn <a href ng-click="..">link</a> into a stylable link in IE // but only if it doesn't have name attribute, in which case it's an anchor if (!attr.href && !attr.name) { attr.$set('href', ''); } // add a comment node to anchors to workaround IE bug that causes element content to be reset // to new attribute content if attribute is updated with value containing @ and element also // contains value with @ // see issue #1949 element.append(document.createComment('IE fix')); } if (!attr.href && !attr.xlinkHref && !attr.name) { return function(scope, element) { // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ? 'xlink:href' : 'href'; element.on('click', function(event){ // if we have no href url, then don't navigate anywhere. if (!element.attr(href)) { event.preventDefault(); } }); }; } } }); /** * @ngdoc directive * @name ngHref * @restrict A * @priority 99 * * @description * Using Angular markup like `{{hash}}` in an href attribute will * make the link go to the wrong URL if the user clicks it before * Angular has a chance to replace the `{{hash}}` markup with its * value. Until Angular replaces the markup the link will be broken * and will most likely return a 404 error. * * The `ngHref` directive solves this problem. * * The wrong way to write it: * ```html * <a href="http://www.gravatar.com/avatar/{{hash}}"/> * ``` * * The correct way to write it: * ```html * <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/> * ``` * * @element A * @param {template} ngHref any string which can contain `{{}}` markup. * * @example * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes * in links and their different behaviors: <example> <file name="index.html"> <input ng-model="value" /><br /> <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br /> <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br /> <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br /> <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br /> <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br /> <a id="link-6" ng-href="{{value}}">link</a> (link, change location) </file> <file name="protractor.js" type="protractor"> it('should execute ng-click but not reload when href without value', function() { element(by.id('link-1')).click(); expect(element(by.model('value')).getAttribute('value')).toEqual('1'); expect(element(by.id('link-1')).getAttribute('href')).toBe(''); }); it('should execute ng-click but not reload when href empty string', function() { element(by.id('link-2')).click(); expect(element(by.model('value')).getAttribute('value')).toEqual('2'); expect(element(by.id('link-2')).getAttribute('href')).toBe(''); }); it('should execute ng-click and change url when ng-href specified', function() { expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/); element(by.id('link-3')).click(); // At this point, we navigate away from an Angular page, so we need // to use browser.driver to get the base webdriver. browser.wait(function() { return browser.driver.getCurrentUrl().then(function(url) { return url.match(/\/123$/); }); }, 1000, 'page should navigate to /123'); }); xit('should execute ng-click but not reload when href empty string and name specified', function() { element(by.id('link-4')).click(); expect(element(by.model('value')).getAttribute('value')).toEqual('4'); expect(element(by.id('link-4')).getAttribute('href')).toBe(''); }); it('should execute ng-click but not reload when no href but name specified', function() { element(by.id('link-5')).click(); expect(element(by.model('value')).getAttribute('value')).toEqual('5'); expect(element(by.id('link-5')).getAttribute('href')).toBe(null); }); it('should only change url when only ng-href', function() { element(by.model('value')).clear(); element(by.model('value')).sendKeys('6'); expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/); element(by.id('link-6')).click(); // At this point, we navigate away from an Angular page, so we need // to use browser.driver to get the base webdriver. browser.wait(function() { return browser.driver.getCurrentUrl().then(function(url) { return url.match(/\/6$/); }); }, 1000, 'page should navigate to /6'); }); </file> </example> */ /** * @ngdoc directive * @name ngSrc * @restrict A * @priority 99 * * @description * Using Angular markup like `{{hash}}` in a `src` attribute doesn't * work right: The browser will fetch from the URL with the literal * text `{{hash}}` until Angular replaces the expression inside * `{{hash}}`. The `ngSrc` directive solves this problem. * * The buggy way to write it: * ```html * <img src="http://www.gravatar.com/avatar/{{hash}}"/> * ``` * * The correct way to write it: * ```html * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/> * ``` * * @element IMG * @param {template} ngSrc any string which can contain `{{}}` markup. */ /** * @ngdoc directive * @name ngSrcset * @restrict A * @priority 99 * * @description * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't * work right: The browser will fetch from the URL with the literal * text `{{hash}}` until Angular replaces the expression inside * `{{hash}}`. The `ngSrcset` directive solves this problem. * * The buggy way to write it: * ```html * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/> * ``` * * The correct way to write it: * ```html * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/> * ``` * * @element IMG * @param {template} ngSrcset any string which can contain `{{}}` markup. */ /** * @ngdoc directive * @name ngDisabled * @restrict A * @priority 100 * * @description * * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs: * ```html * <div ng-init="scope = { isDisabled: false }"> * <button disabled="{{scope.isDisabled}}">Disabled</button> * </div> * ``` * * The HTML specification does not require browsers to preserve the values of boolean attributes * such as disabled. (Their presence means true and their absence means false.) * If we put an Angular interpolation expression into such an attribute then the * binding information would be lost when the browser removes the attribute. * The `ngDisabled` directive solves this problem for the `disabled` attribute. * This complementary directive is not removed by the browser and so provides * a permanent reliable place to store the binding information. * * @example <example> <file name="index.html"> Click me to toggle: <input type="checkbox" ng-model="checked"><br/> <button ng-model="button" ng-disabled="checked">Button</button> </file> <file name="protractor.js" type="protractor"> it('should toggle button', function() { expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy(); element(by.model('checked')).click(); expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy(); }); </file> </example> * * @element INPUT * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy, * then special attribute "disabled" will be set on the element */ /** * @ngdoc directive * @name ngChecked * @restrict A * @priority 100 * * @description * The HTML specification does not require browsers to preserve the values of boolean attributes * such as checked. (Their presence means true and their absence means false.) * If we put an Angular interpolation expression into such an attribute then the * binding information would be lost when the browser removes the attribute. * The `ngChecked` directive solves this problem for the `checked` attribute. * This complementary directive is not removed by the browser and so provides * a permanent reliable place to store the binding information. * @example <example> <file name="index.html"> Check me to check both: <input type="checkbox" ng-model="master"><br/> <input id="checkSlave" type="checkbox" ng-checked="master"> </file> <file name="protractor.js" type="protractor"> it('should check both checkBoxes', function() { expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy(); element(by.model('master')).click(); expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy(); }); </file> </example> * * @element INPUT * @param {expression} ngChecked If the {@link guide/expression expression} is truthy, * then special attribute "checked" will be set on the element */ /** * @ngdoc directive * @name ngReadonly * @restrict A * @priority 100 * * @description * The HTML specification does not require browsers to preserve the values of boolean attributes * such as readonly. (Their presence means true and their absence means false.) * If we put an Angular interpolation expression into such an attribute then the * binding information would be lost when the browser removes the attribute. * The `ngReadonly` directive solves this problem for the `readonly` attribute. * This complementary directive is not removed by the browser and so provides * a permanent reliable place to store the binding information. * @example <example> <file name="index.html"> Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/> <input type="text" ng-readonly="checked" value="I'm Angular"/> </file> <file name="protractor.js" type="protractor"> it('should toggle readonly attr', function() { expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy(); element(by.model('checked')).click(); expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy(); }); </file> </example> * * @element INPUT * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy, * then special attribute "readonly" will be set on the element */ /** * @ngdoc directive * @name ngSelected * @restrict A * @priority 100 * * @description * The HTML specification does not require browsers to preserve the values of boolean attributes * such as selected. (Their presence means true and their absence means false.) * If we put an Angular interpolation expression into such an attribute then the * binding information would be lost when the browser removes the attribute. * The `ngSelected` directive solves this problem for the `selected` attribute. * This complementary directive is not removed by the browser and so provides * a permanent reliable place to store the binding information. * * @example <example> <file name="index.html"> Check me to select: <input type="checkbox" ng-model="selected"><br/> <select> <option>Hello!</option> <option id="greet" ng-selected="selected">Greetings!</option> </select> </file> <file name="protractor.js" type="protractor"> it('should select Greetings!', function() { expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy(); element(by.model('selected')).click(); expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy(); }); </file> </example> * * @element OPTION * @param {expression} ngSelected If the {@link guide/expression expression} is truthy, * then special attribute "selected" will be set on the element */ /** * @ngdoc directive * @name ngOpen * @restrict A * @priority 100 * * @description * The HTML specification does not require browsers to preserve the values of boolean attributes * such as open. (Their presence means true and their absence means false.) * If we put an Angular interpolation expression into such an attribute then the * binding information would be lost when the browser removes the attribute. * The `ngOpen` directive solves this problem for the `open` attribute. * This complementary directive is not removed by the browser and so provides * a permanent reliable place to store the binding information. * @example <example> <file name="index.html"> Check me check multiple: <input type="checkbox" ng-model="open"><br/> <details id="details" ng-open="open"> <summary>Show/Hide me</summary> </details> </file> <file name="protractor.js" type="protractor"> it('should toggle open', function() { expect(element(by.id('details')).getAttribute('open')).toBeFalsy(); element(by.model('open')).click(); expect(element(by.id('details')).getAttribute('open')).toBeTruthy(); }); </file> </example> * * @element DETAILS * @param {expression} ngOpen If the {@link guide/expression expression} is truthy, * then special attribute "open" will be set on the element */ var ngAttributeAliasDirectives = {}; // boolean attrs are evaluated forEach(BOOLEAN_ATTR, function(propName, attrName) { // binding to multiple is not supported if (propName == "multiple") return; var normalized = directiveNormalize('ng-' + attrName); ngAttributeAliasDirectives[normalized] = function() { return { priority: 100, link: function(scope, element, attr) { scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) { attr.$set(attrName, !!value); }); } }; }; }); // aliased input attrs are evaluated forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) { ngAttributeAliasDirectives[ngAttr] = function() { return { priority: 100, link: function(scope, element, attr) { //special case ngPattern when a literal regular expression value //is used as the expression (this way we don't have to watch anything). if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") { var match = attr.ngPattern.match(REGEX_STRING_REGEXP); if (match) { attr.$set("ngPattern", new RegExp(match[1], match[2])); return; } } scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) { attr.$set(ngAttr, value); }); } }; }; }); // ng-src, ng-srcset, ng-href are interpolated forEach(['src', 'srcset', 'href'], function(attrName) { var normalized = directiveNormalize('ng-' + attrName); ngAttributeAliasDirectives[normalized] = function() { return { priority: 99, // it needs to run after the attributes are interpolated link: function(scope, element, attr) { var propName = attrName, name = attrName; if (attrName === 'href' && toString.call(element.prop('href')) === '[object SVGAnimatedString]') { name = 'xlinkHref'; attr.$attr[name] = 'xlink:href'; propName = null; } attr.$observe(normalized, function(value) { if (!value) return; attr.$set(name, value); // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need // to set the property as well to achieve the desired effect. // we use attr[attrName] value since $set can sanitize the url. if (msie && propName) element.prop(propName, attr[name]); }); } }; }; }); /* global -nullFormCtrl */ var nullFormCtrl = { $addControl: noop, $removeControl: noop, $setValidity: noop, $setDirty: noop, $setPristine: noop }; /** * @ngdoc type * @name form.FormController * * @property {boolean} $pristine True if user has not interacted with the form yet. * @property {boolean} $dirty True if user has already interacted with the form. * @property {boolean} $valid True if all of the containing forms and controls are valid. * @property {boolean} $invalid True if at least one containing control or form is invalid. * * @property {Object} $error Is an object hash, containing references to all invalid controls or * forms, where: * * - keys are validation tokens (error names), * - values are arrays of controls or forms that are invalid for given error name. * * * Built-in validation tokens: * * - `email` * - `max` * - `maxlength` * - `min` * - `minlength` * - `number` * - `pattern` * - `required` * - `url` * * @description * `FormController` keeps track of all its controls and nested forms as well as the state of them, * such as being valid/invalid or dirty/pristine. * * Each {@link ng.directive:form form} directive creates an instance * of `FormController`. * */ //asks for $scope to fool the BC controller module FormController.$inject = ['$element', '$attrs', '$scope', '$animate']; function FormController(element, attrs, $scope, $animate) { var form = this, parentForm = element.parent().controller('form') || nullFormCtrl, invalidCount = 0, // used to easily determine if we are valid errors = form.$error = {}, controls = []; // init state form.$name = attrs.name || attrs.ngForm; form.$dirty = false; form.$pristine = true; form.$valid = true; form.$invalid = false; parentForm.$addControl(form); // Setup initial state of the control element.addClass(PRISTINE_CLASS); toggleValidCss(true); // convenience method for easy toggling of classes function toggleValidCss(isValid, validationErrorKey) { validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; $animate.removeClass(element, (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey); $animate.addClass(element, (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); } /** * @ngdoc method * @name form.FormController#$commitViewValue * * @description * Commit all form controls pending updates to the `$modelValue`. * * Updates may be pending by a debounced event or because the input is waiting for a some future * event defined in `ng-model-options`. This method is rarely needed as `NgModelController` * usually handles calling this in response to input events. */ form.$commitViewValue = function() { forEach(controls, function(control) { control.$commitViewValue(); }); }; /** * @ngdoc method * @name form.FormController#$addControl * * @description * Register a control with the form. * * Input elements using ngModelController do this automatically when they are linked. */ form.$addControl = function(control) { // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored // and not added to the scope. Now we throw an error. assertNotHasOwnProperty(control.$name, 'input'); controls.push(control); if (control.$name) { form[control.$name] = control; } }; /** * @ngdoc method * @name form.FormController#$removeControl * * @description * Deregister a control from the form. * * Input elements using ngModelController do this automatically when they are destroyed. */ form.$removeControl = function(control) { if (control.$name && form[control.$name] === control) { delete form[control.$name]; } forEach(errors, function(queue, validationToken) { form.$setValidity(validationToken, true, control); }); arrayRemove(controls, control); }; /** * @ngdoc method * @name form.FormController#$setValidity * * @description * Sets the validity of a form control. * * This method will also propagate to parent forms. */ form.$setValidity = function(validationToken, isValid, control) { var queue = errors[validationToken]; if (isValid) { if (queue) { arrayRemove(queue, control); if (!queue.length) { invalidCount--; if (!invalidCount) { toggleValidCss(isValid); form.$valid = true; form.$invalid = false; } errors[validationToken] = false; toggleValidCss(true, validationToken); parentForm.$setValidity(validationToken, true, form); } } } else { if (!invalidCount) { toggleValidCss(isValid); } if (queue) { if (includes(queue, control)) return; } else { errors[validationToken] = queue = []; invalidCount++; toggleValidCss(false, validationToken); parentForm.$setValidity(validationToken, false, form); } queue.push(control); form.$valid = false; form.$invalid = true; } }; /** * @ngdoc method * @name form.FormController#$setDirty * * @description * Sets the form to a dirty state. * * This method can be called to add the 'ng-dirty' class and set the form to a dirty * state (ng-dirty class). This method will also propagate to parent forms. */ form.$setDirty = function() { $animate.removeClass(element, PRISTINE_CLASS); $animate.addClass(element, DIRTY_CLASS); form.$dirty = true; form.$pristine = false; parentForm.$setDirty(); }; /** * @ngdoc method * @name form.FormController#$setPristine * * @description * Sets the form to its pristine state. * * This method can be called to remove the 'ng-dirty' class and set the form to its pristine * state (ng-pristine class). This method will also propagate to all the controls contained * in this form. * * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after * saving or resetting it. */ form.$setPristine = function () { $animate.removeClass(element, DIRTY_CLASS); $animate.addClass(element, PRISTINE_CLASS); form.$dirty = false; form.$pristine = true; forEach(controls, function(control) { control.$setPristine(); }); }; } /** * @ngdoc directive * @name ngForm * @restrict EAC * * @description * Nestable alias of {@link ng.directive:form `form`} directive. HTML * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a * sub-group of controls needs to be determined. * * Note: the purpose of `ngForm` is to group controls, * but not to be a replacement for the `<form>` tag with all of its capabilities * (e.g. posting to the server, ...). * * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into * related scope, under this name. * */ /** * @ngdoc directive * @name form * @restrict E * * @description * Directive that instantiates * {@link form.FormController FormController}. * * If the `name` attribute is specified, the form controller is published onto the current scope under * this name. * * # Alias: {@link ng.directive:ngForm `ngForm`} * * In Angular forms can be nested. This means that the outer form is valid when all of the child * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to * `<form>` but can be nested. This allows you to have nested forms, which is very useful when * using Angular validation directives in forms that are dynamically generated using the * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name` * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an * `ngForm` directive and nest these in an outer `form` element. * * * # CSS classes * - `ng-valid` is set if the form is valid. * - `ng-invalid` is set if the form is invalid. * - `ng-pristine` is set if the form is pristine. * - `ng-dirty` is set if the form is dirty. * * Keep in mind that ngAnimate can detect each of these classes when added and removed. * * * # Submitting a form and preventing the default action * * Since the role of forms in client-side Angular applications is different than in classical * roundtrip apps, it is desirable for the browser not to translate the form submission into a full * page reload that sends the data to the server. Instead some javascript logic should be triggered * to handle the form submission in an application-specific way. * * For this reason, Angular prevents the default action (form submission to the server) unless the * `<form>` element has an `action` attribute specified. * * You can use one of the following two ways to specify what javascript method should be called when * a form is submitted: * * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element * - {@link ng.directive:ngClick ngClick} directive on the first * button or input field of type submit (input[type=submit]) * * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit} * or {@link ng.directive:ngClick ngClick} directives. * This is because of the following form submission rules in the HTML specification: * * - If a form has only one input field then hitting enter in this field triggers form submit * (`ngSubmit`) * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter * doesn't trigger submit * - if a form has one or more input fields and one or more buttons or input[type=submit] then * hitting enter in any of the input fields will trigger the click handler on the *first* button or * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`) * * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit` * to have access to the updated model. * * @param {string=} name Name of the form. If specified, the form controller will be published into * related scope, under this name. * * ## Animation Hooks * * Animations in ngForm are triggered when any of the associated CSS classes are added and removed. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any * other validations that are performed within the form. Animations in ngForm are similar to how * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well * as JS animations. * * The following example shows a simple way to utilize CSS transitions to style a form element * that has been rendered as invalid after it has been validated: * * <pre> * //be sure to include ngAnimate as a module to hook into more * //advanced animations * .my-form { * transition:0.5s linear all; * background: white; * } * .my-form.ng-invalid { * background: red; * color:white; * } * </pre> * * @example <example deps="angular-animate.js" animations="true" fixBase="true"> <file name="index.html"> <script> function Ctrl($scope) { $scope.userType = 'guest'; } </script> <style> .my-form { -webkit-transition:all linear 0.5s; transition:all linear 0.5s; background: transparent; } .my-form.ng-invalid { background: red; } </style> <form name="myForm" ng-controller="Ctrl" class="my-form"> userType: <input name="input" ng-model="userType" required> <span class="error" ng-show="myForm.input.$error.required">Required!</span><br> <tt>userType = {{userType}}</tt><br> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br> <tt>myForm.$valid = {{myForm.$valid}}</tt><br> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br> </form> </file> <file name="protractor.js" type="protractor"> it('should initialize to model', function() { var userType = element(by.binding('userType')); var valid = element(by.binding('myForm.input.$valid')); expect(userType.getText()).toContain('guest'); expect(valid.getText()).toContain('true'); }); it('should be invalid if empty', function() { var userType = element(by.binding('userType')); var valid = element(by.binding('myForm.input.$valid')); var userInput = element(by.model('userType')); userInput.clear(); userInput.sendKeys(''); expect(userType.getText()).toEqual('userType ='); expect(valid.getText()).toContain('false'); }); </file> </example> * */ var formDirectiveFactory = function(isNgForm) { return ['$timeout', function($timeout) { var formDirective = { name: 'form', restrict: isNgForm ? 'EAC' : 'E', controller: FormController, compile: function() { return { pre: function(scope, formElement, attr, controller) { if (!attr.action) { // we can't use jq events because if a form is destroyed during submission the default // action is not prevented. see #1238 // // IE 9 is not affected because it doesn't fire a submit event and try to do a full // page reload if the form was destroyed by submission of the form via a click handler // on a button in the form. Looks like an IE9 specific bug. var handleFormSubmission = function(event) { scope.$apply(function() { controller.$commitViewValue(); }); event.preventDefault ? event.preventDefault() : event.returnValue = false; // IE }; addEventListenerFn(formElement[0], 'submit', handleFormSubmission); // unregister the preventDefault listener so that we don't not leak memory but in a // way that will achieve the prevention of the default action. formElement.on('$destroy', function() { $timeout(function() { removeEventListenerFn(formElement[0], 'submit', handleFormSubmission); }, 0, false); }); } var parentFormCtrl = formElement.parent().controller('form'), alias = attr.name || attr.ngForm; if (alias) { setter(scope, alias, controller, alias); } if (parentFormCtrl) { formElement.on('$destroy', function() { parentFormCtrl.$removeControl(controller); if (alias) { setter(scope, alias, undefined, alias); } extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards }); } } }; } }; return formDirective; }]; }; var formDirective = formDirectiveFactory(); var ngFormDirective = formDirectiveFactory(true); /* global -VALID_CLASS, -INVALID_CLASS, -PRISTINE_CLASS, -DIRTY_CLASS, -UNTOUCHED_CLASS, -TOUCHED_CLASS */ var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/; var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-z0-9-]+(\.[a-z0-9-]+)*$/i; var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/; var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/; var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)$/; var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/; var MONTH_REGEXP = /^(\d{4})-(\d\d)$/; var TIME_REGEXP = /^(\d\d):(\d\d)$/; var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/; var inputType = { /** * @ngdoc input * @name input[text] * * @description * Standard HTML text input with angular data binding. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Adds `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input. * * @example <example name="text-input-directive"> <file name="index.html"> <script> function Ctrl($scope) { $scope.text = 'guest'; $scope.word = /^\s*\w*\s*$/; } </script> <form name="myForm" ng-controller="Ctrl"> Single word: <input type="text" name="input" ng-model="text" ng-pattern="word" required ng-trim="false"> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.pattern"> Single word only!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var text = element(by.binding('text')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('text')); it('should initialize to model', function() { expect(text.getText()).toContain('guest'); expect(valid.getText()).toContain('true'); }); it('should be invalid if empty', function() { input.clear(); input.sendKeys(''); expect(text.getText()).toEqual('text ='); expect(valid.getText()).toContain('false'); }); it('should be invalid if multi word', function() { input.clear(); input.sendKeys('hello world'); expect(valid.getText()).toContain('false'); }); </file> </example> */ 'text': textInputType, /** * @ngdoc input * @name input[date] * * @description * Input with date validation and transformation. In browsers that do not yet support * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601 * date format (yyyy-MM-dd), for example: `2009-01-06`. The model must always be a Date object. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a * valid ISO date string (yyyy-MM-dd). * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be * a valid ISO date string (yyyy-MM-dd). * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="date-input-directive"> <file name="index.html"> <script> function Ctrl($scope) { $scope.value = new Date(2013, 9, 22); } </script> <form name="myForm" ng-controller="Ctrl as dateCtrl"> Pick a date between in 2013: <input type="date" id="exampleInput" name="input" ng-model="value" placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required /> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.date"> Not a valid date!</span> <tt>value = {{value | date: "yyyy-MM-dd"}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var value = element(by.binding('value | date: "yyyy-MM-dd"')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('value')); // currently protractor/webdriver does not support // sending keys to all known HTML5 input controls // for various browsers (see https://github.com/angular/protractor/issues/562). function setInput(val) { // set the value of the element and force validation. var scr = "var ipt = document.getElementById('exampleInput'); " + "ipt.value = '" + val + "';" + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; browser.executeScript(scr); } it('should initialize to model', function() { expect(value.getText()).toContain('2013-10-22'); expect(valid.getText()).toContain('myForm.input.$valid = true'); }); it('should be invalid if empty', function() { setInput(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); it('should be invalid if over max', function() { setInput('2015-01-01'); expect(value.getText()).toContain(''); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); </file> </example>f */ 'date': createDateInputType('date', DATE_REGEXP, createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']), 'yyyy-MM-dd'), /** * @ngdoc input * @name input[dateTimeLocal] * * @description * Input with datetime validation and transformation. In browsers that do not yet support * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 * local datetime format (yyyy-MM-ddTHH:mm), for example: `2010-12-28T14:57`. The model must be a Date object. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a * valid ISO datetime format (yyyy-MM-ddTHH:mm). * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be * a valid ISO datetime format (yyyy-MM-ddTHH:mm). * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="datetimelocal-input-directive"> <file name="index.html"> <script> function Ctrl($scope) { $scope.value = new Date(2010, 11, 28, 14, 57); } </script> <form name="myForm" ng-controller="Ctrl as dateCtrl"> Pick a date between in 2013: <input type="datetime-local" id="exampleInput" name="input" ng-model="value" placeholder="yyyy-MM-ddTHH:mm" min="2001-01-01T00:00" max="2013-12-31T00:00" required /> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.datetimelocal"> Not a valid date!</span> <tt>value = {{value | date: "yyyy-MM-ddTHH:mm"}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var value = element(by.binding('value | date: "yyyy-MM-ddTHH:mm"')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('value')); // currently protractor/webdriver does not support // sending keys to all known HTML5 input controls // for various browsers (https://github.com/angular/protractor/issues/562). function setInput(val) { // set the value of the element and force validation. var scr = "var ipt = document.getElementById('exampleInput'); " + "ipt.value = '" + val + "';" + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; browser.executeScript(scr); } it('should initialize to model', function() { expect(value.getText()).toContain('2010-12-28T14:57'); expect(valid.getText()).toContain('myForm.input.$valid = true'); }); it('should be invalid if empty', function() { setInput(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); it('should be invalid if over max', function() { setInput('2015-01-01T23:59'); expect(value.getText()).toContain(''); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); </file> </example> */ 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP, createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm']), 'yyyy-MM-ddTHH:mm'), /** * @ngdoc input * @name input[time] * * @description * Input with time validation and transformation. In browsers that do not yet support * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 * local time format (HH:mm), for example: `14:57`. Model must be a Date object. This binding will always output a * Date object to the model of January 1, 1900, or local date `new Date(0, 0, 1, HH, mm)`. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a * valid ISO time format (HH:mm). * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a * valid ISO time format (HH:mm). * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="time-input-directive"> <file name="index.html"> <script> function Ctrl($scope) { $scope.value = new Date(0, 0, 1, 14, 57); } </script> <form name="myForm" ng-controller="Ctrl as dateCtrl"> Pick a between 8am and 5pm: <input type="time" id="exampleInput" name="input" ng-model="value" placeholder="HH:mm" min="08:00" max="17:00" required /> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.time"> Not a valid date!</span> <tt>value = {{value | date: "HH:mm"}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var value = element(by.binding('value | date: "HH:mm"')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('value')); // currently protractor/webdriver does not support // sending keys to all known HTML5 input controls // for various browsers (https://github.com/angular/protractor/issues/562). function setInput(val) { // set the value of the element and force validation. var scr = "var ipt = document.getElementById('exampleInput'); " + "ipt.value = '" + val + "';" + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; browser.executeScript(scr); } it('should initialize to model', function() { expect(value.getText()).toContain('14:57'); expect(valid.getText()).toContain('myForm.input.$valid = true'); }); it('should be invalid if empty', function() { setInput(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); it('should be invalid if over max', function() { setInput('23:59'); expect(value.getText()).toContain(''); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); </file> </example> */ 'time': createDateInputType('time', TIME_REGEXP, createDateParser(TIME_REGEXP, ['HH', 'mm']), 'HH:mm'), /** * @ngdoc input * @name input[week] * * @description * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 * week format (yyyy-W##), for example: `2013-W02`. The model must always be a Date object. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a * valid ISO week format (yyyy-W##). * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be * a valid ISO week format (yyyy-W##). * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="week-input-directive"> <file name="index.html"> <script> function Ctrl($scope) { $scope.value = new Date(2013, 0, 3); } </script> <form name="myForm" ng-controller="Ctrl as dateCtrl"> Pick a date between in 2013: <input id="exampleInput" type="week" name="input" ng-model="value" placeholder="YYYY-W##" min="2012-W32" max="2013-W52" required /> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.week"> Not a valid date!</span> <tt>value = {{value | date: "yyyy-Www"}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var value = element(by.binding('value | date: "yyyy-Www"')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('value')); // currently protractor/webdriver does not support // sending keys to all known HTML5 input controls // for various browsers (https://github.com/angular/protractor/issues/562). function setInput(val) { // set the value of the element and force validation. var scr = "var ipt = document.getElementById('exampleInput'); " + "ipt.value = '" + val + "';" + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; browser.executeScript(scr); } it('should initialize to model', function() { expect(value.getText()).toContain('2013-W01'); expect(valid.getText()).toContain('myForm.input.$valid = true'); }); it('should be invalid if empty', function() { setInput(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); it('should be invalid if over max', function() { setInput('2015-W01'); expect(value.getText()).toContain(''); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); </file> </example> */ 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'), /** * @ngdoc input * @name input[month] * * @description * Input with month validation and transformation. In browsers that do not yet support * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 * month format (yyyy-MM), for example: `2009-01`. The model must always be a Date object. In the event the model is * not set to the first of the month, the first of that model's month is assumed. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be * a valid ISO month format (yyyy-MM). * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must * be a valid ISO month format (yyyy-MM). * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="month-input-directive"> <file name="index.html"> <script> function Ctrl($scope) { $scope.value = new Date(2013, 9, 1); } </script> <form name="myForm" ng-controller="Ctrl as dateCtrl"> Pick a month int 2013: <input id="exampleInput" type="month" name="input" ng-model="value" placeholder="yyyy-MM" min="2013-01" max="2013-12" required /> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.month"> Not a valid month!</span> <tt>value = {{value | date: "yyyy-MM"}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var value = element(by.binding('value | date: "yyyy-MM"')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('value')); // currently protractor/webdriver does not support // sending keys to all known HTML5 input controls // for various browsers (https://github.com/angular/protractor/issues/562). function setInput(val) { // set the value of the element and force validation. var scr = "var ipt = document.getElementById('exampleInput'); " + "ipt.value = '" + val + "';" + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; browser.executeScript(scr); } it('should initialize to model', function() { expect(value.getText()).toContain('2013-10'); expect(valid.getText()).toContain('myForm.input.$valid = true'); }); it('should be invalid if empty', function() { setInput(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); it('should be invalid if over max', function() { setInput('2015-01'); expect(value.getText()).toContain(''); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); </file> </example> */ 'month': createDateInputType('month', MONTH_REGEXP, createDateParser(MONTH_REGEXP, ['yyyy', 'MM']), 'yyyy-MM'), /** * @ngdoc input * @name input[number] * * @description * Text input with number validation and transformation. Sets the `number` validation * error if not a valid number. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="number-input-directive"> <file name="index.html"> <script> function Ctrl($scope) { $scope.value = 12; } </script> <form name="myForm" ng-controller="Ctrl"> Number: <input type="number" name="input" ng-model="value" min="0" max="99" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.number"> Not valid number!</span> <tt>value = {{value}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var value = element(by.binding('value')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('value')); it('should initialize to model', function() { expect(value.getText()).toContain('12'); expect(valid.getText()).toContain('true'); }); it('should be invalid if empty', function() { input.clear(); input.sendKeys(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('false'); }); it('should be invalid if over max', function() { input.clear(); input.sendKeys('123'); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('false'); }); </file> </example> */ 'number': numberInputType, /** * @ngdoc input * @name input[url] * * @description * Text input with URL validation. Sets the `url` validation error key if the content is not a * valid URL. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="url-input-directive"> <file name="index.html"> <script> function Ctrl($scope) { $scope.text = 'http://google.com'; } </script> <form name="myForm" ng-controller="Ctrl"> URL: <input type="url" name="input" ng-model="text" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.url"> Not valid url!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var text = element(by.binding('text')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('text')); it('should initialize to model', function() { expect(text.getText()).toContain('http://google.com'); expect(valid.getText()).toContain('true'); }); it('should be invalid if empty', function() { input.clear(); input.sendKeys(''); expect(text.getText()).toEqual('text ='); expect(valid.getText()).toContain('false'); }); it('should be invalid if not url', function() { input.clear(); input.sendKeys('box'); expect(valid.getText()).toContain('false'); }); </file> </example> */ 'url': urlInputType, /** * @ngdoc input * @name input[email] * * @description * Text input with email validation. Sets the `email` validation error key if not a valid email * address. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="email-input-directive"> <file name="index.html"> <script> function Ctrl($scope) { $scope.text = 'me@example.com'; } </script> <form name="myForm" ng-controller="Ctrl"> Email: <input type="email" name="input" ng-model="text" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.email"> Not valid email!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var text = element(by.binding('text')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('text')); it('should initialize to model', function() { expect(text.getText()).toContain('me@example.com'); expect(valid.getText()).toContain('true'); }); it('should be invalid if empty', function() { input.clear(); input.sendKeys(''); expect(text.getText()).toEqual('text ='); expect(valid.getText()).toContain('false'); }); it('should be invalid if not email', function() { input.clear(); input.sendKeys('xxx'); expect(valid.getText()).toContain('false'); }); </file> </example> */ 'email': emailInputType, /** * @ngdoc input * @name input[radio] * * @description * HTML radio button. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string} value The value to which the expression should be set when selected. * @param {string=} name Property name of the form under which the control is published. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * @param {string} ngValue Angular expression which sets the value to which the expression should * be set when selected. * * @example <example name="radio-input-directive"> <file name="index.html"> <script> function Ctrl($scope) { $scope.color = 'blue'; $scope.specialValue = { "id": "12345", "value": "green" }; } </script> <form name="myForm" ng-controller="Ctrl"> <input type="radio" ng-model="color" value="red"> Red <br/> <input type="radio" ng-model="color" ng-value="specialValue"> Green <br/> <input type="radio" ng-model="color" value="blue"> Blue <br/> <tt>color = {{color | json}}</tt><br/> </form> Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`. </file> <file name="protractor.js" type="protractor"> it('should change state', function() { var color = element(by.binding('color')); expect(color.getText()).toContain('blue'); element.all(by.model('color')).get(0).click(); expect(color.getText()).toContain('red'); }); </file> </example> */ 'radio': radioInputType, /** * @ngdoc input * @name input[checkbox] * * @description * HTML checkbox. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} ngTrueValue The value to which the expression should be set when selected. * @param {string=} ngFalseValue The value to which the expression should be set when not selected. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="checkbox-input-directive"> <file name="index.html"> <script> function Ctrl($scope) { $scope.value1 = true; $scope.value2 = 'YES' } </script> <form name="myForm" ng-controller="Ctrl"> Value1: <input type="checkbox" ng-model="value1"> <br/> Value2: <input type="checkbox" ng-model="value2" ng-true-value="YES" ng-false-value="NO"> <br/> <tt>value1 = {{value1}}</tt><br/> <tt>value2 = {{value2}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> it('should change state', function() { var value1 = element(by.binding('value1')); var value2 = element(by.binding('value2')); expect(value1.getText()).toContain('true'); expect(value2.getText()).toContain('YES'); element(by.model('value1')).click(); element(by.model('value2')).click(); expect(value1.getText()).toContain('false'); expect(value2.getText()).toContain('NO'); }); </file> </example> */ 'checkbox': checkboxInputType, 'hidden': noop, 'button': noop, 'submit': noop, 'reset': noop, 'file': noop }; // A helper function to call $setValidity and return the value / undefined, // a pattern that is repeated a lot in the input validation logic. function validate(ctrl, validatorName, validity, value){ ctrl.$setValidity(validatorName, validity); return validity ? value : undefined; } function addNativeHtml5Validators(ctrl, validatorName, element) { var validity = element.prop('validity'); if (isObject(validity)) { var validator = function(value) { // Don't overwrite previous validation, don't consider valueMissing to apply (ng-required can // perform the required validation) if (!ctrl.$error[validatorName] && (validity.badInput || validity.customError || validity.typeMismatch) && !validity.valueMissing) { ctrl.$setValidity(validatorName, false); return; } return value; }; ctrl.$parsers.push(validator); } } function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { var validity = element.prop('validity'); var placeholder = element[0].placeholder, noevent = {}; // In composition mode, users are still inputing intermediate text buffer, // hold the listener until composition is done. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent if (!$sniffer.android) { var composing = false; element.on('compositionstart', function(data) { composing = true; }); element.on('compositionend', function() { composing = false; listener(); }); } var listener = function(ev) { if (composing) return; var value = element.val(), event = ev && ev.type; // IE (11 and under) seem to emit an 'input' event if the placeholder value changes. // We don't want to dirty the value when this happens, so we abort here. Unfortunately, // IE also sends input events for other non-input-related things, (such as focusing on a // form control), so this change is not entirely enough to solve this. if (msie && (ev || noevent).type === 'input' && element[0].placeholder !== placeholder) { placeholder = element[0].placeholder; return; } // By default we will trim the value // If the attribute ng-trim exists we will avoid trimming // e.g. <input ng-model="foo" ng-trim="false"> if (toBoolean(attr.ngTrim || 'T')) { value = trim(value); } if (ctrl.$viewValue !== value || // If the value is still empty/falsy, and there is no `required` error, run validators // again. This enables HTML5 constraint validation errors to affect Angular validation // even when the first character entered causes an error. (validity && value === '' && !validity.valueMissing)) { if (scope.$$phase) { ctrl.$setViewValue(value, event); } else { scope.$apply(function() { ctrl.$setViewValue(value, event); }); } } }; // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the // input event on backspace, delete or cut if ($sniffer.hasEvent('input')) { element.on('input', listener); } else { var timeout; var deferListener = function(ev) { if (!timeout) { timeout = $browser.defer(function() { listener(ev); timeout = null; }); } }; element.on('keydown', function(event) { var key = event.keyCode; // ignore // command modifiers arrows if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return; deferListener(event); }); // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it if ($sniffer.hasEvent('paste')) { element.on('paste cut', deferListener); } } // if user paste into input using mouse on older browser // or form autocomplete on newer browser, we need "change" event to catch it element.on('change', listener); ctrl.$render = function() { element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue); }; } function weekParser(isoWeek) { if(isDate(isoWeek)) { return isoWeek; } if(isString(isoWeek)) { WEEK_REGEXP.lastIndex = 0; var parts = WEEK_REGEXP.exec(isoWeek); if(parts) { var year = +parts[1], week = +parts[2], firstThurs = getFirstThursdayOfYear(year), addDays = (week - 1) * 7; return new Date(year, 0, firstThurs.getDate() + addDays); } } return NaN; } function createDateParser(regexp, mapping) { return function(iso) { var parts, map; if(isDate(iso)) { return iso; } if(isString(iso)) { regexp.lastIndex = 0; parts = regexp.exec(iso); if(parts) { parts.shift(); map = { yyyy: 0, MM: 1, dd: 1, HH: 0, mm: 0 }; forEach(parts, function(part, index) { if(index < mapping.length) { map[mapping[index]] = +part; } }); return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm); } } return NaN; }; } function createDateInputType(type, regexp, parseDate, format) { return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); ctrl.$parsers.push(function(value) { if(ctrl.$isEmpty(value)) { ctrl.$setValidity(type, true); return null; } if(regexp.test(value)) { ctrl.$setValidity(type, true); return parseDate(value); } ctrl.$setValidity(type, false); return undefined; }); ctrl.$formatters.push(function(value) { if(isDate(value)) { return $filter('date')(value, format); } return ''; }); if(attr.min) { var minValidator = function(value) { var valid = ctrl.$isEmpty(value) || (parseDate(value) >= parseDate(attr.min)); ctrl.$setValidity('min', valid); return valid ? value : undefined; }; ctrl.$parsers.push(minValidator); ctrl.$formatters.push(minValidator); } if(attr.max) { var maxValidator = function(value) { var valid = ctrl.$isEmpty(value) || (parseDate(value) <= parseDate(attr.max)); ctrl.$setValidity('max', valid); return valid ? value : undefined; }; ctrl.$parsers.push(maxValidator); ctrl.$formatters.push(maxValidator); } }; } function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); ctrl.$parsers.push(function(value) { var empty = ctrl.$isEmpty(value); if (empty || NUMBER_REGEXP.test(value)) { ctrl.$setValidity('number', true); return value === '' ? null : (empty ? value : parseFloat(value)); } else { ctrl.$setValidity('number', false); return undefined; } }); addNativeHtml5Validators(ctrl, 'number', element); ctrl.$formatters.push(function(value) { return ctrl.$isEmpty(value) ? '' : '' + value; }); if (attr.min) { var minValidator = function(value) { var min = parseFloat(attr.min); return validate(ctrl, 'min', ctrl.$isEmpty(value) || value >= min, value); }; ctrl.$parsers.push(minValidator); ctrl.$formatters.push(minValidator); } if (attr.max) { var maxValidator = function(value) { var max = parseFloat(attr.max); return validate(ctrl, 'max', ctrl.$isEmpty(value) || value <= max, value); }; ctrl.$parsers.push(maxValidator); ctrl.$formatters.push(maxValidator); } ctrl.$formatters.push(function(value) { return validate(ctrl, 'number', ctrl.$isEmpty(value) || isNumber(value), value); }); } function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); var urlValidator = function(value) { return validate(ctrl, 'url', ctrl.$isEmpty(value) || URL_REGEXP.test(value), value); }; ctrl.$formatters.push(urlValidator); ctrl.$parsers.push(urlValidator); } function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); var emailValidator = function(value) { return validate(ctrl, 'email', ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value), value); }; ctrl.$formatters.push(emailValidator); ctrl.$parsers.push(emailValidator); } function radioInputType(scope, element, attr, ctrl) { // make the name unique, if not defined if (isUndefined(attr.name)) { element.attr('name', nextUid()); } var listener = function(ev) { if (element[0].checked) { scope.$apply(function() { ctrl.$setViewValue(attr.value, ev && ev.type); }); } }; element.on('click', listener); ctrl.$render = function() { var value = attr.value; element[0].checked = (value == ctrl.$viewValue); }; attr.$observe('value', ctrl.$render); } function checkboxInputType(scope, element, attr, ctrl) { var trueValue = attr.ngTrueValue, falseValue = attr.ngFalseValue; if (!isString(trueValue)) trueValue = true; if (!isString(falseValue)) falseValue = false; var listener = function(ev) { scope.$apply(function() { ctrl.$setViewValue(element[0].checked, ev && ev.type); }); }; element.on('click', listener); ctrl.$render = function() { element[0].checked = ctrl.$viewValue; }; // Override the standard `$isEmpty` because a value of `false` means empty in a checkbox. ctrl.$isEmpty = function(value) { return value !== trueValue; }; ctrl.$formatters.push(function(value) { return value === trueValue; }); ctrl.$parsers.push(function(value) { return value ? trueValue : falseValue; }); } /** * @ngdoc directive * @name textarea * @restrict E * * @description * HTML textarea element control with angular data-binding. The data-binding and validation * properties of this element are exactly the same as those of the * {@link ng.directive:input input element}. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input. */ /** * @ngdoc directive * @name input * @restrict E * * @description * HTML input element control with angular data-binding. Input control follows HTML5 input types * and polyfills the HTML5 validation behavior for older browsers. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {boolean=} ngRequired Sets `required` attribute if set to true * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="input-directive"> <file name="index.html"> <script> function Ctrl($scope) { $scope.user = {name: 'guest', last: 'visitor'}; } </script> <div ng-controller="Ctrl"> <form name="myForm"> User name: <input type="text" name="userName" ng-model="user.name" required> <span class="error" ng-show="myForm.userName.$error.required"> Required!</span><br> Last name: <input type="text" name="lastName" ng-model="user.last" ng-minlength="3" ng-maxlength="10"> <span class="error" ng-show="myForm.lastName.$error.minlength"> Too short!</span> <span class="error" ng-show="myForm.lastName.$error.maxlength"> Too long!</span><br> </form> <hr> <tt>user = {{user}}</tt><br/> <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br> <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br> <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br> <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br> <tt>myForm.$valid = {{myForm.$valid}}</tt><br> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br> <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br> <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br> </div> </file> <file name="protractor.js" type="protractor"> var user = element(by.binding('{{user}}')); var userNameValid = element(by.binding('myForm.userName.$valid')); var lastNameValid = element(by.binding('myForm.lastName.$valid')); var lastNameError = element(by.binding('myForm.lastName.$error')); var formValid = element(by.binding('myForm.$valid')); var userNameInput = element(by.model('user.name')); var userLastInput = element(by.model('user.last')); it('should initialize to model', function() { expect(user.getText()).toContain('{"name":"guest","last":"visitor"}'); expect(userNameValid.getText()).toContain('true'); expect(formValid.getText()).toContain('true'); }); it('should be invalid if empty when required', function() { userNameInput.clear(); userNameInput.sendKeys(''); expect(user.getText()).toContain('{"last":"visitor"}'); expect(userNameValid.getText()).toContain('false'); expect(formValid.getText()).toContain('false'); }); it('should be valid if empty when min length is set', function() { userLastInput.clear(); userLastInput.sendKeys(''); expect(user.getText()).toContain('{"name":"guest","last":""}'); expect(lastNameValid.getText()).toContain('true'); expect(formValid.getText()).toContain('true'); }); it('should be invalid if less than required min length', function() { userLastInput.clear(); userLastInput.sendKeys('xx'); expect(user.getText()).toContain('{"name":"guest"}'); expect(lastNameValid.getText()).toContain('false'); expect(lastNameError.getText()).toContain('minlength'); expect(formValid.getText()).toContain('false'); }); it('should be invalid if longer than max length', function() { userLastInput.clear(); userLastInput.sendKeys('some ridiculously long name'); expect(user.getText()).toContain('{"name":"guest"}'); expect(lastNameValid.getText()).toContain('false'); expect(lastNameError.getText()).toContain('maxlength'); expect(formValid.getText()).toContain('false'); }); </file> </example> */ var inputDirective = ['$browser', '$sniffer', '$filter', function($browser, $sniffer, $filter) { return { restrict: 'E', require: ['?ngModel'], link: function(scope, element, attr, ctrls) { if (ctrls[0]) { (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer, $browser, $filter); } } }; }]; var VALID_CLASS = 'ng-valid', INVALID_CLASS = 'ng-invalid', PRISTINE_CLASS = 'ng-pristine', DIRTY_CLASS = 'ng-dirty', UNTOUCHED_CLASS = 'ng-untouched', TOUCHED_CLASS = 'ng-touched'; /** * @ngdoc type * @name ngModel.NgModelController * * @property {string} $viewValue Actual string value in the view. * @property {*} $modelValue The value in the model, that the control is bound to. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever the control reads value from the DOM. Each function is called, in turn, passing the value through to the next. The last return value is used to populate the model. Used to sanitize / convert the value as well as validation. For validation, the parsers should update the validity state using {@link ngModel.NgModelController#$setValidity $setValidity()}, and return `undefined` for invalid values. * * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever the model value changes. Each function is called, in turn, passing the value through to the next. Used to format / convert values for display in the control and validation. * ```js * function formatter(value) { * if (value) { * return value.toUpperCase(); * } * } * ngModel.$formatters.push(formatter); * ``` * * @property {Object.<string, function>} $validators A collection of validators that are applied * whenever the model value changes. The key value within the object refers to the name of the * validator while the function refers to the validation operation. The validation operation is * provided with the model value as an argument and must return a true or false value depending * on the response of that validation. * * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the * view value has changed. It is called with no arguments, and its return value is ignored. * This can be used in place of additional $watches against the model value. * * @property {Object} $error An object hash with all errors as keys. * * @property {boolean} $untouched True if control has not lost focus yet. * @property {boolean} $touched True if control has lost focus. * @property {boolean} $pristine True if user has not interacted with the control yet. * @property {boolean} $dirty True if user has already interacted with the control. * @property {boolean} $valid True if there is no error. * @property {boolean} $invalid True if at least one error on the control. * * @description * * `NgModelController` provides API for the `ng-model` directive. The controller contains * services for data-binding, validation, CSS updates, and value formatting and parsing. It * purposefully does not contain any logic which deals with DOM rendering or listening to * DOM events. Such DOM related logic should be provided by other directives which make use of * `NgModelController` for data-binding. * * ## Custom Control Example * This example shows how to use `NgModelController` with a custom control to achieve * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`) * collaborate together to achieve the desired result. * * Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element * contents be edited in place by the user. This will not work on older browsers. * * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize} * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`). * However, as we are using `$sce` the model can still decide to to provide unsafe content if it marks * that content using the `$sce` service. * * <example name="NgModelController" module="customControl" deps="angular-sanitize.js"> <file name="style.css"> [contenteditable] { border: 1px solid black; background-color: white; min-height: 20px; } .ng-invalid { border: 1px solid red; } </file> <file name="script.js"> angular.module('customControl', ['ngSanitize']). directive('contenteditable', ['$sce', function($sce) { return { restrict: 'A', // only activate on element attribute require: '?ngModel', // get a hold of NgModelController link: function(scope, element, attrs, ngModel) { if(!ngModel) return; // do nothing if no ng-model // Specify how UI should be updated ngModel.$render = function() { element.html($sce.getTrustedHtml(ngModel.$viewValue || '')); }; // Listen for change events to enable binding element.on('blur keyup change', function() { scope.$apply(read); }); read(); // initialize // Write data to the model function read() { var html = element.html(); // When we clear the content editable the browser leaves a <br> behind // If strip-br attribute is provided then we strip this out if( attrs.stripBr && html == '<br>' ) { html = ''; } ngModel.$setViewValue(html); } } }; }]); </file> <file name="index.html"> <form name="myForm"> <div contenteditable name="myWidget" ng-model="userContent" strip-br="true" required>Change me!</div> <span ng-show="myForm.myWidget.$error.required">Required!</span> <hr> <textarea ng-model="userContent"></textarea> </form> </file> <file name="protractor.js" type="protractor"> it('should data-bind and become invalid', function() { if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') { // SafariDriver can't handle contenteditable // and Firefox driver can't clear contenteditables very well return; } var contentEditable = element(by.css('[contenteditable]')); var content = 'Change me!'; expect(contentEditable.getText()).toEqual(content); contentEditable.clear(); contentEditable.sendKeys(protractor.Key.BACK_SPACE); expect(contentEditable.getText()).toEqual(''); expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/); }); </file> * </example> * * */ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout) { this.$viewValue = Number.NaN; this.$modelValue = Number.NaN; this.$validators = {}; this.$parsers = []; this.$formatters = []; this.$viewChangeListeners = []; this.$untouched = true; this.$touched = false; this.$pristine = true; this.$dirty = false; this.$valid = true; this.$invalid = false; this.$name = $attr.name; var ngModelGet = $parse($attr.ngModel), ngModelSet = ngModelGet.assign, pendingDebounce = null, ctrl = this; if (!ngModelSet) { throw minErr('ngModel')('nonassign', "Expression '{0}' is non-assignable. Element: {1}", $attr.ngModel, startingTag($element)); } /** * @ngdoc method * @name ngModel.NgModelController#$render * * @description * Called when the view needs to be updated. It is expected that the user of the ng-model * directive will implement this method. */ this.$render = noop; /** * @ngdoc method * @name ngModel.NgModelController#$isEmpty * * @description * This is called when we need to determine if the value of the input is empty. * * For instance, the required directive does this to work out if the input has data or not. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`. * * You can override this for input directives whose concept of being empty is different to the * default. The `checkboxInputType` directive does this because in its case a value of `false` * implies empty. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is empty. */ this.$isEmpty = function(value) { return isUndefined(value) || value === '' || value === null || value !== value; }; var parentForm = $element.inheritedData('$formController') || nullFormCtrl, invalidCount = 0, // used to easily determine if we are valid $error = this.$error = {}; // keep invalid keys here // Setup initial state of the control $element .addClass(PRISTINE_CLASS) .addClass(UNTOUCHED_CLASS); toggleValidCss(true); // convenience method for easy toggling of classes function toggleValidCss(isValid, validationErrorKey) { validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; $animate.removeClass($element, (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey); $animate.addClass($element, (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); } /** * @ngdoc method * @name ngModel.NgModelController#$setValidity * * @description * Change the validity state, and notifies the form when the control changes validity. (i.e. it * does not notify form if given validator is already marked as invalid). * * This method can be called within $parsers/$formatters. However, if possible, please use the * `ngModel.$validators` pipeline which is designed to handle validations with true/false values. * * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign * to `$error[validationErrorKey]=isValid` so that it is available for data-binding. * The `validationErrorKey` should be in camelCase and will get converted into dash-case * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` * class and can be bound to as `{{someForm.someControl.$error.myError}}` . * @param {boolean} isValid Whether the current state is valid (true) or invalid (false). */ this.$setValidity = function(validationErrorKey, isValid) { // Purposeful use of ! here to cast isValid to boolean in case it is undefined // jshint -W018 if ($error[validationErrorKey] === !isValid) return; // jshint +W018 if (isValid) { if ($error[validationErrorKey]) invalidCount--; if (!invalidCount) { toggleValidCss(true); ctrl.$valid = true; ctrl.$invalid = false; } } else { toggleValidCss(false); ctrl.$invalid = true; ctrl.$valid = false; invalidCount++; } $error[validationErrorKey] = !isValid; toggleValidCss(isValid, validationErrorKey); parentForm.$setValidity(validationErrorKey, isValid, ctrl); }; /** * @ngdoc method * @name ngModel.NgModelController#$setPristine * * @description * Sets the control to its pristine state. * * This method can be called to remove the 'ng-dirty' class and set the control to its pristine * state (ng-pristine class). A model is considered to be pristine when the model has not been changed * from when first compiled within then form. */ this.$setPristine = function () { ctrl.$dirty = false; ctrl.$pristine = true; $animate.removeClass($element, DIRTY_CLASS); $animate.addClass($element, PRISTINE_CLASS); }; /** * @ngdoc method * @name ngModel.NgModelController#$setUntouched * * @description * Sets the control to its untouched state. * * This method can be called to remove the 'ng-touched' class and set the control to its * untouched state (ng-untouched class). Upon compilation, a model is set as untouched * by default, however this function can be used to restore that state if the model has * already been touched by the user. */ this.$setUntouched = function() { ctrl.$touched = false; ctrl.$untouched = true; $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS); }; /** * @ngdoc method * @name ngModel.NgModelController#$setTouched * * @description * Sets the control to its touched state. * * This method can be called to remove the 'ng-untouched' class and set the control to its * touched state (ng-touched class). A model is considered to be touched when the user has * first interacted (focussed) on the model input element and then shifted focus away (blurred) * from the input element. */ this.$setTouched = function() { ctrl.$touched = true; ctrl.$untouched = false; $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS); }; /** * @ngdoc method * @name ngModel.NgModelController#$rollbackViewValue * * @description * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`, * which may be caused by a pending debounced event or because the input is waiting for a some * future event. * * If you have an input that uses `ng-model-options` to set up debounced events or events such * as blur you can have a situation where there is a period when the `$viewValue` * is out of synch with the ngModel's `$modelValue`. * * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue` * programmatically before these debounced/future events have resolved/occurred, because Angular's * dirty checking mechanism is not able to tell whether the model has actually changed or not. * * The `$rollbackViewValue()` method should be called before programmatically changing the model of an * input which may have such events pending. This is important in order to make sure that the * input field will be updated with the new model value and any pending operations are cancelled. * * <example name="ng-model-cancel-update" module="cancel-update-example"> * <file name="app.js"> * angular.module('cancel-update-example', []) * * .controller('CancelUpdateCtrl', function($scope) { * $scope.resetWithCancel = function (e) { * if (e.keyCode == 27) { * $scope.myForm.myInput1.$rollbackViewValue(); * $scope.myValue = ''; * } * }; * $scope.resetWithoutCancel = function (e) { * if (e.keyCode == 27) { * $scope.myValue = ''; * } * }; * }); * </file> * <file name="index.html"> * <div ng-controller="CancelUpdateCtrl"> * <p>Try typing something in each input. See that the model only updates when you * blur off the input. * </p> * <p>Now see what happens if you start typing then press the Escape key</p> * * <form name="myForm" ng-model-options="{ updateOn: 'blur' }"> * <p>With $rollbackViewValue()</p> * <input name="myInput1" ng-model="myValue" ng-keydown="resetWithCancel($event)"><br/> * myValue: "{{ myValue }}" * * <p>Without $rollbackViewValue()</p> * <input name="myInput2" ng-model="myValue" ng-keydown="resetWithoutCancel($event)"><br/> * myValue: "{{ myValue }}" * </form> * </div> * </file> * </example> */ this.$rollbackViewValue = function() { $timeout.cancel(pendingDebounce); ctrl.$viewValue = ctrl.$$lastCommittedViewValue; ctrl.$render(); }; /** * @ngdoc method * @name ngModel.NgModelController#$validate * * @description * Runs each of the registered validations set on the $validators object. */ this.$validate = function() { this.$$runValidators(ctrl.$modelValue, ctrl.$viewValue); }; this.$$runValidators = function(modelValue, viewValue) { forEach(ctrl.$validators, function(fn, name) { ctrl.$setValidity(name, fn(modelValue, viewValue)); }); }; /** * @ngdoc method * @name ngModel.NgModelController#$commitViewValue * * @description * Commit a pending update to the `$modelValue`. * * Updates may be pending by a debounced event or because the input is waiting for a some future * event defined in `ng-model-options`. this method is rarely needed as `NgModelController` * usually handles calling this in response to input events. */ this.$commitViewValue = function() { var viewValue = ctrl.$viewValue; $timeout.cancel(pendingDebounce); if (ctrl.$$lastCommittedViewValue === viewValue) { return; } ctrl.$$lastCommittedViewValue = viewValue; // change to dirty if (ctrl.$pristine) { ctrl.$dirty = true; ctrl.$pristine = false; $animate.removeClass($element, PRISTINE_CLASS); $animate.addClass($element, DIRTY_CLASS); parentForm.$setDirty(); } var modelValue = viewValue; forEach(ctrl.$parsers, function(fn) { modelValue = fn(modelValue); }); if (ctrl.$modelValue !== modelValue && (isUndefined(ctrl.$$invalidModelValue) || ctrl.$$invalidModelValue != modelValue)) { ctrl.$$runValidators(modelValue, viewValue); ctrl.$modelValue = ctrl.$valid ? modelValue : undefined; ctrl.$$invalidModelValue = ctrl.$valid ? undefined : modelValue; ngModelSet($scope, ctrl.$modelValue); forEach(ctrl.$viewChangeListeners, function(listener) { try { listener(); } catch(e) { $exceptionHandler(e); } }); } }; /** * @ngdoc method * @name ngModel.NgModelController#$setViewValue * * @description * Update the view value. * * This method should be called when the view value changes, typically from within a DOM event handler. * For example {@link ng.directive:input input} and * {@link ng.directive:select select} directives call it. * * It will update the $viewValue, then pass this value through each of the functions in `$parsers`, * which includes any validators. The value that comes out of this `$parsers` pipeline, be applied to * `$modelValue` and the **expression** specified in the `ng-model` attribute. * * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called. * * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn` * and the `default` trigger is not listed, all those actions will remain pending until one of the * `updateOn` events is triggered on the DOM element. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions} * directive is used with a custom debounce for this particular event. * * Note that calling this function does not trigger a `$digest`. * * @param {string} value Value from the view. * @param {string} trigger Event that triggered the update. */ this.$setViewValue = function(value, trigger) { ctrl.$viewValue = value; if (!ctrl.$options || ctrl.$options.updateOnDefault) { ctrl.$$debounceViewValueCommit(trigger); } }; this.$$debounceViewValueCommit = function(trigger) { var debounceDelay = 0, options = ctrl.$options, debounce; if(options && isDefined(options.debounce)) { debounce = options.debounce; if(isNumber(debounce)) { debounceDelay = debounce; } else if(isNumber(debounce[trigger])) { debounceDelay = debounce[trigger]; } else if (isNumber(debounce['default'])) { debounceDelay = debounce['default']; } } $timeout.cancel(pendingDebounce); if (debounceDelay) { pendingDebounce = $timeout(function() { ctrl.$commitViewValue(); }, debounceDelay); } else { ctrl.$commitViewValue(); } }; // model -> value $scope.$watch(function ngModelWatch() { var modelValue = ngModelGet($scope); // if scope model value and ngModel value are out of sync if (ctrl.$modelValue !== modelValue && (isUndefined(ctrl.$$invalidModelValue) || ctrl.$$invalidModelValue != modelValue)) { var formatters = ctrl.$formatters, idx = formatters.length; var viewValue = modelValue; while(idx--) { viewValue = formatters[idx](viewValue); } ctrl.$$runValidators(modelValue, viewValue); ctrl.$modelValue = ctrl.$valid ? modelValue : undefined; ctrl.$$invalidModelValue = ctrl.$valid ? undefined : modelValue; if (ctrl.$viewValue !== viewValue) { ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue; ctrl.$render(); } } return modelValue; }); }]; /** * @ngdoc directive * @name ngModel * * @element input * * @description * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a * property on the scope using {@link ngModel.NgModelController NgModelController}, * which is created and exposed by this directive. * * `ngModel` is responsible for: * * - Binding the view into the model, which other directives such as `input`, `textarea` or `select` * require. * - Providing validation behavior (i.e. required, number, email, url). * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors). * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations. * - Registering the control with its parent {@link ng.directive:form form}. * * Note: `ngModel` will try to bind to the property given by evaluating the expression on the * current scope. If the property doesn't already exist on this scope, it will be created * implicitly and added to the scope. * * For best practices on using `ngModel`, see: * * - [https://github.com/angular/angular.js/wiki/Understanding-Scopes] * * For basic examples, how to use `ngModel`, see: * * - {@link ng.directive:input input} * - {@link input[text] text} * - {@link input[checkbox] checkbox} * - {@link input[radio] radio} * - {@link input[number] number} * - {@link input[email] email} * - {@link input[url] url} * - {@link input[date] date} * - {@link input[dateTimeLocal] dateTimeLocal} * - {@link input[time] time} * - {@link input[month] month} * - {@link input[week] week} * - {@link ng.directive:select select} * - {@link ng.directive:textarea textarea} * * # CSS classes * The following CSS classes are added and removed on the associated input/select/textarea element * depending on the validity of the model. * * - `ng-valid` is set if the model is valid. * - `ng-invalid` is set if the model is invalid. * - `ng-pristine` is set if the model is pristine. * - `ng-dirty` is set if the model is dirty. * * Keep in mind that ngAnimate can detect each of these classes when added and removed. * * ## Animation Hooks * * Animations within models are triggered when any of the associated CSS classes are added and removed * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`, * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself. * The animations that are triggered within ngModel are similar to how they work in ngClass and * animations can be hooked into using CSS transitions, keyframes as well as JS animations. * * The following example shows a simple way to utilize CSS transitions to style an input element * that has been rendered as invalid after it has been validated: * * <pre> * //be sure to include ngAnimate as a module to hook into more * //advanced animations * .my-input { * transition:0.5s linear all; * background: white; * } * .my-input.ng-invalid { * background: red; * color:white; * } * </pre> * * @example * <example deps="angular-animate.js" animations="true" fixBase="true"> <file name="index.html"> <script> function Ctrl($scope) { $scope.val = '1'; } </script> <style> .my-input { -webkit-transition:all linear 0.5s; transition:all linear 0.5s; background: transparent; } .my-input.ng-invalid { color:white; background: red; } </style> Update input to see transitions when valid/invalid. Integer is a valid value. <form name="testForm" ng-controller="Ctrl"> <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input" /> </form> </file> * </example> */ var ngModelDirective = function() { return { require: ['ngModel', '^?form', '^?ngModelOptions'], controller: NgModelController, link: { pre: function(scope, element, attr, ctrls) { // Pass the ng-model-options to the ng-model controller if (ctrls[2]) { ctrls[0].$options = ctrls[2].$options; } // notify others, especially parent forms var modelCtrl = ctrls[0], formCtrl = ctrls[1] || nullFormCtrl; formCtrl.$addControl(modelCtrl); scope.$on('$destroy', function() { formCtrl.$removeControl(modelCtrl); }); }, post: function(scope, element, attr, ctrls) { var modelCtrl = ctrls[0]; if (modelCtrl.$options && modelCtrl.$options.updateOn) { element.on(modelCtrl.$options.updateOn, function(ev) { scope.$apply(function() { modelCtrl.$$debounceViewValueCommit(ev && ev.type); }); }); } element.on('blur', function(ev) { scope.$apply(function() { modelCtrl.$setTouched(); }); }); } } }; }; /** * @ngdoc directive * @name ngChange * * @description * Evaluate the given expression when the user changes the input. * The expression is evaluated immediately, unlike the JavaScript onchange event * which only triggers at the end of a change (usually, when the user leaves the * form element or presses the return key). * The expression is not evaluated when the value change is coming from the model. * * Note, this directive requires `ngModel` to be present. * * @element input * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change * in input value. * * @example * <example name="ngChange-directive"> * <file name="index.html"> * <script> * function Controller($scope) { * $scope.counter = 0; * $scope.change = function() { * $scope.counter++; * }; * } * </script> * <div ng-controller="Controller"> * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" /> * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" /> * <label for="ng-change-example2">Confirmed</label><br /> * <tt>debug = {{confirmed}}</tt><br/> * <tt>counter = {{counter}}</tt><br/> * </div> * </file> * <file name="protractor.js" type="protractor"> * var counter = element(by.binding('counter')); * var debug = element(by.binding('confirmed')); * * it('should evaluate the expression if changing from view', function() { * expect(counter.getText()).toContain('0'); * * element(by.id('ng-change-example1')).click(); * * expect(counter.getText()).toContain('1'); * expect(debug.getText()).toContain('true'); * }); * * it('should not evaluate the expression if changing from model', function() { * element(by.id('ng-change-example2')).click(); * expect(counter.getText()).toContain('0'); * expect(debug.getText()).toContain('true'); * }); * </file> * </example> */ var ngChangeDirective = valueFn({ require: 'ngModel', link: function(scope, element, attr, ctrl) { ctrl.$viewChangeListeners.push(function() { scope.$eval(attr.ngChange); }); } }); var requiredDirective = function() { return { require: '?ngModel', link: function(scope, elm, attr, ctrl) { if (!ctrl) return; attr.required = true; // force truthy in case we are on non input element ctrl.$validators.required = function(modelValue, viewValue) { return !attr.required || !ctrl.$isEmpty(viewValue); }; attr.$observe('required', function() { ctrl.$validate(); }); } }; }; var patternDirective = function() { return { require: '?ngModel', link: function(scope, elm, attr, ctrl) { if (!ctrl) return; var regexp, patternExp = attr.ngPattern || attr.pattern; attr.$observe('pattern', function(regex) { if(isString(regex) && regex.length > 0) { regex = new RegExp(regex); } if (regex && !regex.test) { throw minErr('ngPattern')('noregexp', 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp, regex, startingTag(elm)); } regexp = regex || undefined; ctrl.$validate(); }); ctrl.$validators.pattern = function(value) { return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value); }; } }; }; var maxlengthDirective = function() { return { require: '?ngModel', link: function(scope, elm, attr, ctrl) { if (!ctrl) return; var maxlength = 0; attr.$observe('maxlength', function(value) { maxlength = int(value) || 0; ctrl.$validate(); }); ctrl.$validators.maxlength = function(value) { return ctrl.$isEmpty(value) || value.length <= maxlength; }; } }; }; var minlengthDirective = function() { return { require: '?ngModel', link: function(scope, elm, attr, ctrl) { if (!ctrl) return; var minlength = 0; attr.$observe('minlength', function(value) { minlength = int(value) || 0; ctrl.$validate(); }); ctrl.$validators.minlength = function(value) { return ctrl.$isEmpty(value) || value.length >= minlength; }; } }; }; /** * @ngdoc directive * @name ngList * * @description * Text input that converts between a delimited string and an array of strings. The delimiter * can be a fixed string (by default a comma) or a regular expression. * * @element input * @param {string=} ngList optional delimiter that should be used to split the value. If * specified in form `/something/` then the value will be converted into a regular expression. * * @example <example name="ngList-directive"> <file name="index.html"> <script> function Ctrl($scope) { $scope.names = ['igor', 'misko', 'vojta']; } </script> <form name="myForm" ng-controller="Ctrl"> List: <input name="namesInput" ng-model="names" ng-list required> <span class="error" ng-show="myForm.namesInput.$error.required"> Required!</span> <br> <tt>names = {{names}}</tt><br/> <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/> <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var listInput = element(by.model('names')); var names = element(by.binding('{{names}}')); var valid = element(by.binding('myForm.namesInput.$valid')); var error = element(by.css('span.error')); it('should initialize to model', function() { expect(names.getText()).toContain('["igor","misko","vojta"]'); expect(valid.getText()).toContain('true'); expect(error.getCssValue('display')).toBe('none'); }); it('should be invalid if empty', function() { listInput.clear(); listInput.sendKeys(''); expect(names.getText()).toContain(''); expect(valid.getText()).toContain('false'); expect(error.getCssValue('display')).not.toBe('none'); }); </file> </example> */ var ngListDirective = function() { return { require: 'ngModel', link: function(scope, element, attr, ctrl) { var match = /\/(.*)\//.exec(attr.ngList), separator = match && new RegExp(match[1]) || attr.ngList || ','; var parse = function(viewValue) { // If the viewValue is invalid (say required but empty) it will be `undefined` if (isUndefined(viewValue)) return; var list = []; if (viewValue) { forEach(viewValue.split(separator), function(value) { if (value) list.push(trim(value)); }); } return list; }; ctrl.$parsers.push(parse); ctrl.$formatters.push(function(value) { if (isArray(value)) { return value.join(', '); } return undefined; }); // Override the standard $isEmpty because an empty array means the input is empty. ctrl.$isEmpty = function(value) { return !value || !value.length; }; } }; }; var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/; /** * @ngdoc directive * @name ngValue * * @description * Binds the given expression to the value of `input[select]` or `input[radio]`, so * that when the element is selected, the `ngModel` of that element is set to the * bound value. * * `ngValue` is useful when dynamically generating lists of radio buttons using `ng-repeat`, as * shown below. * * @element input * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute * of the `input` element * * @example <example name="ngValue-directive"> <file name="index.html"> <script> function Ctrl($scope) { $scope.names = ['pizza', 'unicorns', 'robots']; $scope.my = { favorite: 'unicorns' }; } </script> <form ng-controller="Ctrl"> <h2>Which is your favorite?</h2> <label ng-repeat="name in names" for="{{name}}"> {{name}} <input type="radio" ng-model="my.favorite" ng-value="name" id="{{name}}" name="favorite"> </label> <div>You chose {{my.favorite}}</div> </form> </file> <file name="protractor.js" type="protractor"> var favorite = element(by.binding('my.favorite')); it('should initialize to model', function() { expect(favorite.getText()).toContain('unicorns'); }); it('should bind the values to the inputs', function() { element.all(by.model('my.favorite')).get(0).click(); expect(favorite.getText()).toContain('pizza'); }); </file> </example> */ var ngValueDirective = function() { return { priority: 100, compile: function(tpl, tplAttr) { if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) { return function ngValueConstantLink(scope, elm, attr) { attr.$set('value', scope.$eval(attr.ngValue)); }; } else { return function ngValueLink(scope, elm, attr) { scope.$watch(attr.ngValue, function valueWatchAction(value) { attr.$set('value', value); }); }; } } }; }; /** * @ngdoc directive * @name ngModelOptions * * @description * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of * events that will trigger a model update and/or a debouncing delay so that the actual update only * takes place when a timer expires; this timer will be reset after another change takes place. * * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might * be different than the value in the actual model. This means that if you update the model you * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in * order to make sure it is synchronized with the model and that any debounced action is canceled. * * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`} * method is by making sure the input is placed inside a form that has a `name` attribute. This is * important because `form` controllers are published to the related scope under the name in their * `name` attribute. * * Any pending changes will take place immediately when an enclosing form is submitted via the * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit` * to have access to the updated model. * * @param {Object} ngModelOptions options to apply to the current model. Valid keys are: * - `updateOn`: string specifying which event should be the input bound to. You can set several * events using an space delimited list. There is a special event called `default` that * matches the default events belonging of the control. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a * custom value for each event. For example: * `ngModelOptions="{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }"` * * @example The following example shows how to override immediate updates. Changes on the inputs within the form will update the model only when the control loses focus (blur event). If `escape` key is pressed while the input field is focused, the value is reset to the value in the current model. <example name="ngModelOptions-directive-blur"> <file name="index.html"> <div ng-controller="Ctrl"> <form name="userForm"> Name: <input type="text" name="userName" ng-model="user.name" ng-model-options="{ updateOn: 'blur' }" ng-keyup="cancel($event)" /><br /> Other data: <input type="text" ng-model="user.data" /><br /> </form> <pre>user.name = <span ng-bind="user.name"></span></pre> </div> </file> <file name="app.js"> function Ctrl($scope) { $scope.user = { name: 'say', data: '' }; $scope.cancel = function (e) { if (e.keyCode == 27) { $scope.userForm.userName.$rollbackViewValue(); } }; } </file> <file name="protractor.js" type="protractor"> var model = element(by.binding('user.name')); var input = element(by.model('user.name')); var other = element(by.model('user.data')); it('should allow custom events', function() { input.sendKeys(' hello'); input.click(); expect(model.getText()).toEqual('say'); other.click(); expect(model.getText()).toEqual('say hello'); }); it('should $rollbackViewValue when model changes', function() { input.sendKeys(' hello'); expect(input.getAttribute('value')).toEqual('say hello'); input.sendKeys(protractor.Key.ESCAPE); expect(input.getAttribute('value')).toEqual('say'); other.click(); expect(model.getText()).toEqual('say'); }); </file> </example> This one shows how to debounce model changes. Model will be updated only 1 sec after last change. If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty. <example name="ngModelOptions-directive-debounce"> <file name="index.html"> <div ng-controller="Ctrl"> <form name="userForm"> Name: <input type="text" name="userName" ng-model="user.name" ng-model-options="{ debounce: 1000 }" /> <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br /> </form> <pre>user.name = <span ng-bind="user.name"></span></pre> </div> </file> <file name="app.js"> function Ctrl($scope) { $scope.user = { name: 'say' }; } </file> </example> */ var ngModelOptionsDirective = function() { return { controller: ['$scope', '$attrs', function($scope, $attrs) { var that = this; this.$options = $scope.$eval($attrs.ngModelOptions); // Allow adding/overriding bound events if (this.$options.updateOn !== undefined) { this.$options.updateOnDefault = false; // extract "default" pseudo-event from list of events that can trigger a model update this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() { that.$options.updateOnDefault = true; return ' '; })); } else { this.$options.updateOnDefault = true; } }] }; }; /** * @ngdoc directive * @name ngBind * @restrict AC * * @description * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element * with the value of a given expression, and to update the text content when the value of that * expression changes. * * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like * `{{ expression }}` which is similar but less verbose. * * It is preferable to use `ngBind` instead of `{{ expression }}` when a template is momentarily * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an * element attribute, it makes the bindings invisible to the user while the page is loading. * * An alternative solution to this problem would be using the * {@link ng.directive:ngCloak ngCloak} directive. * * * @element ANY * @param {expression} ngBind {@link guide/expression Expression} to evaluate. * * @example * Enter a name in the Live Preview text box; the greeting below the text box changes instantly. <example> <file name="index.html"> <script> function Ctrl($scope) { $scope.name = 'Whirled'; } </script> <div ng-controller="Ctrl"> Enter name: <input type="text" ng-model="name"><br> Hello <span ng-bind="name"></span>! </div> </file> <file name="protractor.js" type="protractor"> it('should check ng-bind', function() { var nameInput = element(by.model('name')); expect(element(by.binding('name')).getText()).toBe('Whirled'); nameInput.clear(); nameInput.sendKeys('world'); expect(element(by.binding('name')).getText()).toBe('world'); }); </file> </example> */ var ngBindDirective = ngDirective({ compile: function(templateElement) { templateElement.addClass('ng-binding'); return function (scope, element, attr) { element.data('$binding', attr.ngBind); scope.$watch(attr.ngBind, function ngBindWatchAction(value) { // We are purposefully using == here rather than === because we want to // catch when value is "null or undefined" // jshint -W041 element.text(value == undefined ? '' : value); }); }; } }); /** * @ngdoc directive * @name ngBindTemplate * * @description * The `ngBindTemplate` directive specifies that the element * text content should be replaced with the interpolation of the template * in the `ngBindTemplate` attribute. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}` * expressions. This directive is needed since some HTML elements * (such as TITLE and OPTION) cannot contain SPAN elements. * * @element ANY * @param {string} ngBindTemplate template of form * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval. * * @example * Try it here: enter text in text box and watch the greeting change. <example> <file name="index.html"> <script> function Ctrl($scope) { $scope.salutation = 'Hello'; $scope.name = 'World'; } </script> <div ng-controller="Ctrl"> Salutation: <input type="text" ng-model="salutation"><br> Name: <input type="text" ng-model="name"><br> <pre ng-bind-template="{{salutation}} {{name}}!"></pre> </div> </file> <file name="protractor.js" type="protractor"> it('should check ng-bind', function() { var salutationElem = element(by.binding('salutation')); var salutationInput = element(by.model('salutation')); var nameInput = element(by.model('name')); expect(salutationElem.getText()).toBe('Hello World!'); salutationInput.clear(); salutationInput.sendKeys('Greetings'); nameInput.clear(); nameInput.sendKeys('user'); expect(salutationElem.getText()).toBe('Greetings user!'); }); </file> </example> */ var ngBindTemplateDirective = ['$interpolate', function($interpolate) { return function(scope, element, attr) { // TODO: move this to scenario runner var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate)); element.addClass('ng-binding').data('$binding', interpolateFn); attr.$observe('ngBindTemplate', function(value) { element.text(value); }); }; }]; /** * @ngdoc directive * @name ngBindHtml * * @description * Creates a binding that will innerHTML the result of evaluating the `expression` into the current * element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link * ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize` * is available, for example, by including {@link ngSanitize} in your module's dependencies (not in * core Angular.) You may also bypass sanitization for values you know are safe. To do so, bind to * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example * under {@link ng.$sce#Example Strict Contextual Escaping (SCE)}. * * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you * will have an exception (instead of an exploit.) * * @element ANY * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate. * * @example Try it here: enter text in text box and watch the greeting change. <example module="ngBindHtmlExample" deps="angular-sanitize.js"> <file name="index.html"> <div ng-controller="ngBindHtmlCtrl"> <p ng-bind-html="myHTML"></p> </div> </file> <file name="script.js"> angular.module('ngBindHtmlExample', ['ngSanitize']) .controller('ngBindHtmlCtrl', ['$scope', function ngBindHtmlCtrl($scope) { $scope.myHTML = 'I am an <code>HTML</code>string with <a href="#">links!</a> and other <em>stuff</em>'; }]); </file> <file name="protractor.js" type="protractor"> it('should check ng-bind-html', function() { expect(element(by.binding('myHTML')).getText()).toBe( 'I am an HTMLstring with links! and other stuff'); }); </file> </example> */ var ngBindHtmlDirective = ['$sce', '$parse', function($sce, $parse) { return function(scope, element, attr) { element.addClass('ng-binding').data('$binding', attr.ngBindHtml); var parsed = $parse(attr.ngBindHtml); function getStringValue() { var value = parsed(scope); getStringValue.$$unwatch = parsed.$$unwatch; return (value || '').toString(); } scope.$watch(getStringValue, function ngBindHtmlWatchAction(value) { element.html($sce.getTrustedHtml(parsed(scope)) || ''); }); }; }]; function classDirective(name, selector) { name = 'ngClass' + name; return ['$animate', function($animate) { return { restrict: 'AC', link: function(scope, element, attr) { var oldVal; scope.$watch(attr[name], ngClassWatchAction, true); attr.$observe('class', function(value) { ngClassWatchAction(scope.$eval(attr[name])); }); if (name !== 'ngClass') { scope.$watch('$index', function($index, old$index) { // jshint bitwise: false var mod = $index & 1; if (mod !== (old$index & 1)) { var classes = arrayClasses(scope.$eval(attr[name])); mod === selector ? addClasses(classes) : removeClasses(classes); } }); } function addClasses(classes) { var newClasses = digestClassCounts(classes, 1); attr.$addClass(newClasses); } function removeClasses(classes) { var newClasses = digestClassCounts(classes, -1); attr.$removeClass(newClasses); } function digestClassCounts (classes, count) { var classCounts = element.data('$classCounts') || {}; var classesToUpdate = []; forEach(classes, function (className) { if (count > 0 || classCounts[className]) { classCounts[className] = (classCounts[className] || 0) + count; if (classCounts[className] === +(count > 0)) { classesToUpdate.push(className); } } }); element.data('$classCounts', classCounts); return classesToUpdate.join(' '); } function updateClasses (oldClasses, newClasses) { var toAdd = arrayDifference(newClasses, oldClasses); var toRemove = arrayDifference(oldClasses, newClasses); toRemove = digestClassCounts(toRemove, -1); toAdd = digestClassCounts(toAdd, 1); if (toAdd.length === 0) { $animate.removeClass(element, toRemove); } else if (toRemove.length === 0) { $animate.addClass(element, toAdd); } else { $animate.setClass(element, toAdd, toRemove); } } function ngClassWatchAction(newVal) { if (selector === true || scope.$index % 2 === selector) { var newClasses = arrayClasses(newVal || []); if (!oldVal) { addClasses(newClasses); } else if (!equals(newVal,oldVal)) { var oldClasses = arrayClasses(oldVal); updateClasses(oldClasses, newClasses); } } oldVal = shallowCopy(newVal); } } }; function arrayDifference(tokens1, tokens2) { var values = []; outer: for(var i = 0; i < tokens1.length; i++) { var token = tokens1[i]; for(var j = 0; j < tokens2.length; j++) { if(token == tokens2[j]) continue outer; } values.push(token); } return values; } function arrayClasses (classVal) { if (isArray(classVal)) { return classVal; } else if (isString(classVal)) { return classVal.split(' '); } else if (isObject(classVal)) { var classes = [], i = 0; forEach(classVal, function(v, k) { if (v) { classes = classes.concat(k.split(' ')); } }); return classes; } return classVal; } }]; } /** * @ngdoc directive * @name ngClass * @restrict AC * * @description * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding * an expression that represents all classes to be added. * * The directive operates in three different ways, depending on which of three types the expression * evaluates to: * * 1. If the expression evaluates to a string, the string should be one or more space-delimited class * names. * * 2. If the expression evaluates to an array, each element of the array should be a string that is * one or more space-delimited class names. * * 3. If the expression evaluates to an object, then for each key-value pair of the * object with a truthy value the corresponding key is used as a class name. * * The directive won't add duplicate classes if a particular class was already set. * * When the expression changes, the previously added classes are removed and only then the * new classes are added. * * @animations * add - happens just before the class is applied to the element * remove - happens just before the class is removed from the element * * @element ANY * @param {expression} ngClass {@link guide/expression Expression} to eval. The result * of the evaluation can be a string representing space delimited class * names, an array, or a map of class names to boolean values. In the case of a map, the * names of the properties whose values are truthy will be added as css classes to the * element. * * @example Example that demonstrates basic bindings via ngClass directive. <example> <file name="index.html"> <p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p> <input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br> <input type="checkbox" ng-model="important"> important (apply "bold" class)<br> <input type="checkbox" ng-model="error"> error (apply "red" class) <hr> <p ng-class="style">Using String Syntax</p> <input type="text" ng-model="style" placeholder="Type: bold strike red"> <hr> <p ng-class="[style1, style2, style3]">Using Array Syntax</p> <input ng-model="style1" placeholder="Type: bold, strike or red"><br> <input ng-model="style2" placeholder="Type: bold, strike or red"><br> <input ng-model="style3" placeholder="Type: bold, strike or red"><br> </file> <file name="style.css"> .strike { text-decoration: line-through; } .bold { font-weight: bold; } .red { color: red; } </file> <file name="protractor.js" type="protractor"> var ps = element.all(by.css('p')); it('should let you toggle the class', function() { expect(ps.first().getAttribute('class')).not.toMatch(/bold/); expect(ps.first().getAttribute('class')).not.toMatch(/red/); element(by.model('important')).click(); expect(ps.first().getAttribute('class')).toMatch(/bold/); element(by.model('error')).click(); expect(ps.first().getAttribute('class')).toMatch(/red/); }); it('should let you toggle string example', function() { expect(ps.get(1).getAttribute('class')).toBe(''); element(by.model('style')).clear(); element(by.model('style')).sendKeys('red'); expect(ps.get(1).getAttribute('class')).toBe('red'); }); it('array example should have 3 classes', function() { expect(ps.last().getAttribute('class')).toBe(''); element(by.model('style1')).sendKeys('bold'); element(by.model('style2')).sendKeys('strike'); element(by.model('style3')).sendKeys('red'); expect(ps.last().getAttribute('class')).toBe('bold strike red'); }); </file> </example> ## Animations The example below demonstrates how to perform animations using ngClass. <example module="ngAnimate" deps="angular-animate.js" animations="true"> <file name="index.html"> <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'"> <input id="clearbtn" type="button" value="clear" ng-click="myVar=''"> <br> <span class="base-class" ng-class="myVar">Sample Text</span> </file> <file name="style.css"> .base-class { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; } .base-class.my-class { color: red; font-size:3em; } </file> <file name="protractor.js" type="protractor"> it('should check ng-class', function() { expect(element(by.css('.base-class')).getAttribute('class')).not. toMatch(/my-class/); element(by.id('setbtn')).click(); expect(element(by.css('.base-class')).getAttribute('class')). toMatch(/my-class/); element(by.id('clearbtn')).click(); expect(element(by.css('.base-class')).getAttribute('class')).not. toMatch(/my-class/); }); </file> </example> ## ngClass and pre-existing CSS3 Transitions/Animations The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure to view the step by step details of {@link ngAnimate.$animate#addclass $animate.addClass} and {@link ngAnimate.$animate#removeclass $animate.removeClass}. */ var ngClassDirective = classDirective('', true); /** * @ngdoc directive * @name ngClassOdd * @restrict AC * * @description * The `ngClassOdd` and `ngClassEven` directives work exactly as * {@link ng.directive:ngClass ngClass}, except they work in * conjunction with `ngRepeat` and take effect only on odd (even) rows. * * This directive can be applied only within the scope of an * {@link ng.directive:ngRepeat ngRepeat}. * * @element ANY * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result * of the evaluation can be a string representing space delimited class names or an array. * * @example <example> <file name="index.html"> <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng-repeat="name in names"> <span ng-class-odd="'odd'" ng-class-even="'even'"> {{name}} </span> </li> </ol> </file> <file name="style.css"> .odd { color: red; } .even { color: blue; } </file> <file name="protractor.js" type="protractor"> it('should check ng-class-odd and ng-class-even', function() { expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')). toMatch(/odd/); expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')). toMatch(/even/); }); </file> </example> */ var ngClassOddDirective = classDirective('Odd', 0); /** * @ngdoc directive * @name ngClassEven * @restrict AC * * @description * The `ngClassOdd` and `ngClassEven` directives work exactly as * {@link ng.directive:ngClass ngClass}, except they work in * conjunction with `ngRepeat` and take effect only on odd (even) rows. * * This directive can be applied only within the scope of an * {@link ng.directive:ngRepeat ngRepeat}. * * @element ANY * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The * result of the evaluation can be a string representing space delimited class names or an array. * * @example <example> <file name="index.html"> <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng-repeat="name in names"> <span ng-class-odd="'odd'" ng-class-even="'even'"> {{name}} &nbsp; &nbsp; &nbsp; </span> </li> </ol> </file> <file name="style.css"> .odd { color: red; } .even { color: blue; } </file> <file name="protractor.js" type="protractor"> it('should check ng-class-odd and ng-class-even', function() { expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')). toMatch(/odd/); expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')). toMatch(/even/); }); </file> </example> */ var ngClassEvenDirective = classDirective('Even', 1); /** * @ngdoc directive * @name ngCloak * @restrict AC * * @description * The `ngCloak` directive is used to prevent the Angular html template from being briefly * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this * directive to avoid the undesirable flicker effect caused by the html template display. * * The directive can be applied to the `<body>` element, but the preferred usage is to apply * multiple `ngCloak` directives to small portions of the page to permit progressive rendering * of the browser view. * * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and * `angular.min.js`. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). * * ```css * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak { * display: none !important; * } * ``` * * When this css rule is loaded by the browser, all html elements (including their children) that * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive * during the compilation of the template it deletes the `ngCloak` element attribute, making * the compiled element visible. * * For the best result, the `angular.js` script must be loaded in the head section of the html * document; alternatively, the css rule above must be included in the external stylesheet of the * application. * * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below. * * @element ANY * * @example <example> <file name="index.html"> <div id="template1" ng-cloak>{{ 'hello' }}</div> <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div> </file> <file name="protractor.js" type="protractor"> it('should remove the template directive and css class', function() { expect($('#template1').getAttribute('ng-cloak')). toBeNull(); expect($('#template2').getAttribute('ng-cloak')). toBeNull(); }); </file> </example> * */ var ngCloakDirective = ngDirective({ compile: function(element, attr) { attr.$set('ngCloak', undefined); element.removeClass('ng-cloak'); } }); /** * @ngdoc directive * @name ngController * * @description * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular * supports the principles behind the Model-View-Controller design pattern. * * MVC components in angular: * * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties * are accessed through bindings. * * View — The template (HTML with data bindings) that is rendered into the View. * * Controller — The `ngController` directive specifies a Controller class; the class contains business * logic behind the application to decorate the scope with functions and values * * Note that you can also attach controllers to the DOM by declaring it in a route definition * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller * again using `ng-controller` in the template itself. This will cause the controller to be attached * and executed twice. * * @element ANY * @scope * @param {expression} ngController Name of a globally accessible constructor function or an * {@link guide/expression expression} that on the current scope evaluates to a * constructor function. The controller instance can be published into a scope property * by specifying `as propertyName`. * * @example * Here is a simple form for editing user contact information. Adding, removing, clearing, and * greeting are methods declared on the controller (see source tab). These methods can * easily be called from the angular markup. Any changes to the data are automatically reflected * in the View without the need for a manual update. * * Two different declaration styles are included below: * * * one binds methods and properties directly onto the controller using `this`: * `ng-controller="SettingsController1 as settings"` * * one injects `$scope` into the controller: * `ng-controller="SettingsController2"` * * The second option is more common in the Angular community, and is generally used in boilerplates * and in this guide. However, there are advantages to binding properties directly to the controller * and avoiding scope. * * * Using `controller as` makes it obvious which controller you are accessing in the template when * multiple controllers apply to an element. * * If you are writing your controllers as classes you have easier access to the properties and * methods, which will appear on the scope, from inside the controller code. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal * inheritance masking primitives. * * This example demonstrates the `controller as` syntax. * * <example name="ngControllerAs"> * <file name="index.html"> * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings"> * Name: <input type="text" ng-model="settings.name"/> * [ <a href="" ng-click="settings.greet()">greet</a> ]<br/> * Contact: * <ul> * <li ng-repeat="contact in settings.contacts"> * <select ng-model="contact.type"> * <option>phone</option> * <option>email</option> * </select> * <input type="text" ng-model="contact.value"/> * [ <a href="" ng-click="settings.clearContact(contact)">clear</a> * | <a href="" ng-click="settings.removeContact(contact)">X</a> ] * </li> * <li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li> * </ul> * </div> * </file> * <file name="app.js"> * function SettingsController1() { * this.name = "John Smith"; * this.contacts = [ * {type: 'phone', value: '408 555 1212'}, * {type: 'email', value: 'john.smith@example.org'} ]; * } * * SettingsController1.prototype.greet = function() { * alert(this.name); * }; * * SettingsController1.prototype.addContact = function() { * this.contacts.push({type: 'email', value: 'yourname@example.org'}); * }; * * SettingsController1.prototype.removeContact = function(contactToRemove) { * var index = this.contacts.indexOf(contactToRemove); * this.contacts.splice(index, 1); * }; * * SettingsController1.prototype.clearContact = function(contact) { * contact.type = 'phone'; * contact.value = ''; * }; * </file> * <file name="protractor.js" type="protractor"> * it('should check controller as', function() { * var container = element(by.id('ctrl-as-exmpl')); * expect(container.findElement(by.model('settings.name')) * .getAttribute('value')).toBe('John Smith'); * * var firstRepeat = * container.findElement(by.repeater('contact in settings.contacts').row(0)); * var secondRepeat = * container.findElement(by.repeater('contact in settings.contacts').row(1)); * * expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value')) * .toBe('408 555 1212'); * * expect(secondRepeat.findElement(by.model('contact.value')).getAttribute('value')) * .toBe('john.smith@example.org'); * * firstRepeat.findElement(by.linkText('clear')).click(); * * expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value')) * .toBe(''); * * container.findElement(by.linkText('add')).click(); * * expect(container.findElement(by.repeater('contact in settings.contacts').row(2)) * .findElement(by.model('contact.value')) * .getAttribute('value')) * .toBe('yourname@example.org'); * }); * </file> * </example> * * This example demonstrates the "attach to `$scope`" style of controller. * * <example name="ngController"> * <file name="index.html"> * <div id="ctrl-exmpl" ng-controller="SettingsController2"> * Name: <input type="text" ng-model="name"/> * [ <a href="" ng-click="greet()">greet</a> ]<br/> * Contact: * <ul> * <li ng-repeat="contact in contacts"> * <select ng-model="contact.type"> * <option>phone</option> * <option>email</option> * </select> * <input type="text" ng-model="contact.value"/> * [ <a href="" ng-click="clearContact(contact)">clear</a> * | <a href="" ng-click="removeContact(contact)">X</a> ] * </li> * <li>[ <a href="" ng-click="addContact()">add</a> ]</li> * </ul> * </div> * </file> * <file name="app.js"> * function SettingsController2($scope) { * $scope.name = "John Smith"; * $scope.contacts = [ * {type:'phone', value:'408 555 1212'}, * {type:'email', value:'john.smith@example.org'} ]; * * $scope.greet = function() { * alert($scope.name); * }; * * $scope.addContact = function() { * $scope.contacts.push({type:'email', value:'yourname@example.org'}); * }; * * $scope.removeContact = function(contactToRemove) { * var index = $scope.contacts.indexOf(contactToRemove); * $scope.contacts.splice(index, 1); * }; * * $scope.clearContact = function(contact) { * contact.type = 'phone'; * contact.value = ''; * }; * } * </file> * <file name="protractor.js" type="protractor"> * it('should check controller', function() { * var container = element(by.id('ctrl-exmpl')); * * expect(container.findElement(by.model('name')) * .getAttribute('value')).toBe('John Smith'); * * var firstRepeat = * container.findElement(by.repeater('contact in contacts').row(0)); * var secondRepeat = * container.findElement(by.repeater('contact in contacts').row(1)); * * expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value')) * .toBe('408 555 1212'); * expect(secondRepeat.findElement(by.model('contact.value')).getAttribute('value')) * .toBe('john.smith@example.org'); * * firstRepeat.findElement(by.linkText('clear')).click(); * * expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value')) * .toBe(''); * * container.findElement(by.linkText('add')).click(); * * expect(container.findElement(by.repeater('contact in contacts').row(2)) * .findElement(by.model('contact.value')) * .getAttribute('value')) * .toBe('yourname@example.org'); * }); * </file> *</example> */ var ngControllerDirective = [function() { return { scope: true, controller: '@', priority: 500 }; }]; /** * @ngdoc directive * @name ngCsp * * @element html * @description * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support. * * This is necessary when developing things like Google Chrome Extensions. * * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things). * For us to be compatible, we just need to implement the "getterFn" in $parse without violating * any of these restrictions. * * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp` * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will * be raised. * * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}). * To make those directives work in CSP mode, include the `angular-csp.css` manually. * * In order to use this feature put the `ngCsp` directive on the root element of the application. * * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.* * * @example * This example shows how to apply the `ngCsp` directive to the `html` tag. ```html <!doctype html> <html ng-app ng-csp> ... ... </html> ``` */ // ngCsp is not implemented as a proper directive any more, because we need it be processed while we bootstrap // the system (before $parse is instantiated), for this reason we just have a csp() fn that looks for ng-csp attribute // anywhere in the current doc /** * @ngdoc directive * @name ngClick * * @description * The ngClick directive allows you to specify custom behavior when * an element is clicked. * * @element ANY * @priority 0 * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon * click. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <button ng-click="count = count + 1" ng-init="count=0"> Increment </button> count: {{count}} </file> <file name="protractor.js" type="protractor"> it('should check ng-click', function() { expect(element(by.binding('count')).getText()).toMatch('0'); element(by.css('button')).click(); expect(element(by.binding('count')).getText()).toMatch('1'); }); </file> </example> */ /* * A directive that allows creation of custom onclick handlers that are defined as angular * expressions and are compiled and executed within the current scope. * * Events that are handled via these handler are always configured not to propagate further. */ var ngEventDirectives = {}; forEach( 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '), function(name) { var directiveName = directiveNormalize('ng-' + name); ngEventDirectives[directiveName] = ['$parse', function($parse) { return { compile: function($element, attr) { var fn = $parse(attr[directiveName]); return function ngEventHandler(scope, element) { element.on(lowercase(name), function(event) { scope.$apply(function() { fn(scope, {$event:event}); }); }); }; } }; }]; } ); /** * @ngdoc directive * @name ngDblclick * * @description * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event. * * @element ANY * @priority 0 * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon * a dblclick. (The Event object is available as `$event`) * * @example <example> <file name="index.html"> <button ng-dblclick="count = count + 1" ng-init="count=0"> Increment (on double click) </button> count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngMousedown * * @description * The ngMousedown directive allows you to specify custom behavior on mousedown event. * * @element ANY * @priority 0 * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon * mousedown. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <button ng-mousedown="count = count + 1" ng-init="count=0"> Increment (on mouse down) </button> count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngMouseup * * @description * Specify custom behavior on mouseup event. * * @element ANY * @priority 0 * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon * mouseup. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <button ng-mouseup="count = count + 1" ng-init="count=0"> Increment (on mouse up) </button> count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngMouseover * * @description * Specify custom behavior on mouseover event. * * @element ANY * @priority 0 * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon * mouseover. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <button ng-mouseover="count = count + 1" ng-init="count=0"> Increment (when mouse is over) </button> count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngMouseenter * * @description * Specify custom behavior on mouseenter event. * * @element ANY * @priority 0 * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <button ng-mouseenter="count = count + 1" ng-init="count=0"> Increment (when mouse enters) </button> count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngMouseleave * * @description * Specify custom behavior on mouseleave event. * * @element ANY * @priority 0 * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <button ng-mouseleave="count = count + 1" ng-init="count=0"> Increment (when mouse leaves) </button> count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngMousemove * * @description * Specify custom behavior on mousemove event. * * @element ANY * @priority 0 * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon * mousemove. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <button ng-mousemove="count = count + 1" ng-init="count=0"> Increment (when mouse moves) </button> count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngKeydown * * @description * Specify custom behavior on keydown event. * * @element ANY * @priority 0 * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) * * @example <example> <file name="index.html"> <input ng-keydown="count = count + 1" ng-init="count=0"> key down count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngKeyup * * @description * Specify custom behavior on keyup event. * * @element ANY * @priority 0 * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) * * @example <example> <file name="index.html"> <p>Typing in the input box below updates the key count</p> <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}} <p>Typing in the input box below updates the keycode</p> <input ng-keyup="event=$event"> <p>event keyCode: {{ event.keyCode }}</p> <p>event altKey: {{ event.altKey }}</p> </file> </example> */ /** * @ngdoc directive * @name ngKeypress * * @description * Specify custom behavior on keypress event. * * @element ANY * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon * keypress. ({@link guide/expression#-event- Event object is available as `$event`} * and can be interrogated for keyCode, altKey, etc.) * * @example <example> <file name="index.html"> <input ng-keypress="count = count + 1" ng-init="count=0"> key press count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngSubmit * * @description * Enables binding angular expressions to onsubmit events. * * Additionally it prevents the default action (which for form means sending the request to the * server and reloading the current page), but only if the form does not contain `action`, * `data-action`, or `x-action` attributes. * * @element form * @priority 0 * @param {expression} ngSubmit {@link guide/expression Expression} to eval. * ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <script> function Ctrl($scope) { $scope.list = []; $scope.text = 'hello'; $scope.submit = function() { if ($scope.text) { $scope.list.push(this.text); $scope.text = ''; } }; } </script> <form ng-submit="submit()" ng-controller="Ctrl"> Enter text and hit enter: <input type="text" ng-model="text" name="text" /> <input type="submit" id="submit" value="Submit" /> <pre>list={{list}}</pre> </form> </file> <file name="protractor.js" type="protractor"> it('should check ng-submit', function() { expect(element(by.binding('list')).getText()).toBe('list=[]'); element(by.css('#submit')).click(); expect(element(by.binding('list')).getText()).toContain('hello'); expect(element(by.input('text')).getAttribute('value')).toBe(''); }); it('should ignore empty strings', function() { expect(element(by.binding('list')).getText()).toBe('list=[]'); element(by.css('#submit')).click(); element(by.css('#submit')).click(); expect(element(by.binding('list')).getText()).toContain('hello'); }); </file> </example> */ /** * @ngdoc directive * @name ngFocus * * @description * Specify custom behavior on focus event. * * @element window, input, select, textarea, a * @priority 0 * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon * focus. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ngBlur * * @description * Specify custom behavior on blur event. * * @element window, input, select, textarea, a * @priority 0 * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon * blur. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ngCopy * * @description * Specify custom behavior on copy event. * * @element window, input, select, textarea, a * @priority 0 * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon * copy. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value"> copied: {{copied}} </file> </example> */ /** * @ngdoc directive * @name ngCut * * @description * Specify custom behavior on cut event. * * @element window, input, select, textarea, a * @priority 0 * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon * cut. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value"> cut: {{cut}} </file> </example> */ /** * @ngdoc directive * @name ngPaste * * @description * Specify custom behavior on paste event. * * @element window, input, select, textarea, a * @priority 0 * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon * paste. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'> pasted: {{paste}} </file> </example> */ /** * @ngdoc directive * @name ngIf * @restrict A * * @description * The `ngIf` directive removes or recreates a portion of the DOM tree based on an * {expression}. If the expression assigned to `ngIf` evaluates to a false * value then the element is removed from the DOM, otherwise a clone of the * element is reinserted into the DOM. * * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the * element in the DOM rather than changing its visibility via the `display` css property. A common * case when this difference is significant is when using css selectors that rely on an element's * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes. * * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope * is created when the element is restored. The scope created within `ngIf` inherits from * its parent scope using * [prototypal inheritance](https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance). * An important implication of this is if `ngModel` is used within `ngIf` to bind to * a javascript primitive defined in the parent scope. In this case any modifications made to the * variable within the child scope will override (hide) the value in the parent scope. * * Also, `ngIf` recreates elements using their compiled state. An example of this behavior * is if an element's class attribute is directly modified after it's compiled, using something like * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element * the added class will be lost because the original compiled state is used to regenerate the element. * * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter` * and `leave` effects. * * @animations * enter - happens just after the ngIf contents change and a new DOM element is created and injected into the ngIf container * leave - happens just before the ngIf contents are removed from the DOM * * @element ANY * @scope * @priority 600 * @param {expression} ngIf If the {@link guide/expression expression} is falsy then * the element is removed from the DOM tree. If it is truthy a copy of the compiled * element is added to the DOM tree. * * @example <example module="ngAnimate" deps="angular-animate.js" animations="true"> <file name="index.html"> Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/> Show when checked: <span ng-if="checked" class="animate-if"> I'm removed when the checkbox is unchecked. </span> </file> <file name="animations.css"> .animate-if { background:white; border:1px solid black; padding:10px; } .animate-if.ng-enter, .animate-if.ng-leave { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; } .animate-if.ng-enter, .animate-if.ng-leave.ng-leave-active { opacity:0; } .animate-if.ng-leave, .animate-if.ng-enter.ng-enter-active { opacity:1; } </file> </example> */ var ngIfDirective = ['$animate', function($animate) { return { transclude: 'element', priority: 600, terminal: true, restrict: 'A', $$tlb: true, link: function ($scope, $element, $attr, ctrl, $transclude) { var block, childScope, previousElements; $scope.$watch($attr.ngIf, function ngIfWatchAction(value) { if (toBoolean(value)) { if (!childScope) { $transclude(function (clone, newScope) { childScope = newScope; clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' '); // Note: We only need the first/last node of the cloned nodes. // However, we need to keep the reference to the jqlite wrapper as it might be changed later // by a directive with templateUrl when its template arrives. block = { clone: clone }; $animate.enter(clone, $element.parent(), $element); }); } } else { if(previousElements) { previousElements.remove(); previousElements = null; } if(childScope) { childScope.$destroy(); childScope = null; } if(block) { previousElements = getBlockElements(block.clone); $animate.leave(previousElements, function() { previousElements = null; }); block = null; } } }); } }; }]; /** * @ngdoc directive * @name ngInclude * @restrict ECA * * @description * Fetches, compiles and includes an external HTML fragment. * * By default, the template URL is restricted to the same domain and protocol as the * application document. This is done by calling {@link ng.$sce#getTrustedResourceUrl * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or * [wrap them](ng.$sce#trustAsResourceUrl) as trusted values. Refer to Angular's {@link * ng.$sce Strict Contextual Escaping}. * * In addition, the browser's * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest) * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/) * policy may further restrict whether the template is successfully loaded. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://` * access on some browsers. * * @animations * enter - animation is used to bring new content into the browser. * leave - animation is used to animate existing content away. * * The enter and leave animation occur concurrently. * * @scope * @priority 400 * * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant, * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`. * @param {string=} onload Expression to evaluate when a new partial is loaded. * * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll * $anchorScroll} to scroll the viewport after the content is loaded. * * - If the attribute is not set, disable scrolling. * - If the attribute is set without value, enable scrolling. * - Otherwise enable scrolling only if the expression evaluates to truthy value. * * @example <example module="ngAnimate" deps="angular-animate.js" animations="true"> <file name="index.html"> <div ng-controller="Ctrl"> <select ng-model="template" ng-options="t.name for t in templates"> <option value="">(blank)</option> </select> url of the template: <tt>{{template.url}}</tt> <hr/> <div class="slide-animate-container"> <div class="slide-animate" ng-include="template.url"></div> </div> </div> </file> <file name="script.js"> function Ctrl($scope) { $scope.templates = [ { name: 'template1.html', url: 'template1.html'}, { name: 'template2.html', url: 'template2.html'} ]; $scope.template = $scope.templates[0]; } </file> <file name="template1.html"> Content of template1.html </file> <file name="template2.html"> Content of template2.html </file> <file name="animations.css"> .slide-animate-container { position:relative; background:white; border:1px solid black; height:40px; overflow:hidden; } .slide-animate { padding:10px; } .slide-animate.ng-enter, .slide-animate.ng-leave { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; position:absolute; top:0; left:0; right:0; bottom:0; display:block; padding:10px; } .slide-animate.ng-enter { top:-50px; } .slide-animate.ng-enter.ng-enter-active { top:0; } .slide-animate.ng-leave { top:0; } .slide-animate.ng-leave.ng-leave-active { top:50px; } </file> <file name="protractor.js" type="protractor"> var templateSelect = element(by.model('template')); var includeElem = element(by.css('[ng-include]')); it('should load template1.html', function() { expect(includeElem.getText()).toMatch(/Content of template1.html/); }); it('should load template2.html', function() { if (browser.params.browser == 'firefox') { // Firefox can't handle using selects // See https://github.com/angular/protractor/issues/480 return; } templateSelect.click(); templateSelect.element.all(by.css('option')).get(2).click(); expect(includeElem.getText()).toMatch(/Content of template2.html/); }); it('should change to blank', function() { if (browser.params.browser == 'firefox') { // Firefox can't handle using selects return; } templateSelect.click(); templateSelect.element.all(by.css('option')).get(0).click(); expect(includeElem.isPresent()).toBe(false); }); </file> </example> */ /** * @ngdoc event * @name ngInclude#$includeContentRequested * @eventType emit on the scope ngInclude was declared in * @description * Emitted every time the ngInclude content is requested. */ /** * @ngdoc event * @name ngInclude#$includeContentLoaded * @eventType emit on the current ngInclude scope * @description * Emitted every time the ngInclude content is reloaded. */ /** * @ngdoc event * @name ng.directive:ngInclude#$includeContentError * @eventOf ng.directive:ngInclude * @eventType emit on the scope ngInclude was declared in * @description * Emitted when a template HTTP request yields an erronous response (status < 200 || status > 299) */ var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$animate', '$sce', function($http, $templateCache, $anchorScroll, $animate, $sce) { return { restrict: 'ECA', priority: 400, terminal: true, transclude: 'element', controller: angular.noop, compile: function(element, attr) { var srcExp = attr.ngInclude || attr.src, onloadExp = attr.onload || '', autoScrollExp = attr.autoscroll; return function(scope, $element, $attr, ctrl, $transclude) { var changeCounter = 0, currentScope, previousElement, currentElement; var cleanupLastIncludeContent = function() { if(previousElement) { previousElement.remove(); previousElement = null; } if(currentScope) { currentScope.$destroy(); currentScope = null; } if(currentElement) { $animate.leave(currentElement, function() { previousElement = null; }); previousElement = currentElement; currentElement = null; } }; scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) { var afterAnimation = function() { if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { $anchorScroll(); } }; var thisChangeId = ++changeCounter; if (src) { $http.get(src, {cache: $templateCache}).success(function(response) { if (thisChangeId !== changeCounter) return; var newScope = scope.$new(); ctrl.template = response; // Note: This will also link all children of ng-include that were contained in the original // html. If that content contains controllers, ... they could pollute/change the scope. // However, using ng-include on an element with additional content does not make sense... // Note: We can't remove them in the cloneAttchFn of $transclude as that // function is called before linking the content, which would apply child // directives to non existing elements. var clone = $transclude(newScope, function(clone) { cleanupLastIncludeContent(); $animate.enter(clone, null, $element, afterAnimation); }); currentScope = newScope; currentElement = clone; currentScope.$emit('$includeContentLoaded'); scope.$eval(onloadExp); }).error(function() { if (thisChangeId === changeCounter) { cleanupLastIncludeContent(); scope.$emit('$includeContentError'); } }); scope.$emit('$includeContentRequested'); } else { cleanupLastIncludeContent(); ctrl.template = null; } }); }; } }; }]; // This directive is called during the $transclude call of the first `ngInclude` directive. // It will replace and compile the content of the element with the loaded template. // We need this directive so that the element content is already filled when // the link function of another directive on the same element as ngInclude // is called. var ngIncludeFillContentDirective = ['$compile', function($compile) { return { restrict: 'ECA', priority: -400, require: 'ngInclude', link: function(scope, $element, $attr, ctrl) { $element.html(ctrl.template); $compile($element.contents())(scope); } }; }]; /** * @ngdoc directive * @name ngInit * @restrict AC * * @description * The `ngInit` directive allows you to evaluate an expression in the * current scope. * * <div class="alert alert-error"> * The only appropriate use of `ngInit` is for aliasing special properties of * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you * should use {@link guide/controller controllers} rather than `ngInit` * to initialize values on a scope. * </div> * <div class="alert alert-warning"> * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make * sure you have parenthesis for correct precedence: * <pre class="prettyprint"> * <div ng-init="test1 = (data | orderBy:'name')"></div> * </pre> * </div> * * @priority 450 * * @element ANY * @param {expression} ngInit {@link guide/expression Expression} to eval. * * @example <example> <file name="index.html"> <script> function Ctrl($scope) { $scope.list = [['a', 'b'], ['c', 'd']]; } </script> <div ng-controller="Ctrl"> <div ng-repeat="innerList in list" ng-init="outerIndex = $index"> <div ng-repeat="value in innerList" ng-init="innerIndex = $index"> <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span> </div> </div> </div> </file> <file name="protractor.js" type="protractor"> it('should alias index positions', function() { var elements = element.all(by.css('.example-init')); expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;'); expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;'); expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;'); expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;'); }); </file> </example> */ var ngInitDirective = ngDirective({ priority: 450, compile: function() { return { pre: function(scope, element, attrs) { scope.$eval(attrs.ngInit); } }; } }); /** * @ngdoc directive * @name ngNonBindable * @restrict AC * @priority 1000 * * @description * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current * DOM element. This is useful if the element contains what appears to be Angular directives and * bindings but which should be ignored by Angular. This could be the case if you have a site that * displays snippets of code, for instance. * * @element ANY * * @example * In this example there are two locations where a simple interpolation binding (`{{}}`) is present, * but the one wrapped in `ngNonBindable` is left alone. * * @example <example> <file name="index.html"> <div>Normal: {{1 + 2}}</div> <div ng-non-bindable>Ignored: {{1 + 2}}</div> </file> <file name="protractor.js" type="protractor"> it('should check ng-non-bindable', function() { expect(element(by.binding('1 + 2')).getText()).toContain('3'); expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/); }); </file> </example> */ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); /** * @ngdoc directive * @name ngPluralize * @restrict EA * * @description * `ngPluralize` is a directive that displays messages according to en-US localization rules. * These rules are bundled with angular.js, but can be overridden * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive * by specifying the mappings between * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html) * and the strings to be displayed. * * # Plural categories and explicit number rules * There are two * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html) * in Angular's default en-US locale: "one" and "other". * * While a plural category may match many numbers (for example, in en-US locale, "other" can match * any number that is not 1), an explicit number rule can only match one number. For example, the * explicit number rule for "3" matches the number 3. There are examples of plural categories * and explicit number rules throughout the rest of this documentation. * * # Configuring ngPluralize * You configure ngPluralize by providing 2 attributes: `count` and `when`. * You can also provide an optional attribute, `offset`. * * The value of the `count` attribute can be either a string or an {@link guide/expression * Angular expression}; these are evaluated on the current scope for its bound value. * * The `when` attribute specifies the mappings between plural categories and the actual * string to be displayed. The value of the attribute should be a JSON object. * * The following example shows how to configure ngPluralize: * * ```html * <ng-pluralize count="personCount" when="{'0': 'Nobody is viewing.', * 'one': '1 person is viewing.', * 'other': '{} people are viewing.'}"> * </ng-pluralize> *``` * * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not * specify this rule, 0 would be matched to the "other" category and "0 people are viewing" * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for * other numbers, for example 12, so that instead of showing "12 people are viewing", you can * show "a dozen people are viewing". * * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted * into pluralized strings. In the previous example, Angular will replace `{}` with * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder * for <span ng-non-bindable>{{numberExpression}}</span>. * * # Configuring ngPluralize with offset * The `offset` attribute allows further customization of pluralized text, which can result in * a better user experience. For example, instead of the message "4 people are viewing this document", * you might display "John, Kate and 2 others are viewing this document". * The offset attribute allows you to offset a number by any desired value. * Let's take a look at an example: * * ```html * <ng-pluralize count="personCount" offset=2 * when="{'0': 'Nobody is viewing.', * '1': '{{person1}} is viewing.', * '2': '{{person1}} and {{person2}} are viewing.', * 'one': '{{person1}}, {{person2}} and one other person are viewing.', * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> * </ng-pluralize> * ``` * * Notice that we are still using two plural categories(one, other), but we added * three explicit number rules 0, 1 and 2. * When one person, perhaps John, views the document, "John is viewing" will be shown. * When three people view the document, no explicit number rule is found, so * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category. * In this case, plural category 'one' is matched and "John, Marry and one other person are viewing" * is shown. * * Note that when you specify offsets, you must provide explicit number rules for * numbers from 0 up to and including the offset. If you use an offset of 3, for example, * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for * plural categories "one" and "other". * * @param {string|expression} count The variable to be bound to. * @param {string} when The mapping between plural category to its corresponding strings. * @param {number=} offset Offset to deduct from the total number. * * @example <example> <file name="index.html"> <script> function Ctrl($scope) { $scope.person1 = 'Igor'; $scope.person2 = 'Misko'; $scope.personCount = 1; } </script> <div ng-controller="Ctrl"> Person 1:<input type="text" ng-model="person1" value="Igor" /><br/> Person 2:<input type="text" ng-model="person2" value="Misko" /><br/> Number of People:<input type="text" ng-model="personCount" value="1" /><br/> <!--- Example with simple pluralization rules for en locale ---> Without Offset: <ng-pluralize count="personCount" when="{'0': 'Nobody is viewing.', 'one': '1 person is viewing.', 'other': '{} people are viewing.'}"> </ng-pluralize><br> <!--- Example with offset ---> With Offset(2): <ng-pluralize count="personCount" offset=2 when="{'0': 'Nobody is viewing.', '1': '{{person1}} is viewing.', '2': '{{person1}} and {{person2}} are viewing.', 'one': '{{person1}}, {{person2}} and one other person are viewing.', 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> </ng-pluralize> </div> </file> <file name="protractor.js" type="protractor"> it('should show correct pluralized string', function() { var withoutOffset = element.all(by.css('ng-pluralize')).get(0); var withOffset = element.all(by.css('ng-pluralize')).get(1); var countInput = element(by.model('personCount')); expect(withoutOffset.getText()).toEqual('1 person is viewing.'); expect(withOffset.getText()).toEqual('Igor is viewing.'); countInput.clear(); countInput.sendKeys('0'); expect(withoutOffset.getText()).toEqual('Nobody is viewing.'); expect(withOffset.getText()).toEqual('Nobody is viewing.'); countInput.clear(); countInput.sendKeys('2'); expect(withoutOffset.getText()).toEqual('2 people are viewing.'); expect(withOffset.getText()).toEqual('Igor and Misko are viewing.'); countInput.clear(); countInput.sendKeys('3'); expect(withoutOffset.getText()).toEqual('3 people are viewing.'); expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.'); countInput.clear(); countInput.sendKeys('4'); expect(withoutOffset.getText()).toEqual('4 people are viewing.'); expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.'); }); it('should show data-bound names', function() { var withOffset = element.all(by.css('ng-pluralize')).get(1); var personCount = element(by.model('personCount')); var person1 = element(by.model('person1')); var person2 = element(by.model('person2')); personCount.clear(); personCount.sendKeys('4'); person1.clear(); person1.sendKeys('Di'); person2.clear(); person2.sendKeys('Vojta'); expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.'); }); </file> </example> */ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) { var BRACE = /{}/g; return { restrict: 'EA', link: function(scope, element, attr) { var numberExp = attr.count, whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs offset = attr.offset || 0, whens = scope.$eval(whenExp) || {}, whensExpFns = {}, startSymbol = $interpolate.startSymbol(), endSymbol = $interpolate.endSymbol(), isWhen = /^when(Minus)?(.+)$/; forEach(attr, function(expression, attributeName) { if (isWhen.test(attributeName)) { whens[lowercase(attributeName.replace('when', '').replace('Minus', '-'))] = element.attr(attr.$attr[attributeName]); } }); forEach(whens, function(expression, key) { whensExpFns[key] = $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' + offset + endSymbol)); }); scope.$watch(function ngPluralizeWatch() { var value = parseFloat(scope.$eval(numberExp)); if (!isNaN(value)) { //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise, //check it against pluralization rules in $locale service if (!(value in whens)) value = $locale.pluralCat(value - offset); return whensExpFns[value](scope); } else { return ''; } }, function ngPluralizeWatchAction(newVal) { element.text(newVal); }); } }; }]; /** * @ngdoc directive * @name ngRepeat * * @description * The `ngRepeat` directive instantiates a template once per item from a collection. Each template * instance gets its own scope, where the given loop variable is set to the current collection item, * and `$index` is set to the item index or key. * * Special properties are exposed on the local scope of each template instance, including: * * | Variable | Type | Details | * |-----------|-----------------|-----------------------------------------------------------------------------| * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) | * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. | * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. | * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. | * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). | * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). | * * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}. * This may be useful when, for instance, nesting ngRepeats. * * # Special repeat start and end points * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively. * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on) * up to and including the ending HTML tag where **ng-repeat-end** is placed. * * The example below makes use of this feature: * ```html * <header ng-repeat-start="item in items"> * Header {{ item }} * </header> * <div class="body"> * Body {{ item }} * </div> * <footer ng-repeat-end> * Footer {{ item }} * </footer> * ``` * * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to: * ```html * <header> * Header A * </header> * <div class="body"> * Body A * </div> * <footer> * Footer A * </footer> * <header> * Header B * </header> * <div class="body"> * Body B * </div> * <footer> * Footer B * </footer> * ``` * * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**). * * @animations * **.enter** - when a new item is added to the list or when an item is revealed after a filter * * **.leave** - when an item is removed from the list or when an item is filtered out * * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered * * @element ANY * @scope * @priority 1000 * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These * formats are currently supported: * * * `variable in expression` – where variable is the user defined loop variable and `expression` * is a scope expression giving the collection to enumerate. * * For example: `album in artist.albums`. * * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, * and `expression` is the scope expression giving the collection to enumerate. * * For example: `(name, age) in {'adam':10, 'amalie':12}`. * * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function * which can be used to associate the objects in the collection with the DOM elements. If no tracking function * is specified the ng-repeat associates elements by identity in the collection. It is an error to have * more than one tracking function to resolve to the same key. (This would mean that two distinct objects are * mapped to the same DOM element, which is not possible.) Filters should be applied to the expression, * before specifying a tracking expression. * * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements * will be associated by item identity in the array. * * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements * with the corresponding item in the array by identity. Moving the same object in array would move the DOM * element in the same way in the DOM. * * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this * case the object identity does not matter. Two objects are considered equivalent as long as their `id` * property is same. * * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter * to items in conjunction with a tracking expression. * * @example * This example initializes the scope to a list of names and * then uses `ngRepeat` to display every person: <example module="ngAnimate" deps="angular-animate.js" animations="true"> <file name="index.html"> <div ng-init="friends = [ {name:'John', age:25, gender:'boy'}, {name:'Jessie', age:30, gender:'girl'}, {name:'Johanna', age:28, gender:'girl'}, {name:'Joy', age:15, gender:'girl'}, {name:'Mary', age:28, gender:'girl'}, {name:'Peter', age:95, gender:'boy'}, {name:'Sebastian', age:50, gender:'boy'}, {name:'Erika', age:27, gender:'girl'}, {name:'Patrick', age:40, gender:'boy'}, {name:'Samantha', age:60, gender:'girl'} ]"> I have {{friends.length}} friends. They are: <input type="search" ng-model="q" placeholder="filter friends..." /> <ul class="example-animate-container"> <li class="animate-repeat" ng-repeat="friend in friends | filter:q"> [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. </li> </ul> </div> </file> <file name="animations.css"> .example-animate-container { background:white; border:1px solid black; list-style:none; margin:0; padding:0 10px; } .animate-repeat { line-height:40px; list-style:none; box-sizing:border-box; } .animate-repeat.ng-move, .animate-repeat.ng-enter, .animate-repeat.ng-leave { -webkit-transition:all linear 0.5s; transition:all linear 0.5s; } .animate-repeat.ng-leave.ng-leave-active, .animate-repeat.ng-move, .animate-repeat.ng-enter { opacity:0; max-height:0; } .animate-repeat.ng-leave, .animate-repeat.ng-move.ng-move-active, .animate-repeat.ng-enter.ng-enter-active { opacity:1; max-height:40px; } </file> <file name="protractor.js" type="protractor"> var friends = element.all(by.repeater('friend in friends')); it('should render initial data set', function() { expect(friends.count()).toBe(10); expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.'); expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.'); expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.'); expect(element(by.binding('friends.length')).getText()) .toMatch("I have 10 friends. They are:"); }); it('should update repeater when filter predicate changes', function() { expect(friends.count()).toBe(10); element(by.model('q')).sendKeys('ma'); expect(friends.count()).toBe(2); expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.'); expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.'); }); </file> </example> */ var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { var NG_REMOVED = '$$NG_REMOVED'; var ngRepeatMinErr = minErr('ngRepeat'); return { transclude: 'element', priority: 1000, terminal: true, $$tlb: true, link: function($scope, $element, $attr, ctrl, $transclude){ var expression = $attr.ngRepeat; var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/), trackByExp, trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn, lhs, rhs, valueIdentifier, keyIdentifier, hashFnLocals = {$id: hashKey}; if (!match) { throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.", expression); } lhs = match[1]; rhs = match[2]; trackByExp = match[3]; if (trackByExp) { trackByExpGetter = $parse(trackByExp); trackByIdExpFn = function(key, value, index) { // assign key, value, and $index to the locals so that they can be used in hash functions if (keyIdentifier) hashFnLocals[keyIdentifier] = key; hashFnLocals[valueIdentifier] = value; hashFnLocals.$index = index; return trackByExpGetter($scope, hashFnLocals); }; } else { trackByIdArrayFn = function(key, value) { return hashKey(value); }; trackByIdObjFn = function(key) { return key; }; } match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/); if (!match) { throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.", lhs); } valueIdentifier = match[3] || match[1]; keyIdentifier = match[2]; // Store a list of elements from previous run. This is a hash where key is the item from the // iterator, and the value is objects with following properties. // - scope: bound scope // - element: previous element. // - index: position var lastBlockMap = {}; //watch props $scope.$watchCollection(rhs, function ngRepeatAction(collection){ var index, length, previousNode = $element[0], // current position of the node nextNode, // Same as lastBlockMap but it has the current state. It will become the // lastBlockMap on the next iteration. nextBlockMap = {}, arrayLength, key, value, // key/value of iteration trackById, trackByIdFn, collectionKeys, block, // last object information {scope, element, id} nextBlockOrder = [], elementsToRemove; var updateScope = function(scope, index) { scope[valueIdentifier] = value; if (keyIdentifier) scope[keyIdentifier] = key; scope.$index = index; scope.$first = (index === 0); scope.$last = (index === (arrayLength - 1)); scope.$middle = !(scope.$first || scope.$last); // jshint bitwise: false scope.$odd = !(scope.$even = (index&1) === 0); // jshint bitwise: true }; if (isArrayLike(collection)) { collectionKeys = collection; trackByIdFn = trackByIdExpFn || trackByIdArrayFn; } else { trackByIdFn = trackByIdExpFn || trackByIdObjFn; // if object, extract keys, sort them and use to determine order of iteration over obj props collectionKeys = []; for (var itemKey in collection) { if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) != '$') { collectionKeys.push(itemKey); } } collectionKeys.sort(); } arrayLength = collectionKeys.length; // locate existing items length = nextBlockOrder.length = collectionKeys.length; for(index = 0; index < length; index++) { key = (collection === collectionKeys) ? index : collectionKeys[index]; value = collection[key]; trackById = trackByIdFn(key, value, index); assertNotHasOwnProperty(trackById, '`track by` id'); if(lastBlockMap.hasOwnProperty(trackById)) { block = lastBlockMap[trackById]; delete lastBlockMap[trackById]; nextBlockMap[trackById] = block; nextBlockOrder[index] = block; } else if (nextBlockMap.hasOwnProperty(trackById)) { // restore lastBlockMap forEach(nextBlockOrder, function(block) { if (block && block.scope) lastBlockMap[block.id] = block; }); // This is a duplicate and we need to throw an error throw ngRepeatMinErr('dupes', "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}", expression, trackById); } else { // new never before seen block nextBlockOrder[index] = { id: trackById }; nextBlockMap[trackById] = false; } } // remove existing items for (var blockKey in lastBlockMap) { // lastBlockMap is our own object so we don't need to use special hasOwnPropertyFn if (lastBlockMap.hasOwnProperty(blockKey)) { block = lastBlockMap[blockKey]; elementsToRemove = getBlockElements(block.clone); $animate.leave(elementsToRemove); forEach(elementsToRemove, function(element) { element[NG_REMOVED] = true; }); block.scope.$destroy(); } } // we are not using forEach for perf reasons (trying to avoid #call) for (index = 0, length = collectionKeys.length; index < length; index++) { key = (collection === collectionKeys) ? index : collectionKeys[index]; value = collection[key]; block = nextBlockOrder[index]; if (nextBlockOrder[index - 1]) previousNode = getBlockEnd(nextBlockOrder[index - 1]); if (block.scope) { // if we have already seen this object, then we need to reuse the // associated scope/element nextNode = previousNode; do { nextNode = nextNode.nextSibling; } while(nextNode && nextNode[NG_REMOVED]); if (getBlockStart(block) != nextNode) { // existing item which got moved $animate.move(getBlockElements(block.clone), null, jqLite(previousNode)); } previousNode = getBlockEnd(block); updateScope(block.scope, index); } else { // new item which we don't know about $transclude(function(clone, scope) { block.scope = scope; clone[clone.length++] = document.createComment(' end ngRepeat: ' + expression + ' '); $animate.enter(clone, null, jqLite(previousNode)); previousNode = clone; // Note: We only need the first/last node of the cloned nodes. // However, we need to keep the reference to the jqlite wrapper as it might be changed later // by a directive with templateUrl when its template arrives. block.clone = clone; nextBlockMap[block.id] = block; updateScope(block.scope, index); }); } } lastBlockMap = nextBlockMap; }); } }; function getBlockStart(block) { return block.clone[0]; } function getBlockEnd(block) { return block.clone[block.clone.length - 1]; } }]; /** * @ngdoc directive * @name ngShow * * @description * The `ngShow` directive shows or hides the given HTML element based on the expression * provided to the ngShow attribute. The element is shown or hidden by removing or adding * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined * in AngularJS and sets the display style to none (using an !important flag). * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). * * ```html * <!-- when $scope.myValue is truthy (element is visible) --> * <div ng-show="myValue"></div> * * <!-- when $scope.myValue is falsy (element is hidden) --> * <div ng-show="myValue" class="ng-hide"></div> * ``` * * When the ngShow expression evaluates to false then the ng-hide CSS class is added to the class attribute * on the element causing it to become hidden. When true, the ng-hide CSS class is removed * from the element causing the element not to appear hidden. * * <div class="alert alert-warning"> * **Note:** Here is a list of values that ngShow will consider as a falsy value (case insensitive):<br /> * "f" / "0" / "false" / "no" / "n" / "[]" * </div> * * ## Why is !important used? * * You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector * can be easily overridden by heavier selectors. For example, something as simple * as changing the display style on a HTML list item would make hidden elements appear visible. * This also becomes a bigger issue when dealing with CSS frameworks. * * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the * styling to change how to hide an element then it is just a matter of using !important in their own CSS code. * * ### Overriding .ng-hide * * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide` * class in CSS: * * ```css * .ng-hide { * /&#42; this is just another form of hiding an element &#42;/ * display:block!important; * position:absolute; * top:-9999px; * left:-9999px; * } * ``` * * By default you don't need to override in CSS anything and the animations will work around the display style. * * ## A note about animations with ngShow * * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression * is true and false. This system works like the animation system present with ngClass except that * you must also include the !important flag to override the display property * so that you can perform an animation when the element is hidden during the time of the animation. * * ```css * // * //a working example can be found at the bottom of this page * // * .my-element.ng-hide-add, .my-element.ng-hide-remove { * /&#42; this is required as of 1.3x to properly * apply all styling in a show/hide animation &#42;/ * transition:0s linear all; * } * * .my-element.ng-hide-add-active, * .my-element.ng-hide-remove-active { * /&#42; the transition is defined in the active class &#42;/ * transition:1s linear all; * } * * .my-element.ng-hide-add { ... } * .my-element.ng-hide-add.ng-hide-add-active { ... } * .my-element.ng-hide-remove { ... } * .my-element.ng-hide-remove.ng-hide-remove-active { ... } * ``` * * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display * property to block during animation states--ngAnimate will handle the style toggling automatically for you. * * @animations * addClass: .ng-hide - happens after the ngShow expression evaluates to a truthy value and the just before contents are set to visible * removeClass: .ng-hide - happens after the ngShow expression evaluates to a non truthy value and just before the contents are set to hidden * * @element ANY * @param {expression} ngShow If the {@link guide/expression expression} is truthy * then the element is shown or hidden respectively. * * @example <example module="ngAnimate" deps="angular-animate.js" animations="true"> <file name="index.html"> Click me: <input type="checkbox" ng-model="checked"><br/> <div> Show: <div class="check-element animate-show" ng-show="checked"> <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked. </div> </div> <div> Hide: <div class="check-element animate-show" ng-hide="checked"> <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked. </div> </div> </file> <file name="glyphicons.css"> @import url(//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css); </file> <file name="animations.css"> .animate-show { line-height:20px; opacity:1; padding:10px; border:1px solid black; background:white; } .animate-show.ng-hide-add.ng-hide-add-active, .animate-show.ng-hide-remove.ng-hide-remove-active { -webkit-transition:all linear 0.5s; transition:all linear 0.5s; } .animate-show.ng-hide { line-height:0; opacity:0; padding:0 10px; } .check-element { padding:10px; border:1px solid black; background:white; } </file> <file name="protractor.js" type="protractor"> var thumbsUp = element(by.css('span.glyphicon-thumbs-up')); var thumbsDown = element(by.css('span.glyphicon-thumbs-down')); it('should check ng-show / ng-hide', function() { expect(thumbsUp.isDisplayed()).toBeFalsy(); expect(thumbsDown.isDisplayed()).toBeTruthy(); element(by.model('checked')).click(); expect(thumbsUp.isDisplayed()).toBeTruthy(); expect(thumbsDown.isDisplayed()).toBeFalsy(); }); </file> </example> */ var ngShowDirective = ['$animate', function($animate) { return function(scope, element, attr) { scope.$watch(attr.ngShow, function ngShowWatchAction(value){ $animate[toBoolean(value) ? 'removeClass' : 'addClass'](element, 'ng-hide'); }); }; }]; /** * @ngdoc directive * @name ngHide * * @description * The `ngHide` directive shows or hides the given HTML element based on the expression * provided to the ngHide attribute. The element is shown or hidden by removing or adding * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined * in AngularJS and sets the display style to none (using an !important flag). * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). * * ```html * <!-- when $scope.myValue is truthy (element is hidden) --> * <div ng-hide="myValue" class="ng-hide"></div> * * <!-- when $scope.myValue is falsy (element is visible) --> * <div ng-hide="myValue"></div> * ``` * * When the ngHide expression evaluates to true then the .ng-hide CSS class is added to the class attribute * on the element causing it to become hidden. When false, the ng-hide CSS class is removed * from the element causing the element not to appear hidden. * * <div class="alert alert-warning"> * **Note:** Here is a list of values that ngHide will consider as a falsy value (case insensitive):<br /> * "f" / "0" / "false" / "no" / "n" / "[]" * </div> * * ## Why is !important used? * * You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector * can be easily overridden by heavier selectors. For example, something as simple * as changing the display style on a HTML list item would make hidden elements appear visible. * This also becomes a bigger issue when dealing with CSS frameworks. * * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the * styling to change how to hide an element then it is just a matter of using !important in their own CSS code. * * ### Overriding .ng-hide * * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide` * class in CSS: * * ```css * .ng-hide { * /&#42; this is just another form of hiding an element &#42;/ * display:block!important; * position:absolute; * top:-9999px; * left:-9999px; * } * ``` * * By default you don't need to override in CSS anything and the animations will work around the display style. * * ## A note about animations with ngHide * * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide` * CSS class is added and removed for you instead of your own CSS class. * * ```css * // * //a working example can be found at the bottom of this page * // * .my-element.ng-hide-add, .my-element.ng-hide-remove { * transition:0.5s linear all; * } * * .my-element.ng-hide-add { ... } * .my-element.ng-hide-add.ng-hide-add-active { ... } * .my-element.ng-hide-remove { ... } * .my-element.ng-hide-remove.ng-hide-remove-active { ... } * ``` * * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display * property to block during animation states--ngAnimate will handle the style toggling automatically for you. * * @animations * removeClass: .ng-hide - happens after the ngHide expression evaluates to a truthy value and just before the contents are set to hidden * addClass: .ng-hide - happens after the ngHide expression evaluates to a non truthy value and just before the contents are set to visible * * @element ANY * @param {expression} ngHide If the {@link guide/expression expression} is truthy then * the element is shown or hidden respectively. * * @example <example module="ngAnimate" deps="angular-animate.js" animations="true"> <file name="index.html"> Click me: <input type="checkbox" ng-model="checked"><br/> <div> Show: <div class="check-element animate-hide" ng-show="checked"> <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked. </div> </div> <div> Hide: <div class="check-element animate-hide" ng-hide="checked"> <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked. </div> </div> </file> <file name="glyphicons.css"> @import url(//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css); </file> <file name="animations.css"> .animate-hide { -webkit-transition:all linear 0.5s; transition:all linear 0.5s; line-height:20px; opacity:1; padding:10px; border:1px solid black; background:white; } .animate-hide.ng-hide { line-height:0; opacity:0; padding:0 10px; } .check-element { padding:10px; border:1px solid black; background:white; } </file> <file name="protractor.js" type="protractor"> var thumbsUp = element(by.css('span.glyphicon-thumbs-up')); var thumbsDown = element(by.css('span.glyphicon-thumbs-down')); it('should check ng-show / ng-hide', function() { expect(thumbsUp.isDisplayed()).toBeFalsy(); expect(thumbsDown.isDisplayed()).toBeTruthy(); element(by.model('checked')).click(); expect(thumbsUp.isDisplayed()).toBeTruthy(); expect(thumbsDown.isDisplayed()).toBeFalsy(); }); </file> </example> */ var ngHideDirective = ['$animate', function($animate) { return function(scope, element, attr) { scope.$watch(attr.ngHide, function ngHideWatchAction(value){ $animate[toBoolean(value) ? 'addClass' : 'removeClass'](element, 'ng-hide'); }); }; }]; /** * @ngdoc directive * @name ngStyle * @restrict AC * * @description * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally. * * @element ANY * @param {expression} ngStyle * * {@link guide/expression Expression} which evals to an * object whose keys are CSS style names and values are corresponding values for those CSS * keys. * * Since some CSS style names are not valid keys for an object, they must be quoted. * See the 'background-color' style in the example below. * * @example <example> <file name="index.html"> <input type="button" value="set color" ng-click="myStyle={color:'red'}"> <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}"> <input type="button" value="clear" ng-click="myStyle={}"> <br/> <span ng-style="myStyle">Sample Text</span> <pre>myStyle={{myStyle}}</pre> </file> <file name="style.css"> span { color: black; } </file> <file name="protractor.js" type="protractor"> var colorSpan = element(by.css('span')); it('should check ng-style', function() { expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)'); element(by.css('input[value=\'set color\']')).click(); expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)'); element(by.css('input[value=clear]')).click(); expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)'); }); </file> </example> */ var ngStyleDirective = ngDirective(function(scope, element, attr) { scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) { if (oldStyles && (newStyles !== oldStyles)) { forEach(oldStyles, function(val, style) { element.css(style, '');}); } if (newStyles) element.css(newStyles); }, true); }); /** * @ngdoc directive * @name ngSwitch * @restrict EA * * @description * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location * as specified in the template. * * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element * matches the value obtained from the evaluated expression. In other words, you define a container element * (where you place the directive), place an expression on the **`on="..."` attribute** * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default * attribute is displayed. * * <div class="alert alert-info"> * Be aware that the attribute values to match against cannot be expressions. They are interpreted * as literal string values to match against. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the * value of the expression `$scope.someVal`. * </div> * @animations * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM * * @usage * * ``` * <ANY ng-switch="expression"> * <ANY ng-switch-when="matchValue1">...</ANY> * <ANY ng-switch-when="matchValue2">...</ANY> * <ANY ng-switch-default>...</ANY> * </ANY> * ``` * * * @scope * @priority 800 * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>. * On child elements add: * * * `ngSwitchWhen`: the case statement to match against. If match then this * case will be displayed. If the same match appears multiple times, all the * elements will be displayed. * * `ngSwitchDefault`: the default case when no other case match. If there * are multiple default cases, all of them will be displayed when no other * case match. * * * @example <example module="ngAnimate" deps="angular-animate.js" animations="true"> <file name="index.html"> <div ng-controller="Ctrl"> <select ng-model="selection" ng-options="item for item in items"> </select> <tt>selection={{selection}}</tt> <hr/> <div class="animate-switch-container" ng-switch on="selection"> <div class="animate-switch" ng-switch-when="settings">Settings Div</div> <div class="animate-switch" ng-switch-when="home">Home Span</div> <div class="animate-switch" ng-switch-default>default</div> </div> </div> </file> <file name="script.js"> function Ctrl($scope) { $scope.items = ['settings', 'home', 'other']; $scope.selection = $scope.items[0]; } </file> <file name="animations.css"> .animate-switch-container { position:relative; background:white; border:1px solid black; height:40px; overflow:hidden; } .animate-switch { padding:10px; } .animate-switch.ng-animate { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; position:absolute; top:0; left:0; right:0; bottom:0; } .animate-switch.ng-leave.ng-leave-active, .animate-switch.ng-enter { top:-50px; } .animate-switch.ng-leave, .animate-switch.ng-enter.ng-enter-active { top:0; } </file> <file name="protractor.js" type="protractor"> var switchElem = element(by.css('[ng-switch]')); var select = element(by.model('selection')); it('should start in settings', function() { expect(switchElem.getText()).toMatch(/Settings Div/); }); it('should change to home', function() { select.element.all(by.css('option')).get(1).click(); expect(switchElem.getText()).toMatch(/Home Span/); }); it('should select default', function() { select.element.all(by.css('option')).get(2).click(); expect(switchElem.getText()).toMatch(/default/); }); </file> </example> */ var ngSwitchDirective = ['$animate', function($animate) { return { restrict: 'EA', require: 'ngSwitch', // asks for $scope to fool the BC controller module controller: ['$scope', function ngSwitchController() { this.cases = {}; }], link: function(scope, element, attr, ngSwitchController) { var watchExpr = attr.ngSwitch || attr.on, selectedTranscludes = [], selectedElements = [], previousElements = [], selectedScopes = []; scope.$watch(watchExpr, function ngSwitchWatchAction(value) { var i, ii; for (i = 0, ii = previousElements.length; i < ii; ++i) { previousElements[i].remove(); } previousElements.length = 0; for (i = 0, ii = selectedScopes.length; i < ii; ++i) { var selected = selectedElements[i]; selectedScopes[i].$destroy(); previousElements[i] = selected; $animate.leave(selected, function() { previousElements.splice(i, 1); }); } selectedElements.length = 0; selectedScopes.length = 0; if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) { scope.$eval(attr.change); forEach(selectedTranscludes, function(selectedTransclude) { var selectedScope = scope.$new(); selectedScopes.push(selectedScope); selectedTransclude.transclude(selectedScope, function(caseElement) { var anchor = selectedTransclude.element; selectedElements.push(caseElement); $animate.enter(caseElement, anchor.parent(), anchor); }); }); } }); } }; }]; var ngSwitchWhenDirective = ngDirective({ transclude: 'element', priority: 800, require: '^ngSwitch', link: function(scope, element, attrs, ctrl, $transclude) { ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []); ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element }); } }); var ngSwitchDefaultDirective = ngDirective({ transclude: 'element', priority: 800, require: '^ngSwitch', link: function(scope, element, attr, ctrl, $transclude) { ctrl.cases['?'] = (ctrl.cases['?'] || []); ctrl.cases['?'].push({ transclude: $transclude, element: element }); } }); /** * @ngdoc directive * @name ngTransclude * @restrict AC * * @description * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion. * * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted. * * @element ANY * * @example <example module="transclude"> <file name="index.html"> <script> function Ctrl($scope) { $scope.title = 'Lorem Ipsum'; $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...'; } angular.module('transclude', []) .directive('pane', function(){ return { restrict: 'E', transclude: true, scope: { title:'@' }, template: '<div style="border: 1px solid black;">' + '<div style="background-color: gray">{{title}}</div>' + '<div ng-transclude></div>' + '</div>' }; }); </script> <div ng-controller="Ctrl"> <input ng-model="title"><br> <textarea ng-model="text"></textarea> <br/> <pane title="{{title}}">{{text}}</pane> </div> </file> <file name="protractor.js" type="protractor"> it('should have transcluded', function() { var titleElement = element(by.model('title')); titleElement.clear(); titleElement.sendKeys('TITLE'); var textElement = element(by.model('text')); textElement.clear(); textElement.sendKeys('TEXT'); expect(element(by.binding('title')).getText()).toEqual('TITLE'); expect(element(by.binding('text')).getText()).toEqual('TEXT'); }); </file> </example> * */ var ngTranscludeDirective = ngDirective({ link: function($scope, $element, $attrs, controller, $transclude) { if (!$transclude) { throw minErr('ngTransclude')('orphan', 'Illegal use of ngTransclude directive in the template! ' + 'No parent directive that requires a transclusion found. ' + 'Element: {0}', startingTag($element)); } $transclude(function(clone) { $element.empty(); $element.append(clone); }); } }); /** * @ngdoc directive * @name script * @restrict E * * @description * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the * template can be used by {@link ng.directive:ngInclude `ngInclude`}, * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be * assigned through the element's `id`, which can then be used as a directive's `templateUrl`. * * @param {string} type Must be set to `'text/ng-template'`. * @param {string} id Cache name of the template. * * @example <example> <file name="index.html"> <script type="text/ng-template" id="/tpl.html"> Content of the template. </script> <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a> <div id="tpl-content" ng-include src="currentTpl"></div> </file> <file name="protractor.js" type="protractor"> it('should load template defined inside script tag', function() { element(by.css('#tpl-link')).click(); expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/); }); </file> </example> */ var scriptDirective = ['$templateCache', function($templateCache) { return { restrict: 'E', terminal: true, compile: function(element, attr) { if (attr.type == 'text/ng-template') { var templateUrl = attr.id, // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent text = element[0].text; $templateCache.put(templateUrl, text); } } }; }]; var ngOptionsMinErr = minErr('ngOptions'); /** * @ngdoc directive * @name select * @restrict E * * @description * HTML `SELECT` element with angular data-binding. * * # `ngOptions` * * The `ngOptions` attribute can be used to dynamically generate a list of `<option>` * elements for the `<select>` element using the array or object obtained by evaluating the * `ngOptions` comprehension_expression. * * When an item in the `<select>` menu is selected, the array element or object property * represented by the selected option will be bound to the model identified by the `ngModel` * directive. * * <div class="alert alert-warning"> * **Note:** `ngModel` compares by reference, not value. This is important when binding to an * array of objects. See an example [in this jsfiddle](http://jsfiddle.net/qWzTb/). * </div> * * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can * be nested into the `<select>` element. This element will then represent the `null` or "not selected" * option. See example below for demonstration. * * <div class="alert alert-warning"> * **Note:** `ngOptions` provides an iterator facility for the `<option>` element which should be used instead * of {@link ng.directive:ngRepeat ngRepeat} when you want the * `select` model to be bound to a non-string value. This is because an option element can only * be bound to string values at present. * </div> * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required The control is considered valid only if value is entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {comprehension_expression=} ngOptions in one of the following forms: * * * for array data sources: * * `label` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`for`** `value` **`in`** `array` * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr` * * for object data sources: * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`group by`** `group` * **`for` `(`**`key`**`,`** `value`**`) in`** `object` * * Where: * * * `array` / `object`: an expression which evaluates to an array / object to iterate over. * * `value`: local variable which will refer to each item in the `array` or each property value * of `object` during iteration. * * `key`: local variable which will refer to a property name in `object` during iteration. * * `label`: The result of this expression will be the label for `<option>` element. The * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`). * * `select`: The result of this expression will be bound to the model of the parent `<select>` * element. If not specified, `select` expression will default to `value`. * * `group`: The result of this expression will be used to group options using the `<optgroup>` * DOM element. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be * used to identify the objects in the array. The `trackexpr` will most likely refer to the * `value` variable (e.g. `value.propertyName`). * * @example <example> <file name="index.html"> <script> function MyCntrl($scope) { $scope.colors = [ {name:'black', shade:'dark'}, {name:'white', shade:'light'}, {name:'red', shade:'dark'}, {name:'blue', shade:'dark'}, {name:'yellow', shade:'light'} ]; $scope.myColor = $scope.colors[2]; // red } </script> <div ng-controller="MyCntrl"> <ul> <li ng-repeat="color in colors"> Name: <input ng-model="color.name"> [<a href ng-click="colors.splice($index, 1)">X</a>] </li> <li> [<a href ng-click="colors.push({})">add</a>] </li> </ul> <hr/> Color (null not allowed): <select ng-model="myColor" ng-options="color.name for color in colors"></select><br> Color (null allowed): <span class="nullable"> <select ng-model="myColor" ng-options="color.name for color in colors"> <option value="">-- choose color --</option> </select> </span><br/> Color grouped by shade: <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors"> </select><br/> Select <a href ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</a>.<br> <hr/> Currently selected: {{ {selected_color:myColor} }} <div style="border:solid 1px black; height:20px" ng-style="{'background-color':myColor.name}"> </div> </div> </file> <file name="protractor.js" type="protractor"> it('should check ng-options', function() { expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red'); element.all(by.select('myColor')).first().click(); element.all(by.css('select[ng-model="myColor"] option')).first().click(); expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black'); element(by.css('.nullable select[ng-model="myColor"]')).click(); element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click(); expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null'); }); </file> </example> */ var ngOptionsDirective = valueFn({ terminal: true }); // jshint maxlen: false var selectDirective = ['$compile', '$parse', function($compile, $parse) { //000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888 var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/, nullModelCtrl = {$setViewValue: noop}; // jshint maxlen: 100 return { restrict: 'E', require: ['select', '?ngModel'], controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) { var self = this, optionsMap = {}, ngModelCtrl = nullModelCtrl, nullOption, unknownOption; self.databound = $attrs.ngModel; self.init = function(ngModelCtrl_, nullOption_, unknownOption_) { ngModelCtrl = ngModelCtrl_; nullOption = nullOption_; unknownOption = unknownOption_; }; self.addOption = function(value) { assertNotHasOwnProperty(value, '"option value"'); optionsMap[value] = true; if (ngModelCtrl.$viewValue == value) { $element.val(value); if (unknownOption.parent()) unknownOption.remove(); } }; self.removeOption = function(value) { if (this.hasOption(value)) { delete optionsMap[value]; if (ngModelCtrl.$viewValue == value) { this.renderUnknownOption(value); } } }; self.renderUnknownOption = function(val) { var unknownVal = '? ' + hashKey(val) + ' ?'; unknownOption.val(unknownVal); $element.prepend(unknownOption); $element.val(unknownVal); unknownOption.prop('selected', true); // needed for IE }; self.hasOption = function(value) { return optionsMap.hasOwnProperty(value); }; $scope.$on('$destroy', function() { // disable unknown option so that we don't do work when the whole select is being destroyed self.renderUnknownOption = noop; }); }], link: function(scope, element, attr, ctrls) { // if ngModel is not defined, we don't need to do anything if (!ctrls[1]) return; var selectCtrl = ctrls[0], ngModelCtrl = ctrls[1], multiple = attr.multiple, optionsExp = attr.ngOptions, nullOption = false, // if false, user will not be able to select it (used by ngOptions) emptyOption, // we can't just jqLite('<option>') since jqLite is not smart enough // to create it in <select> and IE barfs otherwise. optionTemplate = jqLite(document.createElement('option')), optGroupTemplate =jqLite(document.createElement('optgroup')), unknownOption = optionTemplate.clone(); // find "null" option for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) { if (children[i].value === '') { emptyOption = nullOption = children.eq(i); break; } } selectCtrl.init(ngModelCtrl, nullOption, unknownOption); // required validator if (multiple) { ngModelCtrl.$isEmpty = function(value) { return !value || value.length === 0; }; } if (optionsExp) setupAsOptions(scope, element, ngModelCtrl); else if (multiple) setupAsMultiple(scope, element, ngModelCtrl); else setupAsSingle(scope, element, ngModelCtrl, selectCtrl); //////////////////////////// function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) { ngModelCtrl.$render = function() { var viewValue = ngModelCtrl.$viewValue; if (selectCtrl.hasOption(viewValue)) { if (unknownOption.parent()) unknownOption.remove(); selectElement.val(viewValue); if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy } else { if (isUndefined(viewValue) && emptyOption) { selectElement.val(''); } else { selectCtrl.renderUnknownOption(viewValue); } } }; selectElement.on('change', function() { scope.$apply(function() { if (unknownOption.parent()) unknownOption.remove(); ngModelCtrl.$setViewValue(selectElement.val()); }); }); } function setupAsMultiple(scope, selectElement, ctrl) { var lastView; ctrl.$render = function() { var items = new HashMap(ctrl.$viewValue); forEach(selectElement.find('option'), function(option) { option.selected = isDefined(items.get(option.value)); }); }; // we have to do it on each watch since ngModel watches reference, but // we need to work of an array, so we need to see if anything was inserted/removed scope.$watch(function selectMultipleWatch() { if (!equals(lastView, ctrl.$viewValue)) { lastView = shallowCopy(ctrl.$viewValue); ctrl.$render(); } }); selectElement.on('change', function() { scope.$apply(function() { var array = []; forEach(selectElement.find('option'), function(option) { if (option.selected) { array.push(option.value); } }); ctrl.$setViewValue(array); }); }); } function setupAsOptions(scope, selectElement, ctrl) { var match; if (!(match = optionsExp.match(NG_OPTIONS_REGEXP))) { throw ngOptionsMinErr('iexp', "Expected expression in form of " + "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" + " but got '{0}'. Element: {1}", optionsExp, startingTag(selectElement)); } var displayFn = $parse(match[2] || match[1]), valueName = match[4] || match[6], keyName = match[5], groupByFn = $parse(match[3] || ''), valueFn = $parse(match[2] ? match[1] : valueName), valuesFn = $parse(match[7]), track = match[8], trackFn = track ? $parse(match[8]) : null, // This is an array of array of existing option groups in DOM. // We try to reuse these if possible // - optionGroupsCache[0] is the options with no option group // - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element optionGroupsCache = [[{element: selectElement, label:''}]]; if (nullOption) { // compile the element since there might be bindings in it $compile(nullOption)(scope); // remove the class, which is added automatically because we recompile the element and it // becomes the compilation root nullOption.removeClass('ng-scope'); // we need to remove it before calling selectElement.empty() because otherwise IE will // remove the label from the element. wtf? nullOption.remove(); } // clear contents, we'll add what's needed based on the model selectElement.empty(); selectElement.on('change', function() { scope.$apply(function() { var optionGroup, collection = valuesFn(scope) || [], locals = {}, key, value, optionElement, index, groupIndex, length, groupLength, trackIndex; if (multiple) { value = []; for (groupIndex = 0, groupLength = optionGroupsCache.length; groupIndex < groupLength; groupIndex++) { // list of options for that group. (first item has the parent) optionGroup = optionGroupsCache[groupIndex]; for(index = 1, length = optionGroup.length; index < length; index++) { if ((optionElement = optionGroup[index].element)[0].selected) { key = optionElement.val(); if (keyName) locals[keyName] = key; if (trackFn) { for (trackIndex = 0; trackIndex < collection.length; trackIndex++) { locals[valueName] = collection[trackIndex]; if (trackFn(scope, locals) == key) break; } } else { locals[valueName] = collection[key]; } value.push(valueFn(scope, locals)); } } } } else { key = selectElement.val(); if (key == '?') { value = undefined; } else if (key === ''){ value = null; } else { if (trackFn) { for (trackIndex = 0; trackIndex < collection.length; trackIndex++) { locals[valueName] = collection[trackIndex]; if (trackFn(scope, locals) == key) { value = valueFn(scope, locals); break; } } } else { locals[valueName] = collection[key]; if (keyName) locals[keyName] = key; value = valueFn(scope, locals); } } // Update the null option's selected property here so $render cleans it up correctly if (optionGroupsCache[0].length > 1) { if (optionGroupsCache[0][1].id !== key) { optionGroupsCache[0][1].selected = false; } } } ctrl.$setViewValue(value); }); }); ctrl.$render = render; // TODO(vojta): can't we optimize this ? scope.$watch(render); function render() { // Temporary location for the option groups before we render them var optionGroups = {'':[]}, optionGroupNames = [''], optionGroupName, optionGroup, option, existingParent, existingOptions, existingOption, modelValue = ctrl.$modelValue, values = valuesFn(scope) || [], keys = keyName ? sortedKeys(values) : values, key, groupLength, length, groupIndex, index, locals = {}, selected, selectedSet = false, // nothing is selected yet lastElement, element, label; if (multiple) { if (trackFn && isArray(modelValue)) { selectedSet = new HashMap([]); for (var trackIndex = 0; trackIndex < modelValue.length; trackIndex++) { locals[valueName] = modelValue[trackIndex]; selectedSet.put(trackFn(scope, locals), modelValue[trackIndex]); } } else { selectedSet = new HashMap(modelValue); } } // We now build up the list of options we need (we merge later) for (index = 0; length = keys.length, index < length; index++) { key = index; if (keyName) { key = keys[index]; if ( key.charAt(0) === '$' ) continue; locals[keyName] = key; } locals[valueName] = values[key]; optionGroupName = groupByFn(scope, locals) || ''; if (!(optionGroup = optionGroups[optionGroupName])) { optionGroup = optionGroups[optionGroupName] = []; optionGroupNames.push(optionGroupName); } if (multiple) { selected = isDefined( selectedSet.remove(trackFn ? trackFn(scope, locals) : valueFn(scope, locals)) ); } else { if (trackFn) { var modelCast = {}; modelCast[valueName] = modelValue; selected = trackFn(scope, modelCast) === trackFn(scope, locals); } else { selected = modelValue === valueFn(scope, locals); } selectedSet = selectedSet || selected; // see if at least one item is selected } label = displayFn(scope, locals); // what will be seen by the user // doing displayFn(scope, locals) || '' overwrites zero values label = isDefined(label) ? label : ''; optionGroup.push({ // either the index into array or key from object id: trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index), label: label, selected: selected // determine if we should be selected }); } if (!multiple) { if (nullOption || modelValue === null) { // insert null option if we have a placeholder, or the model is null optionGroups[''].unshift({id:'', label:'', selected:!selectedSet}); } else if (!selectedSet) { // option could not be found, we have to insert the undefined item optionGroups[''].unshift({id:'?', label:'', selected:true}); } } // Now we need to update the list of DOM nodes to match the optionGroups we computed above for (groupIndex = 0, groupLength = optionGroupNames.length; groupIndex < groupLength; groupIndex++) { // current option group name or '' if no group optionGroupName = optionGroupNames[groupIndex]; // list of options for that group. (first item has the parent) optionGroup = optionGroups[optionGroupName]; if (optionGroupsCache.length <= groupIndex) { // we need to grow the optionGroups existingParent = { element: optGroupTemplate.clone().attr('label', optionGroupName), label: optionGroup.label }; existingOptions = [existingParent]; optionGroupsCache.push(existingOptions); selectElement.append(existingParent.element); } else { existingOptions = optionGroupsCache[groupIndex]; existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element // update the OPTGROUP label if not the same. if (existingParent.label != optionGroupName) { existingParent.element.attr('label', existingParent.label = optionGroupName); } } lastElement = null; // start at the beginning for(index = 0, length = optionGroup.length; index < length; index++) { option = optionGroup[index]; if ((existingOption = existingOptions[index+1])) { // reuse elements lastElement = existingOption.element; if (existingOption.label !== option.label) { lastElement.text(existingOption.label = option.label); } if (existingOption.id !== option.id) { lastElement.val(existingOption.id = option.id); } // lastElement.prop('selected') provided by jQuery has side-effects if (existingOption.selected !== option.selected) { lastElement.prop('selected', (existingOption.selected = option.selected)); } } else { // grow elements // if it's a null option if (option.id === '' && nullOption) { // put back the pre-compiled element element = nullOption; } else { // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but // in this version of jQuery on some browser the .text() returns a string // rather then the element. (element = optionTemplate.clone()) .val(option.id) .prop('selected', option.selected) .text(option.label); } existingOptions.push(existingOption = { element: element, label: option.label, id: option.id, selected: option.selected }); if (lastElement) { lastElement.after(element); } else { existingParent.element.append(element); } lastElement = element; } } // remove any excessive OPTIONs in a group index++; // increment since the existingOptions[0] is parent element not OPTION while(existingOptions.length > index) { existingOptions.pop().element.remove(); } } // remove any excessive OPTGROUPs from select while(optionGroupsCache.length > groupIndex) { optionGroupsCache.pop()[0].element.remove(); } } } } }; }]; var optionDirective = ['$interpolate', function($interpolate) { var nullSelectCtrl = { addOption: noop, removeOption: noop }; return { restrict: 'E', priority: 100, compile: function(element, attr) { if (isUndefined(attr.value)) { var interpolateFn = $interpolate(element.text(), true); if (!interpolateFn) { attr.$set('value', element.text()); } } return function (scope, element, attr) { var selectCtrlName = '$selectController', parent = element.parent(), selectCtrl = parent.data(selectCtrlName) || parent.parent().data(selectCtrlName); // in case we are in optgroup if (selectCtrl && selectCtrl.databound) { // For some reason Opera defaults to true and if not overridden this messes up the repeater. // We don't want the view to drive the initialization of the model anyway. element.prop('selected', false); } else { selectCtrl = nullSelectCtrl; } if (interpolateFn) { scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) { attr.$set('value', newVal); if (oldVal !== newVal) { selectCtrl.removeOption(oldVal); } selectCtrl.addOption(newVal); }); } else { selectCtrl.addOption(attr.value); } element.on('$destroy', function() { selectCtrl.removeOption(attr.value); }); }; } }; }]; var styleDirective = valueFn({ restrict: 'E', terminal: false }); if (window.angular.bootstrap) { //AngularJS is already loaded, so we can return here... console.log('WARNING: Tried to load angular more than once.'); return; } //try to bind to jquery now so that one can write angular.element().read() //but we will rebind on bootstrap again. bindJQuery(); publishExternalAPI(angular); jqLite(document).ready(function() { angularInit(document, bootstrap); }); })(window, document); !window.angular.$$csp() && window.angular.element(document).find('head').prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-animate){display:none !important;}ng\\:form{display:block;}</style>');
/** * @license Highcharts JS v9.3.2 (2021-11-29) * * Old IE (v6, v7, v8) module for Highcharts v6+. * * (c) 2010-2021 Highsoft AS * Author: Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { factory['default'] = factory; module.exports = factory; } else if (typeof define === 'function' && define.amd) { define('highcharts/modules/oldie', ['highcharts'], function (Highcharts) { factory(Highcharts); factory.Highcharts = Highcharts; return factory; }); } else { factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined); } }(function (Highcharts) { var _modules = Highcharts ? Highcharts._modules : {}; function _registerModule(obj, path, args, fn) { if (!obj.hasOwnProperty(path)) { obj[path] = fn.apply(null, args); } } _registerModule(_modules, 'Extensions/Oldie/VMLAxis3D.js', [_modules['Core/Utilities.js']], function (U) { /* * * * (c) 2010-2021 Torstein Honsi * * Extension to the VML Renderer * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ var addEvent = U.addEvent; /* * * * Class * * */ /* eslint-disable valid-jsdoc */ var VMLAxis3DAdditions = /** @class */ (function () { /* * * * Constructors * * */ function VMLAxis3DAdditions(axis) { this.axis = axis; } return VMLAxis3DAdditions; }()); var VMLAxis3D = /** @class */ (function () { function VMLAxis3D() { } /* * * * Static Properties * * */ VMLAxis3D.compose = function (AxisClass) { AxisClass.keepProps.push('vml'); addEvent(AxisClass, 'destroy', VMLAxis3D.onDestroy); addEvent(AxisClass, 'init', VMLAxis3D.onInit); addEvent(AxisClass, 'render', VMLAxis3D.onRender); }; /** * @private */ VMLAxis3D.onDestroy = function () { var axis = this, vml = axis.vml; if (vml) { var el_1; [ 'backFrame', 'bottomFrame', 'sideFrame' ].forEach(function (prop) { el_1 = vml[prop]; if (el_1) { vml[prop] = el_1.destroy(); } }, this); } }; /** * @private */ VMLAxis3D.onInit = function () { var axis = this; if (!axis.vml) { axis.vml = new VMLAxis3DAdditions(axis); } }; /** * @private */ VMLAxis3D.onRender = function () { var axis = this; var vml = axis.vml; // VML doesn't support a negative z-index if (vml.sideFrame) { vml.sideFrame.css({ zIndex: 0 }); vml.sideFrame.front.attr({ fill: vml.sideFrame.color }); } if (vml.bottomFrame) { vml.bottomFrame.css({ zIndex: 1 }); vml.bottomFrame.front.attr({ fill: vml.bottomFrame.color }); } if (vml.backFrame) { vml.backFrame.css({ zIndex: 0 }); vml.backFrame.front.attr({ fill: vml.backFrame.color }); } }; return VMLAxis3D; }()); return VMLAxis3D; }); _registerModule(_modules, 'Extensions/Oldie/VMLRenderer3D.js', [_modules['Core/Axis/Axis.js'], _modules['Core/DefaultOptions.js'], _modules['Extensions/Oldie/VMLAxis3D.js']], function (Axis, D, VMLAxis3D) { /* * * * (c) 2010-2021 Torstein Honsi * * Extension to the VML Renderer * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ var setOptions = D.setOptions; var VMLRenderer3D = /** @class */ (function () { function VMLRenderer3D() { } /* * * * Static Properties * * */ VMLRenderer3D.compose = function (vmlClass, svgClass) { var svgProto = svgClass.prototype; var vmlProto = vmlClass.prototype; setOptions({ animate: false }); vmlProto.face3d = svgProto.face3d; vmlProto.polyhedron = svgProto.polyhedron; vmlProto.elements3d = svgProto.elements3d; vmlProto.element3d = svgProto.element3d; vmlProto.cuboid = svgProto.cuboid; vmlProto.cuboidPath = svgProto.cuboidPath; vmlProto.toLinePath = svgProto.toLinePath; vmlProto.toLineSegments = svgProto.toLineSegments; vmlProto.arc3d = function (shapeArgs) { var result = svgProto.arc3d.call(this, shapeArgs); result.css({ zIndex: result.zIndex }); return result; }; vmlProto.arc3dPath = svgProto.arc3dPath; VMLAxis3D.compose(Axis); }; return VMLRenderer3D; }()); return VMLRenderer3D; }); _registerModule(_modules, 'Extensions/Oldie/Oldie.js', [_modules['Core/Chart/Chart.js'], _modules['Core/Color/Color.js'], _modules['Core/Globals.js'], _modules['Core/DefaultOptions.js'], _modules['Core/Pointer.js'], _modules['Core/Renderer/RendererRegistry.js'], _modules['Core/Renderer/SVG/SVGElement.js'], _modules['Core/Renderer/SVG/SVGRenderer.js'], _modules['Core/Utilities.js'], _modules['Extensions/Oldie/VMLRenderer3D.js']], function (Chart, Color, H, D, Pointer, RendererRegistry, SVGElement, SVGRenderer, U, VMLRenderer3D) { /* * * * (c) 2010-2021 Torstein Honsi * * License: www.highcharts.com/license * * Support for old IE browsers (6, 7 and 8) in Highcharts v6+. * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ var color = Color.parse; var deg2rad = H.deg2rad, doc = H.doc, noop = H.noop, svg = H.svg, win = H.win; var getOptions = D.getOptions; var addEvent = U.addEvent, createElement = U.createElement, css = U.css, defined = U.defined, discardElement = U.discardElement, erase = U.erase, extend = U.extend, extendClass = U.extendClass, isArray = U.isArray, isNumber = U.isNumber, isObject = U.isObject, pick = U.pick, pInt = U.pInt, uniqueKey = U.uniqueKey; var VMLRenderer, VMLElement; /** * Path to the pattern image required by VML browsers in order to * draw radial gradients. * * @type {string} * @default http://code.highcharts.com/{version}/gfx/vml-radial-gradient.png * @since 2.3.0 * @requires modules/oldie * @apioption global.VMLRadialGradientURL */ getOptions().global.VMLRadialGradientURL = 'http://code.highcharts.com/9.3.2/gfx/vml-radial-gradient.png'; // Utilites if (doc && !doc.defaultView) { H.getStyle = U.getStyle = function getStyle(el, prop) { var val, alias = { width: 'clientWidth', height: 'clientHeight' }[prop]; if (el.style[prop]) { return pInt(el.style[prop]); } if (prop === 'opacity') { prop = 'filter'; } // Getting the rendered width and height if (alias) { el.style.zoom = 1; return Math.max(el[alias] - 2 * getStyle(el, 'padding'), 0); } val = el.currentStyle[prop.replace(/\-(\w)/g, function (a, b) { return b.toUpperCase(); })]; if (prop === 'filter') { val = val.replace(/alpha\(opacity=([0-9]+)\)/, function (a, b) { return (b / 100); }); } return val === '' ? 1 : pInt(val); }; } /* eslint-disable no-invalid-this, valid-jsdoc */ if (!svg) { // Prevent wrapping from creating false offsetWidths in export in legacy IE. // This applies only to charts for export, where IE runs the SVGRenderer // instead of the VMLRenderer // (#1079, #1063) addEvent(SVGElement, 'afterInit', function () { if (this.element.nodeName === 'text') { this.css({ position: 'absolute' }); } }); /** * Old IE override for pointer normalize, adds chartX and chartY to event * arguments. * * @ignore * @function Highcharts.Pointer#normalize */ Pointer.prototype.normalize = function (e, chartPosition) { e = e || win.event; if (!e.target) { e.target = e.srcElement; } // Get mouse position if (!chartPosition) { this.chartPosition = chartPosition = this.getChartPosition(); } return extend(e, { // #2005, #2129: the second case is for IE10 quirks mode within // framesets chartX: Math.round(Math.max(e.x, e.clientX - chartPosition.left)), chartY: Math.round(e.y) }); }; /** * Further sanitize the mock-SVG that is generated when exporting charts in * oldIE. * * @private * @function Highcharts.Chart#ieSanitizeSVG */ Chart.prototype.ieSanitizeSVG = function (svg) { svg = svg .replace(/<IMG /g, '<image ') .replace(/<(\/?)TITLE>/g, '<$1title>') .replace(/height=([^" ]+)/g, 'height="$1"') .replace(/width=([^" ]+)/g, 'width="$1"') .replace(/hc-svg-href="([^"]+)">/g, 'xlink:href="$1"/>') .replace(/ id=([^" >]+)/g, ' id="$1"') // #4003 .replace(/class=([^" >]+)/g, 'class="$1"') .replace(/ transform /g, ' ') .replace(/:(path|rect)/g, '$1') .replace(/style="([^"]+)"/g, function (s) { return s.toLowerCase(); }); return svg; }; /** * VML namespaces can't be added until after complete. Listening * for Perini's doScroll hack is not enough. * * @private * @function Highcharts.Chart#isReadyToRender */ Chart.prototype.isReadyToRender = function () { var chart = this; // Note: win == win.top is required if (!svg && (win == win.top && // eslint-disable-line eqeqeq doc.readyState !== 'complete')) { doc.attachEvent('onreadystatechange', function () { doc.detachEvent('onreadystatechange', chart.firstRender); if (doc.readyState === 'complete') { chart.firstRender(); } }); return false; } return true; }; // IE compatibility hack for generating SVG content that it doesn't really // understand. Used by the exporting module. if (!doc.createElementNS) { doc.createElementNS = function (ns, tagName) { return doc.createElement(tagName); }; } /** * Old IE polyfill for addEventListener, called from inside the addEvent * function. * * @private * @function Highcharts.addEventListenerPolyfill<T> */ H.addEventListenerPolyfill = function (type, fn) { var el = this; /** * @private */ function wrappedFn(e) { e.target = e.srcElement || win; // #2820 fn.call(el, e); } if (el.attachEvent) { if (!el.hcEventsIE) { el.hcEventsIE = {}; } // unique function string (#6746) if (!fn.hcKey) { fn.hcKey = uniqueKey(); } // Link wrapped fn with original fn, so we can get this in // removeEvent el.hcEventsIE[fn.hcKey] = wrappedFn; el.attachEvent('on' + type, wrappedFn); } }; /** * @private * @function Highcharts.removeEventListenerPolyfill<T> */ H.removeEventListenerPolyfill = function (type, fn) { if (this.detachEvent) { fn = this.hcEventsIE[fn.hcKey]; this.detachEvent('on' + type, fn); } }; /** * The VML element wrapper. * * @private * @class * @name Highcharts.VMLElement * * @augments Highcharts.SVGElement */ VMLElement = { docMode8: doc && doc.documentMode === 8, /** * Initialize a new VML element wrapper. It builds the markup as a * string to minimize DOM traffic. * * @function Highcharts.VMLElement#init */ init: function (renderer, nodeName) { var wrapper = this, markup = ['<', nodeName, ' filled="f" stroked="f"'], style = ['position: ', 'absolute', ';'], isDiv = nodeName === 'div'; // divs and shapes need size if (nodeName === 'shape' || isDiv) { style.push('left:0;top:0;width:1px;height:1px;'); } style.push('visibility: ', isDiv ? 'hidden' : 'visible'); markup.push(' style="', style.join(''), '"/>'); // create element with default attributes and style if (nodeName) { markup = isDiv || nodeName === 'span' || nodeName === 'img' ? markup.join('') : renderer.prepVML(markup); wrapper.element = createElement(markup); } wrapper.renderer = renderer; }, /** * Add the node to the given parent * * @function Highcharts.VMLElement */ add: function (parent) { var wrapper = this, renderer = wrapper.renderer, element = wrapper.element, box = renderer.box, inverted = parent && parent.inverted, // get the parent node parentNode = parent ? parent.element || parent : box; if (parent) { this.parentGroup = parent; } // if the parent group is inverted, apply inversion on all children if (inverted) { // only on groups renderer.invertChild(element, parentNode); } // append it parentNode.appendChild(element); // align text after adding to be able to read offset wrapper.added = true; if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) { wrapper.updateTransform(); } // fire an event for internal hooks if (wrapper.onAdd) { wrapper.onAdd(); } // IE8 Standards can't set the class name before the element is // appended if (this.className) { this.attr('class', this.className); } return wrapper; }, /** * VML always uses htmlUpdateTransform * * @function Highcharts.VMLElement#updateTransform */ updateTransform: SVGElement.prototype .htmlUpdateTransform, /** * Set the rotation of a span with oldIE's filter * * @function Highcharts.VMLElement#setSpanRotation */ setSpanRotation: function () { // Adjust for alignment and rotation. Rotation of useHTML content is // not yet implemented but it can probably be implemented for // Firefox 3.5+ on user request. FF3.5+ has support for CSS3 // transform. The getBBox method also needs to be updated to // compensate for the rotation, like it currently does for SVG. // Test case: https://jsfiddle.net/highcharts/Ybt44/ var rotation = this.rotation, costheta = Math.cos(rotation * deg2rad), sintheta = Math.sin(rotation * deg2rad); css(this.element, { filter: rotation ? [ 'progid:DXImageTransform.Microsoft.Matrix(M11=', costheta, ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta, ', sizingMethod=\'auto expand\')' ].join('') : 'none' }); }, /** * Get the positioning correction for the span after rotating. * * @function Highcharts.VMLElement#getSpanCorrection */ getSpanCorrection: function (width, baseline, alignCorrection, rotation, align) { var costheta = rotation ? Math.cos(rotation * deg2rad) : 1, sintheta = rotation ? Math.sin(rotation * deg2rad) : 0, height = pick(this.elemHeight, this.element.offsetHeight), quad, nonLeft = align && align !== 'left'; // correct x and y this.xCorr = (costheta < 0 && -width); this.yCorr = (sintheta < 0 && -height); // correct for baseline and corners spilling out after rotation quad = costheta * sintheta < 0; this.xCorr += (sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection)); this.yCorr -= (costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1)); // correct for the length/height of the text if (nonLeft) { this.xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1); if (rotation) { this.yCorr -= (height * alignCorrection * (sintheta < 0 ? -1 : 1)); } css(this.element, { textAlign: align }); } }, /** * Converts a subset of an SVG path definition to its VML counterpart. * Takes an array as the parameter and returns a string. * * @function Highcharts.VMLElement#pathToVML */ pathToVML: function (value) { // convert paths var i = value.length, path = []; while (i--) { // Multiply by 10 to allow subpixel precision. // Substracting half a pixel seems to make the coordinates // align with SVG, but this hasn't been tested thoroughly if (isNumber(value[i])) { path[i] = Math.round(value[i] * 10) - 5; } else if (value[i] === 'Z') { // close the path path[i] = 'x'; } else { path[i] = value[i]; // When the start X and end X coordinates of an arc are too // close, they are rounded to the same value above. In this // case, substract or add 1 from the end X and Y positions. // #186, #760, #1371, #1410. if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) { // Start and end X if (path[i + 5] === path[i + 7]) { path[i + 7] += value[i + 7] > value[i + 5] ? 1 : -1; } // Start and end Y if (path[i + 6] === path[i + 8]) { path[i + 8] += value[i + 8] > value[i + 6] ? 1 : -1; } } } } return path.join(' ') || 'x'; }, /** * Set the element's clipping to a predefined rectangle * * @function Highcharts.VMLElement#clip */ clip: function (clipRect) { var wrapper = this, clipMembers, cssRet; if (clipRect) { clipMembers = clipRect.members; // Ensure unique list of elements (#1258) erase(clipMembers, wrapper); clipMembers.push(wrapper); wrapper.destroyClip = function () { erase(clipMembers, wrapper); }; cssRet = clipRect.getCSS(wrapper); } else { if (wrapper.destroyClip) { wrapper.destroyClip(); } cssRet = { clip: wrapper.docMode8 ? 'inherit' : 'rect(auto)' }; // #1214 } return wrapper.css(cssRet); }, /** * Set styles for the element * * @function Highcharts.VMLElement#css */ css: SVGElement.prototype.htmlCss, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to * sIEve, discardElement does not. * * @function Highcharts.VMLElement#safeRemoveChild */ safeRemoveChild: function (element) { // discardElement will detach the node from its parent before // attaching it to the garbage bin. Therefore it is important that // the node is attached and have parent. if (element.parentNode) { discardElement(element); } }, /** * Extend element.destroy by removing it from the clip members array * * @function Highcharts.VMLElement#destroy */ destroy: function () { if (this.destroyClip) { this.destroyClip(); } return SVGElement.prototype.destroy.apply(this); }, /** * Add an event listener. VML override for normalizing event parameters. * * @function Highcharts.VMLElement#on */ on: function (eventType, handler) { // simplest possible event model for internal use this.element['on' + eventType] = function () { var e = win.event; e.target = e.srcElement; handler(e); }; return this; }, /** * In stacked columns, cut off the shadows so that they don't overlap * * @function Highcharts.VMLElement#cutOffPath */ cutOffPath: function (path, length) { var len; // The extra comma tricks the trailing comma remover in // "gulp scripts" task path = path.split(/[ ,]/); len = path.length; if (len === 9 || len === 11) { path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length; } return path.join(' '); }, /** * Apply a drop shadow by copying elements and giving them different * strokes. * * @function Highcharts.VMLElement#shadow */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, element = this.element, renderer = this.renderer, shadow, elemStyle = element.style, markup, path = element.path, strokeWidth, modifiedPath, shadowWidth, shadowElementOpacity; // some times empty paths are not strings if (path && typeof path.value !== 'string') { path = 'x'; } modifiedPath = path; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; for (i = 1; i <= 3; i++) { strokeWidth = (shadowWidth * 2) + 1 - (2 * i); // Cut off shadows for stacked column items if (cutOff) { modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5); } markup = [ '<shape isShadow="true" strokeweight="', strokeWidth, '" filled="false" path="', modifiedPath, '" coordsize="10 10" style="', element.style.cssText, '" />' ]; shadow = createElement(renderer.prepVML(markup), null, { left: (pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1)) + 'px', top: (pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1)) + 'px' }); if (cutOff) { shadow.cutOff = strokeWidth + 1; } // apply the opacity markup = [ '<stroke color="', shadowOptions.color || "#000000" /* neutralColor100 */, '" opacity="', shadowElementOpacity * i, '"/>' ]; createElement(renderer.prepVML(markup), null, null, shadow); // insert it if (group) { group.element.appendChild(shadow); } else { element.parentNode .insertBefore(shadow, element); } // record it shadows.push(shadow); } this.shadows = shadows; } return this; }, updateShadows: noop, setAttr: function (key, value) { if (this.docMode8) { // IE8 setAttribute bug this.element[key] = value; } else { this.element.setAttribute(key, value); } }, getAttr: function (key) { if (this.docMode8) { // IE8 setAttribute bug return this.element[key]; } return this.element.getAttribute(key); }, classSetter: function (value) { // IE8 Standards mode has problems retrieving the className unless // set like this. IE8 Standards can't set the class name before the // element is appended. (this.added ? this.element : this).className = value; }, dashstyleSetter: function (value, key, element) { var strokeElem = element.getElementsByTagName('stroke')[0] || createElement(this.renderer.prepVML(['<stroke/>']), null, null, element); strokeElem[key] = value || 'solid'; // Because changing stroke-width will change the dash length and // cause an epileptic effect this[key] = value; }, dSetter: function (value, key, element) { var i, shadows = this.shadows; value = value || []; // Used in getter for animation this.d = value.join && value.join(' '); element.path = value = this.pathToVML(value); // update shadows if (shadows) { i = shadows.length; while (i--) { shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value; } } this.setAttr(key, value); }, fillSetter: function (value, key, element) { var nodeName = element.nodeName; if (nodeName === 'SPAN') { // text color element.style.color = value; } else if (nodeName !== 'IMG') { // #1336 element.filled = value !== 'none'; this.setAttr('fillcolor', this.renderer.color(value, element, key, this)); } }, 'fill-opacitySetter': function (value, key, element) { createElement(this.renderer.prepVML(['<', key.split('-')[0], ' opacity="', value, '"/>']), null, null, element); }, // Don't bother - animation is too slow and filters introduce artifacts opacitySetter: noop, rotationSetter: function (value, key, element) { var style = element.style; // style is for #1873: this[key] = style[key] = value; // Correction for the 1x1 size of the shape container. Used in gauge // needles. style.left = -Math.round(Math.sin(value * deg2rad) + 1) + 'px'; style.top = Math.round(Math.cos(value * deg2rad)) + 'px'; }, strokeSetter: function (value, key, element) { this.setAttr('strokecolor', this.renderer.color(value, element, key, this)); }, 'stroke-widthSetter': function (value, key, element) { element.stroked = !!value; // VML "stroked" attribute this[key] = value; // used in getter, issue #113 if (isNumber(value)) { value += 'px'; } this.setAttr('strokeweight', value); }, titleSetter: function (value, key) { this.setAttr(key, value); }, visibilitySetter: function (value, key, element) { // Handle inherited visibility if (value === 'inherit') { value = 'visible'; } // Let the shadow follow the main element if (this.shadows) { this.shadows.forEach(function (shadow) { shadow.style[key] = value; }); } // Instead of toggling the visibility CSS property, move the div out // of the viewport. This works around #61 and #586 if (element.nodeName === 'DIV') { value = value === 'hidden' ? '-999em' : 0; // In order to redraw, IE7 needs the div to be visible when // tucked away outside the viewport. So the visibility is // actually opposite of the expected value. This applies to the // tooltip only. if (!this.docMode8) { element.style[key] = value ? 'visible' : 'hidden'; } key = 'top'; } element.style[key] = value; }, xSetter: function (value, key, element) { this[key] = value; // used in getter if (key === 'x') { key = 'left'; } else if (key === 'y') { key = 'top'; } // clipping rectangle special if (this.updateClipping) { // the key is now 'left' or 'top' for 'x' and 'y' this[key] = value; this.updateClipping(); } else { // normal element.style[key] = value; } }, zIndexSetter: function (value, key, element) { element.style[key] = value; }, fillGetter: function () { return this.getAttr('fillcolor') || ''; }, strokeGetter: function () { return this.getAttr('strokecolor') || ''; }, // #7850 classGetter: function () { return this.getAttr('className') || ''; } }; VMLElement['stroke-opacitySetter'] = VMLElement['fill-opacitySetter']; H.VMLElement = VMLElement = extendClass(SVGElement, VMLElement); // Some shared setters VMLElement.prototype.ySetter = VMLElement.prototype.widthSetter = VMLElement.prototype.heightSetter = VMLElement.prototype.xSetter; /** * The VML renderer * * @private * @class * @name Highcharts.VMLRenderer * * @augments Highcharts.SVGRenderer */ var VMLRendererExtension = { Element: VMLElement, isIE8: win.navigator.userAgent.indexOf('MSIE 8.0') > -1, /** * Initialize the VMLRenderer. * * @function Highcharts.VMLRenderer#init * @param {Highcharts.HTMLDOMElement} container * @param {number} width * @param {number} height */ init: function (container, width, height) { var renderer = this, boxWrapper, box, css; // Extended SVGRenderer member this.crispPolyLine = SVGRenderer.prototype.crispPolyLine; renderer.alignedObjects = []; boxWrapper = renderer.createElement('div') .css({ position: 'relative' }); box = boxWrapper.element; container.appendChild(boxWrapper.element); // generate the containing box renderer.isVML = true; renderer.box = box; renderer.boxWrapper = boxWrapper; renderer.gradients = {}; renderer.cache = {}; // Cache for numerical bounding boxes renderer.cacheKeys = []; renderer.imgCount = 0; renderer.setSize(width, height, false); // The only way to make IE6 and IE7 print is to use a global // namespace. However, with IE8 the only way to make the dynamic // shapes visible in screen and print mode seems to be to add the // xmlns attribute and the behaviour style inline. if (!doc.namespaces.hcv) { doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml'); // Setup default CSS (#2153, #2368, #2384) css = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' + '{ behavior:url(#default#VML); display: inline-block; } '; try { doc.createStyleSheet().cssText = css; } catch (e) { doc.styleSheets[0].cssText += css; } } }, /** * Detect whether the renderer is hidden. This happens when one of the * parent elements has display: none * * @function Highcharts.VMLRenderer#isHidden */ isHidden: function () { return !this.box.offsetWidth; }, /** * Define a clipping rectangle. In VML it is accomplished by storing the * values for setting the CSS style to all associated members. * * @function Highcharts.VMLRenderer#clipRect */ clipRect: function (x, y, width, height) { // create a dummy element var clipRect = this.createElement(), isObj = isObject(x); // mimic a rectangle with its style object for automatic updating in // attr return extend(clipRect, { members: [], count: 0, left: (isObj ? x.x : x) + 1, top: (isObj ? x.y : y) + 1, width: (isObj ? x.width : width) - 1, height: (isObj ? x.height : height) - 1, getCSS: function (wrapper) { var element = wrapper.element, nodeName = element.nodeName, isShape = nodeName === 'shape', inverted = wrapper.inverted, rect = this, top = rect.top - (isShape ? element.offsetTop : 0), left = rect.left, right = left + rect.width, bottom = top + rect.height, ret = { clip: 'rect(' + Math.round(inverted ? left : top) + 'px,' + Math.round(inverted ? bottom : right) + 'px,' + Math.round(inverted ? right : bottom) + 'px,' + Math.round(inverted ? top : left) + 'px)' }; // issue 74 workaround if (!inverted && wrapper.docMode8 && nodeName === 'DIV') { extend(ret, { width: right + 'px', height: bottom + 'px' }); } return ret; }, // used in attr and animation to update the clipping of all // members updateClipping: function () { clipRect.members.forEach(function (member) { // Member.element is falsy on deleted series, like in // stock/members/series-remove demo. Should be removed // from members, but this will do. if (member.element) { member.css(clipRect.getCSS(member)); } }); } }); }, /** * Take a color and return it if it's a string, make it a gradient if * it's a gradient configuration object, and apply opacity. * * @function Highcharts.VMLRenderer#color<T> * * @param {T} color * The color or config object * * @return {T} * Processed color */ color: function (colorOption, elem, prop, wrapper) { var renderer = this, colorObject, regexRgba = /^rgba/, markup, fillType, ret = 'none'; // Check for linear or radial gradient if (colorOption && colorOption.linearGradient) { fillType = 'gradient'; } else if (colorOption && colorOption.radialGradient) { fillType = 'pattern'; } if (fillType) { var stopColor_1, stopOpacity_1, gradient = (colorOption.linearGradient || colorOption.radialGradient), x1 = void 0, y1 = void 0, x2 = void 0, y2 = void 0, opacity1_1, opacity2_1, color1_1, color2_1, fillAttr_1 = '', stops = colorOption.stops, firstStop = void 0, lastStop = void 0, colors_1 = [], addFillNode_1 = function () { // Add the fill subnode. When colors attribute is used, // the meanings of opacity and o:opacity2 are reversed. markup = ['<fill colors="' + colors_1.join(',') + '" opacity="', opacity2_1, '" o:opacity2="', opacity1_1, '" type="', fillType, '" ', fillAttr_1, 'focus="100%" method="any" />']; createElement(renderer.prepVML(markup), null, null, elem); }; // Extend from 0 to 1 firstStop = stops[0]; lastStop = stops[stops.length - 1]; if (firstStop[0] > 0) { stops.unshift([ 0, firstStop[1] ]); } if (lastStop[0] < 1) { stops.push([ 1, lastStop[1] ]); } // Compute the stops stops.forEach(function (stop, i) { if (regexRgba.test(stop[1])) { colorObject = color(stop[1]); stopColor_1 = colorObject.get('rgb'); stopOpacity_1 = colorObject.get('a'); } else { stopColor_1 = stop[1]; stopOpacity_1 = 1; } // Build the color attribute colors_1.push((stop[0] * 100) + '% ' + stopColor_1); // Only start and end opacities are allowed, so we use the // first and the last if (!i) { opacity1_1 = stopOpacity_1; color2_1 = stopColor_1; } else { opacity2_1 = stopOpacity_1; color1_1 = stopColor_1; } }); // Apply the gradient to fills only. if (prop === 'fill') { // Handle linear gradient angle if (fillType === 'gradient') { x1 = gradient.x1 || gradient[0] || 0; y1 = gradient.y1 || gradient[1] || 0; x2 = gradient.x2 || gradient[2] || 0; y2 = gradient.y2 || gradient[3] || 0; fillAttr_1 = 'angle="' + (90 - Math.atan((y2 - y1) / // y vector (x2 - x1) // x vector ) * 180 / Math.PI) + '"'; addFillNode_1(); // Radial (circular) gradient } else { var r = gradient.r, sizex_1 = r * 2, sizey_1 = r * 2, cx_1 = gradient.cx, cy_1 = gradient.cy, radialReference_1 = elem.radialReference, bBox_1, applyRadialGradient = function () { if (radialReference_1) { bBox_1 = wrapper.getBBox(); cx_1 += (radialReference_1[0] - bBox_1.x) / bBox_1.width - 0.5; cy_1 += (radialReference_1[1] - bBox_1.y) / bBox_1.height - 0.5; sizex_1 *= radialReference_1[2] / bBox_1.width; sizey_1 *= radialReference_1[2] / bBox_1.height; } fillAttr_1 = 'src="' + getOptions().global.VMLRadialGradientURL + '" ' + 'size="' + sizex_1 + ',' + sizey_1 + '" ' + 'origin="0.5,0.5" ' + 'position="' + cx_1 + ',' + cy_1 + '" ' + 'color2="' + color2_1 + '" '; addFillNode_1(); }; // Apply radial gradient if (wrapper.added) { applyRadialGradient(); } else { // We need to know the bounding box to get the size // and position right wrapper.onAdd = applyRadialGradient; } // The fill element's color attribute is broken in IE8 // standards mode, so we need to set the parent shape's // fillcolor attribute instead. ret = color1_1; } // Gradients are not supported for VML stroke, return the first // color. #722. } else { ret = stopColor_1; } // If the color is an rgba color, split it and add a fill node to // hold the opacity component } else if (regexRgba.test(colorOption) && elem.tagName !== 'IMG') { colorObject = color(colorOption); wrapper[prop + '-opacitySetter'](colorObject.get('a'), prop, elem); ret = colorObject.get('rgb'); } else { // 'stroke' or 'fill' node var propNodes = elem.getElementsByTagName(prop); if (propNodes.length) { propNodes[0].opacity = 1; propNodes[0].type = 'solid'; } ret = colorOption; } return ret; }, /** * Take a VML string and prepare it for either IE8 or IE6/IE7. * * @function Highcharts.VMLRenderer#prepVML * * @param {Array<(number|string)>} markup * A string array of the VML markup to prepare */ prepVML: function (markup) { var vmlStyle = 'display:inline-block;behavior:url(#default#VML);', isIE8 = this.isIE8; markup = markup.join(''); if (isIE8) { // add xmlns and style inline markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />'); if (markup.indexOf('style="') === -1) { markup = markup.replace('/>', ' style="' + vmlStyle + '" />'); } else { markup = markup.replace('style="', 'style="' + vmlStyle); } } else { // add namespace markup = markup.replace('<', '<hcv:'); } return markup; }, /** * Create rotated and aligned text * * @function Highcharts.VMLRenderer#text */ text: SVGRenderer.prototype.html, /** * Create and return a path element * * @function Highcharts.VMLRenderer#path * * @param {Highcharts.VMLAttributes|Highcharts.VMLPathArray} [path] */ path: function (path) { var attr = { // subpixel precision down to 0.1 (width and height = 1px) coordsize: '10 10' }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } // create the shape return this.createElement('shape').attr(attr); }, /** * Create and return a circle element. In VML circles are implemented as * shapes, which is faster than v:oval * * @function Highcharts.VMLRenderer#circle */ circle: function (x, y, r) { var circle = this.symbol('circle'); if (isObject(x)) { r = x.r; y = x.y; x = x.x; } circle.isCircle = true; // Causes x and y to mean center (#1682) circle.r = r; return circle.attr({ x: x, y: y }); }, /** * Create a group using an outer div and an inner v:group to allow * rotating and flipping. A simple v:group would have problems with * positioning child HTML elements and CSS clip. * * @function Highcharts.VMLRenderer#g * * @param {string} name * The name of the group */ g: function (name) { var wrapper, attribs; // set the class name if (name) { attribs = { 'className': 'highcharts-' + name, 'class': 'highcharts-' + name }; } // the div to hold HTML and clipping wrapper = this.createElement('div').attr(attribs); return wrapper; }, /** * VML override to create a regular HTML image. * * @function Highcharts.VMLRenderer#image */ image: function (src, x, y, width, height) { var obj = this.createElement('img').attr({ src: src }); if (arguments.length > 1) { obj.attr({ x: x, y: y, width: width, height: height }); } return obj; }, /** * For rectangles, VML uses a shape for rect to overcome bugs and * rotation problems * * @function Highcharts.VMLRenderer#createElement */ createElement: function (nodeName) { return nodeName === 'rect' ? this.symbol(nodeName) : SVGRenderer.prototype.createElement.call(this, nodeName); }, /** * In the VML renderer, each child of an inverted div (group) is * inverted * * @function Highcharts.VMLRenderer#invertChild */ invertChild: function (element, parentNode) { var ren = this, parentStyle = parentNode.style, imgStyle = element.tagName === 'IMG' && element.style; // #1111 css(element, { flip: 'x', left: (pInt(parentStyle.width) - (imgStyle ? pInt(imgStyle.top) : 1)) + 'px', top: (pInt(parentStyle.height) - (imgStyle ? pInt(imgStyle.left) : 1)) + 'px', rotation: -90 }); // Recursively invert child elements, needed for nested composite // shapes like box plots and error bars. #1680, #1806. [].forEach.call(element.childNodes, function (child) { ren.invertChild(child, element); }); }, /** * Symbol definitions that override the parent SVG renderer's symbols * * @name Highcharts.VMLRenderer#symbols * @type {Highcharts.Dictionary<Function>} */ symbols: { // VML specific arc function arc: function (x, y, w, h, options) { var start = options.start, end = options.end, radius = options.r || w || h, innerRadius = options.innerR, cosStart = Math.cos(start), sinStart = Math.sin(start), cosEnd = Math.cos(end), sinEnd = Math.sin(end), ret; if (end - start === 0) { // no angle, don't show it. return ['x']; } ret = [ 'wa', x - radius, y - radius, x + radius, y + radius, x + radius * cosStart, y + radius * sinStart, x + radius * cosEnd, y + radius * sinEnd // end y ]; if (options.open && !innerRadius) { ret.push('e', 'M', x, // - innerRadius, y // - innerRadius ); } ret.push('at', // anti clockwise arc to x - innerRadius, // left y - innerRadius, // top x + innerRadius, // right y + innerRadius, // bottom x + innerRadius * cosEnd, // start x y + innerRadius * sinEnd, // start y x + innerRadius * cosStart, // end x y + innerRadius * sinStart, // end y 'x', // finish path 'e' // close ); ret.isArc = true; return ret; }, // Add circle symbol path. This performs significantly faster than // v:oval. circle: function (x, y, w, h, wrapper) { if (wrapper && defined(wrapper.r)) { w = h = 2 * wrapper.r; } // Center correction, #1682 if (wrapper && wrapper.isCircle) { x -= w / 2; y -= h / 2; } // Return the path return [ 'wa', x, y, x + w, y + h, x + w, y + h / 2, x + w, y + h / 2, 'e' // close ]; }, /** * Add rectangle symbol path which eases rotation and omits arcsize * problems compared to the built-in VML roundrect shape. When * borders are not rounded, use the simpler square path, else use * the callout path without the arrow. */ rect: function (x, y, w, h, options) { return SVGRenderer.prototype.symbols[!defined(options) || !options.r ? 'square' : 'callout'].call(0, x, y, w, h, options); } } }; H.VMLRenderer = VMLRenderer = function () { this.init.apply(this, arguments); }; extend(VMLRenderer.prototype, SVGRenderer.prototype); extend(VMLRenderer.prototype, VMLRendererExtension); // general renderer RendererRegistry.registerRendererType('VMLRenderer', VMLRenderer, true); // 3D additions VMLRenderer3D.compose(VMLRenderer, SVGRenderer); } SVGRenderer.prototype.getSpanWidth = function (wrapper, tspan) { var renderer = this, bBox = wrapper.getBBox(true), actualWidth = bBox.width; // Old IE cannot measure the actualWidth for SVG elements (#2314) if (!svg && renderer.forExport) { actualWidth = renderer.measureSpanWidth(tspan.firstChild.data, wrapper.styles); } return actualWidth; }; // This method is used with exporting in old IE, when emulating SVG (see #2314) SVGRenderer.prototype.measureSpanWidth = function (text, styles) { var measuringSpan = doc.createElement('span'), offsetWidth, textNode = doc.createTextNode(text); measuringSpan.appendChild(textNode); css(measuringSpan, styles); this.box.appendChild(measuringSpan); offsetWidth = measuringSpan.offsetWidth; discardElement(measuringSpan); // #2463 return offsetWidth; }; }); _registerModule(_modules, 'masters/modules/oldie.src.js', [], function () { }); }));
/** * @license Highmaps JS v8.1.2 (2020-06-16) * @module highcharts/highmaps * * (c) 2011-2018 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; import Highcharts from './highcharts.src.js'; import './modules/map.src.js'; Highcharts.product = 'Highmaps'; export default Highcharts;
/* eslint-disable */ ;(function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD define(['../core'], factory); } else if (typeof exports === 'object') { // Node.js module.exports = factory(require('../core')); } else { // Browser root.Blockly.Msg = factory(root.Blockly); } }(this, function(Blockly) { var Blockly = {};Blockly.Msg={};// This file was automatically generated. Do not modify. 'use strict'; Blockly.Msg["ADD_COMMENT"] = "ئىزاھات قوشۇش"; Blockly.Msg["CANNOT_DELETE_VARIABLE_PROCEDURE"] = "Can't delete the variable '%1' because it's part of the definition of the function '%2'"; // untranslated Blockly.Msg["CHANGE_VALUE_TITLE"] = "قىممەت ئۆزگەرتىش:"; Blockly.Msg["CLEAN_UP"] = "بۆلەكنى رەتلەش"; Blockly.Msg["COLLAPSED_WARNINGS_WARNING"] = "Collapsed blocks contain warnings."; // untranslated Blockly.Msg["COLLAPSE_ALL"] = "قاتلىنىش بۆلىكى"; Blockly.Msg["COLLAPSE_BLOCK"] = "قاتلىنىش بۆلىكى"; Blockly.Msg["COLOUR_BLEND_COLOUR1"] = "رەڭ 1"; Blockly.Msg["COLOUR_BLEND_COLOUR2"] = "رەڭ 2"; Blockly.Msg["COLOUR_BLEND_HELPURL"] = "https://meyerweb.com/eric/tools/color-blend/#:::rgbp"; // untranslated Blockly.Msg["COLOUR_BLEND_RATIO"] = "نىسبەت"; Blockly.Msg["COLOUR_BLEND_TITLE"] = "ئارىلاش"; Blockly.Msg["COLOUR_BLEND_TOOLTIP"] = "Blends two colours together with a given ratio (0.0 - 1.0)."; // untranslated Blockly.Msg["COLOUR_PICKER_HELPURL"] = "https://zh.wikipedia.org/wiki/رەڭگى"; Blockly.Msg["COLOUR_PICKER_TOOLTIP"] = " تاختىدىن رەڭنى تاللاڭ"; Blockly.Msg["COLOUR_RANDOM_HELPURL"] = "http://randomcolour.com"; // untranslated Blockly.Msg["COLOUR_RANDOM_TITLE"] = "خالىغان رەڭ"; Blockly.Msg["COLOUR_RANDOM_TOOLTIP"] = "ئىختىيارىي بىر رەڭنى تاللاڭ"; Blockly.Msg["COLOUR_RGB_BLUE"] = "كۆك"; Blockly.Msg["COLOUR_RGB_GREEN"] = "يېشىل"; Blockly.Msg["COLOUR_RGB_HELPURL"] = "https://www.december.com/html/spec/colorpercompact.html"; // untranslated Blockly.Msg["COLOUR_RGB_RED"] = "قىزىل"; Blockly.Msg["COLOUR_RGB_TITLE"] = "رەڭگى"; Blockly.Msg["COLOUR_RGB_TOOLTIP"] = "Create a colour with the specified amount of red, green, and blue. All values must be between 0 and 100."; // untranslated Blockly.Msg["CONTROLS_FLOW_STATEMENTS_HELPURL"] = "https://github.com/google/blockly/wiki/Loops#loop-termination-blocks"; // untranslated Blockly.Msg["CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK"] = "ئۈزۈلۈپ ئايلىنىش"; Blockly.Msg["CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE"] = " كىيىنكى قېتىم داۋاملىق ئايلىنىشن"; Blockly.Msg["CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK"] = "ئۇنىڭ دەۋرىي ئۈزۈلۈش ئۆز ئىچىگە ئالىدۇ ."; Blockly.Msg["CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE"] = "بۇ ئايلىنىشنىڭ قالغان قىسمى ئاتلاپ ئۆتۈپ كېتىدۇ ، ھەمدە داۋاملىق كېلەر قېتىملىق ئىتېراتسىيە ."; Blockly.Msg["CONTROLS_FLOW_STATEMENTS_WARNING"] = "ئاگاھلاندۇرۇش : بۇ پەقەت بىر ئايلىنىش دەۋرى ئىچىدە ئىشلىتىشكە بولىدۇ ."; Blockly.Msg["CONTROLS_FOREACH_HELPURL"] = "https://github.com/google/blockly/wiki/Loops#for-each"; // untranslated Blockly.Msg["CONTROLS_FOREACH_TITLE"] = "for each item %1 in list %2"; // untranslated Blockly.Msg["CONTROLS_FOREACH_TOOLTIP"] = "For each item in a list, set the variable '%1' to the item, and then do some statements."; // untranslated Blockly.Msg["CONTROLS_FOR_HELPURL"] = "https://github.com/google/blockly/wiki/Loops#count-with"; // untranslated Blockly.Msg["CONTROLS_FOR_TITLE"] = "count with %1 from %2 to %3 by %4"; // untranslated Blockly.Msg["CONTROLS_FOR_TOOLTIP"] = "Have the variable '%1' take on the values from the start number to the end number, counting by the specified interval, and do the specified blocks."; // untranslated Blockly.Msg["CONTROLS_IF_ELSEIF_TOOLTIP"] = "بۇ بىلمەيمىز جۈملە بۆلىكى قوشۇلۇپ بىر if شەرتى ."; Blockly.Msg["CONTROLS_IF_ELSE_TOOLTIP"] = "ئەڭ ئاخىرقى قوشۇش ، ھەممە ئەھۋالنى ئۆز ئىچىگە ئالىدۇ بايرىمىدا بىلمەيمىز ifپارچىلىرى ."; Blockly.Msg["CONTROLS_IF_HELPURL"] = "https://github.com/google/blockly/wiki/IfElse"; // untranslated Blockly.Msg["CONTROLS_IF_IF_TOOLTIP"] = "كۆپۈيۈپ كىتىدۇ، ئۆچۈرۈش ياكى قايتا تىزىلغان بايرام « if ( سۆزىنىڭ پارچە قايتىدىن تەقسىملەش ."; Blockly.Msg["CONTROLS_IF_MSG_ELSE"] = "ئۇنداق بولمىسا"; Blockly.Msg["CONTROLS_IF_MSG_ELSEIF"] = "ئۇنداق بولمىسا ئەگەر"; Blockly.Msg["CONTROLS_IF_MSG_IF"] = "ئەگەر"; Blockly.Msg["CONTROLS_IF_TOOLTIP_1"] = "ئەگەر قىممىتى ھەقىقەتەن ، بەزى جۈملە ."; Blockly.Msg["CONTROLS_IF_TOOLTIP_2"] = "ئەگەر قىممىتى ھەقىقەتەن ، ئۇنداقتا نىڭ بىر جۈملە . ئۇنداق بولمايدىكەن، ئىككىنچى جۈملىسى ئىجرا قىلىندى ."; Blockly.Msg["CONTROLS_IF_TOOLTIP_3"] = "ئەگەر تۇنجى قىممىتى ھەقىقەتەن ، ئۇنداقتا نىڭ بىر جۈملە . ئۇنداق بولمايدىكەن، ئەگەر ئىككىنچى قىممىتى ، ئۇنداقتا ئىككىنچى پارچىنىڭ جۈملە ."; Blockly.Msg["CONTROLS_IF_TOOLTIP_4"] = "ئەگەر تۇنجى قىممىتى ھەقىقەتەن ، ئۇنداقتا نىڭ بىر جۈملە . ئۇنداق بولمايدىكەن، ئەگەر ئىككىنچى قىممىتى ، بولسا ئىجرا قىلىش جۈملىسى ئىشككى پارچە . ئەگەر قىممىتى يوق ، ئۇنداقتا ئەڭ ئاخىرقى بىر جۈملىسى ."; Blockly.Msg["CONTROLS_REPEAT_HELPURL"] = "https://zh.wikipedia.org/wiki/Forئايلىنىش"; Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"] = "ئىجرا"; Blockly.Msg["CONTROLS_REPEAT_TITLE"] = "تەكرار %1قېتىم"; Blockly.Msg["CONTROLS_REPEAT_TOOLTIP"] = "Do some statements several times."; // untranslated Blockly.Msg["CONTROLS_WHILEUNTIL_HELPURL"] = "https://github.com/google/blockly/wiki/Loops#repeat"; // untranslated Blockly.Msg["CONTROLS_WHILEUNTIL_OPERATOR_UNTIL"] = "تەكرارلىقى"; Blockly.Msg["CONTROLS_WHILEUNTIL_OPERATOR_WHILE"] = "تەكرار بولۇش"; Blockly.Msg["CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL"] = "While a value is false, then do some statements."; // untranslated Blockly.Msg["CONTROLS_WHILEUNTIL_TOOLTIP_WHILE"] = "While a value is true, then do some statements."; // untranslated Blockly.Msg["DELETE_ALL_BLOCKS"] = "ھەممىنى ئۆچۈرۈش %1 پارچىمۇ؟"; Blockly.Msg["DELETE_BLOCK"] = "بۆلەك ئۆچۈرۈش"; Blockly.Msg["DELETE_VARIABLE"] = "“%1” ئۆزگەرگۈچى مىقدارنى ئۆچۈرۈش"; Blockly.Msg["DELETE_VARIABLE_CONFIRMATION"] = "ئۆچۈرۈش “%2” ئۆزگەرگۈچى مىقدار%1 ئىشلىتىلىش ئورنى بارمۇ؟"; Blockly.Msg["DELETE_X_BLOCKS"] = "بۆلەك %1 نى ئۆچۈرۈش"; Blockly.Msg["DISABLE_BLOCK"] = "چەكلەنگەن بۆلەك"; Blockly.Msg["DUPLICATE_BLOCK"] = "كۆچۈرۈش"; Blockly.Msg["DUPLICATE_COMMENT"] = "Duplicate Comment"; // untranslated Blockly.Msg["ENABLE_BLOCK"] = "قوزغىتىلغان بۆلەك"; Blockly.Msg["EXPAND_ALL"] = "ئېچىلىش بۆلىكى"; Blockly.Msg["EXPAND_BLOCK"] = "ئېچىلىش بۆلىكى"; Blockly.Msg["EXTERNAL_INPUTS"] = "سىرتقى كىرگۈزۈش"; Blockly.Msg["HELP"] = "ياردەم"; Blockly.Msg["INLINE_INPUTS"] = "تاق قۇرلۇق كىرگۈزۈش"; Blockly.Msg["IOS_CANCEL"] = "ۋاز كەچ"; Blockly.Msg["IOS_ERROR"] = "خاتالىق"; Blockly.Msg["IOS_OK"] = "ماقۇل"; Blockly.Msg["IOS_PROCEDURES_ADD_INPUT"] = "+ كىرگۈزۈپ قوشۇش"; Blockly.Msg["IOS_PROCEDURES_ALLOW_STATEMENTS"] = "كېلىشىمگە قوشۇلۇش"; Blockly.Msg["IOS_PROCEDURES_DUPLICATE_INPUTS_ERROR"] = "بۇنىڭدا مەزمۇننى قايتا كىرگۈزۈش ئىقتىدارى بار ."; Blockly.Msg["IOS_PROCEDURES_INPUTS"] = "كىرگۈزۈش"; Blockly.Msg["IOS_VARIABLES_ADD_BUTTON"] = "قوشۇش"; Blockly.Msg["IOS_VARIABLES_ADD_VARIABLE"] = "+ ئۆزگەرگۈچى مىقدار قوشۇش"; Blockly.Msg["IOS_VARIABLES_DELETE_BUTTON"] = "ئۆچۈرۈش"; Blockly.Msg["IOS_VARIABLES_EMPTY_NAME_ERROR"] = "سىز ئۆزگەرگۈچى مىقدار نامى ئىشلىتىشكە بولمايدۇ ."; Blockly.Msg["IOS_VARIABLES_RENAME_BUTTON"] = "ئىسىم ئۆزگەرتىش"; Blockly.Msg["IOS_VARIABLES_VARIABLE_NAME"] = "ئۆزگەرگۈچى مىقدارنىڭ نامى"; Blockly.Msg["LISTS_CREATE_EMPTY_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#create-empty-list"; // untranslated Blockly.Msg["LISTS_CREATE_EMPTY_TITLE"] = "create empty list"; // untranslated Blockly.Msg["LISTS_CREATE_EMPTY_TOOLTIP"] = "Returns a list, of length 0, containing no data records"; // untranslated Blockly.Msg["LISTS_CREATE_WITH_CONTAINER_TITLE_ADD"] = "list"; // untranslated Blockly.Msg["LISTS_CREATE_WITH_CONTAINER_TOOLTIP"] = "Add, remove, or reorder sections to reconfigure this list block."; // untranslated Blockly.Msg["LISTS_CREATE_WITH_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated Blockly.Msg["LISTS_CREATE_WITH_INPUT_WITH"] = "create list with"; // untranslated Blockly.Msg["LISTS_CREATE_WITH_ITEM_TOOLTIP"] = "Add an item to the list."; // untranslated Blockly.Msg["LISTS_CREATE_WITH_TOOLTIP"] = "Create a list with any number of items."; // untranslated Blockly.Msg["LISTS_GET_INDEX_FIRST"] = "تۇنجى"; Blockly.Msg["LISTS_GET_INDEX_FROM_END"] = "# from end"; // untranslated Blockly.Msg["LISTS_GET_INDEX_FROM_START"] = "#"; // untranslated Blockly.Msg["LISTS_GET_INDEX_GET"] = "قولغا كەلتۈرۈش"; Blockly.Msg["LISTS_GET_INDEX_GET_REMOVE"] = "get and remove"; // untranslated Blockly.Msg["LISTS_GET_INDEX_LAST"] = "ئاخىرقى"; Blockly.Msg["LISTS_GET_INDEX_RANDOM"] = "خالىغانچە"; Blockly.Msg["LISTS_GET_INDEX_REMOVE"] = "چىقىرىۋىتىش"; Blockly.Msg["LISTS_GET_INDEX_TAIL"] = ""; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_FIRST"] = "Returns the first item in a list."; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_FROM"] = "Returns the item at the specified position in a list."; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_LAST"] = "Returns the last item in a list."; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_RANDOM"] = "Returns a random item in a list."; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST"] = "Removes and returns the first item in a list."; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM"] = "Removes and returns the item at the specified position in a list."; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST"] = "Removes and returns the last item in a list."; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM"] = "Removes and returns a random item in a list."; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST"] = "Removes the first item in a list."; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM"] = "Removes the item at the specified position in a list."; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST"] = "Removes the last item in a list."; // untranslated Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM"] = "Removes a random item in a list."; // untranslated Blockly.Msg["LISTS_GET_SUBLIST_END_FROM_END"] = "to # from end"; // untranslated Blockly.Msg["LISTS_GET_SUBLIST_END_FROM_START"] = "to #"; // untranslated Blockly.Msg["LISTS_GET_SUBLIST_END_LAST"] = "to last"; // untranslated Blockly.Msg["LISTS_GET_SUBLIST_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#getting-a-sublist"; // untranslated Blockly.Msg["LISTS_GET_SUBLIST_START_FIRST"] = "get sub-list from first"; // untranslated Blockly.Msg["LISTS_GET_SUBLIST_START_FROM_END"] = "get sub-list from # from end"; // untranslated Blockly.Msg["LISTS_GET_SUBLIST_START_FROM_START"] = "get sub-list from #"; // untranslated Blockly.Msg["LISTS_GET_SUBLIST_TAIL"] = ""; // untranslated Blockly.Msg["LISTS_GET_SUBLIST_TOOLTIP"] = "Creates a copy of the specified portion of a list."; // untranslated Blockly.Msg["LISTS_INDEX_FROM_END_TOOLTIP"] = "%1 is the last item."; // untranslated Blockly.Msg["LISTS_INDEX_FROM_START_TOOLTIP"] = "%1 is the first item."; // untranslated Blockly.Msg["LISTS_INDEX_OF_FIRST"] = "find first occurrence of item"; // untranslated Blockly.Msg["LISTS_INDEX_OF_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list"; // untranslated Blockly.Msg["LISTS_INDEX_OF_LAST"] = "find last occurrence of item"; // untranslated Blockly.Msg["LISTS_INDEX_OF_TOOLTIP"] = "Returns the index of the first/last occurrence of the item in the list. Returns %1 if item is not found."; // untranslated Blockly.Msg["LISTS_INLIST"] = "in list"; // untranslated Blockly.Msg["LISTS_ISEMPTY_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#is-empty"; // untranslated Blockly.Msg["LISTS_ISEMPTY_TITLE"] = "%1 is empty"; // untranslated Blockly.Msg["LISTS_ISEMPTY_TOOLTIP"] = "Returns true if the list is empty."; // untranslated Blockly.Msg["LISTS_LENGTH_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#length-of"; // untranslated Blockly.Msg["LISTS_LENGTH_TITLE"] = "length of %1"; // untranslated Blockly.Msg["LISTS_LENGTH_TOOLTIP"] = "Returns the length of a list."; // untranslated Blockly.Msg["LISTS_REPEAT_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated Blockly.Msg["LISTS_REPEAT_TITLE"] = "create list with item %1 repeated %2 times"; // untranslated Blockly.Msg["LISTS_REPEAT_TOOLTIP"] = "Creates a list consisting of the given value repeated the specified number of times."; // untranslated Blockly.Msg["LISTS_REVERSE_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#reversing-a-list"; // untranslated Blockly.Msg["LISTS_REVERSE_MESSAGE0"] = "reverse %1"; // untranslated Blockly.Msg["LISTS_REVERSE_TOOLTIP"] = "Reverse a copy of a list."; // untranslated Blockly.Msg["LISTS_SET_INDEX_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#in-list--set"; // untranslated Blockly.Msg["LISTS_SET_INDEX_INPUT_TO"] = "as"; // untranslated Blockly.Msg["LISTS_SET_INDEX_INSERT"] = "قىستۇرۇڭ"; Blockly.Msg["LISTS_SET_INDEX_SET"] = "تەڭشەك"; Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST"] = "Inserts the item at the start of a list."; // untranslated Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_INSERT_FROM"] = "Inserts the item at the specified position in a list."; // untranslated Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_INSERT_LAST"] = "Append the item to the end of a list."; // untranslated Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM"] = "Inserts the item randomly in a list."; // untranslated Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_SET_FIRST"] = "Sets the first item in a list."; // untranslated Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_SET_FROM"] = "Sets the item at the specified position in a list."; // untranslated Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_SET_LAST"] = "Sets the last item in a list."; // untranslated Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_SET_RANDOM"] = "Sets a random item in a list."; // untranslated Blockly.Msg["LISTS_SORT_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#sorting-a-list"; // untranslated Blockly.Msg["LISTS_SORT_ORDER_ASCENDING"] = "يۇقىرىغا"; Blockly.Msg["LISTS_SORT_ORDER_DESCENDING"] = "تۆۋەنگە"; Blockly.Msg["LISTS_SORT_TITLE"] = "sort %1 %2 %3"; // untranslated Blockly.Msg["LISTS_SORT_TOOLTIP"] = "Sort a copy of a list."; // untranslated Blockly.Msg["LISTS_SORT_TYPE_IGNORECASE"] = "ھەرب بويىچە تىزىل، چوڭ كىچىك يېزىلىش ھېساپ قىلىنمايدۇ"; Blockly.Msg["LISTS_SORT_TYPE_NUMERIC"] = "سان بويىچە تىزىل"; Blockly.Msg["LISTS_SORT_TYPE_TEXT"] = " ھەرپ بويىچە تىزىل"; Blockly.Msg["LISTS_SPLIT_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#splitting-strings-and-joining-lists"; // untranslated Blockly.Msg["LISTS_SPLIT_LIST_FROM_TEXT"] = "make list from text"; // untranslated Blockly.Msg["LISTS_SPLIT_TEXT_FROM_LIST"] = "make text from list"; // untranslated Blockly.Msg["LISTS_SPLIT_TOOLTIP_JOIN"] = "Join a list of texts into one text, separated by a delimiter."; // untranslated Blockly.Msg["LISTS_SPLIT_TOOLTIP_SPLIT"] = "Split text into a list of texts, breaking at each delimiter."; // untranslated Blockly.Msg["LISTS_SPLIT_WITH_DELIMITER"] = "with delimiter"; // untranslated Blockly.Msg["LOGIC_BOOLEAN_FALSE"] = "يالغان"; Blockly.Msg["LOGIC_BOOLEAN_HELPURL"] = "https://github.com/google/blockly/wiki/Logic#values"; // untranslated Blockly.Msg["LOGIC_BOOLEAN_TOOLTIP"] = "راست ياكى يالغان قايتىش"; Blockly.Msg["LOGIC_BOOLEAN_TRUE"] = "ھەقىقىي"; Blockly.Msg["LOGIC_COMPARE_HELPURL"] = "https://zh.wikipedia.org/wiki/ تەڭ ئەمەس"; Blockly.Msg["LOGIC_COMPARE_TOOLTIP_EQ"] = "ئەگەر ئىككى دانە كىرگۈزۈش نەتىجىسى تەڭ بولسا ، راستىنلا كەينىگە قايتسا."; Blockly.Msg["LOGIC_COMPARE_TOOLTIP_GT"] = "ئەگەر تۇنجى كىرگۈزۈش نەتىجىسى ئىشككىنچى چوڭ بولسا راستىنلا كەينىگە قايتسا ."; Blockly.Msg["LOGIC_COMPARE_TOOLTIP_GTE"] = "ئەگەر تۇنجى كىرگۈزۈش نەتىجىدە ئىشككىنچى كىچىك بولسا راستىنلا كەينىگە قايتسا ."; Blockly.Msg["LOGIC_COMPARE_TOOLTIP_LT"] = "ئەگەر تۇنجى كىرگۈزۈش نەتىجىدە ئىشككىنچى كىچىك بولسا راستىنلا كەينىگە قايتسا ."; Blockly.Msg["LOGIC_COMPARE_TOOLTIP_LTE"] = "ئەگەر تۇنجى كىرگۈزۈش نەتىجىسى ئىككىنچى كىرگۈزۈش نەتىجىسى تىن تۆۋەن ياكى شۇنىڭغا تەڭ بولسا راستىنلا كەينىگە قايتسا ."; Blockly.Msg["LOGIC_COMPARE_TOOLTIP_NEQ"] = "ئەگەر ئىككى دانە كىرگۈزۈش نەتىجىسى تەڭ بولمايدۇ ، بەك كەلدى ."; Blockly.Msg["LOGIC_NEGATE_HELPURL"] = "https://github.com/google/blockly/wiki/Logic#not"; // untranslated Blockly.Msg["LOGIC_NEGATE_TITLE"] = "ئەمەس%1"; Blockly.Msg["LOGIC_NEGATE_TOOLTIP"] = "Returns true if the input is false. Returns false if the input is true."; // untranslated Blockly.Msg["LOGIC_NULL"] = "قۇرۇق"; Blockly.Msg["LOGIC_NULL_HELPURL"] = "https://en.wikipedia.org/wiki/Nullable_type"; // untranslated Blockly.Msg["LOGIC_NULL_TOOLTIP"] = " نۆلگە قايتىش"; Blockly.Msg["LOGIC_OPERATION_AND"] = "ۋە"; Blockly.Msg["LOGIC_OPERATION_HELPURL"] = "https://github.com/google/blockly/wiki/Logic#logical-operations"; // untranslated Blockly.Msg["LOGIC_OPERATION_OR"] = "ياكى"; Blockly.Msg["LOGIC_OPERATION_TOOLTIP_AND"] = "Return true if both inputs are true."; // untranslated Blockly.Msg["LOGIC_OPERATION_TOOLTIP_OR"] = "Return true if at least one of the inputs is true."; // untranslated Blockly.Msg["LOGIC_TERNARY_CONDITION"] = "سىناق"; Blockly.Msg["LOGIC_TERNARY_HELPURL"] = "https://en.wikipedia.org/wiki/%3F:"; // untranslated Blockly.Msg["LOGIC_TERNARY_IF_FALSE"] = "ئەگەر يالغان بولسا"; Blockly.Msg["LOGIC_TERNARY_IF_TRUE"] = "ئەگەر راست بولسا"; Blockly.Msg["LOGIC_TERNARY_TOOLTIP"] = "Check the condition in 'test'. If the condition is true, returns the 'if true' value; otherwise returns the 'if false' value."; // untranslated Blockly.Msg["MATH_ADDITION_SYMBOL"] = "+"; // untranslated Blockly.Msg["MATH_ARITHMETIC_HELPURL"] = "https://zh.wikipedia.org/wiki/ئارىفمېتىكىلىق"; Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_ADD"] = "Return the sum of the two numbers."; // untranslated Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_DIVIDE"] = "Return the quotient of the two numbers."; // untranslated Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_MINUS"] = "Return the difference of the two numbers."; // untranslated Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_MULTIPLY"] = "Return the product of the two numbers."; // untranslated Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_POWER"] = "Return the first number raised to the power of the second number."; // untranslated Blockly.Msg["MATH_ATAN2_HELPURL"] = "https://en.wikipedia.org/wiki/Atan2"; // untranslated Blockly.Msg["MATH_ATAN2_TITLE"] = "atan2 of X:%1 Y:%2"; // untranslated Blockly.Msg["MATH_ATAN2_TOOLTIP"] = "Return the arctangent of point (X, Y) in degrees from -180 to 180."; // untranslated Blockly.Msg["MATH_CHANGE_HELPURL"] = "https://zh.wikipedia.org/wiقوشۇش"; Blockly.Msg["MATH_CHANGE_TITLE"] = " ئۆزگەرتىش %1 دىن %2"; Blockly.Msg["MATH_CHANGE_TOOLTIP"] = "Add a number to variable '%1'."; // untranslated Blockly.Msg["MATH_CONSTANT_HELPURL"] = "https://zh.wikipedia.org/wiki/ماتېماتىكا تۇراقلىق سانى"; Blockly.Msg["MATH_CONSTANT_TOOLTIP"] = "Return one of the common constants: π (3.141…), e (2.718…), φ (1.618…), sqrt(2) (1.414…), sqrt(½) (0.707…), or ∞ (infinity)."; // untranslated Blockly.Msg["MATH_CONSTRAIN_HELPURL"] = "https://en.wikipedia.org/wiki/Clamping_(graphics)"; // untranslated Blockly.Msg["MATH_CONSTRAIN_TITLE"] = "constrain %1 low %2 high %3"; // untranslated Blockly.Msg["MATH_CONSTRAIN_TOOLTIP"] = "Constrain a number to be between the specified limits (inclusive)."; // untranslated Blockly.Msg["MATH_DIVISION_SYMBOL"] = "÷"; // untranslated Blockly.Msg["MATH_IS_DIVISIBLE_BY"] = "پۈتۈن بۆلۈنۈش"; Blockly.Msg["MATH_IS_EVEN"] = "جۈپ سان"; Blockly.Msg["MATH_IS_NEGATIVE"] = " مەنپى"; Blockly.Msg["MATH_IS_ODD"] = " تاق سان"; Blockly.Msg["MATH_IS_POSITIVE"] = "مۇسبەت"; Blockly.Msg["MATH_IS_PRIME"] = "تۈپ سان"; Blockly.Msg["MATH_IS_TOOLTIP"] = "Check if a number is an even, odd, prime, whole, positive, negative, or if it is divisible by certain number. Returns true or false."; // untranslated Blockly.Msg["MATH_IS_WHOLE"] = "پۈتۈن سان"; Blockly.Msg["MATH_MODULO_HELPURL"] = "https://zh.wikipedia.org/wiki/مودېل ھېسابى"; Blockly.Msg["MATH_MODULO_TITLE"] = "remainder of %1 ÷ %2"; // untranslated Blockly.Msg["MATH_MODULO_TOOLTIP"] = "Return the remainder from dividing the two numbers."; // untranslated Blockly.Msg["MATH_MULTIPLICATION_SYMBOL"] = "×"; // untranslated Blockly.Msg["MATH_NUMBER_HELPURL"] = "https://zh.wikipedia.org/wiki/سان"; Blockly.Msg["MATH_NUMBER_TOOLTIP"] = "بىر سان."; Blockly.Msg["MATH_ONLIST_HELPURL"] = ""; // untranslated Blockly.Msg["MATH_ONLIST_OPERATOR_AVERAGE"] = "جەدۋەل ئىچىدىكى ئوتتۇرىچە سان"; Blockly.Msg["MATH_ONLIST_OPERATOR_MAX"] = " جەدۋەلدىكى ئەڭ چوڭ قىممەت"; Blockly.Msg["MATH_ONLIST_OPERATOR_MEDIAN"] = "جەدۋەلدىكى ئوتتۇرا سان"; Blockly.Msg["MATH_ONLIST_OPERATOR_MIN"] = "جەدۋەل ئىچىدىكى ئەڭ كىچىك قىممەت"; Blockly.Msg["MATH_ONLIST_OPERATOR_MODE"] = " جەدۋەل ھالىتى"; Blockly.Msg["MATH_ONLIST_OPERATOR_RANDOM"] = "random item of list"; // untranslated Blockly.Msg["MATH_ONLIST_OPERATOR_STD_DEV"] = "standard deviation of list"; // untranslated Blockly.Msg["MATH_ONLIST_OPERATOR_SUM"] = "sum of list"; // untranslated Blockly.Msg["MATH_ONLIST_TOOLTIP_AVERAGE"] = "Return the average (arithmetic mean) of the numeric values in the list."; // untranslated Blockly.Msg["MATH_ONLIST_TOOLTIP_MAX"] = "Return the largest number in the list."; // untranslated Blockly.Msg["MATH_ONLIST_TOOLTIP_MEDIAN"] = " جەدۋەلدىكى ئوتتۇرا سانغا قايتىش"; Blockly.Msg["MATH_ONLIST_TOOLTIP_MIN"] = " جەدۋەلدىكى ئەڭ كىچىك سانغا قايتىش"; Blockly.Msg["MATH_ONLIST_TOOLTIP_MODE"] = "Return a list of the most common item(s) in the list."; // untranslated Blockly.Msg["MATH_ONLIST_TOOLTIP_RANDOM"] = "Return a random element from the list."; // untranslated Blockly.Msg["MATH_ONLIST_TOOLTIP_STD_DEV"] = "Return the standard deviation of the list."; // untranslated Blockly.Msg["MATH_ONLIST_TOOLTIP_SUM"] = "Return the sum of all the numbers in the list."; // untranslated Blockly.Msg["MATH_POWER_SYMBOL"] = "^"; // untranslated Blockly.Msg["MATH_RANDOM_FLOAT_HELPURL"] = "https://en.wikipedia.org/wiki/Random_number_generation"; // untranslated Blockly.Msg["MATH_RANDOM_FLOAT_TITLE_RANDOM"] = "random fraction"; // untranslated Blockly.Msg["MATH_RANDOM_FLOAT_TOOLTIP"] = "Return a random fraction between 0.0 (inclusive) and 1.0 (exclusive)."; // untranslated Blockly.Msg["MATH_RANDOM_INT_HELPURL"] = "https://en.wikipedia.org/wiki/Random_number_generation"; // untranslated Blockly.Msg["MATH_RANDOM_INT_TITLE"] = "random integer from %1 to %2"; // untranslated Blockly.Msg["MATH_RANDOM_INT_TOOLTIP"] = "Return a random integer between the two specified limits, inclusive."; // untranslated Blockly.Msg["MATH_ROUND_HELPURL"] = "https://zh.wikipedia.org/wiki/سانلىق قىممەت تۈزىتىش"; Blockly.Msg["MATH_ROUND_OPERATOR_ROUND"] = "تۆۋەنگە تارتىڭ"; Blockly.Msg["MATH_ROUND_OPERATOR_ROUNDDOWN"] = "تۆۋەنگە تارتىڭ"; Blockly.Msg["MATH_ROUND_OPERATOR_ROUNDUP"] = " تۆۋەنگە تارتىڭ"; Blockly.Msg["MATH_ROUND_TOOLTIP"] = "Round a number up or down."; // untranslated Blockly.Msg["MATH_SINGLE_HELPURL"] = "https://zh.wikipedia.org/wiki/كۋادرات يىلتىز"; Blockly.Msg["MATH_SINGLE_OP_ABSOLUTE"] = "مۇتلەق"; Blockly.Msg["MATH_SINGLE_OP_ROOT"] = " كۋادرات يىلتىز"; Blockly.Msg["MATH_SINGLE_TOOLTIP_ABS"] = "Return the absolute value of a number."; // untranslated Blockly.Msg["MATH_SINGLE_TOOLTIP_EXP"] = "Return e to the power of a number."; // untranslated Blockly.Msg["MATH_SINGLE_TOOLTIP_LN"] = "Return the natural logarithm of a number."; // untranslated Blockly.Msg["MATH_SINGLE_TOOLTIP_LOG10"] = "Return the base 10 logarithm of a number."; // untranslated Blockly.Msg["MATH_SINGLE_TOOLTIP_NEG"] = "Return the negation of a number."; // untranslated Blockly.Msg["MATH_SINGLE_TOOLTIP_POW10"] = "Return 10 to the power of a number."; // untranslated Blockly.Msg["MATH_SINGLE_TOOLTIP_ROOT"] = "Return the square root of a number."; // untranslated Blockly.Msg["MATH_SUBTRACTION_SYMBOL"] = "-"; // untranslated Blockly.Msg["MATH_TRIG_ACOS"] = "acos"; // untranslated Blockly.Msg["MATH_TRIG_ASIN"] = "asin"; // untranslated Blockly.Msg["MATH_TRIG_ATAN"] = "atan"; // untranslated Blockly.Msg["MATH_TRIG_COS"] = "cos"; // untranslated Blockly.Msg["MATH_TRIG_HELPURL"] = "https://zh.wikipedia.org/wiki/ترىگونومېتىرىيىلىك فۇنكسىيە"; Blockly.Msg["MATH_TRIG_SIN"] = "sin"; // untranslated Blockly.Msg["MATH_TRIG_TAN"] = "tan"; // untranslated Blockly.Msg["MATH_TRIG_TOOLTIP_ACOS"] = "Return the arccosine of a number."; // untranslated Blockly.Msg["MATH_TRIG_TOOLTIP_ASIN"] = "Return the arcsine of a number."; // untranslated Blockly.Msg["MATH_TRIG_TOOLTIP_ATAN"] = "Return the arctangent of a number."; // untranslated Blockly.Msg["MATH_TRIG_TOOLTIP_COS"] = "Return the cosine of a degree (not radian)."; // untranslated Blockly.Msg["MATH_TRIG_TOOLTIP_SIN"] = "Return the sine of a degree (not radian)."; // untranslated Blockly.Msg["MATH_TRIG_TOOLTIP_TAN"] = "Return the tangent of a degree (not radian)."; // untranslated Blockly.Msg["NEW_COLOUR_VARIABLE"] = "Create colour variable..."; // untranslated Blockly.Msg["NEW_NUMBER_VARIABLE"] = "Create number variable..."; // untranslated Blockly.Msg["NEW_STRING_VARIABLE"] = "Create string variable..."; // untranslated Blockly.Msg["NEW_VARIABLE"] = "ئۆزگەرگۈچى مىقدار ... قۇرۇش"; Blockly.Msg["NEW_VARIABLE_TITLE"] = "يېڭى ئۆزگەرگۈچى مىقدار نامى:"; Blockly.Msg["NEW_VARIABLE_TYPE_TITLE"] = "New variable type:"; // untranslated Blockly.Msg["ORDINAL_NUMBER_SUFFIX"] = ""; // untranslated Blockly.Msg["PROCEDURES_ALLOW_STATEMENTS"] = "allow statements"; // untranslated Blockly.Msg["PROCEDURES_BEFORE_PARAMS"] = "with:"; // untranslated Blockly.Msg["PROCEDURES_CALLNORETURN_HELPURL"] = "https://en.wikipedia.org/wiki/Subroutine"; // untranslated Blockly.Msg["PROCEDURES_CALLNORETURN_TOOLTIP"] = "Run the user-defined function '%1'."; // untranslated Blockly.Msg["PROCEDURES_CALLRETURN_HELPURL"] = "https://en.wikipedia.org/wiki/Subroutine"; // untranslated Blockly.Msg["PROCEDURES_CALLRETURN_TOOLTIP"] = "Run the user-defined function '%1' and use its output."; // untranslated Blockly.Msg["PROCEDURES_CALL_BEFORE_PARAMS"] = "with:"; // untranslated Blockly.Msg["PROCEDURES_CREATE_DO"] = "Create '%1'"; // untranslated Blockly.Msg["PROCEDURES_DEFNORETURN_COMMENT"] = "Describe this function..."; // untranslated Blockly.Msg["PROCEDURES_DEFNORETURN_DO"] = ""; // untranslated Blockly.Msg["PROCEDURES_DEFNORETURN_HELPURL"] = "https://en.wikipedia.org/wiki/Subroutine"; // untranslated Blockly.Msg["PROCEDURES_DEFNORETURN_PROCEDURE"] = "do something"; // untranslated Blockly.Msg["PROCEDURES_DEFNORETURN_TITLE"] = "to"; // untranslated Blockly.Msg["PROCEDURES_DEFNORETURN_TOOLTIP"] = "Creates a function with no output."; // untranslated Blockly.Msg["PROCEDURES_DEFRETURN_HELPURL"] = "https://en.wikipedia.org/wiki/Subroutine"; // untranslated Blockly.Msg["PROCEDURES_DEFRETURN_RETURN"] = "return"; // untranslated Blockly.Msg["PROCEDURES_DEFRETURN_TOOLTIP"] = "Creates a function with an output."; // untranslated Blockly.Msg["PROCEDURES_DEF_DUPLICATE_WARNING"] = "Warning: This function has duplicate parameters."; // untranslated Blockly.Msg["PROCEDURES_HIGHLIGHT_DEF"] = "Highlight function definition"; // untranslated Blockly.Msg["PROCEDURES_IFRETURN_HELPURL"] = "http://c2.com/cgi/wiki?GuardClause"; // untranslated Blockly.Msg["PROCEDURES_IFRETURN_TOOLTIP"] = "If a value is true, then return a second value."; // untranslated Blockly.Msg["PROCEDURES_IFRETURN_WARNING"] = "Warning: This block may be used only within a function definition."; // untranslated Blockly.Msg["PROCEDURES_MUTATORARG_TITLE"] = "input name:"; // untranslated Blockly.Msg["PROCEDURES_MUTATORARG_TOOLTIP"] = "Add an input to the function."; // untranslated Blockly.Msg["PROCEDURES_MUTATORCONTAINER_TITLE"] = "inputs"; // untranslated Blockly.Msg["PROCEDURES_MUTATORCONTAINER_TOOLTIP"] = "Add, remove, or reorder inputs to this function."; // untranslated Blockly.Msg["REDO"] = "قايتىلاش"; Blockly.Msg["REMOVE_COMMENT"] = "ئىزاھاتنى ئۆچۈرۈش"; Blockly.Msg["RENAME_VARIABLE"] = "ئۆزگەرگۈچى مىقدارغا قايتا نام قويۇش"; Blockly.Msg["RENAME_VARIABLE_TITLE"] = "بارلىق بۆلەك “%1\" ئۆزگەرگۈچى مىقدار قايتا ناملىنىپ :"; Blockly.Msg["TEXT_APPEND_HELPURL"] = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated Blockly.Msg["TEXT_APPEND_TITLE"] = "to %1 append text %2"; // untranslated Blockly.Msg["TEXT_APPEND_TOOLTIP"] = "Append some text to variable '%1'."; // untranslated Blockly.Msg["TEXT_CHANGECASE_HELPURL"] = "https://github.com/google/blockly/wiki/Text#adjusting-text-case"; // untranslated Blockly.Msg["TEXT_CHANGECASE_OPERATOR_LOWERCASE"] = "to lower case"; // untranslated Blockly.Msg["TEXT_CHANGECASE_OPERATOR_TITLECASE"] = "to Title Case"; // untranslated Blockly.Msg["TEXT_CHANGECASE_OPERATOR_UPPERCASE"] = "to UPPER CASE"; // untranslated Blockly.Msg["TEXT_CHANGECASE_TOOLTIP"] = "Return a copy of the text in a different case."; // untranslated Blockly.Msg["TEXT_CHARAT_FIRST"] = "get first letter"; // untranslated Blockly.Msg["TEXT_CHARAT_FROM_END"] = "get letter # from end"; // untranslated Blockly.Msg["TEXT_CHARAT_FROM_START"] = "get letter #"; // untranslated Blockly.Msg["TEXT_CHARAT_HELPURL"] = "https://github.com/google/blockly/wiki/Text#extracting-text"; // untranslated Blockly.Msg["TEXT_CHARAT_LAST"] = "get last letter"; // untranslated Blockly.Msg["TEXT_CHARAT_RANDOM"] = "get random letter"; // untranslated Blockly.Msg["TEXT_CHARAT_TAIL"] = ""; // untranslated Blockly.Msg["TEXT_CHARAT_TITLE"] = "in text %1 %2"; // untranslated Blockly.Msg["TEXT_CHARAT_TOOLTIP"] = "Returns the letter at the specified position."; // untranslated Blockly.Msg["TEXT_COUNT_HELPURL"] = "https://github.com/google/blockly/wiki/Text#counting-substrings"; // untranslated Blockly.Msg["TEXT_COUNT_MESSAGE0"] = "count %1 in %2"; // untranslated Blockly.Msg["TEXT_COUNT_TOOLTIP"] = "Count how many times some text occurs within some other text."; // untranslated Blockly.Msg["TEXT_CREATE_JOIN_ITEM_TOOLTIP"] = "Add an item to the text."; // untranslated Blockly.Msg["TEXT_CREATE_JOIN_TITLE_JOIN"] = " قوشۇش"; Blockly.Msg["TEXT_CREATE_JOIN_TOOLTIP"] = "Add, remove, or reorder sections to reconfigure this text block."; // untranslated Blockly.Msg["TEXT_GET_SUBSTRING_END_FROM_END"] = "to letter # from end"; // untranslated Blockly.Msg["TEXT_GET_SUBSTRING_END_FROM_START"] = "to letter #"; // untranslated Blockly.Msg["TEXT_GET_SUBSTRING_END_LAST"] = "to last letter"; // untranslated Blockly.Msg["TEXT_GET_SUBSTRING_HELPURL"] = "https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text"; // untranslated Blockly.Msg["TEXT_GET_SUBSTRING_INPUT_IN_TEXT"] = "in text"; // untranslated Blockly.Msg["TEXT_GET_SUBSTRING_START_FIRST"] = "get substring from first letter"; // untranslated Blockly.Msg["TEXT_GET_SUBSTRING_START_FROM_END"] = "get substring from letter # from end"; // untranslated Blockly.Msg["TEXT_GET_SUBSTRING_START_FROM_START"] = "get substring from letter #"; // untranslated Blockly.Msg["TEXT_GET_SUBSTRING_TAIL"] = ""; // untranslated Blockly.Msg["TEXT_GET_SUBSTRING_TOOLTIP"] = "Returns a specified portion of the text."; // untranslated Blockly.Msg["TEXT_INDEXOF_HELPURL"] = "https://github.com/google/blockly/wiki/Text#finding-text"; // untranslated Blockly.Msg["TEXT_INDEXOF_OPERATOR_FIRST"] = "find first occurrence of text"; // untranslated Blockly.Msg["TEXT_INDEXOF_OPERATOR_LAST"] = "find last occurrence of text"; // untranslated Blockly.Msg["TEXT_INDEXOF_TITLE"] = "in text %1 %2 %3"; // untranslated Blockly.Msg["TEXT_INDEXOF_TOOLTIP"] = "Returns the index of the first/last occurrence of the first text in the second text. Returns %1 if text is not found."; // untranslated Blockly.Msg["TEXT_ISEMPTY_HELPURL"] = "https://github.com/google/blockly/wiki/Text#checking-for-empty-text"; // untranslated Blockly.Msg["TEXT_ISEMPTY_TITLE"] = "%1 is empty"; // untranslated Blockly.Msg["TEXT_ISEMPTY_TOOLTIP"] = "Returns true if the provided text is empty."; // untranslated Blockly.Msg["TEXT_JOIN_HELPURL"] = "https://github.com/google/blockly/wiki/Text#text-creation"; // untranslated Blockly.Msg["TEXT_JOIN_TITLE_CREATEWITH"] = "create text with"; // untranslated Blockly.Msg["TEXT_JOIN_TOOLTIP"] = "Create a piece of text by joining together any number of items."; // untranslated Blockly.Msg["TEXT_LENGTH_HELPURL"] = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated Blockly.Msg["TEXT_LENGTH_TITLE"] = "length of %1"; // untranslated Blockly.Msg["TEXT_LENGTH_TOOLTIP"] = "Returns the number of letters (including spaces) in the provided text."; // untranslated Blockly.Msg["TEXT_PRINT_HELPURL"] = "https://github.com/google/blockly/wiki/Text#printing-text"; // untranslated Blockly.Msg["TEXT_PRINT_TITLE"] = "print %1"; // untranslated Blockly.Msg["TEXT_PRINT_TOOLTIP"] = "Print the specified text, number or other value."; // untranslated Blockly.Msg["TEXT_PROMPT_HELPURL"] = "https://github.com/google/blockly/wiki/Text#getting-input-from-the-user"; // untranslated Blockly.Msg["TEXT_PROMPT_TOOLTIP_NUMBER"] = "Prompt for user for a number."; // untranslated Blockly.Msg["TEXT_PROMPT_TOOLTIP_TEXT"] = "Prompt for user for some text."; // untranslated Blockly.Msg["TEXT_PROMPT_TYPE_NUMBER"] = "prompt for number with message"; // untranslated Blockly.Msg["TEXT_PROMPT_TYPE_TEXT"] = "prompt for text with message"; // untranslated Blockly.Msg["TEXT_REPLACE_HELPURL"] = "https://github.com/google/blockly/wiki/Text#replacing-substrings"; // untranslated Blockly.Msg["TEXT_REPLACE_MESSAGE0"] = "replace %1 with %2 in %3"; // untranslated Blockly.Msg["TEXT_REPLACE_TOOLTIP"] = "Replace all occurances of some text within some other text."; // untranslated Blockly.Msg["TEXT_REVERSE_HELPURL"] = "https://github.com/google/blockly/wiki/Text#reversing-text"; // untranslated Blockly.Msg["TEXT_REVERSE_MESSAGE0"] = "reverse %1"; // untranslated Blockly.Msg["TEXT_REVERSE_TOOLTIP"] = "Reverses the order of the characters in the text."; // untranslated Blockly.Msg["TEXT_TEXT_HELPURL"] = "https://en.wikipedia.org/wiki/String_(computer_science)"; // untranslated Blockly.Msg["TEXT_TEXT_TOOLTIP"] = "A letter, word, or line of text."; // untranslated Blockly.Msg["TEXT_TRIM_HELPURL"] = "https://github.com/google/blockly/wiki/Text#trimming-removing-spaces"; // untranslated Blockly.Msg["TEXT_TRIM_OPERATOR_BOTH"] = "trim spaces from both sides of"; // untranslated Blockly.Msg["TEXT_TRIM_OPERATOR_LEFT"] = "trim spaces from left side of"; // untranslated Blockly.Msg["TEXT_TRIM_OPERATOR_RIGHT"] = "trim spaces from right side of"; // untranslated Blockly.Msg["TEXT_TRIM_TOOLTIP"] = "Return a copy of the text with spaces removed from one or both ends."; // untranslated Blockly.Msg["TODAY"] = "بۈگۈن"; Blockly.Msg["UNDO"] = "يېنىۋال"; Blockly.Msg["VARIABLES_DEFAULT_NAME"] = "تۈر"; Blockly.Msg["VARIABLES_GET_CREATE_SET"] = "Create 'set %1'"; // untranslated Blockly.Msg["VARIABLES_GET_HELPURL"] = "https://github.com/google/blockly/wiki/Variables#get"; // untranslated Blockly.Msg["VARIABLES_GET_TOOLTIP"] = "Returns the value of this variable."; // untranslated Blockly.Msg["VARIABLES_SET"] = "set %1 to %2"; // untranslated Blockly.Msg["VARIABLES_SET_CREATE_GET"] = "Create 'get %1'"; // untranslated Blockly.Msg["VARIABLES_SET_HELPURL"] = "https://github.com/google/blockly/wiki/Variables#set"; // untranslated Blockly.Msg["VARIABLES_SET_TOOLTIP"] = "Sets this variable to be equal to the input."; // untranslated Blockly.Msg["VARIABLE_ALREADY_EXISTS"] = "ئىسم مەۋجۇت “%1” ئۆزگەرگۈچى"; Blockly.Msg["VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE"] = "ئىسىملىك“%1” ئۆزگەرگۈچى مىقدار مەۋجۇت بولۇپ تۇرىدۇ ، لېكىن يەنە بىر ئۆزگەرگۈچى مىقدار تىپى بولۇش سۈپىتى بىلەن “%2” مەۋجۇت ."; Blockly.Msg["WORKSPACE_COMMENT_DEFAULT_TEXT"] = "Say something..."; // untranslated Blockly.Msg["CONTROLS_FOREACH_INPUT_DO"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"]; Blockly.Msg["CONTROLS_FOR_INPUT_DO"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"]; Blockly.Msg["CONTROLS_IF_ELSEIF_TITLE_ELSEIF"] = Blockly.Msg["CONTROLS_IF_MSG_ELSEIF"]; Blockly.Msg["CONTROLS_IF_ELSE_TITLE_ELSE"] = Blockly.Msg["CONTROLS_IF_MSG_ELSE"]; Blockly.Msg["CONTROLS_IF_IF_TITLE_IF"] = Blockly.Msg["CONTROLS_IF_MSG_IF"]; Blockly.Msg["CONTROLS_IF_MSG_THEN"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"]; Blockly.Msg["CONTROLS_WHILEUNTIL_INPUT_DO"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"]; Blockly.Msg["LISTS_CREATE_WITH_ITEM_TITLE"] = Blockly.Msg["VARIABLES_DEFAULT_NAME"]; Blockly.Msg["LISTS_GET_INDEX_HELPURL"] = Blockly.Msg["LISTS_INDEX_OF_HELPURL"]; Blockly.Msg["LISTS_GET_INDEX_INPUT_IN_LIST"] = Blockly.Msg["LISTS_INLIST"]; Blockly.Msg["LISTS_GET_SUBLIST_INPUT_IN_LIST"] = Blockly.Msg["LISTS_INLIST"]; Blockly.Msg["LISTS_INDEX_OF_INPUT_IN_LIST"] = Blockly.Msg["LISTS_INLIST"]; Blockly.Msg["LISTS_SET_INDEX_INPUT_IN_LIST"] = Blockly.Msg["LISTS_INLIST"]; Blockly.Msg["MATH_CHANGE_TITLE_ITEM"] = Blockly.Msg["VARIABLES_DEFAULT_NAME"]; Blockly.Msg["PROCEDURES_DEFRETURN_COMMENT"] = Blockly.Msg["PROCEDURES_DEFNORETURN_COMMENT"]; Blockly.Msg["PROCEDURES_DEFRETURN_DO"] = Blockly.Msg["PROCEDURES_DEFNORETURN_DO"]; Blockly.Msg["PROCEDURES_DEFRETURN_PROCEDURE"] = Blockly.Msg["PROCEDURES_DEFNORETURN_PROCEDURE"]; Blockly.Msg["PROCEDURES_DEFRETURN_TITLE"] = Blockly.Msg["PROCEDURES_DEFNORETURN_TITLE"]; Blockly.Msg["TEXT_APPEND_VARIABLE"] = Blockly.Msg["VARIABLES_DEFAULT_NAME"]; Blockly.Msg["TEXT_CREATE_JOIN_ITEM_TITLE_ITEM"] = Blockly.Msg["VARIABLES_DEFAULT_NAME"]; Blockly.Msg["MATH_HUE"] = "230"; Blockly.Msg["LOOPS_HUE"] = "120"; Blockly.Msg["LISTS_HUE"] = "260"; Blockly.Msg["LOGIC_HUE"] = "210"; Blockly.Msg["VARIABLES_HUE"] = "330"; Blockly.Msg["TEXTS_HUE"] = "160"; Blockly.Msg["PROCEDURES_HUE"] = "290"; Blockly.Msg["COLOUR_HUE"] = "20"; Blockly.Msg["VARIABLES_DYNAMIC_HUE"] = "310"; return Blockly.Msg; }));
!function(){"use strict";jQuery.ime.register({id:"nb-normforms",name:"Norsk normal transliterasjon",description:"Norwegian input method with most common form transliterated",date:"2012-12-04",URL:"http://www.evertype.com/alphabets/bokmaal-norwegian.pdf",author:"John Erling Blad",license:"GPLv3",version:"1.0",contextLength:1,maxKeyLength:3,patterns:[["aa","å"],["AA","Å"],["Aa","Å"],["ae","æ"],["AE","Æ"],["Ae","Æ"],["oe","ø"],["OE","Ø"],["Oe","Ø"],["åa","a","aa"],["ÅA","A","AA"],["Åa","A","Aa"],["åA","a","aA"],["æe","e","ae"],["ÆE","E","AE"],["Æe","E","Ae"],["æE","e","aE"],["øe","e","oe"],["ØE","E","OE"],["Øe","E","Oe"],["øE","e","oE"]]})}();
import deprecate from 'util-deprecate'; import Preview from './preview'; const preview = new Preview(); export const storiesOf = preview.storiesOf.bind(preview); export const setAddon = preview.setAddon.bind(preview); export const addDecorator = preview.addDecorator.bind(preview); export const configure = preview.configure.bind(preview); export const getStorybook = preview.getStorybook.bind(preview); export const getStorybookUI = preview.getStorybookUI.bind(preview); // NOTE export these to keep backwards compatibility import { action as deprecatedAction } from '@storybook/addon-actions'; import { linkTo as deprecatedLinkTo } from '@storybook/addon-links'; export const action = deprecate( deprecatedAction, '@storybook/react action is deprecated. See: https://github.com/storybooks/storybook/tree/master/packages/addon-actions', ); export const linkTo = deprecate( deprecatedLinkTo, '@storybook/react linkTo is deprecated. See: https://github.com/storybooks/storybook/tree/master/packages/addon-links', );
'use strict'; angular.element(document).ready(function() { //Fixing facebook bug with redirect if (window.location.hash === '#_=_') window.location.hash = '#!'; //Then init the app angular.bootstrap(document, ['mean']); }); // Dynamically add angular modules declared by packages var packageModules = []; for (var index in window.modules) { angular.module(window.modules[index].module, window.modules[index].angularDependencies || []); packageModules.push(window.modules[index].module); } // Default modules var modules = ['ngCookies', 'ngResource', 'ui.bootstrap', 'ui.router', 'cgBusy' ,'mgo-angular-wizard', 'ngFileUpload', 'truncate', 'ui.tinymce', 'toaster', 'angularSpinners', 'underscore']; modules = modules.concat(packageModules); // Combined modules angular.module('mean', modules);
tinymce.addI18n('zh_CN.GB2312', { 'Cut': '\u526a\u5207', 'Heading 5': '\u7ae0\u8282\u6807\u98985', 'Header 2': '\u6807\u98982', 'Your browser doesn\'t support direct access to the clipboard. Please use the Ctrl+X\/C\/V keyboard shortcuts instead.': '\u4f60\u7684\u6d4f\u89c8\u5668\u4e0d\u652f\u6301\u8bbf\u95ee\u526a\u5207\u677f\uff0c\u8bf7\u4f7f\u7528Ctrl+X\/C\/V\u5feb\u6377\u952e\u66ff\u4ee3\u3002', 'Heading 4': '\u7ae0\u8282\u6807\u98984', 'Div': '\u5411\u540e', 'Heading 2': '\u7ae0\u8282\u6807\u98982', 'Paste': '\u7c98\u5e16', 'Close': '\u5173\u95ed', 'Font Family': '\u5b57\u4f53', 'Pre': '\u5411\u524d', 'Align right': '\u5c45\u4e2d\u5bf9\u9f50', 'New document': '\u65b0\u6587\u6863', 'Blockquote': '\u5757\u5f15\u7528', 'Numbered list': '\u6570\u5b57\u5217\u8868', 'Heading 1': '\u7ae0\u8282\u6807\u98981', 'Headings': '\u7ae0\u8282\u6807\u9898', 'Increase indent': '\u589e\u52a0\u7f29\u8fdb', 'Formats': '\u683c\u5f0f\u5316', 'Headers': ' \u6807\u9898', 'Select all': '\u5168\u9009', 'Header 3': '\u6807\u98983', 'Blocks': '\u5757', 'Undo': '\u64a4\u9500', 'Strikethrough': '\u5220\u9664\u7ebf', 'Bullet list': '\u7b26\u53f7\u5217\u8868', 'Header 1': '\u6807\u98981', 'Superscript': '\u4e0a\u89d2\u6807', 'Clear formatting': '\u6e05\u9664\u683c\u5f0f', 'Font Sizes': '\u5b57\u53f7', 'Subscript': '\u4e0b\u89d2\u6807', 'Header 6': '\u6807\u98986', 'Redo': '\u91cd\u505a', 'Paragraph': '\u6bb5\u843d', 'Ok': '\u786e\u8ba4', 'Bold': '\u7c97\u4f53', 'Code': '\u4ee3\u7801', 'Italic': '\u659c\u4f53', 'Align center': '\u5c45\u4e2d\u5bf9\u9f50', 'Header 5': '\u6807\u98985', 'Heading 6': '\u7ae0\u8282\u6807\u98986', 'Heading 3': '\u7ae0\u8282\u6807\u98983', 'Decrease indent': '\u51cf\u5c0f\u7f29\u8fdb', 'Header 4': '\u6807\u98984', 'Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off.': '\u7c98\u8d34\u73b0\u5728\u662f\u7eaf\u6587\u672c\u6a21\u5f0f\u3002\u5185\u5bb9\u5c06\u7c98\u8d34\u4e3a\u7eaf\u6587\u672c\u5f62\u5f0f\uff0c\b\u76f4\u5230\u60a8\u5207\u6362\u9009\u9879\u5f00\u5173\u3002', 'Underline': '\u4e0b\u5212\u7ebf', 'Cancel': '\u53d6\u6d88', 'Justify': '\u4e24\u7aef\u5bf9\u9f50', 'Inline': '\u5185\u5d4c', 'Copy': '\u590d\u5236', 'Align left': '\u5de6\u5bf9\u9f50', 'Visual aids': '\u53ef\u89c6\u5316\u5de5\u5177', 'Lower Greek': '\u5c0f\u5199\u5e0c\u814a\u5b57\u6bcd', 'Square': '\u65b9\u5f62', 'Default': '\u9ed8\u8ba4', 'Lower Alpha': '\u5c0f\u5199\u5b57\u6bcd', 'Circle': '\u5706\u5f62', 'Disc': '\u78c1\u76d8', 'Upper Alpha': '\u5927\u5199\u5b57\u6bcd', 'Upper Roman': '\u5927\u5199\u7f57\u9a6c\u5b57\u6bcd', 'Lower Roman': '\u5c0f\u5199\u7f57\u9a6c\u5b57\u6bcd', 'Id should start with a letter, followed only by letters, numbers, dashes, dots, colons or underscores.': '\u6807\u8bc6\u7b26\u5e94\u8be5\u4ee5\u5b57\u6bcd\u5f00\u5934\uff0c\u540e\u8ddf\u5b57\u6bcd\u3001\u6570\u5b57\u3001\u7834\u6298\u53f7\u3001\u70b9\u3001\u5192\u53f7\u6216\u4e0b\u5212\u7ebf\u3002', 'Name': '\u540d\u79f0', 'Anchor': '\u951a\u70b9', 'Id': '\u6807\u8bc6\u7b26', 'You have unsaved changes are you sure you want to navigate away?': '\u60a8\u8fd8\u6ca1\u6709\u4fdd\u5b58\uff0c\u60a8\u786e\u5b9a\u8981\u79bb\u5f00\uff1f', 'Restore last draft': '\u6062\u590d\u6700\u540e\u8349\u7a3f', 'Special character': '\u7279\u6b8a\u5b57\u7b26', 'Source code': '\u6e90\u4ee3\u7801', 'Language': '\u8bed\u8a00', 'Insert\/Edit code sample': '\u63d2\u5165\/\u7f16\u8f91\u4ee3\u7801\u793a\u4f8b', 'B': 'B\u503c', 'R': 'R\u503c', 'G': 'G\u503c', 'Color': '\u989c\u8272', 'Right to left': '\u4ece\u53f3\u5230\u5de6', 'Left to right': '\u4ece\u5de6\u5230\u53f3', 'Emoticons': '\u8868\u60c5', 'Robots': '\u641c\u7d22\u673a\u5668\u4eba\u7528Robots\u6587\u4ef6', 'Document properties': '\u7b14\u8bb0\u5c5e\u6027', 'Title': '\u6807\u9898', 'Keywords': '\u5173\u952e\u5b57', 'Encoding': '\u7f16\u7801', 'Description': '\u63cf\u8ff0', 'Author': '\u4f5c\u8005', 'Fullscreen': '\u5168\u5c4f', 'Horizontal line': '\u6c34\u5e73\u7ebf', 'Horizontal space': '\u6c34\u5e73\u95f4\u8ddd', 'Insert\/edit image': '\u63d2\u5165\/\u7f16\u8f91 \u56fe\u7247', 'General': '\u5e38\u89c4', 'Advanced': '\u9ad8\u7ea7\u9009\u9879', 'Source': '\u6e90', 'Border': '\u8fb9', 'Constrain proportions': '\u9650\u5236\u6bd4\u4f8b', 'Vertical space': '\u5782\u76f4\u95f4\u8ddd', 'Image description': '\u56fe\u7247\u63cf\u8ff0', 'Style': '\u6837\u5f0f', 'Dimensions': '\u5c3a\u5bf8', 'Insert image': '\u63d2\u5165\u56fe\u7247', 'Image': '\u56fe\u7247', 'Zoom in': '\u653e\u5927', 'Contrast': '\u5bf9\u6bd4\u5ea6', 'Back': '\u8fd4\u56de', 'Gamma': '\u7070\u5ea6', 'Flip horizontally': '\u6c34\u5e73\u7ffb\u8f6c', 'Resize': '\u8c03\u6574\u5927\u5c0f', 'Sharpen': '\u9510\u5316', 'Zoom out': '\u7f29\u5c0f', 'Image options': '\u56fe\u7247\u9009\u9879', 'Apply': '\u5e94\u7528', 'Brightness': '\u4eae\u5ea6', 'Rotate clockwise': '\u987a\u65f6\u9488\u65cb\u8f6c', 'Rotate counterclockwise': '\u9006\u65f6\u9488\u65cb\u8f6c', 'Edit image': '\u7f16\u8f91\u56fe\u7247', 'Color levels': '\u8272\u9636', 'Crop': '\u526a\u88c1', 'Orientation': '\u65b9\u5411', 'Flip vertically': '\u5782\u76f4\u7ffb\u8f6c', 'Invert': '\u53cd\u8272', 'Date\/time': '\u65e5\u671f\u002f\u65f6\u95f4', 'Insert date\/time': '\u63d2\u5165\u65e5\u671f\/\u65f6\u95f4', 'Remove link': '\u5220\u9664\u94fe\u63a5', 'Url': 'URL\u94fe\u63a5', 'Text to display': '\u8981\u663e\u793a\u7684\u6587\u5b57', 'Anchors': '\u951a\u70b9', 'Insert link': '\u63d2\u5165\u94fe\u63a5', 'Link': '\u94fe\u63a5', 'New window': '\u65b0\u7a97\u53e3', 'None': '\u65e0\u503c', 'The URL you entered seems to be an external link. Do you want to add the required http:\/\/ prefix?': '\u60a8\u8f93\u5165\u7684\u7f51\u5740\u4f3c\u4e4e\u662f\u4e00\u4e2a\u5916\u90e8\u94fe\u63a5\u3002\u662f\u5426\u9700\u8981\u6dfb\u52a0HTTP:\/\/\u524d\u7f00\uff1f', 'Paste or type a link': 'Paste or type a link', 'Target': '\u76ee\u6807', 'The URL you entered seems to be an email address. Do you want to add the required mailto: prefix?': '\u60a8\u8f93\u5165\u7684\u7f51\u5740\u4f3c\u4e4e\u662f\u4e00\u4e2a\u7535\u5b50\u90ae\u4ef6\u5730\u5740\u3002\u662f\u5426\u9700\u8981\u6dfb\u52a0mailto\uff1a\u524d\u7f00\uff1f', 'Insert\/edit link': '\u63d2\u5165\/\u7f16\u8f91 \u94fe\u63a5', 'Insert\/edit video': '\u63d2\u5165\/\u7f16\u8f91 \u89c6\u9891', 'Media': '\u63d2\u5165\u002f\u7f16\u8f91\u5a92\u4f53', 'Alternative source': '\u66ff\u4ee3\u6e90', 'Paste your embed code below:': '\u4e0b\u9762\u7c98\u8d34\u60a8\u7684\u5d4c\u5165\u4ee3\u7801\uff1a', 'Insert video': '\u63d2\u5165\u89c6\u9891', 'Poster': '\u6d77\u62a5', 'Insert\/edit media': '\u63d2\u5165\u002f\u7f16\u8f91\u5a92\u4f53', 'Embed': '\u5185\u5d4c', 'Nonbreaking space': '\u4e0d\u95f4\u65ad\u7a7a\u683c', 'Page break': '\u5206\u9875\u7b26', 'Paste as text': '\u4f5c\u4e3a\u6587\u672c\u7c98\u5e16', 'Preview': '\u9884\u89c8', 'Print': '\u6253\u5370', 'Save': '\u4fdd\u5b58', 'Could not find the specified string.': '\u627e\u4e0d\u5230\u6307\u5b9a\u7684\u5b57\u7b26\u4e32\u3002', 'Replace': '\u66ff\u6362', 'Next': '\u5148\u4e00\u4e2a', 'Whole words': '\b\u5168\u90e8\u5b57\u7b26', 'Find and replace': '\u67e5\u627e\u548c\u66ff\u6362', 'Replace with': '\u7528...\u6765\u4ee3\u66ff', 'Find': '\u67e5\u627e', 'Replace all': '\u66ff\u6362\u5168\u90e8', 'Match case': '\u76f8\u7b26', 'Prev': '\u4e0a\u4e00\u4e2a', 'Spellcheck': '\u62fc\u5199\u68c0\u67e5', 'Finish': '\u5b8c\u6210', 'Ignore all': '\u5168\u90e8\u5ffd\u7565', 'Ignore': '\u5ffd\u7565', 'Add to Dictionary': '\u52a0\u5165\u5230\u5b57\u5178', 'Insert row before': '\u5728\u524d\u63d2\u5165\u884c', 'Rows': '\u884c\u6570', 'Height': '\u9ad8', 'Paste row after': '\u5728\u540e\u7c98\u5e16\u884c', 'Alignment': '\u5bf9\u9f50\u65b9\u5f0f', 'Border color': '\u8fb9\u6846\u989c\u8272', 'Column group': '\u521b\u5efa\u5217\u7ec4', 'Row': '\u884c', 'Insert column before': '\u5728\u524d\u63d2\u5165\u5217', 'Split cell': '\u5206\u5272\u5355\u5143\u683c', 'Cell padding': '\u5355\u5143\u683c\u8fb9\u8ddd', 'Cell spacing': '\u5355\u5143\u683c\u95f4\u8ddd', 'Row type': '\u884c\u7c7b\u578b', 'Insert table': '\u63d2\u5165\u8868\u683c', 'Body': '\u4f53\u90e8', 'Caption': '\u8bf4\u660e\u6587\u5b57', 'Footer': '\u811a\u90e8', 'Delete row': '\u5220\u9664\u884c', 'Paste row before': '\u5728\u524d\u7c98\u5e16\u884c', 'Scope': '\u9002\u7528\u8303\u56f4', 'Delete table': '\u5220\u9664\u8868\u683c', 'H Align': '\u6c34\u5e73\u5bf9\u9f50', 'Top': '\u4e0a', 'Header cell': '\b\u6807\u9898\u5355\u5143', 'Column': '\u5217', 'Row group': '\b\u521b\u5efa\u884c\u7ec4', 'Cell': '\u5355\u5143\u683c', 'Middle': '\u4e2d', 'Cell type': '\u5355\u5143\u683c\u7c7b\u578b', 'Copy row': '\u590d\u5236\u884c', 'Row properties': '\u884c\u5c5e\u6027', 'Table properties': '\u8868\u683c\u5c5e\u6027', 'Bottom': '\u4e0b', 'V Align': '\u5782\u76f4\u5bf9\u9f50', 'Header': '\u5934\u90e8', 'Right': '\u53f3', 'Insert column after': '\u5728\u540e\u63d2\u5165\u5217', 'Cols': '\u5217\u6570', 'Insert row after': '\u5728\u540e\u63d2\u5165\u884c', 'Width': '\u5bbd', 'Cell properties': '\u884c\u5c5e\u6027', 'Left': '\u5de6', 'Cut row': '\u526a\u5207\u884c', 'Delete column': '\u5220\u9664\u5217', 'Center': '\u4e2d\u95f4', 'Merge cells': '\u5408\u5e76\u5355\u5143\u683c', 'Insert template': '\u63d2\u5165\u6a21\u677f', 'Templates': '\u6a21\u677f', 'Background color': '\u80cc\u666f\u989c\u8272', 'Custom...': '\u81ea\u5b9a\u4e49...', 'Custom color': '\u81ea\u5b9a\u4e49\u989c\u8272', 'No color': '\u65e0\u989c\u8272', 'Text color': '\u6587\u5b57\u989c\u8272', 'Table of Contents': 'Table of Contents', 'Show blocks': '\u663e\u793a\u5757', 'Show invisible characters': '\u663e\u793a\u4e0d\u53ef\u89c1\u5b57\u7b26', 'Words: {0}': '\u5b57\u7b26\u6570:{0}', 'Insert': '\u63d2\u5165', 'File': '\u6587\u4ef6', 'Edit': '\u7f16\u8f91', 'Rich Text Area. Press ALT-F9 for menu. Press ALT-F10 for toolbar. Press ALT-0 for help': '\u5bcc\u6587\u5b57\u57df\u3002\u83dc\u5355\u6309 ALT-F9 \uff0c\u5de5\u5177\u6761\u6309ALT-F10\uff0c\u5e2e\u52a9\u6309ALT-0', 'Tools': '\u5de5\u5177', 'View': '\u89c6\u56fe', 'Table': '\u8868\u683c', 'Format': '\u683c\u5f0f', 'Template': '\u6a21\u677f', 'Insert New Note': '\u65b0\u5efa\u7b14\u8bb0' });
var _initProto; const dec = () => {}; class Foo { static { [_initProto] = babelHelpers.applyDecs(this, [[dec, 2, "a"], [dec, 2, "a"]], []); } constructor(...args) { _initProto(this); } a() { return 1; } a() { return 2; } }
'use strict'; var path = require('path'), fs = require('fs'), ss = require( '../../../../lib/socketstream'), Router = require('../../../../lib/http/router').Router, options = ss.client.options, defineAbcClient = require('../abcClient'); var responseStub = { writeHead: function() {}, end: function(body) { this.body = body; } }; describe('development mode asset server', function () { var router = new Router(); ss.root = ss.api.root = path.join(__dirname, '../../../../fixtures/project'); beforeEach(function() { // back to initial client state ss.client.assets.unload(); ss.client.assets.load(); ss.client.formatters.add('javascript'); ss.client.formatters.add('css'); }); afterEach(function() { ss.client.forget(); }); it('should serve system loader module',function() { var client = defineAbcClient({ code: './abc/index.a' }, function() { require('../../../../lib/client/serve/dev')(ss.api, router, options); }); var browserify = fs.readFileSync(path.join(__dirname,'../../../../lib/client/bundler/browserify.client.js'),'utf8'); // dev time URL var req = {url: '/assets/abc/'+client.id+'.js?mod=loader' }; router.route(req.url,req,responseStub).should.equal(true); responseStub.body.should.equal(browserify); }); it('should provide a route for serving system libraries and modules', function() { var client = defineAbcClient({ code: './abc/index.a' }, function() { require('../../../../lib/client/serve/dev')(ss.api, router, options); }); // dev time URL var req = {url: '/assets/abc/'+client.id+'.js?mod=eventemitter2' }; router.route(req.url,req,responseStub).should.equal(true); var ee = fs.readFileSync(path.join(__dirname,'../../../../lib/client/system/modules/eventemitter2.js')); responseStub.body.should.equal('require.define("eventemitter2", function (require, module, exports, __dirname, __filename){\n'+ ee+ '\n});'); }); it('should provide a route for serving an application\'s client code',function() { var client = defineAbcClient({ code: './abc/index.a' }, function() { require('../../../../lib/client/serve/dev')(ss.api, router, options); }); // dev time URL var req = {url: '/assets/abc/'+client.id+'.js?_=/abc/index.js' }; router.route(req.url,req,responseStub).should.equal(true); responseStub.body.should.equal('require.define("/abc/index", function (require, module, exports, __dirname, __filename){\n// test\n\n});'); // dev time URL req = {url: '/assets/abc/'+client.id+'.js?_=abc/index.js' }; router.route(req.url,req,responseStub).should.equal(true); responseStub.body.should.equal('require.define("/abc/index", function (require, module, exports, __dirname, __filename){\n// test\n\n});'); }); it('should provide a route for serving requests for CSS files', function() { var client = defineAbcClient({ code: './abc/index.a' }, function() { require('../../../../lib/client/serve/dev')(ss.api, router, options); }); // dev time URL var req = {url: '/assets/abc/'+client.id+'.css?_=abc/style.css' }; router.route(req.url,req,responseStub).should.equal(true); responseStub.body.should.equal('/* style.css */\n'); }); it('should define modules importedBy correctly with pathPrefix'); it('should handle strings as served content'); it('should handle Buffers as served content'); it('should serve content with correct header'); });
PlainTemplate = {};