ezuikit.js 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266
  1. /**
  2. * jssdk 3.5.0
  3. */
  4. (function (global, factory) {
  5. "use strict";
  6. if (typeof module === "object" && typeof module.exports === "object") {
  7. module.exports = global.document ?
  8. factory(global, true) :
  9. function (w) {
  10. if (!w.document) {
  11. throw new Error("EZUIPlayer requires a window with a document");
  12. }
  13. return factory(w);
  14. };
  15. } else {
  16. factory(global);
  17. }
  18. // Pass this if window is not defined yet
  19. })(typeof window !== "undefined" ? window : this, function (window, noGlobal) {
  20. /**
  21. * @preserve HTML5 Shiv 3.7.3 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
  22. */
  23. !function (a, b) { function c(a, b) { var c = a.createElement("p"), d = a.getElementsByTagName("head")[0] || a.documentElement; return c.innerHTML = "x<style>" + b + "</style>", d.insertBefore(c.lastChild, d.firstChild) } function d() { var a = t.elements; return "string" == typeof a ? a.split(" ") : a } function e(a, b) { var c = t.elements; "string" != typeof c && (c = c.join(" ")), "string" != typeof a && (a = a.join(" ")), t.elements = c + " " + a, j(b) } function f(a) { var b = s[a[q]]; return b || (b = {}, r++, a[q] = r, s[r] = b), b } function g(a, c, d) { if (c || (c = b), l) return c.createElement(a); d || (d = f(c)); var e; return e = d.cache[a] ? d.cache[a].cloneNode() : p.test(a) ? (d.cache[a] = d.createElem(a)).cloneNode() : d.createElem(a), !e.canHaveChildren || o.test(a) || e.tagUrn ? e : d.frag.appendChild(e) } function h(a, c) { if (a || (a = b), l) return a.createDocumentFragment(); c = c || f(a); for (var e = c.frag.cloneNode(), g = 0, h = d(), i = h.length; i > g; g++)e.createElement(h[g]); return e } function i(a, b) { b.cache || (b.cache = {}, b.createElem = a.createElement, b.createFrag = a.createDocumentFragment, b.frag = b.createFrag()), a.createElement = function (c) { return t.shivMethods ? g(c, a, b) : b.createElem(c) }, a.createDocumentFragment = Function("h,f", "return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&(" + d().join().replace(/[\w\-:]+/g, function (a) { return b.createElem(a), b.frag.createElement(a), 'c("' + a + '")' }) + ");return n}")(t, b.frag) } function j(a) { a || (a = b); var d = f(a); return !t.shivCSS || k || d.hasCSS || (d.hasCSS = !!c(a, "article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")), l || i(a, d), a } var k, l, m = "3.7.3", n = a.html5 || {}, o = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i, p = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i, q = "_html5shiv", r = 0, s = {}; !function () { try { var a = b.createElement("a"); a.innerHTML = "<xyz></xyz>", k = "hidden" in a, l = 1 == a.childNodes.length || function () { b.createElement("a"); var a = b.createDocumentFragment(); return "undefined" == typeof a.cloneNode || "undefined" == typeof a.createDocumentFragment || "undefined" == typeof a.createElement }() } catch (c) { k = !0, l = !0 } }(); var t = { elements: n.elements || "abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video", version: m, shivCSS: n.shivCSS !== !1, supportsUnknownElements: l, shivMethods: n.shivMethods !== !1, type: "default", shivDocument: j, createElement: g, createDocumentFragment: h, addElements: e }; a.html5 = t, j(b), "object" == typeof module && module.exports && (module.exports = t) }("undefined" != typeof window ? window : this, document);
  24. /*! @source http://purl.eligrey.com/github/classList.js/blob/master/classList.js */
  25. if ("document" in self) { if (!("classList" in document.createElement("_"))) { (function (j) { "use strict"; if (!("Element" in j)) { return } var a = "classList", f = "prototype", m = j.Element[f], b = Object, k = String[f].trim || function () { return this.replace(/^\s+|\s+$/g, "") }, c = Array[f].indexOf || function (q) { var p = 0, o = this.length; for (; p < o; p++) { if (p in this && this[p] === q) { return p } } return -1 }, n = function (o, p) { this.name = o; this.code = DOMException[o]; this.message = p }, g = function (p, o) { if (o === "") { throw new n("SYNTAX_ERR", "An invalid or illegal string was specified") } if (/\s/.test(o)) { throw new n("INVALID_CHARACTER_ERR", "String contains an invalid character") } return c.call(p, o) }, d = function (s) { var r = k.call(s.getAttribute("class") || ""), q = r ? r.split(/\s+/) : [], p = 0, o = q.length; for (; p < o; p++) { this.push(q[p]) } this._updateClassName = function () { s.setAttribute("class", this.toString()) } }, e = d[f] = [], i = function () { return new d(this) }; n[f] = Error[f]; e.item = function (o) { return this[o] || null }; e.contains = function (o) { o += ""; return g(this, o) !== -1 }; e.add = function () { var s = arguments, r = 0, p = s.length, q, o = false; do { q = s[r] + ""; if (g(this, q) === -1) { this.push(q); o = true } } while (++r < p); if (o) { this._updateClassName() } }; e.remove = function () { var t = arguments, s = 0, p = t.length, r, o = false, q; do { r = t[s] + ""; q = g(this, r); while (q !== -1) { this.splice(q, 1); o = true; q = g(this, r) } } while (++s < p); if (o) { this._updateClassName() } }; e.toggle = function (p, q) { p += ""; var o = this.contains(p), r = o ? q !== true && "remove" : q !== false && "add"; if (r) { this[r](p) } if (q === true || q === false) { return q } else { return !o } }; e.toString = function () { return this.join(" ") }; if (b.defineProperty) { var l = { get: i, enumerable: true, configurable: true }; try { b.defineProperty(m, a, l) } catch (h) { if (h.number === -2146823252) { l.enumerable = false; b.defineProperty(m, a, l) } } } else { if (b[f].__defineGetter__) { m.__defineGetter__(a, i) } } }(self)) } else { (function () { var b = document.createElement("_"); b.classList.add("c1", "c2"); if (!b.classList.contains("c2")) { var c = function (e) { var d = DOMTokenList.prototype[e]; DOMTokenList.prototype[e] = function (h) { var g, f = arguments.length; for (g = 0; g < f; g++) { h = arguments[g]; d.call(this, h) } } }; c("add"); c("remove") } b.classList.toggle("c3", false); if (b.classList.contains("c3")) { var a = DOMTokenList.prototype.toggle; DOMTokenList.prototype.toggle = function (d, e) { if (1 in arguments && !this.contains(d) === !e) { return e } else { return a.call(this, d) } } } b = null }()) } };
  26. Date.prototype.Format = function (fmt) { //author: meizz
  27. var o = {
  28. "M+": this.getMonth() + 1, //月份
  29. "d+": this.getDate(), //日
  30. "h+": this.getHours(), //小时
  31. "m+": this.getMinutes(), //分
  32. "s+": this.getSeconds(), //秒
  33. "q+": Math.floor((this.getMonth() + 3) / 3), //季度
  34. "S": this.getMilliseconds() //毫秒
  35. };
  36. if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  37. for (var k in o)
  38. if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  39. return fmt;
  40. };
  41. var Domain = 'https://open.ys7.com';
  42. var logDomain = 'https://log.ys7.com/statistics.do';
  43. var jqueryJS = Domain + '/sdk/js/2.0/js/jquery.min.js';
  44. var ckplayerJS = Domain + '/sdk/js/2.0/js/ckplayer/ckplayer.js';
  45. var ckplayerSWF = Domain + '/sdk/js/2.0/js/ckplayer/ckplayer.swf';
  46. var m3u8SWF = Domain + '/sdk/js/2.0/js/ckplayer/m3u8.swf';
  47. var flv_js = Domain + '/sdk/js/2.0/js/flv.min.js';
  48. var hlsJS = Domain + '/sdk/js/2.0/js/hls.min.js';
  49. var mpegJS = Domain + '/sdk/js/2.0/js/jsmpeg.min.js';
  50. var wav = Domain + '/sdk/js/2.0/js/wav-audio-encoder.js';
  51. // 当前页面是否是https协议
  52. var isHttps = window.location.protocol === 'https:' ? true : false;
  53. // 是否为移动端
  54. var isMobile = !!navigator.userAgent.match(/(iPhone|iPod|iPad|Android|ios|SymbianOS)/i);
  55. var testVideo = document.createElement('video');
  56. // 是否支持video标签和addEventListener方法(主要为了区别ie8)
  57. var isModernBrowser = !!testVideo.canPlayType && !!window.addEventListener;
  58. // 是否能使用video原生播放hls,目前只有safari可以支持原生video播放。
  59. var isNativeSupportHls = isModernBrowser && testVideo.canPlayType('application/vnd.apple.mpegURL');
  60. // 是否能使用hls.js播放
  61. var isSupportHls = false;
  62. // 是否使用flash
  63. var useFlash = false;
  64. // 初始化播放时间
  65. var playStartTime = new Date().getTime();
  66. // 本地信息上报
  67. var LOCALINFO = 'open_netstream_localinfo';
  68. // 预览主表上报
  69. var PLAY_MAIN = 'open_netstream_play_main';
  70. // 日志上报(轻应用独立上报)
  71. var LOCALINFO_EZUIKIT = 'open_ezuikit_localinfo';
  72. var PERFORMANCE_EZUIKIT = 'open_ezuikit_performance';
  73. var appKey = "";
  74. function dclog(obj) {
  75. var domain = window.location.protocol + '//' + window.location.host;
  76. var logObj = {
  77. Ver: 'v.2.6.5',
  78. PlatAddr: domain,
  79. ExterVer: 'Ez.2.6.5',
  80. OpId: uuid(),
  81. CltType: 102,
  82. AppId: appKey,
  83. StartTime: (new Date()).Format('yyyy-MM-dd hh:mm:ss.S'), // 每个日志包含当前的时间
  84. OS: navigator.platform
  85. }
  86. for (var i in obj) {
  87. logObj[i] = obj[i];
  88. }
  89. var tempArray = [];
  90. for (var j in logObj) {
  91. tempArray.push(j + '=' + logObj[j]);
  92. }
  93. var params = '?' + tempArray.join('&');
  94. // 上报一次本地统计信息
  95. var img = new Image();
  96. img.src = logDomain + params;
  97. }
  98. // 日志上报-2019-09-10
  99. function ezuikitDclog(obj) {
  100. var domain = window.location.protocol + '//' + window.location.host;
  101. var logObj = {
  102. version: 'v.2.6.5',
  103. plate_addr: domain,
  104. appId: appKey,
  105. st: new Date().getTime(), // 每个日志包含当前的时间
  106. }
  107. for (var i in obj) {
  108. logObj[i] = obj[i];
  109. }
  110. var tempArray = [];
  111. for (var j in logObj) {
  112. tempArray.push(j + '=' + logObj[j]);
  113. }
  114. var params = '?' + tempArray.join('&');
  115. // 上报一次本地统计信息
  116. var img = new Image();
  117. img.src = logDomain + params;
  118. }
  119. var RTMP_REG = /^rtmp/;
  120. var HLS_REG = /\.m3u8/;
  121. // 获取元素样式
  122. function getStyle(el) {
  123. return window.getComputedStyle
  124. ? window.getComputedStyle(el, null)
  125. : el.currentStyle;
  126. }
  127. // 加载js
  128. function addJs (filepath, callback, isReadyFun) {
  129. var headerScript = document.getElementsByTagName('head')[0].getElementsByTagName("script");
  130. var isReady = false;
  131. if(isReadyFun) {
  132. isReady = isReadyFun();
  133. } else {
  134. for (var i = 0; i < headerScript.length; i++) {
  135. if (headerScript[i].getAttribute("src") == filepath) {
  136. isReady = true;
  137. callback();
  138. }
  139. }
  140. }
  141. if (!isReady) {
  142. var oJs = document.createElement("script");
  143. oJs.setAttribute("src", filepath);
  144. oJs.onload = callback;
  145. document.getElementsByTagName("head")[0].appendChild(oJs);
  146. } else {
  147. callback();
  148. }
  149. };
  150. function addCss(filepath, callback) {
  151. var headerLink = document.getElementsByTagName('head')[0].getElementsByTagName("link");
  152. var isReady = false;
  153. for (var i = 0; i < headerLink.length; i++) {
  154. if (headerLink[i].getAttribute("href") == filepath) {
  155. isReady = true;
  156. }
  157. }
  158. if (!isReady) {
  159. var oJs = document.createElement('link');
  160. oJs.rel = 'stylesheet';
  161. oJs.type = 'text/css';
  162. oJs.href = filepath;
  163. oJs.onload = callback;
  164. document.getElementsByTagName("head")[0].appendChild(oJs);
  165. }
  166. }
  167. // 通用请求方法
  168. function request(url, method, params, header, success, error) {
  169. var _url = url;
  170. var http_request = new XMLHttpRequest();
  171. http_request.onreadystatechange = function () {
  172. if (http_request.readyState == 4) {
  173. if (http_request.status == 200) {
  174. if (isJSON(http_request.responseText)) {
  175. var _data = JSON.parse(http_request.responseText);
  176. success(_data);
  177. } else {
  178. success(http_request.responseText)
  179. }
  180. }
  181. }
  182. };
  183. http_request.open(method, _url, true);
  184. // http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  185. var data = new FormData();
  186. for (var i in params) {
  187. data.append(i, params[i]);
  188. }
  189. http_request.send(data);
  190. };
  191. /** 获取url参数 */
  192. function getQueryString(name, url) { var r = new RegExp("(\\?|#|&)" + name + "=(.*?)(#|&|$)"); var m = (url || location.href).match(r); return decodeURIComponent(m ? m[2] : ''); }
  193. /** 判断是否为promise对象 */
  194. function isPromise(obj) { return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; }
  195. /** 生成uuid */
  196. function uuid() { var s = []; var hexDigits = "0123456789abcdef"; for (var i = 0; i < 36; i++) { s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1) }; s[14] = "4"; s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); s[8] = s[13] = s[18] = s[23] = "-"; var uuid = s.join(""); return uuid; }
  197. /**获取浏览器名称,版本 */
  198. function getBrowserInfo() { var Sys = {}; var ua = navigator.userAgent.toLowerCase(); var re = /(msie|firefox|chrome|opera|version).*?([\d.]+)/; var m = ua.match(re); try { Sys.browser = m[1].replace(/version/, "'safari"); Sys.ver = m[2]; } catch (e) { console.log("getBrowserInfo fail.") } return Sys; }
  199. /** 是否为JSON格式字符串 */
  200. function isJSON(str) { if (typeof str == 'string') { try { var obj = JSON.parse(str); if (typeof obj == 'object' && obj) { return true; } else { return false; } } catch (e) { return false; } } console.log('It is not a string!') }
  201. /** insertAfter */
  202. function insertAfter(newElement, targetElement) { var parent = targetElement.parentNode; if (parent.lastChild == targetElement) { parent.appendChild(newElement); } else { parent.insertBefore(newElement, targetElement.nextSibling); } }
  203. var EZUIPlayer = function (playParams) {
  204. if (!isModernBrowser) {
  205. throw new Error('不支持ie8等低版本浏览器');
  206. return;
  207. }
  208. /**定义播放配置项 */
  209. this.opt = {};
  210. this.opt.sources = [];
  211. this.handlers = {};
  212. // 修订 - 支持JS Decoder 允许非字符串配置项
  213. if (typeof playParams === 'object' && playParams.hasOwnProperty('decoderPath')) {
  214. if (typeof playParams.audioId === 'undefined') {
  215. playParams["audioId"] = 0;
  216. }
  217. this.playParams = playParams;
  218. /* 校验播放器配置参数合法性 */
  219. var oS = document.createElement('style');
  220. document.getElementsByTagName("head")[0].appendChild(oS);
  221. oS.innerHTML = '.draw-window {border: none!important}';
  222. // 解码器路径
  223. if (typeof playParams.decoderPath !== 'string' || typeof playParams.decoderPath === 'undefined') {
  224. throw new Error('EZUIDecoder requires the path of decoder');
  225. return;
  226. }
  227. // Id
  228. if (typeof playParams.id !== 'string' || typeof playParams.id === 'undefined') {
  229. throw new Error('EZUIDecoder requires parameter id');
  230. return;
  231. }
  232. if (typeof playParams.url !== 'string' || typeof playParams.url === 'undefined') {
  233. throw new Error('EZUIDecoder requires parameter url');
  234. return;
  235. }
  236. // 状态提示
  237. this.loadingStart = function () {
  238. var oS = document.createElement('style');
  239. document.getElementsByTagName("head")[0].appendChild(oS);
  240. oS.innerHTML = '@keyframes antRotate {to {transform: rotate(400deg);transform-origin:50% 50%;}} .loading {display: inline-block;z-index: 1000;-webkit-animation: antRotate 1s infinite linear;animation: antRotate 1s infinite linear;}';
  241. if (playParams && playParams.id) {
  242. var domId = playParams.id;
  243. var domElement = document.getElementById(domId);
  244. var windowWidth = domElement.offsetWidth;
  245. var windowHeight = domElement.offsetHeight || playParams.height || 400;
  246. var offsetTop = domElement.offsetTop;
  247. var offsetLeft = domElement.offsetLeft;
  248. // 先执行清空loading
  249. if (document.getElementById('loading-id-0')) {
  250. document.getElementById('loading-id-0').parentNode.removeChild(document.getElementById('loading-id-0'))
  251. }
  252. var loadingContainerDOM = document.createElement('div');
  253. loadingContainerDOM.setAttribute('id', 'loading-id-0');
  254. var style = 'position:absolute;outline:none;'
  255. style += 'width: 0px;'
  256. style += 'height: 0px;'
  257. style += 'top:' + offsetTop + 'px;'
  258. style += 'left:' + offsetLeft + 'px;'
  259. loadingContainerDOM.setAttribute('style', style);
  260. var loadingContainer = document.getElementById("loading-id-0");
  261. loadingContainerDOM.style.height = windowHeight;
  262. loadingContainerDOM.setAttribute('class', 'loading-container');
  263. // loadingContainerDOM.innerHTML= loading;
  264. insertAfter(loadingContainerDOM, domElement);
  265. var splitBasis = playParams.splitBasis || 1;
  266. var windowLength = playParams.url.split(",").length;
  267. for (var i = 0; i < windowLength; i++) {
  268. var loadingContainer = document.createElement('div');
  269. var loadingStatusDOM = document.createElement('div');
  270. loadingContainer.setAttribute('class', 'loading-item');
  271. loadingContainer.setAttribute('id', 'loading-item-' + i);
  272. //loadingContainer.setAttribute('style','display:inline-flex;flex-direction:column;justify-content:center;align-items: center;width:'+(windowWidth / splitBasis)+'px;height:'+(windowHeight /splitBasis )+'px;outline:none;vertical-align: top;position:absolute');
  273. var style = 'display:inline-flex;flex-direction:column;justify-content:center;align-items: center;width:' + (windowWidth / splitBasis) + 'px;height:' + (windowHeight / splitBasis) + 'px;outline:none;vertical-align: top;position:absolute;';
  274. style += ('left:' + calLoadingPostion(windowHeight, windowWidth, splitBasis, i).left + 'px;');
  275. style += ('top:' + calLoadingPostion(windowHeight, windowWidth, splitBasis, i).top + 'px;');
  276. loadingContainer.setAttribute('style', style);
  277. function calLoadingPostion(windowHeight, windowWidth, splitBasis, i) {
  278. var top = parseInt(i / splitBasis, 10) * (windowHeight / splitBasis);
  279. var left = (i % splitBasis) * (windowWidth / splitBasis);
  280. return {
  281. top: top,
  282. left: left
  283. }
  284. }
  285. var loadingDOM = document.createElement('div');
  286. loadingStatusDOM.innerHTML = "";
  287. loadingStatusDOM.style.color = "#fff";
  288. loadingDOM.setAttribute('class', 'loading');
  289. var loading = '<svg t="1567069979438" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2399" width="32" height="32"><path d="M538.5344 266.4448a133.12 133.12 0 1 1 133.12-133.12 133.4272 133.4272 0 0 1-133.12 133.12zM255.0144 372.1984a121.6768 121.6768 0 1 1 121.6768-121.6768 121.856 121.856 0 0 1-121.6768 121.6768zM134.72 647.424a107.3664 107.3664 0 1 1 107.3664-107.264A107.52 107.52 0 0 1 134.72 647.424z m120.32 272.4608a90.9824 90.9824 0 1 1 90.9824-90.9824A91.1616 91.1616 0 0 1 255.04 919.8848zM538.5344 1024a79.36 79.36 0 1 1 79.36-79.36 79.36 79.36 0 0 1-79.36 79.36z m287.6928-134.144a64.1792 64.1792 0 1 1 64.1792-64.1792 64.3584 64.3584 0 0 1-64.1792 64.1792z m117.76-296.704a52.6336 52.6336 0 1 1 52.6592-52.6336 52.608 52.608 0 0 1-52.6336 52.6336z m-158.72-338.7136a40.96 40.96 0 1 1 12.0064 28.8512 40.5248 40.5248 0 0 1-12.0064-28.8512z" fill="#ffffff" p-id="2400"></path></svg>';
  290. if (playParams.loading && playParams.loading.svg) {
  291. loading = playParams.loading.svg;
  292. }
  293. loadingDOM.innerHTML = loading;
  294. loadingContainer.appendChild(loadingDOM);
  295. // loadingContainer.appendChild(loading);
  296. loadingContainer.appendChild(loadingStatusDOM);
  297. loadingContainerDOM.appendChild(loadingContainer)
  298. }
  299. }
  300. }
  301. this.loadingSet = function (index, opt) {
  302. var loadingContainer = document.getElementById('loading-id-0');
  303. if (document.getElementById('loading-item-' + index)) {
  304. var textElement = document.getElementById('loading-item-' + index).childNodes[1];
  305. textElement.innerHTML = opt.text;
  306. if (opt.color) {
  307. textElement.style.color = opt.color;
  308. }
  309. }
  310. }
  311. this.loadingSetIcon = function (i, type) {
  312. var _this = this;
  313. if (playParams && playParams.id) {
  314. var domId = playParams.id;
  315. var domElement = document.getElementById(domId);
  316. var windowWidth = domElement.offsetWidth;
  317. var windowHeight = domElement.offsetHeight || playParams.height || 400;
  318. var offsetTop = domElement.offsetTop;
  319. var offsetLeft = domElement.offsetLeft;
  320. // 先执行清空loading
  321. if (document.getElementById('loading-id-0')) {
  322. document.getElementById('loading-id-0').parentNode.removeChild(document.getElementById('loading-id-0'))
  323. }
  324. var loadingContainerDOM = document.createElement('div');
  325. loadingContainerDOM.setAttribute('id', 'loading-id-0');
  326. var style = 'position:absolute;outline:none;'
  327. style += 'width: 0px;'
  328. style += 'height: 0px;'
  329. style += 'top:' + offsetTop + 'px;'
  330. style += 'left:' + offsetLeft + 'px;'
  331. loadingContainerDOM.setAttribute('style', style);
  332. var loadingContainer = document.getElementById("loading-id-0");
  333. loadingContainerDOM.style.height = windowHeight;
  334. loadingContainerDOM.setAttribute('class', 'loading-container');
  335. insertAfter(loadingContainerDOM, domElement);
  336. var splitBasis = playParams.splitBasis || 1;
  337. var windowLength = playParams.url.split(",").length;
  338. var loadingContainer = document.createElement('div');
  339. var loadingStatusDOM = document.createElement('div');
  340. loadingContainer.setAttribute('class', 'loading-item');
  341. loadingContainer.setAttribute('id', 'loading-item-' + i);
  342. //loadingContainer.setAttribute('style','display:inline-flex;flex-direction:column;justify-content:center;align-items: center;width:'+(windowWidth / splitBasis)+'px;height:'+(windowHeight /splitBasis )+'px;outline:none;vertical-align: top;position:absolute');
  343. var style = 'display:inline-flex;flex-direction:column;justify-content:center;align-items: center;width:' + (windowWidth / splitBasis) + 'px;height:' + (windowHeight / splitBasis) + 'px;outline:none;vertical-align: top;position:absolute;';
  344. style += ('left:' + calLoadingPostion(windowHeight, windowWidth, splitBasis, i).left + 'px;');
  345. style += ('top:' + calLoadingPostion(windowHeight, windowWidth, splitBasis, i).top + 'px;');
  346. loadingContainer.setAttribute('style', style);
  347. function calLoadingPostion(windowHeight, windowWidth, splitBasis, i) {
  348. var top = parseInt(i / splitBasis, 10) * (windowHeight / splitBasis);
  349. var left = (i % splitBasis) * (windowWidth / splitBasis);
  350. return {
  351. top: top,
  352. left: left
  353. }
  354. }
  355. var loadingDOM = document.createElement('div');
  356. loadingStatusDOM.innerHTML = "";
  357. loadingStatusDOM.style.color = "#fff";
  358. loadingDOM.setAttribute('class', type);
  359. var icon = '';
  360. switch (type) {
  361. case 'retry':
  362. icon = '<svg t="1590935684181" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1623" width="32" height="32"><path d="M972.8 102.4c-30.72 0-51.2 20.48-51.2 51.2v51.2c-51.2-71.68-122.88-128-204.8-158.72C460.8-66.56 158.72 51.2 46.08 307.2S51.2 865.28 307.2 977.92 865.28 972.8 977.92 716.8H972.8c0-30.72-20.48-51.2-51.2-51.2s-51.2 20.48-51.2 51.2h-5.12c-46.08 76.8-112.64 138.24-199.68 174.08-209.92 87.04-445.44-15.36-532.48-225.28S148.48 215.04 358.4 133.12c189.44-81.92 404.48 0 506.88 174.08H768c-30.72 0-51.2 20.48-51.2 51.2s20.48 51.2 51.2 51.2h204.8c30.72 0 51.2-20.48 51.2-51.2V153.6c0-30.72-20.48-51.2-51.2-51.2z" p-id="1624" fill="#ffffff"></path></svg>';
  363. loadingDOM.style.cursor = 'pointer';
  364. loadingDOM.onclick = function () {
  365. console.log("点击重试", i);
  366. // _this.loadingStart();
  367. _this.play(i);
  368. }
  369. break;
  370. }
  371. loadingDOM.innerHTML = icon;
  372. loadingContainer.appendChild(loadingDOM);
  373. loadingContainer.appendChild(loadingStatusDOM);
  374. loadingContainerDOM.appendChild(loadingContainer)
  375. }
  376. }
  377. this.loadingEnd = function (index) {
  378. var loadingItemContainerDOM = document.getElementById('loading-item-' + index);
  379. if (loadingItemContainerDOM) {
  380. loadingItemContainerDOM.parentNode.removeChild(loadingItemContainerDOM);
  381. var loadingContainerDOM = document.getElementById('loading-id-0');
  382. if (loadingContainerDOM && loadingContainerDOM.children.length === 0) {
  383. loadingContainerDOM.parentNode.removeChild(loadingContainerDOM);
  384. }
  385. }
  386. }
  387. // 将播放地址配置在实例 opt 属性中
  388. this.opt.sources.push(playParams.url);
  389. // JSDecoder 只有一个播放地址
  390. this.opt.currentSource = this.opt.sources[0];
  391. /* 获取解码器用户配置项 - 开始 */
  392. /**
  393. * 调试模式配置
  394. * 可通过dev属性指定API服务域名
  395. */
  396. var domain = "https://open.ys7.com";
  397. if (playParams.env) {
  398. var environmentParams = playParams.env;
  399. domain = environmentParams.domain;
  400. }
  401. /** 创建jSPlugin 对象 */
  402. this.jSPlugin = {};
  403. var _this = this;
  404. /** 根据播放参数获取真实播放地址 */
  405. this.loadingStart();
  406. playStartTime = new Date().getTime();
  407. // var getRealUrl = this.getRealUrl(playParams);
  408. var initDecoder = this.initDecoder(playParams);
  409. // 初始化播放器
  410. _this.loadingSet(0, { text: _this.opt.domain !== 'open' ? 'Initialize the player...' : '初始化播放器...' });
  411. if (isPromise(initDecoder)) {
  412. initDecoder.then(function (data) {
  413. _this.loadingSet(0, { text: _this.opt.domain !== 'open' ? 'Initialization is complete' : '初始化完成' });
  414. _this.loadingEnd(0);
  415. if(playParams.autoplay){
  416. setTimeout(function () {
  417. _this.play();
  418. }, 2000)
  419. }
  420. })
  421. }
  422. } else {
  423. var domain = "https://open.ys7.com";
  424. if (playParams && playParams.env) {
  425. domain = playParams.env.domain;
  426. }
  427. var elementID = '';
  428. if (typeof playParams === 'string') { //缩写模式 new EZUIPlayer('myplayer')
  429. elementID = playParams;
  430. } else if (typeof playParams === 'object') { //标准模式 new EZUIPlayer({id: 'myplayer'})
  431. elementID = playParams.id;
  432. }
  433. this.videoId = elementID;
  434. this.video = document.getElementById(elementID);
  435. if (!this.video) {
  436. throw new Error('EZUIPlayer requires parameter videoId');
  437. }
  438. var sources = this.video.getElementsByTagName('source');
  439. // 转为数组对象,不受removeChild影响
  440. sources = Array.prototype.slice.call(sources, 0);
  441. if (this.video.src) {
  442. // 移动端删除rtmp地址
  443. if (isMobile && RTMP_REG.test(this.video.src)) {
  444. this.video.removeAttribute('src');
  445. this.video.load();
  446. } else {
  447. this.opt.sources.push(this.video.src);
  448. }
  449. }
  450. var l = sources.length;
  451. if (l > 0) {
  452. for (var i = 0; i < l; i++) {
  453. // 移动端删除rtmp地址
  454. if (isMobile && RTMP_REG.test(sources[i].src)) {
  455. this.video.removeChild(sources[i]);
  456. } else {
  457. this.opt.sources.push(sources[i].src);
  458. }
  459. }
  460. }
  461. if (this.opt.sources.length < 1) {
  462. throw new Error('no source found in video tag.');
  463. }
  464. this.opt.cur = 0;
  465. this.opt.poster = this.video.poster;
  466. var videoStyle = getStyle(this.video);
  467. var width = this.video.width;
  468. var height = this.video.height;
  469. if (width) {
  470. this.opt.width = width;
  471. if (height) {
  472. this.opt.height = height;
  473. } else {
  474. this.opt.height = 'auto';
  475. }
  476. this.log('video width:' + this.opt.width + ' height:' + this.opt.height);
  477. } else {
  478. this.opt.width = videoStyle.width;
  479. this.opt.height = videoStyle.height;
  480. this.log('videoStyle.width:' + videoStyle.width + ' wideoStyle.height:' + videoStyle.height);
  481. }
  482. this.opt.parentId = elementID;
  483. this.opt.autoplay = this.video.autoplay ? true : false;
  484. this.log('autoplay:' + this.video.autoplay);
  485. this.opt.currentSource = this.opt.sources[this.opt.cur];
  486. this.getRealUrl(playParams);
  487. }
  488. /* 创建播放,错误,停止事件钩子,上报用户行为 */
  489. this.handlers = {};
  490. this.initTime = (new Date()).getTime();
  491. this.on('play', function () {
  492. // 上报播放成功信息
  493. dclog({
  494. systemName: PLAY_MAIN,
  495. playurl: this.opt.currentSource,
  496. Time: (new Date()).Format('yyyy-MM-dd hh:mm:ss.S'),
  497. Enc: 0, // 0 不加密 1 加密
  498. PlTp: 1, // 1 直播 2 回放
  499. Via: 911, // 2 私有流 911 标准流
  500. ErrCd: 0,
  501. OpId: uuid(),
  502. Cost: (new Date()).getTime() - this.initTime // 毫秒数
  503. });
  504. });
  505. this.retry = 2;
  506. this.on('error', function () {
  507. dclog({
  508. systemName: PLAY_MAIN,
  509. playurl: this.opt.currentSource,
  510. cost: -1,
  511. ErrCd: -1,
  512. Via: 911, // 2 私有流 911 标准流
  513. OpId: uuid(),
  514. });
  515. });
  516. var deviceSerial = '';
  517. var playUid = '';
  518. var accessToken = '';
  519. var uuidReg = /[a-z0-9]{32}/;
  520. var deviceSerialReg = /[a-zA-Z0-9]{9}\/[0-9]{0,2}\./;
  521. if (typeof playParams === 'string') {
  522. var url = this.opt.currentSource;
  523. if (uuidReg.test(url)) {
  524. playUid = url.match(uuidReg)[0];
  525. } else if (deviceSerialReg.test(url)) {
  526. deviceSerial = url.match(deviceSerialReg)[0].split('/')[0];
  527. }
  528. } else if (typeof playParams === 'object') {
  529. var url = playParams.url;
  530. if (uuidReg.test(url)) {
  531. playUid = url.match(uuidReg);
  532. } else if (deviceSerialReg.test(url)) {
  533. deviceSerial = url.match(deviceSerialReg)[0].split('/')[0];
  534. }
  535. if (playParams.accessToken) {
  536. accessToken = playParams.accessToken;
  537. }
  538. }
  539. if(domain === "https://open.ys7.com"){
  540. var appInfoSuccess = function (data) {
  541. if (data.retcode === 0 && data.data) {
  542. appKey = data.data.appKey;
  543. }
  544. // 上报一次本地信息
  545. dclog({
  546. systemName: LOCALINFO,
  547. });
  548. // 上报一次本地信息-新
  549. ezuikitDclog({
  550. systemName: LOCALINFO_EZUIKIT,
  551. os: navigator.platform,
  552. browser: JSON.stringify(getBrowserInfo()),
  553. })
  554. }
  555. var appInfoError = function (error) {
  556. // 上报一次本地信息
  557. dclog({
  558. systemName: LOCALINFO
  559. });
  560. // 上报一次本地信息-新
  561. ezuikitDclog({
  562. systemName: LOCALINFO_EZUIKIT,
  563. os: navigator.platform,
  564. browser: JSON.stringify(getBrowserInfo()),
  565. })
  566. }
  567. // 获取appKey
  568. request(domain + '/jssdk/ezopen/getAppInfo?uuid=' + playUid + '&accessToken=' + accessToken + "&deviceSerial=" + deviceSerial + "&channelNo=1",
  569. 'GET',
  570. '',
  571. '',
  572. appInfoSuccess,
  573. appInfoError
  574. );
  575. }
  576. // 全屏变化回调
  577. function fullscreenchange(data) {
  578. if(!data) {
  579. _this.jSPlugin.JS_Resize(_this.playParams.width, _this.playParams.height);
  580. }else {
  581. _this.jSPlugin.JS_Resize(document.documentElement.clientWidth , document.documentElement.clientHeight);
  582. }
  583. }
  584. if (typeof document.fullScreen !== "undefined") {
  585. document.addEventListener("fullscreenchange", function() {
  586. var e = document.fullscreen || false;
  587. fullscreenchange(e)
  588. })
  589. } else if (typeof document.webkitIsFullScreen !== "undefined") {
  590. document.addEventListener("webkitfullscreenchange", function() {
  591. var e = document.webkitIsFullScreen || false;
  592. console.log("EEEEEE-1",e);
  593. fullscreenchange(e)
  594. })
  595. } else if (typeof document.mozFullScreen !== "undefined") {
  596. document.addEventListener("mozfullscreenchange", function() {
  597. var e = document.mozFullScreen || false;
  598. fullscreenchange(e)
  599. })
  600. }
  601. };
  602. // 事件监听
  603. EZUIPlayer.prototype.on = function (eventName, callback) {
  604. if (typeof eventName !== 'string' || typeof callback !== 'function') {
  605. return;
  606. }
  607. if (typeof this.handlers[eventName] === 'undefined') {
  608. this.handlers[eventName] = [];
  609. }
  610. this.handlers[eventName].push(callback);
  611. };
  612. // 事件触发
  613. EZUIPlayer.prototype.emit = function () {
  614. if (this.handlers[arguments[0]] instanceof Array) {
  615. var handlers = this.handlers[arguments[0]];
  616. var l = handlers.length;
  617. for (var i = 0; i < l; i++) {
  618. handlers[i].apply(this, Array.prototype.slice.call(arguments, 1));
  619. }
  620. }
  621. };
  622. // 日志
  623. EZUIPlayer.prototype.log = function (msg, className) {
  624. this.emit('log', msg, className);
  625. };
  626. EZUIPlayer.prototype.getRealUrl = function (playParams) {
  627. var _this = this;
  628. var apiDomain = 'https://open.ys7.com';
  629. /** jsDecoder 获取真实地址 -- 开始 */
  630. if (playParams && playParams.hasOwnProperty('decoderPath')) {
  631. if(playParams.url.split(",")[0].indexOf('open.ezviz.com') !==-1){ ///海外
  632. var host = "https://open.ys7.com";
  633. var hostName = playParams.url.split(",")[0].match(/ezopen:\/\/(\S*)\.ezviz\.com/)[1];
  634. if (playParams.env) {
  635. var environmentParams = playParams.env;
  636. domain = environmentParams.domain;
  637. if(domain.match(/https:\/\/(\S*)\.ezviz(\S*)\.com/)) {
  638. hostName = domain.match(/https:\/\/(\S*)\.ezviz(\S*)\.com/)[1];
  639. }
  640. }
  641. if(hostName.indexOf("@")!== -1){
  642. hostName = hostName.split("@")[1];
  643. }
  644. switch (hostName){
  645. case 'isgpopen':
  646. host = "https://isgpopen.ezvizlife.com";
  647. break;
  648. case 'ieuopen':
  649. host = "https://ieuopen.ezvizlife.com";
  650. break;
  651. case 'isaopen':
  652. host = "https://isaopen.ezvizlife.com";
  653. break;
  654. case 'irusopen':
  655. host = "https://irusopen.ezvizru.com";
  656. break;
  657. case 'testusopen':
  658. host = "https://testusopen.ezvizlife.com";
  659. break;
  660. }
  661. apiDomain = host;
  662. }
  663. if (playParams && playParams.env) {
  664. apiDomain = playParams.env.domain;
  665. }
  666. // 检测加密状态
  667. if(playParams.url.indexOf("@") === -1){
  668. const deviceInfoSuccess = function(data){
  669. if (data.code == 200 && data.data) {
  670. if(data.data.isEncrypt === 1) {
  671. if (playParams && playParams.handleError) {
  672. playParams.handleError(Object.assign({retcode: -1,msg: '设备已经加密,请输入验证码播放'}));
  673. }
  674. }
  675. }
  676. }
  677. const deviceInfoError = function(data){
  678. }
  679. var deviceSerial = playParams.url.split("/")[3];
  680. request(apiDomain + '/api/lapp/device/info', 'POST', {accessToken:playParams.accessToken,deviceSerial:deviceSerial}, '', deviceInfoSuccess, deviceInfoError);
  681. }
  682. // api 获取真实地址开始时间
  683. var getRealUrlDurationST = new Date().getTime();
  684. var getRealUrlPromise = function (resolve, reject, ezopenURL) {
  685. var realUrl = '';
  686. if (!/^ezopen:\/\//.test(ezopenURL)) { // JSDecoder ws协议播放
  687. resolve(ezopenURL);
  688. } else {
  689. // 向API请求真实地址
  690. var apiUrl = apiDomain + "/api/lapp/live/url/ezopen";
  691. var apiSuccess = function (data) {
  692. if (data.code == 200 || data.retcode == 0) {
  693. var playUrl ="";
  694. if(data.ext && data.ext.token){
  695. realUrl += data.data;
  696. stream = data.ext.token;
  697. playUrl = data.data;
  698. }else if(data.data && data.data.token) {
  699. realUrl += data.data.url;
  700. stream = data.data.token;
  701. playUrl = data.data.url;
  702. }
  703. var type= playParams.url.indexOf('live') !== -1 ? 'live' : 'playback';
  704. if(type === 'live'){
  705. realUrl = realUrl + '&ssn=' + stream + '&auth=1&biz=4&cln=100' ;
  706. }else {
  707. realUrl = realUrl + '&ssn=' + stream + '&auth=1&cln=100';
  708. }
  709. console.log(realUrl)
  710. /**参数容错处理 start*/
  711. if (playUrl.indexOf('playback') !== -1) { //回放
  712. var wsBegin = getQueryString('begin', playUrl) || getQueryString('begin', playParams.url);
  713. var wsEnd = getQueryString('end', playUrl) || getQueryString('end', playParams.url);
  714. // 兼容各种时间格式
  715. if (!wsBegin) {
  716. var defaultDate = new Date();
  717. realUrl = realUrl + '&begin=' + defaultDate.Format('yyyyMMdd') + 'T000000Z';
  718. } else {
  719. realUrl = realUrl.replace('&begin=' + getQueryString('begin', playUrl), '&begin=' + formatRecTime(wsBegin, '000000'))
  720. if(!getQueryString('begin',realUrl)){
  721. realUrl += '&begin=' + formatRecTime(wsBegin, '000000');
  722. }
  723. }
  724. if (!wsEnd) {
  725. realUrl = realUrl + '&end=' + formatRecTime(getQueryString('begin', realUrl).substr(0, 8), '235959');
  726. } else {
  727. realUrl = realUrl.replace('&end=' + getQueryString('end', playUrl), '&end=' + formatRecTime(wsEnd, '235959'))
  728. if(!getQueryString('end',realUrl)){
  729. realUrl += '&end=' + formatRecTime(wsEnd, '235959');
  730. }
  731. }
  732. // api错误处理
  733. if (!getQueryString('stream', playUrl)) {
  734. realUrl = realUrl.replace('stream', '&stream');
  735. }
  736. if (playParams.url.indexOf('.cloud') !== -1) {
  737. // 调用回放API接口获取回放片段 - start
  738. var recBegin = reRormatRecTime(getQueryString('begin', realUrl));
  739. var recEnd = reRormatRecTime(getQueryString('end', realUrl));
  740. var deviceSerial = getQueryString('serial', realUrl)
  741. var channelNo = getQueryString('chn', realUrl);
  742. var recSliceUrl = apiDomain + "/api/lapp/video/by/time";
  743. var recSliceParams = {
  744. accessToken: playParams.accessToken,
  745. recType: 1,
  746. deviceSerial: deviceSerial,
  747. channelNo: channelNo,
  748. startTime: recBegin,
  749. endTime: recEnd,
  750. version: '2.0'
  751. }
  752. function recAPISuccess(data) {
  753. if (data.code == 200) {
  754. var recSliceArr = [];
  755. if (data.data && data.data.files && data.data.files.length > 0) {
  756. var dataArr = data.data.files;
  757. var nextFileTime = new Date().getTime();
  758. var isAll = data.data.isAll;
  759. // mock
  760. // var number = 0;
  761. //isAll = false;
  762. if (isAll) {
  763. recSliceArr = recSliceArrFun(dataArr);
  764. var recSliceArrJSON = JSON.stringify(recSliceArr).replace('\\', '');
  765. realUrl += ('&recSlice=' + recSliceArrJSON.replace('\\', '')) + '&r='+ Math.random();
  766. resolve(realUrl);
  767. } else {
  768. recTransaction();
  769. // 云存储回调事务
  770. function recTransaction() {
  771. function recAPIV2Success(data) {
  772. if (data.data && data.data.files && data.data.files.length > 0) {
  773. //if(number < 2 ) {
  774. if(data.data.isAll == false) {
  775. if(data.data.files){
  776. dataArr = dataArr.concat(data.data.files);
  777. }
  778. nextFileTime = data.data.nextFileTime > 0 ? data.data.nextFileTime : new Date().getTime();
  779. recTransaction();
  780. } else {
  781. recSliceArr = recSliceArrFun(dataArr);
  782. var recSliceArrJSON = JSON.stringify(recSliceArr).replace('\\', '');
  783. realUrl += ('&recSlice=' + recSliceArrJSON.replace('\\', '')) + '&r='+ Math.random();
  784. resolve(realUrl);
  785. }
  786. // mock
  787. //number = number + 1;
  788. } else {
  789. recSliceArr = recSliceArrFun(dataArr);
  790. var recSliceArrJSON = JSON.stringify(recSliceArr).replace('\\', '');
  791. realUrl += ('&recSlice=' + recSliceArrJSON.replace('\\', '')) + '&r='+ Math.random();
  792. resolve(realUrl);
  793. }
  794. }
  795. function recAPIV2Error (err) {
  796. console.log(err);
  797. }
  798. recSliceParams.startTime = nextFileTime;
  799. request(recSliceUrl, 'POST', recSliceParams, '', recAPIV2Success, recAPIV2Error);
  800. }
  801. }
  802. } else {
  803. _this.log('未找到录像片段', 'error');
  804. _this.loadingSet(0, { text: _this.opt.domain !== 'open' ? 'Get device live view address' : '获取设备播放地址' })
  805. resolve(JSON.stringify({ code: -1, msg: _this.opt.domain !== 'open' ? 'Not found video clips' : "未找到录像片段" }))
  806. // reject('未找到录像片段');
  807. }
  808. } else {
  809. _this.log(data.msg, 'error');
  810. _this.loadingSet(0, { text: _this.opt.domain !== 'open' ? 'Get device live view address complete' : '获取设备播放地址' });
  811. resolve(JSON.stringify({ code: -1, msg: _this.opt.domain !== 'open' ? 'Not found video clips' : "未找到录像片段" }))
  812. //reject('未找到录像片段');
  813. }
  814. function recSliceArrFun(data) {
  815. var downloadPathArr = [];
  816. var currentDP = downloadPathArr.length
  817. data.forEach(function (item, index) {
  818. if (downloadPathArr.length == 0 || (item.downloadPath !== downloadPathArr[downloadPathArr.length - 1].downloadPath)) {
  819. downloadPathArr.push({
  820. downloadPath: item.downloadPath,
  821. ownerId: item.ownerId,
  822. iStorageVersion: item.iStorageVersion,
  823. videoType: item.videoType,
  824. iPlaySpeed: 0,
  825. startTime: item.startTime,
  826. endTime: item.endTime
  827. })
  828. } else {
  829. downloadPathArr[downloadPathArr.length - 1].endTime = item.endTime;
  830. }
  831. })
  832. return downloadPathArr;
  833. }
  834. }
  835. function recAPIError(err) {
  836. console.log("获取回放片段错误")
  837. }
  838. request(recSliceUrl, 'POST', recSliceParams, '', recAPISuccess, recAPIError);
  839. } else {// 本地回放
  840. //alarm rec - start
  841. if (playParams.url.indexOf('alarmId') !== -1) {
  842. console.log("进入alarmId回放")
  843. // 调用回放API接口获取回放片段 - start
  844. var alarmId = getQueryString('alarmId', realUrl)
  845. var recBegin = reRormatRecTime(getQueryString('begin', realUrl));
  846. var recEnd = reRormatRecTime(getQueryString('end', realUrl));
  847. var deviceSerial = getQueryString('serial', realUrl)
  848. var channelNo = getQueryString('chn', realUrl);
  849. var recSliceUrl = apiDomain + "/api/lapp/video/by/id";
  850. var recSliceParams = {
  851. accessToken: playParams.accessToken,
  852. // recType: 1,
  853. deviceSerial: deviceSerial,
  854. channelNo: channelNo,
  855. alarmId: alarmId,
  856. // startTime:recBegin,
  857. // endTime:recEnd
  858. }
  859. function recAPISuccess(data) {
  860. if (data.code == 200) {
  861. var recSliceArr = [];
  862. if (data.data) {
  863. recSliceArr = recSliceArrFun([data.data]);
  864. var recSliceArrJSON = JSON.stringify(recSliceArr).replace('\\', '');
  865. realUrl += ('&recSlice=' + recSliceArrJSON.replace('\\', ''));
  866. console.log("realUrl", realUrl, data.data.recType);
  867. if (data.data.recType == 1) {
  868. realUrl = realUrl.replace('/playback', '/cloudplayback')
  869. } else {
  870. realUrl = realUrl.replace('/cloudplayback', '/playback')
  871. }
  872. _this.opt.sources[0] = realUrl;
  873. resolve(realUrl);
  874. // request(nodeUrl, 'GET', '', '', nodeSuccess, nodeError);
  875. } else {
  876. _this.log('未找到录像片段', 'error');
  877. _this.loadingSet(0, { text: _this.opt.domain !== 'open' ? 'Get device live view address' : '获取设备播放地址' })
  878. resolve(JSON.stringify({ code: -1, msg:_this.opt.domain !== 'open' ? 'Not found video clips' : "未找到录像片段" }))
  879. // reject('未找到录像片段');
  880. }
  881. } else {
  882. _this.log(data.msg, 'error');
  883. _this.loadingSet(0, { text: _this.opt.domain !== 'open' ? 'Get device live view address' : '获取设备播放地址' });
  884. resolve(JSON.stringify({ code: -1, msg: _this.opt.domain !== 'open' ? 'Not found video clips' : "未找到录像片段" }))
  885. //reject('未找到录像片段');
  886. }
  887. function recSliceArrFun(data) {
  888. var downloadPathArr = [];
  889. var currentDP = downloadPathArr.length
  890. data.forEach(function (item, index) {
  891. if (downloadPathArr.length == 0 || (item.downloadPath !== downloadPathArr[downloadPathArr.length - 1].downloadPath)) {
  892. downloadPathArr.push({
  893. downloadPath: item.downloadPath,
  894. ownerId: item.ownerId,
  895. iStorageVersion: item.iStorageVersion,
  896. videoType: item.videoType,
  897. iPlaySpeed: 0,
  898. startTime: item.startTime,
  899. endTime: item.endTime
  900. })
  901. } else {
  902. downloadPathArr[downloadPathArr.length - 1].endTime = item.endTime;
  903. }
  904. })
  905. console.log("downloadPathArr", downloadPathArr)
  906. return downloadPathArr;
  907. }
  908. }
  909. function recAPIError(err) {
  910. console.log("获取回放片段错误")
  911. }
  912. request(recSliceUrl, 'POST', recSliceParams, '', recAPISuccess, recAPIError);
  913. } else {
  914. // arlar rec - end
  915. // request(nodeUrl, 'GET', '', '', nodeSuccess, nodeError);
  916. resolve(realUrl);
  917. }
  918. }
  919. } else {
  920. // 预览直接获取回放片段
  921. // request(nodeUrl, 'GET', '', '', nodeSuccess, nodeError);
  922. resolve(realUrl);
  923. }
  924. getPlayTokenST = new Date().getTime();
  925. // 执行一次API服务请求上报
  926. var getRealUrlDurationET = new Date().getTime();
  927. ezuikitDclog({
  928. systemName: PERFORMANCE_EZUIKIT,
  929. bn: 0,
  930. browser: JSON.stringify(getBrowserInfo()),
  931. duration: getRealUrlDurationET - getRealUrlDurationST,
  932. rt: 200,
  933. })
  934. } else {
  935. // 将错误信息捕获到用户自定义错误回调中
  936. if (playParams && playParams.handleError) {
  937. playParams.handleError(Object.assign({retcode: data.code || -1,msg: data.msg || '其他错误'}));
  938. }
  939. // 执行一次API服务请求服务错误上报
  940. var getRealUrlDurationET = new Date().getTime();
  941. ezuikitDclog({
  942. systemName: PERFORMANCE_EZUIKIT,
  943. bn: 0,
  944. browser: JSON.stringify(getBrowserInfo()),
  945. duration: getRealUrlDurationET - getRealUrlDurationST,
  946. rt: data.code || 500,
  947. msg: data.msg || '未知服务错误'
  948. })
  949. resolve(JSON.stringify(data), 'error')
  950. //throw new Error('获取播放设备信息失败');
  951. }
  952. /**参数容错处理 end*/
  953. }
  954. var apiError = function (error) {
  955. // 将错误信息捕获到用户自定义错误回调中
  956. if (playParams && playParams.handleError) {
  957. playParams.handleError(Object.assign({retcode: error.code || -1,msg: error.msg || '其他错误'}));
  958. }
  959. var getRealUrlDurationET = new Date().getTime();
  960. ezuikitDclog({
  961. systemName: PERFORMANCE_EZUIKIT,
  962. bn: 0,
  963. browser: JSON.stringify(getBrowserInfo()),
  964. duration: getRealUrlDurationET - getRealUrlDurationST,
  965. rt: 500,
  966. msg: data.msg || '网络错误'
  967. })
  968. resolve(JSON.stringify(error))
  969. //throw new Error('获取播放设备信息失败');
  970. }
  971. var isHttp = 'false';
  972. // if (playParams && playParams.env && playParams.env.domain) {
  973. // isHttp = playParams.env.domain.indexOf('https') !== -1 ? 'false' : 'true';
  974. // } else {
  975. // isHttp = window.location.href.indexOf('https') !== -1 ? 'false' : 'true';
  976. // }
  977. var apiParams = {
  978. ezopen: ezopenURL,
  979. userAgent: window.navigator.userAgent,
  980. isFlv: false,
  981. addressTypes: null,
  982. isHttp: isHttp,
  983. accessToken: playParams.accessToken,
  984. }
  985. request(apiUrl, 'POST', apiParams, '', apiSuccess, apiError);
  986. }
  987. }
  988. var urlList = playParams.url.split(',');
  989. var promiseTaskList = [];
  990. var promiseTaskFun = function (ezopenURL) {
  991. return new Promise(function (resolve, reject) { return getRealUrlPromise(resolve, reject, ezopenURL) })
  992. };
  993. urlList.map(function (item, index) {
  994. _this.loadingSet(index, { text: _this.opt.domain !== 'open' ? 'Get device live view address' : '获取设备播放地址' });
  995. var adaptHost = item.match(/ezopen:\/\/(\S*)\.com/)[1] + '.com';
  996. if(adaptHost.indexOf("@")!== -1){
  997. adaptHost = adaptHost.split("@")[1];
  998. }
  999. var adaptItem = item.replace(adaptHost, _this.opt.domain !== 'open' ?'open.ezviz.com' : 'open.ys7.com');
  1000. promiseTaskList.push(promiseTaskFun(adaptItem));
  1001. });
  1002. var getRealUrlPromiseObj = Promise.all(promiseTaskList)
  1003. .then(function (result) {
  1004. // 获取真实地址成功后,赋值到opt属性中
  1005. _this.opt.sources = result;
  1006. _this.opt.currentSource = result[0];
  1007. result.forEach(function (item, index) {
  1008. _this.loadingSet(index, { text: _this.opt.domain !== 'open' ? 'Get live view Address Success' : '获取播放地址成功' })
  1009. })
  1010. })
  1011. .catch(function (err) {
  1012. _this.log("获取真实地址错误" + JSON.stringify(err), 'error')
  1013. })
  1014. return getRealUrlPromiseObj;
  1015. } else {
  1016. if (!this.opt.currentSource) {
  1017. this.log('未找到合适的播放URL', 'error');
  1018. return;
  1019. }
  1020. var me = this;
  1021. // 如果不是ezopen打头的,走原来的播放模式
  1022. if (!/^ezopen:\/\//.test(this.opt.currentSource)) {
  1023. this.tryPlay(this.opt.currentSource);
  1024. } else {
  1025. // 如果是ezopen协议地址,先校验一下地址的合法性
  1026. if (!/^ezopen:\/\//.test(this.opt.currentSource)) {
  1027. throw new Error('EZOPEN地址必须要以ezopen://开头');
  1028. return;
  1029. } else if (this.opt.currentSource.indexOf('.com/') === -1) {
  1030. throw new Error('EZOPEN地址格式不正确');
  1031. return;
  1032. } else if (!/[a-z\d]{32}(\.hd)?\.live/.test(this.opt.currentSource)) {
  1033. throw new Error('EZOPEN地址格式uuid格式不正确');
  1034. return;
  1035. } else if (/(.*.hls.*|.*.m3u8.*|.*.wss.*|.*.flv.*|.*.rtmp.*){2,}/.test(this.opt.currentSource)) {
  1036. throw new Error('EZOPEN地址多于两个播放协议');
  1037. return;
  1038. } else if (this.opt.currentSource.search(/(.hls|.m3u8|.wss|.flv|.rtmp)/) !== -1 && !/.live(.hls|.m3u8|.wss|.flv|.rtmp)/.test(this.opt.currentSource)) {
  1039. throw new Error('请指定正确的播放协议');
  1040. return;
  1041. } else if (this.opt.currentSource.search(/(.hls|.m3u8|.wss|.flv|.rtmp)/) === -1 && !/[a-z\d]{32}(\.hd)?\.live$/.test(this.opt.currentSource)) {
  1042. throw new Error('EZOPEN地址结尾不正确');
  1043. return;
  1044. } else {
  1045. /* 获取播放地址 - 开始 */
  1046. var that = this;
  1047. addJs(flv_js, function () {
  1048. var para = {
  1049. "ezopen": that.opt.currentSource,
  1050. "userAgent": window.navigator.userAgent,
  1051. "isFlv": flvjs && flvjs.isSupported() ? flvjs.isSupported() : false,
  1052. "addressTypes": "HLS,RTMP,WS,FLV",
  1053. "isHttp": window.location.protocol.indexOf('s') > 0 ? false : true,
  1054. };
  1055. dclog({
  1056. "ezopen": that.opt.currentSource,
  1057. "userAgent": window.navigator.userAgent,
  1058. "isFlv": flvjs && flvjs.isSupported() ? flvjs.isSupported() : false,
  1059. "addressTypes": "HLS,RTMP,WS,FLV",
  1060. "isHttp": window.location.protocol.indexOf('s') > 0 ? false : true,
  1061. 'systemName': 'EZOPEN',
  1062. });
  1063. that.log('---------------------------------------');
  1064. that.log('入参(ezopen)是: ' + para.ezopen);
  1065. that.log('---------------------------------------');
  1066. that.log('入参(userAgent)是: ' + para.userAgent);
  1067. that.log('---------------------------------------');
  1068. that.log('入参(isFlv)是: ' + para.isFlv);
  1069. that.log('---------------------------------------');
  1070. that.log('入参(addressTypes)是: ' + para.addressTypes);
  1071. that.log('---------------------------------------');
  1072. that.log('入参(isHttp)是: ' + para.isHttp);
  1073. that.log('---------------------------------------');
  1074. var apiUrl = apiDomain + "/api/lapp/live/url/ezopen";
  1075. var apiSuccess = function (data) {
  1076. if (data.code == 200) {
  1077. that.log('播放地址是: ' + data.data);
  1078. that.video.src = data.data;
  1079. that.video.load();
  1080. that.tryPlay(data.data);
  1081. } else {
  1082. that.log('data: ' + JSON.stringify(data));
  1083. throw new Error(data.msg);
  1084. return;
  1085. }
  1086. }
  1087. var apiError = function (error) {
  1088. console.log("getdecoder url from api error", error);
  1089. }
  1090. request(apiUrl, 'POST', para, '', apiSuccess, apiError);
  1091. });
  1092. } /* 获取播放地址 - 结束 */
  1093. }
  1094. }
  1095. // 格式化回放时间
  1096. function formatRecTime(time, defaultTime) {
  1097. // 用户格式 无需更改 => 20182626T000000Z
  1098. // return time
  1099. // 用户格式需要更改
  1100. //用户时间长度为 14 20181226000000 =》 20181226000000
  1101. // 用户长度为12 201812260000 =》 201812260000 + defaultTime后面2位
  1102. // 用户长度为10 2018122600 =》 201812260000 + defaultTime后面4位
  1103. // 用户长度为8 20181226 =》 201812260000 + defaultTime后面6位
  1104. // 结果 20181226000000 14位
  1105. // 插入 TZ
  1106. var reg = /^[0-9]{8}T[0-9]{6}Z$/;
  1107. if (reg.test(time)) { // 用户格式 无需更改 => 20182626T000000Z
  1108. return time;
  1109. } else if (/[0-9]{8,14}/.test(time)) {
  1110. var start = 6 - (14 - time.length);
  1111. var end = defaultTime.length;
  1112. var standardTime = time + defaultTime.substring(start, end);
  1113. return standardTime.slice(0, 8) + 'T' + standardTime.slice(8) + 'Z';
  1114. } else {
  1115. throw new Error('回放时间格式有误,请确认');
  1116. }
  1117. }
  1118. function reRormatRecTime(time) {
  1119. var year = time.slice(0, 4);
  1120. var month = time.slice(4, 6);
  1121. var day = time.slice(6, 8);
  1122. var hour = time.slice(9, 11);
  1123. var minute = time.slice(11, 13);
  1124. var second = time.slice(13, 15);
  1125. var date = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
  1126. if (_this.opt.domain !== 'open') {
  1127. return new Date(date.replace(/-/g, '/')).getTime() + (8 * 60*60*1000);
  1128. }
  1129. return new Date(date.replace(/-/g, '/')).getTime();
  1130. }
  1131. };
  1132. // 尝试播放
  1133. EZUIPlayer.prototype.tryPlay = function (playParams) {
  1134. this.log("开始尝试播放,播放配置参数为:");
  1135. this.log(playParams);
  1136. var _this = this;
  1137. // JSDecoder 播放
  1138. if (playParams && typeof playParams === 'object' && playParams.decoderPath) {
  1139. /** 初始化Decoder */
  1140. // this.initDecoder(playParams);
  1141. // 自动播放
  1142. // if(playParams.autoplay){
  1143. // console.log('配置了自动播放');
  1144. // setTimeout(function(){
  1145. // _this.play();
  1146. // },2000)
  1147. // }
  1148. } else {
  1149. this.opt.currentSource = playParams;
  1150. var me = this;
  1151. // 如果是HLS地址
  1152. if (/\.m3u8/.test(playParams)) {
  1153. // 如果是手机浏览器环境,或者原生支持HLS播放的,直接使用video标签播放
  1154. // 否则尝试使用hls.js播放,
  1155. // 最后使用flash
  1156. if (isMobile || isNativeSupportHls) {
  1157. this.log('使用原生video');
  1158. this.video.style.heght = this.opt.height = Number(this.opt.width.replace(/px$/g, '')) * 9 / 16 + 'px';
  1159. this.initVideoEvent();
  1160. } else {
  1161. var isPlayUrlHttps = playParams.indexOf('https') !== -1;
  1162. if (isHttps && !isPlayUrlHttps) { //https网站,http视频源安全问题需要flash播放
  1163. addJs(ckplayerJS, function () {
  1164. me.initCKPlayer();
  1165. });
  1166. } else {
  1167. addJs(hlsJS, function () {
  1168. isSupportHls = Hls.isSupported();
  1169. if (isSupportHls) {
  1170. me.log('使用hls.js');
  1171. me.initHLS(playParams);
  1172. } else {
  1173. useFlash = true;
  1174. me.log('2 使用flash');
  1175. addJs(ckplayerJS, function () {
  1176. me.initCKPlayer();
  1177. });
  1178. }
  1179. });
  1180. }
  1181. }
  1182. } else if (/^rtmp:/.test(playParams)) {
  1183. if (isMobile) {
  1184. this.opt.cur++;
  1185. this.tryPlay(playParams);
  1186. return;
  1187. } else {
  1188. addJs(ckplayerJS, function () {
  1189. me.initCKPlayer(playParams);
  1190. });
  1191. }
  1192. } else if (/^wss:|^ws:/.test(playParams)) {
  1193. /*
  1194. * WS协议的JSMpeg的不支持IE11以下的版本
  1195. * 开放平台官网不支持IE8打开,所以官网上面不兼容两个人版本IE9 ,和IE10
  1196. *
  1197. * */
  1198. if (!ltIE11()) {
  1199. addJs(mpegJS, function () {
  1200. me.initJSmpeg(playParams);
  1201. });
  1202. } else {
  1203. alert('WS协议不支持Ie11以下的浏览器!请使用IE11,或者更高版本的浏览器');
  1204. return;
  1205. }
  1206. } else if (/\.flv/.test(this.opt.currentSource)) {
  1207. addJs(flv_js, function () {
  1208. me.log("使用flv.js播放");
  1209. me.initflv();
  1210. });
  1211. }
  1212. }
  1213. };
  1214. // 初始化hls.js
  1215. EZUIPlayer.prototype.initHLS = function (hlsURL) {
  1216. var me = this;
  1217. var hls = new Hls({ defaultAudioCodec: 'mp4a.40.2' }); // 萤石设备默认使用 AAC LC 音频编码
  1218. hls.loadSource(hlsURL);
  1219. hls.attachMedia(this.video);
  1220. hls.on(Hls.Events.MANIFEST_PARSED, function () {
  1221. if (me.opt.autoplay) {
  1222. me.video.play();
  1223. }
  1224. me.initVideoEvent();
  1225. });
  1226. hls.on(Hls.Events.ERROR, function (event, data) {
  1227. if (data.fatal) {
  1228. switch (data.type) {
  1229. case Hls.ErrorTypes.NETWORK_ERROR:
  1230. // try to recover network error
  1231. console.log("fatal network error encountered, try to recover");
  1232. hls.startLoad();
  1233. break;
  1234. case Hls.ErrorTypes.MEDIA_ERROR:
  1235. console.log("fatal media error encountered, try to recover");
  1236. hls.recoverMediaError();
  1237. break;
  1238. default:
  1239. // cannot recover
  1240. hls.destroy();
  1241. break;
  1242. }
  1243. }
  1244. });
  1245. this.hls = hls;
  1246. };
  1247. // 初始化ckplayer
  1248. EZUIPlayer.prototype.initCKPlayer = function (url) {
  1249. this.log('ckplayer初始化');
  1250. var me = this;
  1251. var events = {
  1252. 'play': function () { me.emit('play') },
  1253. 'pause': function () { me.emit('pause') },
  1254. 'error': function () { me.emit('error') }
  1255. };
  1256. window.ckplayer_status = function () {
  1257. me.log(arguments);
  1258. events[arguments[0]] && events[arguments[0]]();
  1259. };
  1260. // 新增相同id的div标签,然后删除video标签
  1261. this.videoFlash = document.createElement('DIV');
  1262. this.video.parentNode.replaceChild(this.videoFlash, this.video);
  1263. this.video = this.videoFlash;
  1264. this.videoFlash.id = this.opt.parentId;
  1265. var flashvars = null;
  1266. // 如果rtmp服务器环境设置了视频暂停则断开链接
  1267. // 需要修改ckplayer.js setup参数第30个值
  1268. // 在播放暂停后点击播放是否采用重新链接的方式
  1269. if (/^rtmp/.test(this.opt.currentSource)) {
  1270. flashvars = {
  1271. f: this.opt.currentSource,
  1272. c: 0,
  1273. p: this.opt.autoplay ? 1 : 0,
  1274. i: this.opt.poster,
  1275. lv: 1,
  1276. loaded: 'loadHandler'
  1277. };
  1278. } else if (/\.m3u8/.test(this.opt.currentSource)) {
  1279. flashvars = {
  1280. s: 4, // 4-使用swf视频流插件播放
  1281. f: m3u8SWF,
  1282. a: this.opt.currentSource,
  1283. c: 0, // 0-使用ckplayer.js的配置 1-使用ckplayer.xml的配置
  1284. lv: 1, // 1-直播 0-普通方式
  1285. p: this.opt.autoplay ? 1 : 0, // 1-默认播放 0-默认暂停
  1286. i: this.opt.poster,
  1287. loaded: 'loadHandler'
  1288. };
  1289. } else {
  1290. flashvars = {
  1291. f: this.opt.currentSource,
  1292. c: 0,
  1293. p: 1,
  1294. loaded: 'loadHandler'
  1295. };
  1296. }
  1297. var params = { bgcolor: '#FFF', allowFullScreen: true, allowScriptAccess: 'always', wmode: 'transparent' };
  1298. this.flashId = this.opt.parentId + 'flashId';
  1299. window.CKobject.embedSWF(ckplayerSWF, this.opt.parentId, this.flashId, this.opt.width, this.opt.height, flashvars, params);
  1300. };
  1301. EZUIPlayer.prototype.initVideoEvent = function () {
  1302. var me = this;
  1303. var EVENT = {
  1304. 'loadstart': function (e) {
  1305. me.log('loadstart...当浏览器开始查找音频/视频时...');
  1306. me.emit('loadstart', e);
  1307. },
  1308. 'durationchange': function (e) {
  1309. me.log('durationchange...当音频/视频的时长已更改时...');
  1310. me.emit('durationchange', e);
  1311. },
  1312. 'loadedmetadata': function (e) {
  1313. me.log('loadedmetadata...当浏览器已加载音频/视频的元数据时...');
  1314. me.emit('loadedmetadata', e);
  1315. },
  1316. 'loadeddata': function (e) {
  1317. me.log('loadeddata...当浏览器已加载音频/视频的当前帧时...');
  1318. me.emit('loadeddata', e);
  1319. },
  1320. 'progress': function (e) {
  1321. me.log('progress...当浏览器正在下载音频/视频时...');
  1322. me.emit('progress', e);
  1323. },
  1324. 'canplay': function (e) {
  1325. me.log('canplay...当浏览器可以播放音频/视频时...');
  1326. me.emit('canplay', e);
  1327. },
  1328. 'canplaythrough': function (e) {
  1329. me.log('canplaythrough...当浏览器可在不因缓冲而停顿的情况下进行播放时...');
  1330. me.emit('canplaythrough', e);
  1331. },
  1332. 'abort': function (e) {
  1333. me.log('abort...当音频/视频的加载已放弃时...');
  1334. me.emit('abort', e);
  1335. },
  1336. 'emptied': function (e) {
  1337. me.log('emptied...当目前的播放列表为空时...');
  1338. me.emit('emptied', e);
  1339. },
  1340. 'ended': function (e) {
  1341. me.log('ended...当目前的播放列表已结束时...');
  1342. me.emit('ended', e);
  1343. },
  1344. 'pause': function (e) {
  1345. me.log('pause...当音频/视频已暂停时...');
  1346. me.emit('pause', e);
  1347. },
  1348. 'play': function (e) {
  1349. me.log('play...当音频/视频已开始或不再暂停时...');
  1350. me.emit('play', e);
  1351. },
  1352. 'playing': function (e) {
  1353. me.log('playing...当音频/视频在已因缓冲而暂停或停止后已就绪时...');
  1354. me.emit('playing', e);
  1355. },
  1356. 'ratechange': function (e) {
  1357. me.log('ratechange...当音频/视频的播放速度已更改时...');
  1358. me.emit('ratechange', e);
  1359. },
  1360. 'seeked': function (e) {
  1361. me.log('seeked...当用户已移动/跳跃到音频/视频中的新位置时...');
  1362. me.emit('seeked', e);
  1363. },
  1364. 'seeking': function (e) {
  1365. me.log('seeking...当用户开始移动/跳跃到音频/视频中的新位置时...');
  1366. me.emit('seeking', e);
  1367. },
  1368. 'stalled': function (e) {
  1369. me.log('stalled...当浏览器尝试获取媒体数据,但数据不可用时...');
  1370. me.emit('stalled', e);
  1371. },
  1372. 'suspend': function (e) {
  1373. me.log('suspend...当浏览器刻意不获取媒体数据时...');
  1374. me.emit('suspend', e);
  1375. if (me.opt.autoplay) {
  1376. me.video.play();
  1377. }
  1378. },
  1379. 'timeupdate': function (e) {
  1380. //me.log('timeupdate...当目前的播放位置已更改时...');
  1381. me.emit('timeupdate', e);
  1382. },
  1383. 'volumechange': function (e) {
  1384. me.log('volumechange...当音量已更改时...');
  1385. me.emit('volumechange', e);
  1386. },
  1387. 'waiting': function (e) {
  1388. me.log('waiting...当视频由于需要缓冲下一帧而停止...');
  1389. me.emit('waiting', e);
  1390. },
  1391. 'error': function (e) {
  1392. me.log('error...当在音频/视频加载期间发生错误时...');
  1393. me.emit('error', e);
  1394. }
  1395. };
  1396. for (var i in EVENT) {
  1397. this.video.addEventListener(i, EVENT[i], false);
  1398. }
  1399. ios11Hack(this.video);
  1400. };
  1401. EZUIPlayer.prototype.initJSmpeg = function (jsmpegUrl) {
  1402. this.canvasEle = document.createElement('canvas');
  1403. this.canvasEle.style.width = this.opt.width;
  1404. this.canvasEle.style.height = this.opt.height;
  1405. this.video.parentNode.replaceChild(this.canvasEle, this.video);
  1406. this.canvasEle.id = this.opt.parentId;
  1407. var player;
  1408. if (player && player.destroy) {
  1409. player.destroy();
  1410. }
  1411. player = new JSMpeg.Player(jsmpegUrl, { canvas: this.canvasEle });
  1412. this.JSmpeg = player;
  1413. };
  1414. EZUIPlayer.prototype.initflv = function () {
  1415. if (flvjs.isSupported()) {
  1416. var player = this.video;
  1417. var hasControls = player.getAttribute('controls');
  1418. if (!hasControls) {
  1419. player.setAttribute('controls', true);
  1420. }
  1421. var flvPlayer = flvjs.createPlayer({
  1422. type: 'flv',
  1423. url: this.opt.currentSource,
  1424. isLive: true,
  1425. }, {
  1426. enableStashBuffer: true,
  1427. stashInitialSize: 128,
  1428. enableWorker: true
  1429. });
  1430. flvPlayer.attachMediaElement(player);
  1431. flvPlayer.load();
  1432. flvPlayer.play();
  1433. } else {
  1434. this.log("浏览器不支持flv播放");
  1435. throw new Error('浏览器不支持flv播放');
  1436. return;
  1437. }
  1438. this.flv = flvPlayer;
  1439. };
  1440. EZUIPlayer.prototype.openFlvFrameTrace = function (thresholdSecond) {
  1441. if(!thresholdSecond) {
  1442. thresholdSecond = 3; // 默认为3秒
  1443. }
  1444. var flvPlayer = this.flv;
  1445. var videoElement = this.video;
  1446. // 延时倍速追加
  1447. flvPlayer.flvFrameTrace = setInterval(function(){
  1448. if(flvPlayer.buffered.length) {
  1449. var end = flvPlayer.buffered.end(0);
  1450. var diff = end - flvPlayer.currentTime;
  1451. // console.log("buffered.length2",flvPlayer.buffered.length);
  1452. console.log("flvPlayer.buffered.end(0)",flvPlayer.buffered.end(0));
  1453. if(diff > thresholdSecond && videoElement.playbackRate === 1) { // 时差超过3秒
  1454. //启用2倍速播放
  1455. console.log("启用2倍速播放",end,flvPlayer.currentTime,diff,(diff > thresholdSecond))
  1456. videoElement.playbackRate = 2; // 倍速播放
  1457. // flvPlayer.currentTime = (flvPlayer.buffered.end(0) - 1);
  1458. } else if (diff < thresholdSecond && videoElement.playbackRate === 2 ) {
  1459. //启用1倍速度播放
  1460. console.log("启用1倍速播放",end,flvPlayer.currentTime,diff,(diff > thresholdSecond))
  1461. videoElement.playbackRate = 1; // 倍速播放
  1462. }
  1463. }
  1464. },2000);
  1465. }
  1466. EZUIPlayer.prototype.closeFlvFrameTrace = function() {
  1467. var flvPlayer = this.flv;
  1468. if(flvPlayer.flvFrameTrace) {
  1469. this.video.playbackRate = 1;
  1470. clearInterval(flvPlayer.flvFrameTrace);
  1471. }
  1472. }
  1473. EZUIPlayer.prototype.rePlay = function (playParams) {
  1474. this.loadingStart();
  1475. // _this.loadingSet(0,{text:'获取设备播放地址'})
  1476. var _this = this;
  1477. var getRealUrl = this.getRealUrl(playParams);
  1478. /**是否自动播放 */
  1479. if (isPromise(getRealUrl)) {
  1480. getRealUrl.then(function (data) {
  1481. _this.play(playParams);
  1482. })
  1483. .catch(function (err) {
  1484. console.log("播放错误", err)
  1485. });
  1486. }
  1487. }
  1488. EZUIPlayer.prototype.play = function (data) {
  1489. if (!!window['CKobject']) {
  1490. this.opt.autoplay = true;
  1491. this.initCKPlayer();
  1492. } else if (!!this.video) { // video播放 包含flv, hls
  1493. if (!!this.hls) { // hls开始播放依赖 this.hls
  1494. this.opt.autoplay = true;
  1495. this.hls.startLoad();
  1496. this.video.play();
  1497. } else if (!!this.JSmpeg) {
  1498. this.JSmpeg.play();
  1499. } else { // 其他开始播放使用原生video
  1500. this.opt.autoplay = true;
  1501. this.video.play();
  1502. }
  1503. } else if (!!this.jSPlugin) {
  1504. this.loadingStart(0);
  1505. var playParams = this.playParams;
  1506. var audioId = 0
  1507. if(playParams && playParams.audioId){
  1508. audioId = playParams.audioId;
  1509. }else if(playParams && playParams.audioId === -1){
  1510. audioId = undefined;
  1511. }
  1512. if ( typeof data === 'string'){
  1513. playParams.url = data;
  1514. }else if(typeof data === 'object'){
  1515. playParams = Object.assign(playParams,data);
  1516. }
  1517. var _this = this;
  1518. var playPromise = new Promise(function(resolve, reject){
  1519. var getRealUrl = _this.getRealUrl(playParams);
  1520. getRealUrl.then(function () {
  1521. function getPlayParams(url) {
  1522. var websocketConnectUrl = url.split('?')[0].replace('/live', '').replace('/playback', '');
  1523. // console.log("playParams,",playParams,playParams.env.wsUrl)
  1524. if(playParams && playParams.env && playParams.env.wsUrl){
  1525. websocketConnectUrl= playParams.env.wsUrl;
  1526. }
  1527. console.log("_this.opt.sources.", _this.opt.sources)
  1528. var websocketStreamingParam = (url.indexOf('/live') === -1 ? (url.indexOf('cloudplayback') !== -1 ? '/cloudplayback?' : '/playback?') : '/live?') + url.split('?')[1];
  1529. if(playParams.websocketParams) {
  1530. Object.keys(playParams.websocketParams).map(function(item){
  1531. websocketStreamingParam += ("&"+ item +"=" + playParams.websocketParams[item]);
  1532. })
  1533. }
  1534. // 本地回放仅支持主码流 - 2019-11-05 修订
  1535. if (websocketStreamingParam.indexOf('/playback') !== -1) {
  1536. websocketStreamingParam = websocketStreamingParam.replace("stream=2", 'stream=1');
  1537. }
  1538. // 本地回放仅支持主码流
  1539. return { websocketConnectUrl: websocketConnectUrl, websocketStreamingParam: websocketStreamingParam }
  1540. }
  1541. _this.opt.sources.forEach(function (item, index) {
  1542. if (getQueryString('dev', item) || item.indexOf('ws') !== -1) {
  1543. _this.log("开始播放, 第" + (index + 1) + '路,' + '地址:' + item);
  1544. _this.loadingSet(index, { text: _this.opt.domain !== 'open' ? 'Ready to play...' : '准备播放...', color: '#fff' })
  1545. // 设置秘钥 - 如果地址中包含秘钥参数,播放前配置到JSPlugin对应实例中
  1546. var validateCode = getQueryString('checkCode', item);
  1547. if (validateCode) {
  1548. _this.log('设置秘钥,视频路数:' + (index + 1) + '验证码:' + validateCode)
  1549. _this.jSPlugin.JS_SetSecretKey(index, validateCode);
  1550. }
  1551. var playST = new Date().getTime();
  1552. var wsUrl = ''
  1553. var wsParams = ''
  1554. wsUrl = getPlayParams(item).websocketConnectUrl;
  1555. wsParams = {
  1556. playURL: getPlayParams(item).websocketStreamingParam
  1557. }
  1558. _this.jSPlugin.JS_Play(wsUrl, wsParams, index).then(function () {
  1559. _this.log('播放成功,当前播放第' + (index + 1) + '路');
  1560. _this.loadingSet(index, { text: _this.opt.domain !== 'open' ? 'Played successfully...' : '播放成功...' });
  1561. //单次播放日志上报
  1562. ezuikitDclog({
  1563. systemName: PERFORMANCE_EZUIKIT,
  1564. bn: 2,
  1565. browser: JSON.stringify(getBrowserInfo()),
  1566. duration: new Date().getTime() - playST,
  1567. rt: 200,
  1568. })
  1569. // 播放成功
  1570. ezuikitDclog({
  1571. systemName: PERFORMANCE_EZUIKIT,
  1572. bn: 99,
  1573. browser: JSON.stringify(getBrowserInfo()),
  1574. duration: new Date().getTime() - playStartTime,
  1575. rt: 200,
  1576. })
  1577. _this.loadingEnd(index);
  1578. // 默认开启声音
  1579. // 默认开启第一路声音
  1580. if (typeof(audioId) !== "undefined" && audioId === index) {
  1581. _this.log("默认开启第1路声音");
  1582. setTimeout(function () {
  1583. var openSoundRT = _this.openSound(0);
  1584. if (isPromise(openSoundRT)) {
  1585. openSoundRT.then(function(){
  1586. _this.log('开启声音成功');
  1587. })
  1588. .catch(function(err){
  1589. _this.log('开启声音失败', 'error');
  1590. })
  1591. }else if(openSoundRT == 0) {
  1592. _this.log('开启声音成功', data)
  1593. }else {
  1594. _this.log('开启声音失败', 'error')
  1595. }
  1596. console.log("openSoundRT", openSoundRT)
  1597. }, 100)
  1598. }
  1599. // 播放成功回调
  1600. if (playParams && playParams.handleSuccess) {
  1601. playParams.handleSuccess();
  1602. }
  1603. if(_this.playControls){
  1604. _this.playControls.setPlayStatus(1)
  1605. }
  1606. if ((index + 1) === _this.opt.sources.length) {
  1607. resolve({code:0})
  1608. }
  1609. // 播放成功日志上报
  1610. var PlTp = 1;
  1611. if (playParams && playParams.url) {
  1612. if (playParams.url.indexOf('rec') !== -1) {
  1613. PlTp = 2;
  1614. }
  1615. }
  1616. dclog({
  1617. systemName: PLAY_MAIN,
  1618. playurl: encodeURIComponent(item),
  1619. Time: (new Date()).Format('yyyy-MM-dd hh:mm:ss.S'),
  1620. Enc: 0, // 0 不加密 1 加密
  1621. PlTp: PlTp, // 1 直播 2 回放
  1622. Via: 2, // 2 服务端取流
  1623. ErrCd: 0,
  1624. OpId: uuid(),
  1625. Cost: (new Date()).getTime() - _this.initTime, // 毫秒数
  1626. Serial: getQueryString('dev', item),
  1627. Channel: getQueryString('chn', item),
  1628. });
  1629. }, function (err) {
  1630. _this.log('播放失败' + JSON.stringify(err), 'error');
  1631. var errorInfo = JSON.parse(_this.errorCode).find(function (item) { return item.detailCode.substr(-4) == err.oError.errorCode });
  1632. ezuikitDclog({
  1633. systemName: PERFORMANCE_EZUIKIT,
  1634. bn: 2,
  1635. browser: JSON.stringify(getBrowserInfo()),
  1636. duration: new Date().getTime() - playStartTime,
  1637. rt: err.oError ? err.oError.errorCode : 500,
  1638. msg: errorInfo ? errorInfo.description : (_this.opt.domain !== 'open' ? 'Other error' : '其他错误')
  1639. })
  1640. var msg = errorInfo ? errorInfo.description : (_this.opt.domain !== 'open' ? 'Other error' : '其他错误');
  1641. _this.loadingSet(index, { text: msg, color: 'red' });
  1642. dclog({
  1643. systemName: PLAY_MAIN,
  1644. playurl: encodeURIComponent(item),
  1645. cost: -1,
  1646. ErrCd: (err && err.oError && err.oError.errorCode && (err.oError.errorCode + "").substr(-4)) || -1,
  1647. Via: 2,
  1648. OpId: uuid(),
  1649. Serial: getQueryString('dev', item),
  1650. Channel: getQueryString('chn', item),
  1651. });
  1652. if (playParams && playParams.handleError) {
  1653. var errorInfo = JSON.parse(_this.errorCode).find(function (item) { return item.detailCode.substr(-4) == err.oError.errorCode })
  1654. playParams.handleError({ retcode: err.oError.errorCode, msg: errorInfo ? errorInfo.description : (_this.opt.domain !== 'open' ? 'Other error' : '其他错误') });
  1655. }
  1656. if ((index + 1) === _this.opt.sources.length) {
  1657. resolve({ retcode: err.oError.errorCode, msg: errorInfo ? errorInfo.description : (_this.opt.domain !== 'open' ? 'Other error' : '其他错误') })
  1658. }
  1659. })
  1660. } else {
  1661. if (isJSON(item) && JSON.parse(item).msg) {
  1662. _this.loadingSet(index, { text: JSON.parse(item).msg, color: 'red' })
  1663. }
  1664. }
  1665. })
  1666. })
  1667. })
  1668. return playPromise;
  1669. }
  1670. };
  1671. EZUIPlayer.prototype.initDecoder = function (playParams) {
  1672. this.opt.id = playParams.id;
  1673. this.log("初始化解码器---开始");
  1674. var _this = this;
  1675. _this.opt.domain = playParams.url.split(",")[0].match(/ezopen:\/\/(\S*)\.(ys7|ezviz)\.com/)[1];
  1676. if (playParams.env) {
  1677. var environmentParams = playParams.env;
  1678. domain = environmentParams.domain;
  1679. if(domain.match(/https:\/\/(\S*)\.ezviz(\S*)\.com/)) {
  1680. _this.opt.domain = domain.match(/https:\/\/(\S*)\.ezviz(\S*)\.com/)[1];
  1681. }
  1682. }
  1683. if( _this.opt.domain.indexOf("@")!== -1) {
  1684. _this.opt.domain = _this.opt.domain.split("@")[1];
  1685. }
  1686. var initDecoderDurationST = new Date().getTime();
  1687. // DOM id
  1688. function initDecoder(resolve, reject) {
  1689. var jsPluginPath = playParams.decoderPath + '/js/jsPlugin-1.2.0.min.js?v=20211012';
  1690. if(playParams.decoderVersion) {
  1691. var jsPluginPath = playParams.decoderPath + '/js/versions/' + playParams.decoderVersion + '/jsPlugin-1.2.0.min.js?v=20211012';
  1692. if(playParams.decoderVersion === "v4.0") {
  1693. addJs( playParams.decoderPath + '/js/versions/' + playParams.decoderVersion +'/AudioRenderer.js',()=>{})
  1694. addJs( playParams.decoderPath + '/js/versions/' + playParams.decoderVersion +'/SuperRender_10.js',()=>{})
  1695. }
  1696. }
  1697. document.getElementById(playParams.id).style.width = (playParams.width || 600) + 'px';
  1698. document.getElementById(playParams.id).style.height= (playParams.height || 400) + 'px';
  1699. /** 初始化解码器 */
  1700. addJs(jsPluginPath, function () {
  1701. _this.log("下载解码器完成,开始初始化");
  1702. /* decoder 属性配置 */
  1703. _this.jSPlugin = new JSPlugin({
  1704. szId: playParams.id,
  1705. iType: 2,
  1706. // iMode: 0,
  1707. iWidth: playParams.width || 600,
  1708. iHeight: playParams.height || 400,
  1709. iMaxSplit: Math.ceil(Math.sqrt(playParams.url.split(",").length)),
  1710. iCurrentSplit: playParams.splitBasis || Math.ceil(Math.sqrt(playParams.url.split(",").length)),
  1711. szBasePath: playParams.decoderVersion ? ( playParams.decoderPath + '/js/versions/' + playParams.decoderVersion) : (playParams.decoderPath + '/js'),
  1712. oStyle: {
  1713. border: "none",
  1714. background: "#000000"
  1715. }
  1716. });
  1717. _this.jSPlugin.EventCallback = {
  1718. loadEventHandler: function () {
  1719. },
  1720. zoomEventResponse: function (/*iMode, aPoint*/) { //电子放大回调
  1721. },
  1722. windowEventSelect: function (iWndIndex) { //插件选中窗口回调
  1723. },
  1724. pluginErrorHandler: function (iWndIndex, iErrorCode, oError) { //插件错误回调
  1725. console.log(iWndIndex, iErrorCode, oError);
  1726. if(iErrorCode === 1003) {
  1727. if (playParams && playParams.handleError) {
  1728. playParams.handleError({ retcode: iErrorCode, msg: oError ? oError : '连接断开,请重试' });
  1729. if(playParams.url.indexOf("alarmId")!== -1) {
  1730. _this.loadingSetIcon(iWndIndex, 'retry');
  1731. _this.loadingSet(iWndIndex, { text: '播放结束' });
  1732. } else {
  1733. _this.loadingSetIcon(iWndIndex, 'retry');
  1734. _this.loadingSet(iWndIndex, { text: '连接断开,请重试' });
  1735. }
  1736. }
  1737. }
  1738. },
  1739. windowEventOver: function (iWndIndex) {
  1740. },
  1741. windowEventOut: function (iWndIndex) {
  1742. },
  1743. windowEventUp: function (iWndIndex) {
  1744. },
  1745. windowFullCcreenChange: function (bFull) {
  1746. },
  1747. firstFrameDisplay: function (iWndIndex, iWidth, iHeight) {
  1748. },
  1749. performanceLack: function () {
  1750. },
  1751. mouseEvent: function (iMouseEventType, iMouseX, iMouseY) {
  1752. }
  1753. }
  1754. _this.jSPlugin.oEventCallback = _this.jSPlugin.EventCallback;
  1755. // _this.jSPlugin.JS_SetWindowControlCallback({
  1756. // windowEventSelect: function (iWndIndex) { //插件选中窗口回调
  1757. // iWind = iWndIndex;
  1758. // },
  1759. // pluginErrorHandler: function (iWndIndex, iErrorCode, oError) { //插件错误回调
  1760. // console.log(iWndIndex, iErrorCode, oError);
  1761. // if (playParams && playParams.handleError) {
  1762. // playParams.handleError({ retcode: iErrorCode, msg: oError ? oError : '播放失败,请重试' });
  1763. // if(playParams.url.indexOf("alarmId")!== -1) {
  1764. // _this.loadingSetIcon(iWndIndex, 'retry');
  1765. // _this.loadingSet(iWndIndex, { text: '播放结束' });
  1766. // } else {
  1767. // _this.loadingSetIcon(iWndIndex, 'retry');
  1768. // _this.loadingSet(iWndIndex, { text: '播放失败,请重试' });
  1769. // }
  1770. // }
  1771. // },
  1772. // });
  1773. // _this.jSPlugin.JS_SetOptions({
  1774. // //bSupportSound: false //是否支持音频,默认支持
  1775. // bSupporDoubleClickFull: typeof playParams.isSupporDoubleClickFull === 'undefined' ? true : playParams.isSupporDoubleClickFull, //是否双击窗口全屏,默认支持
  1776. // //bOnlySupportMSE: true //只支持MSE
  1777. // bOnlySupportJSDecoder: (typeof playParams.useMSE === 'undefined' || playParams.useMSE === false) ? true : false, //是否强制使用jsdecoder
  1778. // }).then(function () {
  1779. // console.log("JS_SetOptions");
  1780. // });
  1781. // 注册全屏事件
  1782. // window.onresize = function () {
  1783. // var width = document.documentElement.clientWidth;
  1784. // var height = document.documentElement.clientHeight;
  1785. // _this.jSPlugin.JS_Resize(width || playParams.width || 600, height || playParams.height || 400);
  1786. // }
  1787. _this.log("初始化解码器----完成");
  1788. if(playParams.controls && playParams.controls.length >0) {
  1789. var videoControlsJsPath = playParams.decoderPath + '/deviceControls/videoControls.js';
  1790. var videoControlsCssPath = playParams.decoderPath + '/deviceControls/deviceControls.css';
  1791. addJs(videoControlsJsPath,function(){
  1792. addCss(videoControlsCssPath,function(){
  1793. var VideoControlsDOM = document.createElement('div')
  1794. VideoControlsDOM.id="video-controls-container";
  1795. VideoControlsDOM.className="video-controls-container";
  1796. document.getElementById(playParams.id).style.position = 'relative';
  1797. document.getElementById(playParams.id).appendChild(VideoControlsDOM)
  1798. var setPlayStatusCallBack = function(status) {
  1799. console.log("setPlayStatusCallBack",status);
  1800. if(status === 1){
  1801. _this.play();
  1802. // setTimeout(()=>{
  1803. // _this.openSound(0);
  1804. // },3000);
  1805. }else {
  1806. _this.closeSound(0);
  1807. _this.stop()
  1808. }
  1809. }
  1810. var setVoiceStatusCallBack = function(status) {
  1811. console.log("setVoiceStatusCallBack",status);
  1812. if(status === 1){
  1813. console.log("图标开启声音");
  1814. _this.openSound(0);
  1815. }else {
  1816. console.log("图标关闭声音")
  1817. _this.closeSound(0)
  1818. }
  1819. }
  1820. var setHdStatusCallBack = function(status) {
  1821. console.log("setHdStatusCallBack",status);
  1822. if(status === 1){
  1823. console.log("图标换高清");
  1824. _this.closeSound(0);
  1825. var stopPromise = _this.stop();
  1826. stopPromise.then(function(){
  1827. _this.play({
  1828. url: playParams.url.replace('.live','.hd.live')
  1829. })
  1830. })
  1831. }else {
  1832. _this.closeSound(0);
  1833. var stopPromise = _this.stop();
  1834. stopPromise.then(function(){
  1835. _this.play({
  1836. url: playParams.url.replace('.hd.live','.live')
  1837. })
  1838. })
  1839. }
  1840. }
  1841. var setFullScreenStatusCallBack = function(status){
  1842. var playStatus = _this.playControls.state.playStatus;
  1843. console.log("setFullScreenStatusCallBack",status);
  1844. if(playStatus == 1) {
  1845. _this.fullScreen();
  1846. }
  1847. }
  1848. _this.playControls = new VideoControls({
  1849. id: 'video-controls-container',
  1850. setPlayStatusCallBack: setPlayStatusCallBack,
  1851. setVoiceStatusCallBack:setVoiceStatusCallBack,
  1852. setHdStatusCallBack:setHdStatusCallBack,
  1853. setFullScreenStatusCallBack:setFullScreenStatusCallBack,
  1854. hd: (playParams.url.indexOf('.hd') !== -1 ) ? 1 : 0,
  1855. controls: playParams.controls,
  1856. });
  1857. })
  1858. })
  1859. }
  1860. // 执行一次初始化解码器服务请求上报
  1861. ezuikitDclog({
  1862. systemName: PERFORMANCE_EZUIKIT,
  1863. bn: 1,
  1864. browser: JSON.stringify(getBrowserInfo()),
  1865. duration: new Date().getTime() - initDecoderDurationST,
  1866. rt: 200,
  1867. })
  1868. resolve('200 OK')
  1869. },()=>{
  1870. return !!window.JSPlugin;
  1871. });
  1872. /**
  1873. * 加载错误码
  1874. * 错误码维护平台 - omm管理系统
  1875. */
  1876. var errorCodeLan = 'zh';
  1877. var errorCodePath = playParams.decoderPath + "/js/errorCode.json";
  1878. var errorCodeKey = 'errorCode';
  1879. if(_this.opt.domain !== 'open'){
  1880. errorCodeLan = 'en';
  1881. errorCodePath = playParams.decoderPath + "/js/errorCode-EN.json";
  1882. errorCodeKey = "errorCode-EN"
  1883. }
  1884. function success(data) {
  1885. if (data.code == 200) {
  1886. if (!window.localStorage) {
  1887. return false;
  1888. } else {
  1889. var storage = window.localStorage;
  1890. //写入a字段
  1891. storage[errorCodeKey] = JSON.stringify(data.data);
  1892. _this.errorCode = storage[errorCodeKey];
  1893. }
  1894. }
  1895. }
  1896. if (!window.localStorage) {
  1897. request(
  1898. errorCodePath,
  1899. "get",
  1900. {
  1901. language: 1,
  1902. time: new Date().getTime(),
  1903. appKey: '26810f3acd794862b608b6cfbc32a6b8',
  1904. },
  1905. '',
  1906. success
  1907. );
  1908. } else {
  1909. var storage = window.localStorage;
  1910. var errorCode = storage[errorCodeKey];
  1911. if (!errorCode) {
  1912. request(
  1913. errorCodePath,
  1914. "get",
  1915. {
  1916. language: 1,
  1917. time: new Date().getTime(),
  1918. appKey: '26810f3acd794862b608b6cfbc32a6b8',
  1919. },
  1920. '',
  1921. success
  1922. );
  1923. } else {
  1924. _this.errorCode = storage[errorCodeKey];
  1925. }
  1926. }
  1927. }
  1928. var initDecoderPromise = new Promise(initDecoder);
  1929. return initDecoderPromise;
  1930. }
  1931. EZUIPlayer.prototype.stop = function (i, unDestory) {
  1932. // 执行停止
  1933. this.log("停止播放" + this.opt.currentSource);
  1934. this.opt.autoplay = false;
  1935. if (!!window['CKobject']) {
  1936. //CKobject.getObjectById(this.flashId).destroy();
  1937. this.video.src = ""
  1938. // this.video.remove();
  1939. } else if (!!this.video) {
  1940. if (!!this.hls) { // hls停止依赖this.hls
  1941. // 通过暂停停止播放
  1942. this.video.pause();
  1943. this.video.src = ""
  1944. // 停止取流
  1945. this.hls.stopLoad();
  1946. } else if (!!this.flv) {
  1947. this.flv.pause();
  1948. this.flv.unload();
  1949. this.flv.detachMediaElement();
  1950. this.flv.destroy();
  1951. this.flv = null;
  1952. } else if (!!this.JSmpeg) {
  1953. this.JSmpeg.stop();
  1954. // this.JSmpeg.destroy();
  1955. }
  1956. } else if (!!this.jSPlugin) {
  1957. var _this = this;
  1958. if (typeof i === "undefined") {
  1959. _this.closeSound(0)
  1960. return this.jSPlugin.JS_Stop(0).then(function () {
  1961. _this.log("停止播放成功" + _this.opt.currentSource);
  1962. console.log("stop success");
  1963. // 额外销毁worker
  1964. // _this.jSPlugin.JS_DestroyWorker();
  1965. _this.loadingEnd(0);
  1966. //removeChild(0);
  1967. if(_this.playControls){
  1968. _this.playControls.setPlayStatus(0);
  1969. }
  1970. }, function () {
  1971. _this.log("停止播放失败" + _this.opt.currentSource);
  1972. console.log("stop failed");
  1973. });
  1974. } else {
  1975. return this.jSPlugin.JS_Stop(i).then(function () {
  1976. _this.log("第" + i + "路停止播放成功" + _this.opt.currentSource);
  1977. _this.loadingEnd(i);
  1978. console.log("stop success");
  1979. }, function () {
  1980. _this.log("第" + i + "路停止播放失败" + _this.opt.currentSource);
  1981. _this.loadingEnd(i);
  1982. console.log("stop failed");
  1983. });
  1984. // 额外销毁worker - 多窗口暂不销毁
  1985. // this.jSPlugin.JS_DestroyWorker();
  1986. //removeChild(i);
  1987. }
  1988. }
  1989. };
  1990. EZUIPlayer.prototype.destroy = function (i) {
  1991. this.jSPlugin.JS_DestroyWorker();
  1992. }
  1993. // 获取OSD时间
  1994. // EZUIPlayer.prototype.getOSDTime = function (callback, iWind) {
  1995. // if (!!this.jSPlugin) {
  1996. // this.jSPlugin.JS_GetOSDTime(iWind || 0).then(function (iTime) {
  1997. // callback(iTime * 1000);
  1998. // }, function (err) {
  1999. // console.log("get OSD Time error", err);
  2000. // });
  2001. // } else {
  2002. // throw new Error("Method not support");
  2003. // }
  2004. // }
  2005. // 返回promise的getOSDTime方法
  2006. EZUIPlayer.prototype.getOSDTime = function (wNum) {
  2007. var _this = this;
  2008. if (!!this.jSPlugin) {
  2009. return _this.jSPlugin.JS_GetOSDTime(wNum || 0);
  2010. } else {
  2011. throw new Error("Method not support");
  2012. }
  2013. }
  2014. // 返回promise的getOSDTime方法
  2015. EZUIPlayer.prototype.getVersion = function (wNum) {
  2016. var _this = this;
  2017. if (!!this.jSPlugin) {
  2018. console.log(_this.jSPlugin.JS_GetSdkVersion());
  2019. } else {
  2020. throw new Error("Method not support");
  2021. }
  2022. }
  2023. // 开启声音
  2024. EZUIPlayer.prototype.openSound = function (iWind) {
  2025. if (!!this.jSPlugin) {
  2026. var _this = this;
  2027. var openSoundRT = this.jSPlugin.JS_OpenSound(iWind || 0);
  2028. if (isPromise(openSoundRT)) {
  2029. openSoundRT.then(function(){
  2030. _this.log('开启声音成功');
  2031. if(_this.playControls){
  2032. _this.playControls.setVoiceStatus(1)
  2033. }
  2034. })
  2035. .catch(function(err){
  2036. _this.log('开启声音失败', 'error');
  2037. })
  2038. } else if(openSoundRT === 0 ){
  2039. _this.log('开启声音成功');
  2040. if(_this.playControls){
  2041. _this.playControls.setVoiceStatus(1)
  2042. }
  2043. }else {
  2044. _this.log('开启声音失败', 'error');
  2045. }
  2046. return openSoundRT;
  2047. } else {
  2048. throw new Error("Method not support");
  2049. }
  2050. }
  2051. // 全屏
  2052. EZUIPlayer.prototype.fullScreen = function () {
  2053. if (!!this.jSPlugin) {
  2054. return this.jSPlugin.JS_FullScreenDisplay(1);
  2055. } else {
  2056. throw new Error("Method not support");
  2057. }
  2058. }
  2059. // 关闭声音
  2060. EZUIPlayer.prototype.closeSound = function (iWind) {
  2061. if (!!this.jSPlugin) {
  2062. var _this = this;
  2063. var closeSoundRT = this.jSPlugin.JS_CloseSound(iWind || 0);
  2064. if (isPromise(closeSoundRT)) {
  2065. closeSoundRT.then(function(){
  2066. _this.log('关闭声音成功');
  2067. if(_this.playControls){
  2068. _this.playControls.setVoiceStatus(0)
  2069. }
  2070. })
  2071. .catch(function(err){
  2072. _this.log('关闭声音失败', 'error');
  2073. })
  2074. } else if(closeSoundRT === 0 ){
  2075. _this.log('关闭声音成功');
  2076. if(_this.playControls){
  2077. _this.playControls.setVoiceStatus(0)
  2078. }
  2079. }else {
  2080. _this.log('关闭声音失败', 'error');
  2081. }
  2082. return closeSoundRT;
  2083. } else {
  2084. throw new Error("Method not support");
  2085. }
  2086. }
  2087. // 视频截图
  2088. EZUIPlayer.prototype.capturePicture = function (iWind, pictureName,callback,isUndownload) {
  2089. if (!!this.jSPlugin) {
  2090. return this.jSPlugin.JS_CapturePicture(iWind, pictureName,'JPEG',callback,isUndownload);
  2091. } else {
  2092. throw new Error("Method not support");
  2093. }
  2094. }
  2095. // 开始录像
  2096. EZUIPlayer.prototype.startSave = function (iWind, fileName) {
  2097. if (!!this.jSPlugin) {
  2098. this.log("开始录制录像");
  2099. return this.jSPlugin.JS_StartSave(iWind, fileName)
  2100. } else {
  2101. throw new Error("Method not support");
  2102. }
  2103. }
  2104. // 结束录像
  2105. EZUIPlayer.prototype.stopSave = function (iWind) {
  2106. if (!!this.jSPlugin) {
  2107. return this.jSPlugin.JS_StopSave(iWind);
  2108. this.log("结束录制录像");
  2109. } else {
  2110. throw new Error("Method not support");
  2111. }
  2112. }
  2113. EZUIPlayer.prototype.reSize = function (width, height) {
  2114. if (!!this.jSPlugin) {
  2115. return this.jSPlugin.JS_Resize(width, height);
  2116. } else {
  2117. throw new Error("Method not support");
  2118. }
  2119. }
  2120. EZUIPlayer.prototype.pause = function () {
  2121. this.opt.autoplay = false;
  2122. if (!!window['CKobject']) {
  2123. CKobject.getObjectById(this.flashId).videoPause();
  2124. } else if (!!this.video) {
  2125. if (!!this.JSmpeg) {
  2126. this.JSmpeg.pause();
  2127. } else {
  2128. this.video.pause();
  2129. }
  2130. } else if (!!this.jSPlugin) {
  2131. this.jSPlugin.JS_Pause(0).then(function () {
  2132. }, function () {
  2133. });
  2134. }
  2135. };
  2136. EZUIPlayer.prototype.load = function () {
  2137. if (!!window['CKobject']) {
  2138. // flash load
  2139. } else if (!!this.video) {
  2140. this.video.load();
  2141. }
  2142. };
  2143. // 开启电子放大
  2144. EZUIPlayer.prototype.enableZoom = function (iWind) {
  2145. if (!!this.jSPlugin) {
  2146. return this.jSPlugin.JS_EnableZoom(iWind || 0);
  2147. } else {
  2148. throw new Error("Method not support");
  2149. }
  2150. }
  2151. // 关闭电子放大
  2152. EZUIPlayer.prototype.closeZoom = function (iWind) {
  2153. if (!!this.jSPlugin) {
  2154. return this.jSPlugin.JS_DisableZoom(iWind || 0);
  2155. } else {
  2156. throw new Error("Method not support");
  2157. }
  2158. }
  2159. // 返回promise的getOSDTime方法
  2160. EZUIPlayer.prototype.controlsSwitchDisabled = function (value) {
  2161. if(this.playControls){
  2162. this.playControls.switchDisabled(value)
  2163. }
  2164. }
  2165. // iOS11手机HLS直播在m3u8响应时间过长后不继续请求的hack
  2166. function ios11Hack(video) { var isloadeddata = false; var isPlaying = false; var stalledCount = 0; video.addEventListener('loadeddata', function () { isloadeddata = true; }, false); video.addEventListener('stalled', function () { stalledCount++; if (!isPlaying) { if (stalledCount >= 2 && !isloadeddata) { video.load(); video.play(); isloadeddata = false; isPlaying = false; stalledCount = 0; } } }, false); video.addEventListener('playing', function () { isPlaying = true; }); }
  2167. function ltIE11() { var userAgent = navigator.userAgent; var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; if (isIE) { return true; } else { return false; } }
  2168. var EZUIKit = {
  2169. 'EZUIPlayer': EZUIPlayer,
  2170. };
  2171. // 兼容1.4 以下旧版本
  2172. // var EZUIPlayer = EZuikit.EZUIPlayer;
  2173. if (!noGlobal) {
  2174. window.EZUIKit = EZUIKit;
  2175. // 兼容1.4 以下旧版本
  2176. window.EZUIPlayer = EZUIPlayer;
  2177. }
  2178. return EZUIKit;
  2179. });