'use strict';var sy={TAB:0,Ym:1,Ks:2},ty=function(){return new qb("MediaRouter.CastStreaming.Session.Launch")},uy=function(){return new wb("MediaRouter.CastStreaming.Session.Length")},vy=function(a){Ab("MediaRouter.CastStreaming.Start.Success",a,sy)};var wy=eb("mr.mirror.cast.LogUploader"),yy=function(a,b,c){xy("raw_events.log.gz",a,b,c);return b?"https://crash.corp.google.com/samples?reportid=&q="+encodeURIComponent("UserComments='"+b+"'"):""},xy=function(a,b,c,d){if(0==b.size)wy.info("Trying to upload an empty file to Crash"),d&&d(null);else{var e=new FormData;e.append("prod","Cast");e.append("ver",chrome.runtime.getManifest().version);e.append(a,b);c&&e.append("comments",c);gw("https://clients2.google.com/cr/report",function(f){f=f.target;
var g=null;qw(f)?(g=sw(f),wy.info("Upload to Crash succeeded: "+g)):wy.info("Upload to Crash failed. HTTP status: "+f.Ha());d&&d(g)},"POST",e,void 0,3E4)}};var zy=function(){this.g=0;vm(this)},By=function(){Ay||(Ay=new zy);return Ay},Cy=function(){var a=By(),b={fraction:.01,autoSubmitTimeLimitMillis:6048E5},c=b.autoSubmitTimeLimitMillis,d=Date.now();return a.g&&c&&d-a.g<c?!1:Math.random()<b.fraction};zy.prototype.Ya=function(){return"mirror.cast.LogUtils"};zy.prototype.Ob=function(){return[void 0,{lastAutoSubmitMillis:this.g}]};zy.prototype.Nb=function(){var a=tm(this);this.g=a&&a.lastAutoSubmitMillis||0};var Ay=null;eb("mr.mirror.cast.LogUtils");var Dy={QI:"OFFER",ZA:"ANSWER",GJ:"PRESENTATION",eF:"GET_STATUS",yM:"STATUS_RESPONSE",ZE:"GET_CAPABILITIES",zC:"CAPABILITIES_RESPONSE",yL:"RPC"};var Ey=function(){this.capabilities=this.status=this.g=this.error=this.rpc=this.result=this.type=this.h=this.sessionId=null},Hy=function(a){try{if("string"!==typeof a)throw SyntaxError("Cannot parse non-string as JSON");var b;Fy(JSON.parse(a),function(d){b=Gy(d)},function(){throw Error("non-Object result from JSON parse");});return b}catch(d){var c=d instanceof SyntaxError?"JSON parse error: "+d.message:"Type coercion error: "+d.message}"string"==typeof a?a="a string: "+a:a instanceof ArrayBuffer?
(a=new Uint8Array(a),a="an ArrayBuffer whose base64 is "+btoa(String.fromCharCode.apply(null,a))):a="of invalid data type "+typeof a;throw Error(c+". Input was "+a);},Gy=function(a){var b=new Ey;null!=a.sessionId&&(b.sessionId=String(a.sessionId));Iy(a.seqNum,function(f){b.h=f},function(){throw Error('"seqNum" must be a number');});if("type"in a){for(var c=String(a.type).toUpperCase(),d=n(Object.keys(Dy)),e=d.next();!e.done;e=d.next())if(Dy[e.value]==c){b.type=c;break}if(!b.type)throw Error('not a known message "type"');
}"result"in a&&(b.result=String(a.result));if("rpc"in a){if("string"!==typeof a.rpc)throw Error('"rpc" must be a String containing a base64 payload');b.rpc=new Uint8Array([].concat(p(atob(a.rpc))).map(function(f){return f.charCodeAt(0)}))}Fy(a.error,function(f){b.error=Jy(f)},function(){throw Error('"error" must be an Object');});Fy(a.answer,function(f){b.g=Ky(f)},function(){throw Error('"answer" must be an Object');});Fy(a.status,function(f){b.status=Ly(f)},function(){throw Error('"status" must be an Object');
});Fy(a.capabilities,function(f){b.capabilities=My(f)},function(){throw Error('"capabilities" must be an Object');});return b},Fy=function(a,b,c){void 0!==a&&(a instanceof Object?b(a):c())},Iy=function(a,b,c){void 0!==a&&("number"!==typeof a?c():b(a))},Ny=function(a,b,c){void 0!==a&&(a instanceof Array&&a.every(function(d){return"number"===typeof d})?b(a):c())},Oy=function(a,b,c){void 0!==a&&(a instanceof Array?b(a.map(function(d){return String(d)})):c())},Py=function(){this.C=null;this.g=[];this.h=
[];this.j=this.l=this.m=null},Ky=function(a){var b=new Py;Iy(a.udpPort,function(c){b.C=c},function(){throw Error('"answer.udpPort" must be a number');});Ny(a.sendIndexes,function(c){b.g=c},function(){throw Error('"answer.sendIndexes" must be an array of numbers');});Ny(a.ssrcs,function(c){b.h=c},function(){throw Error('"answer.ssrcs" must be an array of numbers');});"IV"in a&&(b.m=String(a.IV));"receiverGetStatus"in a&&(b.l="true"==String(a.receiverGetStatus).toLowerCase());"castMode"in a&&(b.j=String(a.castMode));
return b},Qy=function(){this.details=this.description=this.code=null},Jy=function(a){var b=new Qy;Iy(a.code,function(c){b.code=c},function(){throw Error('"error.code" must be a number');});"description"in a&&(b.description=String(a.description));Fy(a.details,function(c){b.details=c},function(){throw Error('"error.details" must be an Object');});return b},Ry=function(){this.h=this.g=null},Ly=function(a){var b=new Ry;Iy(a.wifiSnr,function(c){b.g=c},function(){throw Error('"status.wifiSnr" must be a number');
});Ny(a.wifiSpeed,function(c){b.h=c},function(){throw Error('"status.wifiSpeed" must be an array of numbers');});return b},Sy=function(){this.h=this.g=null},My=function(a){var b=new Sy;Oy(a.mediaCaps,function(c){b.g=c},function(){throw Error('"capabilities.mediaCaps" must be an array');});if("keySystems"in a){a=a.keySystems;if(!(a instanceof Array))throw Error('"capabilities.keySystems" must be an array');b.h=a.map(function(c){var d;Fy(c,function(e){d=Ty(e)},function(){throw Error('"capabilities.keySystems" entries must be *Objects');
});return d})}return b},Uy=function(){this.h=this.m=this.C=this.l=this.u=this.g=this.s=this.codecs=this.initDataTypes=this.j=null},Ty=function(a){var b=new Uy;"keySystemName"in a&&(b.j=String(a.keySystemName));Oy(a.initDataTypes,function(c){b.initDataTypes=c},function(){throw Error('"capabilities.initDataTypes" must be an array');});Oy(a.codecs,function(c){b.codecs=c},function(){throw Error('"capabilities.codecs" must be an array');});Oy(a.secureCodecs,function(c){b.s=c},function(){throw Error('"capabilities.secureCodecs" must be an array');
});Oy(a.audioRobustness,function(c){b.g=c},function(){throw Error('"capabilities.audioRobustness" must be an array');});Oy(a.videoRobustness,function(c){b.u=c},function(){throw Error('"capabilities.videoRobustness" must be an array');});"persistentLicenseSessionSupport"in a&&(b.l=String(a.persistentLicenseSessionSupport));"persistentReleaseMessageSessionSupport"in a&&(b.C=String(a.persistentReleaseMessageSessionSupport));"persistentStateSupport"in a&&(b.m=String(a.persistentStateSupport));"distinctiveIdentifierSupport"in
a&&(b.h=String(a.distinctiveIdentifierSupport));return b};var Vy=function(a){this.o=eb("mr.mirror.cast.MessageDispatcher");this.l=a;this.g=null;this.h=new Map;this.j=0},Wy=function(a,b,c){if(a.h.has(b))throw Error("Attempt to multiple-subscribe to the same response type: "+b);a.h.set(b,c);a.j=0;mb(a.o,"Added subscriber for "+b+"-type messages.");a.g||(a.g=nx(a.l),a.g.onMessage=a.C.bind(a))},Xy=function(a,b){a.h.delete(b)&&mb(a.o,function(){return"Removed subscriber of "+b+"-type messages."});0==a.h.size&&a.g&&(a.g.dispose(),a.g=null)};
Vy.prototype.sendMessage=function(a){return this.g?"RPC"==a.type?this.g.sendMessage(a,{namespace:"urn:x-cast:com.google.cast.remoting"}):this.g.sendMessage(a,{namespace:"urn:x-cast:com.google.cast.webrtc"}):Promise.reject(Error("Require at least one subscriber before sending messages."))};
var Yy=function(a,b,c,d,e){var f=null,g=function(){Xy(a,c);null!=f&&(clearTimeout(f),f=null)};try{Wy(a,c,function(h){e(h)&&g()})}catch(h){e(null,h);return}f=setTimeout(function(){g();e(null,Error("timeout"))},d);a.sendMessage(b).catch(function(h){g();e(null,h)})};
Vy.prototype.C=function(a){if(a&&"string"===typeof a.namespace_&&a.namespace_.startsWith("urn:x-cast:com.google.cast.")){do{var b=void 0;try{b=Hy(a.data)}catch(d){b=d.message;break}if(b.type){var c=this.h.get(b.type);if(c)try{c(b);return}catch(d){b="Error thrown during delivery. Response was: "+(JSON.stringify(b)+". Error from subscriber callback was: ")+(d.message+".")}else b="Message was ignored: "+JSON.stringify(b)}else b="Message did not include response type: "+JSON.stringify(b)}while(0);10>
this.j?this.o.L(b):mb(this.o,b);++this.j}};var Zy=function(){this.g=Promise.resolve(1)},az=function(a,b,c){return $y(a,function(d){return d==b},c)},bz=function(a,b){var c=[3,4];return $y(a,function(d){return-1!=c.indexOf(d)},b)},cz=function(a,b){a.g=a.g.catch(function(){return 1});return $y(a,function(){return!0},b)},$y=function(a,b,c){var d,e,f=new Promise(function(g,h){d=g;e=h});a.g=a.g.then(function(g){if(!b(g))return e(Error("Operation requires a different starting checkpoint than "+g)),Promise.resolve(g);var h=new dz(g);try{var m=c(h)}catch(q){m=
Promise.reject(q)}return m.then(function(q){return d(q)},function(q){return e(q)}).then(function(){if(null===h.g)throw Error("A prior operation that started at "+(g+" did not complete."));return h.g})},function(g){e(g);throw g;});return f},dz=function(a){this.h=a;this.g=null},ez=function(a,b){a.g="number"===typeof b?b:a.h};var fz=chrome.cast.streaming,gz=eb("mr.mirror.cast.StreamingLaunchWorkflow"),iz=function(a,b,c,d,e){this.N=a.sessionId;this.F=a.gi;this.W=a.We;this.j=b;this.V=c;this.K=d;this.Y=hz(e,"onAnswer",this.F);this.Ab=hz(e,"onSessionStop",this.F);this.o=gz;this.D=new Zy;this.s=this.G=this.u=this.h=this.g=this.m=this.C=this.l=null};
iz.prototype.start=function(a,b,c){var d=this;if(!a&&!b)return Promise.reject(Error("No tracks to stream"));var e=a instanceof jz,f=b instanceof jz;(e&&b&&!f||f&&a&&!e)&&Mb("Mixing remoting and non-remoting tracks");return az(this.D,1,function(g){d.l=a;d.C=b;d.m=c;d.o.info(function(){return"Launching streaming for "+kz(d)+" to a "+(d.W+".")});return lz(d).then(d.H.bind(d)).then(function(h){return mz(d,h).then(function(m){d.Y();var q=nz(d,m,h);d.g=oz(d,d.g,q);d.h=oz(d,d.h,q);if(!d.g&&!d.h)throw Error("Receiver did not select any offers from: "+
JSON.stringify(h));d.G=!!m.l;d.s=function(r,z){r==d.g?d.m.Nf("Audio stream (id="+r+") error: "+z):r==d.h&&d.m.Nf("Video stream (id="+r+") error: "+z)};fz.rtpStream.onError.addListener(d.s);return pz(d,m,q)})}).then(function(){d.o.info(function(){return"Launched streaming for "+kz(d)});d.m.rh(d);ez(g,2);return{St:d.g,uA:d.h}})})};
iz.prototype.stop=function(){var a=this;return cz(this.D,function(b){if(!a.l&&!a.C)return ez(b,1),Promise.resolve();a.o.info(function(){return"Stopping streaming for "+kz(a)+"."});a.s&&(fz.rtpStream.onError.removeListener(a.s),a.s=null);if(a.m){var c=a.m.ki();a.m=null}else c=Promise.resolve();return c.then(function(){a.g&&(fz.rtpStream.stop(a.g),fz.rtpStream.destroy(a.g),a.g=null);a.h&&(fz.rtpStream.stop(a.h),fz.rtpStream.destroy(a.h),a.h=null);a.u&&(fz.udpTransport.destroy(a.u),a.u=null);a.Ab();
a.o.info(function(){return"Stopped streaming for "+kz(a)+"."});a.l=null;a.C=null;ez(b,1)})})};
var qz=function(a,b){var c=JSON.stringify(b);return Promise.all([a.g&&new Promise(function(d){return fz.rtpStream.getRawEvents(a.g,c,d)}),a.h&&new Promise(function(d){return fz.rtpStream.getRawEvents(a.h,c,d)})]).catch(function(d){a.o.error("Unexpected error when calling getRawEvents()",d);return[]}).then(function(d){return new Blob(d.filter(function(e){return!!e}),{type:"application/gzip"})})},rz=function(a){return Promise.all([a.g&&new Promise(function(b){return fz.rtpStream.getStats(a.g,b)}),a.h&&
new Promise(function(b){return fz.rtpStream.getStats(a.h,b)})]).catch(function(b){a.o.error("Unexpected error when calling getStats()",b);return[]}).then(function(b){return Object.assign.apply(Object,[{}].concat(p(b.filter(function(c){return!!c}))))})},kz=function(a){if(a.l&&a.C)var b="audio+video ";else if(a.l)b="audio-only ";else if(a.C)b="video-only ";else return"stopped";return a.l instanceof jz||a.C instanceof jz?b+"remoting":b+"streaming"},lz=function(a){return new Promise(function(b){var c=
function(d,e,f){d&&!a.l&&(fz.rtpStream.destroy(d),d=null);e&&!a.C&&(fz.rtpStream.destroy(e),e=null);a.o.info(function(){return"Created Cast Streaming session: audioStreamId="+d+", videoStreamId="+e+"."});a.g=d;a.h=e;a.u=f;b()};a.l instanceof jz||a.C instanceof jz?fz.session.create(null,null,c):fz.session.create(a.l,a.C,c)})};
iz.prototype.H=function(){for(var a=pk(),b=pk(),c=[],d=n([this.g,this.h]),e=d.next();!e.done;e=d.next())if(e=e.value)for(var f=e==this.g,g=f?127:96,h=f?Math.floor(499999*Math.random())+1:Math.floor(499999*Math.random())+500001,m=f?48E3:9E4,q=n(fz.rtpStream.getSupportedParams(e)),r=q.next();!r.done;r=q.next())r=r.value,r.payload.payloadType=g,r.payload.maxLatency=this.j.maxLatencyMillis,r.payload.minLatency=this.j.minLatencyMillis,r.payload.animatedLatency=this.j.animatedLatencyMillis,r.payload.ssrc=
h,r.payload.clockRate=m,r.payload.aesKey=a,r.payload.aesIvMask=b,f?(r.payload.channels=2,r.payload.maxBitrate=this.j.audioBitrate,r.payload.maxFrameRate=100):(r.payload.minBitrate=this.j.minVideoBitrate,r.payload.maxBitrate=this.j.maxVideoBitrate,r.payload.maxFrameRate=this.j.maxFrameRate),c.push(new sz(e,r));return c};
var oz=function(a,b,c){b&&!c.some(function(d){return d.Pg==b})&&(a.o.L("Destroying RTP stream not selected by the receiver: id="+b),fz.rtpStream.destroy(b),b=null);return b},mz=function(a,b){return new Promise(function(c,d){for(var e=[],f=0;f<b.length;++f){var g=b[f].params,h={index:f,codecName:g.payload.codecName.toLowerCase(),rtpProfile:"cast",rtpPayloadType:g.payload.payloadType,ssrc:g.payload.ssrc,targetDelay:g.payload.animatedLatency,aesKey:g.payload.aesKey,aesIvMask:g.payload.aesIvMask,timeBase:"1/"+
g.payload.clockRate,receiverRtcpEventLog:a.j.enableLogging,rtpExtensions:["adaptive_playout_delay"]};a.j.dscpEnabled&&(h.receiverRtcpDscp=46);127==g.payload.payloadType?Object.assign(h,{type:"audio_source",bitRate:0<g.payload.maxBitrate?1E3*g.payload.maxBitrate:60*g.payload.maxFrameRate+g.payload.clockRate*g.payload.channels,sampleRate:g.payload.clockRate,channels:g.payload.channels}):Object.assign(h,{type:"video_source",renderMode:"video",maxFrameRate:Math.round(1E3*g.payload.maxFrameRate)+"/1000",
maxBitRate:1E3*g.payload.maxBitrate,resolutions:[{width:a.j.maxWidth,height:a.j.maxHeight}]});e.push(h)}var m=a.l instanceof jz||a.C instanceof jz?"remoting":"mirroring",q={type:"OFFER",sessionId:a.N,seqNum:Gn(a.V),offer:{castMode:m,receiverGetStatus:!0,supportedStreams:e}};a.o.info(function(){return"Sending OFFER message: "+JSON.stringify(q)});Yy(a.K,q,"ANSWER",1E4,function(r,z){if(null==r)d(z);else if("ok"==r.result&&r.g){if(r.h!=q.seqNum)return a.o.L("Ignoring ANSWER for OFFER with different seqNum: "+
JSON.stringify(r)),!1;((z=r.g.j)&&z!=m||!z&&"mirroring"!=m)&&a.o.error("Expected receiver to ANSWER with castMode="+m+", but got: "+z);mb(a.o,function(){return"Received ANSWER: "+JSON.stringify(r)});c(r.g)}else d(Error("Non-OK ANSWER received: "+JSON.stringify(r)));return!0})})},nz=function(a,b,c){if(b.g.length!=b.h.length)return a.o.error("sendIndexes.length != ssrcs.length in ANSWER: "+JSON.stringify(b)),[];for(var d=[],e={},f=0;f<b.g.length;e={Zf:e.Zf},++f){var g=b.g[f];if(0>g||g>=c.length)return a.o.error("Receiver selected invalid index ("+
g+" < "+c.length+") in ANSWER: "+JSON.stringify(b)),[];e.Zf=c[g];if(d.some(function(h){return function(m){return m.Pg==h.Zf.Pg}}(e)))return a.o.error("Receiver selected same RTP stream twice in ANSWER: "+JSON.stringify(b)),[];e.Zf.params.payload.feedbackSsrc=b.h[g];if(d.some(function(h){return function(m){return m.params.payload.feedbackSsrc==h.Zf.params.payload.feedbackSsrc}}(e)))return a.o.error("Receiver provided same SSRC for two different RTP streams in ANSWER: "+JSON.stringify(b)),[];d.push(e.Zf)}return d},
pz=function(a,b,c){var d=null,e=function(){d&&(fz.rtpStream.onStarted.removeListener(d),d=null)};return(new Promise(function(f,g){var h=b.C||2344;a.o.info(function(){return"Starting RTP streams to receiver at "+(a.F+":"+h)+(" for selected offers: "+JSON.stringify(c))});var m=a.u||-1;a.j.dscpEnabled&&(a.o.info("Enabled DSCP in sender."),fz.udpTransport.setOptions(m,{DSCP:!0}));fz.udpTransport.setDestination(m,{address:a.F,port:h});var q=new Set(c.map(function(z){return z.Pg}));d=function(z){q.delete(z);
0==q.size&&f()};fz.rtpStream.onStarted.addListener(d);m=n(c);for(var r=m.next();!r.done;r=m.next())r=r.value,fz.rtpStream.toggleLogging(r.Pg,a.j.enableLogging),fz.rtpStream.start(r.Pg,r.params);setTimeout(function(){g(Error("Timeout: RTP streams failed to start."))},1E4)})).then(e).catch(function(f){e();throw f;})},hz=function(a,b,c){return a&&b in a?function(){try{a[b](c)}catch(d){gz.error("Error from testHooks."+b,d)}}:function(){}},sz=function(a,b){this.Pg=a;this.params=b},jz=function(){};var tz=eb("mr.mirror.cast.MediaRemoter"),wz=function(a,b,c,d,e,f){this.s=a;this.K=uz(b,this.s.yb);this.V=new iz(this.s.yb,c,d,e,f);this.G=e;this.C=new Zy;this.j=new vz;this.D=new mojo.Binding(mojo.MirrorServiceRemoter,this,null);this.o=tz;this.F=this.g=this.m=this.l=this.H=null;this.h=!0;this.u=this.N.bind(this)},zz=function(a,b,c){return az(a.C,1,function(d){a.H=b;a.l=c;var e=a.D.createInterfacePtrAndBind();a.D.setConnectionErrorHandler(function(){a.o.info("Remoter mojo pipe connection error.");
xz(a)});a.g=new mojo.MirrorServiceRemotingSourcePtr;var f=Gj(a.s.mediaSource||"");if(!f)throw Error("Failed to parse tab ID from source:\n          "+a.s.mediaSource);a.o.info("Connecting remoter to browser: tabId="+f);(pj.get("mr.ProviderManager")||null).onMediaRemoterCreated(f,e,mojo.makeRequest(a.g));a.g.ptr.setConnectionErrorHandler(function(){a.o.info("RemotingSource mojo pipe connection error.");xz(a)});return yz(a).then(function(){if(a.h)a.g.onSinkAvailable(a.K);ez(d,2)})})},xz=function(a){return cz(a.C,
function(b){a.g&&(a.g.ptr.reset(),a.g=null);var c=a.m;a.m=null;a.l=null;a.H=null;a.D.close();chrome.settingsPrivate.onPrefsChanged.hasListener(a.u)&&chrome.settingsPrivate.onPrefsChanged.removeListener(a.u);return new Promise(function(d){window.setTimeout(function(){Az(a).then(function(){ez(b,1);d();c&&c()})},250)})})};k=wz.prototype;k.Az=function(a){Bz(this.j,a)};k.rh=function(a){this.l&&this.l.rh(a)};k.ki=function(){return this.l?this.l.ki():Promise.resolve()};
k.Nf=function(a,b){this.o.error("Error during streaming: "+a,b);if(this.g)this.g.onError();xz(this)};
k.start=function(){var a=this,b=!1;this.o.info(function(){b=!0;return"Starting next media remoting session."});b&&Cz(this.j,function(c){return a.o.info(c)});Dz(this.j);az(this.C,2,function(c){return(0,a.H)().then(function(d){a.m=d;Wy(a.G,"RPC",function(e){if(e.rpc){var f=a.j;e=e.rpc;f.m&&(++f.s,f.h+=e.length,f.m(e))}});ez(c,3)}).catch(function(d){return Az(a).then(function(){ez(c);throw d;})})}).then(function(){a.o.info("Remoting started successfully.")}).catch(function(c){a.o.error("Failed to start remoting",c);
a.g.onError()})};k.Zz=function(a,b){var c=this;return az(this.C,3,function(d){return c.V.start(a?new jz:null,b?new jz:null,c).then(function(e){Ez(c.j,function(f){return c.G.sendMessage(f)},function(f){c.g.onMessageFromSink(f)});ez(d,4);return{audio_stream_id:e.St||-1,video_stream_id:e.uA||-1}}).catch(function(e){return Az(c).then(function(){ez(d);throw e;})})}).catch(function(d){c.o.error("Failed to start remoting streams",d);xz(c);return{audio_stream_id:-1,video_stream_id:-1}})};
k.stop=function(a){var b=this;bz(this.C,function(c){b.g.onStopped(a);return Az(b).then(function(){b.o.info("Remoting stopped.");ez(c,5);(0,b.m)().then(function(){return az(b.C,5,function(d){if(b.g&&b.h)b.g.onSinkAvailable(b.K);ez(d,2);return Promise.resolve()})}).catch(function(d){throw d;});b.m=null})}).catch(function(c){b.o.error("Failed to stop remoting: ",c);xz(b)})};
k.vu=function(){null===this.F&&(this.F=If(this.s.yb.gi).then(function(a){return a.h||!1}));return this.F.then(function(a){return{rate:(a?1E7:5E6)/8}})};
var Az=function(a){return a.V.stop().then(function(){Xy(a.G,"RPC");Fz(a.j);Gz(a.j)})},yz=function(a){return new Promise(function(b){chrome.settingsPrivate.getPref("media_router.media_remoting.enabled",function(c){chrome.runtime.lastError?a.o.error("Encountered error getting media remoting pref: "+JSON.stringify(chrome.runtime.lastError)):c.type!=chrome.settingsPrivate.PrefType.BOOLEAN?a.o.error("Pref value not a boolean: "+JSON.stringify(c)):(a.h=!!c.value,a.o.info("Initializing mediaRemotingEnabled_ with value read from pref: "+
a.h));chrome.settingsPrivate.onPrefsChanged.hasListener(a.u)||chrome.settingsPrivate.onPrefsChanged.addListener(a.u);b()})})};
wz.prototype.N=function(a){if(this.g){a=n(a);for(var b=a.next();!b.done;b=a.next())if(b=b.value,"media_router.media_remoting.enabled"==b.key){if(b.type!=chrome.settingsPrivate.PrefType.BOOLEAN){this.o.error("Pref value not a boolean: "+JSON.stringify(b));break}a=!!b.value;if(this.h==a)break;this.h=a;this.o.info("mediaRemotingEnabled_ changed to: "+this.h);if(this.h)this.g.onSinkAvailable(this.K);else this.g.onStopped(mojo.RemotingStopReason.USER_DISABLED);break}}};
var uz=function(a,b){var c=new mojo.RemotingSinkMetadata;c.features=[];c.friendly_name=b.Vz||"";c.audio_capabilities=[];c.video_capabilities=[];var d=mojo.RemotingSinkAudioCapability,e=mojo.RemotingSinkVideoCapability,f=c.audio_capabilities,g=c.video_capabilities,h=b.We||"";(a.g||[]).forEach(function(m){switch(m){case "audio":f.push(d.CODEC_BASELINE_SET);break;case "aac":f.push(d.CODEC_AAC);break;case "opus":f.push(d.CODEC_OPUS);break;case "video":g.push(e.CODEC_BASELINE_SET);break;case "4k":g.push(e.SUPPORT_4K);
break;case "h264":g.push(e.CODEC_H264);break;case "vp8":g.push(e.CODEC_VP8);break;case "vp9":h.startsWith("Chromecast Ultra")&&g.push(e.CODEC_VP9);break;case "hevc":h.startsWith("Chromecast Ultra")&&g.push(e.CODEC_HEVC);break;default:tz.info("Unknown mediaCap name: "+m)}});b.We&&"Chromecast Ultra"==b.We&&g.push(e.SUPPORT_4K);return c};wz.prototype.estimateTransmissionCapacity=wz.prototype.vu;wz.prototype.stop=wz.prototype.stop;wz.prototype.startDataStreams=wz.prototype.Zz;wz.prototype.start=wz.prototype.start;
wz.prototype.sendMessageToSink=wz.prototype.Az;
var vz=function(){this.m=this.C=this.g=null;this.F=this.h=this.s=this.j=this.u=0;this.l=null},Dz=function(a){a.g=[];Hz(a,performance.now())},Ez=function(a,b,c){a.C=b;a.m=c;a.g?(b=a.g,a.g=null,b.forEach(function(d){return Bz(a,d.data).then(d.Cz,d.Dq)})):Hz(a,performance.now())},Fz=function(a){if(a.g){var b=Error("Stop before delivering pending message");a.g.forEach(function(c){return c.Dq(b)});a.g=null}a.C=null;a.m=null},Bz=function(a,b){if(a.C){var c=btoa(String.fromCharCode.apply(null,b));++a.u;
a.j+=b.length;return a.C({type:"RPC",rpc:c})}return a.g?new Promise(function(d,e){a.g.push({data:b,Cz:d,Dq:e})}):Promise.reject(Error("RPC pipe not started"))},Cz=function(a,b){Gz(a);a.l=setInterval(function(){if(a.g)var c=a.g.length+" messages are waiting to send.";else{c=performance.now();var d=(c-a.F)/1E3;d="Over the past "+d.toFixed(1)+" seconds, sent "+(a.u+" messages ("+Math.round(a.j/d)+" bytes/sec) and received ")+(a.s+" messages ("+Math.round(a.h/d)+" bytes/sec).");Hz(a,c);c=d}b(c)},3E4)},
Gz=function(a){null!=a.l&&(clearInterval(a.l),a.l=null)},Hz=function(a,b){a.u=0;a.j=0;a.s=0;a.h=0;a.F=b};var Iz=function(a){return a&&a.getAudioTracks()&&0<a.getAudioTracks().length?a.getAudioTracks()[0]:null},Jz=function(a){return a&&a.getVideoTracks()&&0<a.getVideoTracks().length?a.getVideoTracks()[0]:null};var Kz=function(a,b,c,d,e){this.j=new iz(a,b,c,d,void 0===e?null:e);this.o=eb("mr.mirror.cast.MediaStreamer");this.C=new Zy;this.l=this.h=this.g=this.m=null};Kz.prototype.start=function(a,b){var c=this;return az(this.C,1,function(d){c.m=a;c.g=Iz(a);c.g&&"ended"==c.g.readyState&&(c.g=null);c.h=Jz(a);c.h&&"ended"==c.h.readyState&&(c.h=null);if(!c.g&&!c.h)return ez(d),Promise.reject(Error("No MediaStream tracks to stream."));c.l=b;return c.j.start(c.g,c.h,c.l).then(function(){return ez(d,2)})})};
Kz.prototype.stop=function(){var a=this;return cz(this.C,function(b){return a.j.stop().then(function(){a.g=null;a.h=null;a.m=null;a.l=null;ez(b,1)})})};var Lz=function(a){return az(a.C,2,function(b){a.o.info("Suspending media streaming...");return a.j.stop().then(function(){a.o.info("Suspended media streaming.");ez(b,3)})})};
Kz.prototype.resume=function(){var a=this;return az(this.C,3,function(b){a.g&&"ended"==a.g.readyState&&(a.g=null);a.h&&"ended"==a.h.readyState&&(a.h=null);if(!a.g&&!a.h)return Promise.reject(Error("Cannot resume: All tracks have ended."));a.o.info("Resuming media streaming...");return a.j.start(a.g,a.h,a.l).then(function(){a.o.info("Resumed media streaming.");ez(b,2)})})};var Mz=function(a,b,c){this.C=a;this.l=b;this.j=c;this.o=eb("mr.mirror.cast.WifiStatusMonitor");this.g=null;this.h=[]};Mz.prototype.start=function(){var a=this;null==this.g&&(mb(this.o,"Starting Wifi Status Monitoring."),this.h=[],Wy(this.j,"STATUS_RESPONSE",function(b){return Nz(a,b)}),this.g=setInterval(function(){return Oz(a)},12E4),Oz(this))};Mz.prototype.stop=function(){null!=this.g&&(mb(this.o,"Stopping Wifi Status Monitoring."),clearInterval(this.g),this.g=null,Xy(this.j,"STATUS_RESPONSE"))};
var Nz=function(a,b){if(null!=a.g)if(b.status){var c={};null!=b.status.g&&(c.wifiSnr=b.status.g);null!=b.status.h&&(c.wifiSpeed=b.status.h[3]);0==Object.keys(c).length?a.o.L(function(){return"No status fields populated in response: "+JSON.stringify(b)}):(c.timestamp=Date.now(),30==a.h.length&&a.h.shift(),a.h.push(c),a.o.info(function(){return"Current Wifi status: "+JSON.stringify(c)}))}else a.o.L(function(){return"Ignoring response without status: "+JSON.stringify(b)})},Oz=function(a){a.j.sendMessage({type:"GET_STATUS",
sessionId:a.C,seqNum:Gn(a.l),get_status:["wifiSnr","wifiSpeed"]})};var Pz=function(a,b,c,d){this.H=b.gi;this.K={extVersion:chrome.runtime.getManifest().version,extChannel:"public",mirrorSettings:Wj(a),sender:navigator.userAgent||"UNKNOWN",receiverProductName:b.We};this.G=c;this.D=d;this.l=this.h=this.s=this.m=this.C=this.u=this.j=null;this.g=[]};Pz.prototype.rh=function(a){null!=this.h&&clearInterval(this.h);this.j=a;this.u=Date.now();this.h=setInterval(this.F.bind(this,a),9E5)};
Pz.prototype.ki=function(){null!=this.h&&(clearInterval(this.h),this.h=null);if(null!=this.j){var a=this.F(this.j);this.j=null;return a}return Promise.resolve()};Pz.prototype.Nf=function(a,b){null==this.C&&(this.C=Date.now(),"function"===typeof a?this.m=a():"string"===typeof a&&(this.m=a),b&&"string"===typeof b.stack&&(this.s=b.stack))};
var Rz=function(a,b){return(null==a.j?Promise.resolve():a.F(a.j)).then(function(){var c=b.map(function(d){d=Qz(a,d);var e=d.map(function(g){return g.events}).filter(function(g){return null!=g}),f=["["];d.map(function(g){return g.Og}).forEach(function(g,h){0<h&&f.push(",");f.push(g)});f.push("]");return{events:new Blob(e,{type:"application/gzip"}),Og:new Blob(f,{type:"application/json"})}});a.g=[];return c})};
Pz.prototype.F=function(a){var b=this;if(null!=this.l)return this.l;var c=If(this.H).then(function(d){d={receiverVersion:d.g,receiverConnected:d.l,receiverOnEthernet:d.h,receiverHasUpdatePending:d.j,receiverUptimeSeconds:d.C};Object.assign(d,b.K);var e=Date.now();Object.assign(d,{startTime:b.u,endTime:e,activity:kz(a),receiverWifiStatus:Array.from(b.D.h)});b.u=e;null!=b.C&&(Object.assign(d,{streamingErrorTime:b.C,streamingErrorMessage:b.m,streamingErrorCause:b.s}),b.C=null,b.m=null,b.s=null);return d});
return(this.l=Promise.all([c.then(function(d){return qz(a,d)}),c,rz(a)]).then(function(d){var e=n(d);d=e.next().value;var f=e.next().value;e=e.next().value;b.g.push({events:d,Og:new Blob([JSON.stringify(Object.assign({tags:f},e))],{type:"application/json"})});b.g=Qz(b,b.G);b.l=null}))||Promise.resolve()};
var Qz=function(a,b){b-=2;for(var c=[],d=a.g.length-1;0<=d;--d){b-=a.g[d].Og.size+1;if(0>b)break;c.push({events:null,Og:a.g[d].Og});if(null!=a.g[d].events){var e=a.g[d].events.size;b>=e&&(c[c.length-1].events=a.g[d].events,b-=e)}}return c.reverse()};var Sz=function(a,b,c,d){d=void 0===d?null:d;Tj.call(this,b);var e=b.yb;this.F=e.sessionId;this.H=a;this.V=d;this.o=eb("mr.mirror.cast.Session");this.u=new Zy;this.s=new Fn("mirror.cast.SeqNumGenerator");this.m=new Vy(b.id);this.C=new Kz(e,this.H,this.s,this.m,this.V);this.l=null;this.g=new Pz(a,e,c,new Mz(this.F,this.s,this.m));this.D=null};t(Sz,Tj);k=Sz.prototype;
k.start=function(a){var b=this;return az(this.u,1,function(c){var d=ty();return b.C.start(a,b).then(function(){b.C.j.G&&(b.g.D.start(),Tz(b));d.end();b.D=uy();ez(c,2);return b})})};k.stop=function(){var a=this;return cz(this.u,function(b){a.D&&(a.D.end(),a.D=null);a.g.D.stop();return a.C.stop().then(function(){return a.l?xz(a.l):Promise.resolve()}).then(function(){a.l=null;ez(b,4)})})};
k.Bq=function(){var a=this,b={sessionId:this.F,seqNum:Gn(this.s),type:"PRESENTATION",icons:[],title:Rj(this.Oc)};this.o.info("Sending session metadata update to receiver: "+this.F);this.m.sendMessage(b).catch(function(c){a.o.L("Failed to send activity to sink: "+c.message)})};k.rh=function(a){this.g.rh(a)};k.ki=function(){return this.g.ki()};k.Nf=function(a,b){this.g.Nf(a,b);this.o.error(a,b);this.stop()};
var Uz=function(a,b){return Rz(a.g,b)},Tz=function(a){Vz(a).then(function(b){(b.g||[]).includes("video")?Wz(a,b):a.o.L(function(){return"Receiver incapable of Media Remoting: "+JSON.stringify(b)})}).catch(function(b){a.o.L("None/Invalid capabilites response. Media Remoting disabled.",b)})},Vz=function(a){return new Promise(function(b,c){var d={type:"GET_CAPABILITIES",sessionId:a.F,seqNum:Gn(a.s)};a.o.info(function(){return"Sending GET_CAPABILITIES message: "+JSON.stringify(d)});Yy(a.m,d,"CAPABILITIES_RESPONSE",
3E4,function(e,f){if(null==e)return c(f),!0;if("ok"!=e.result||!e.capabilities)return c(Error("Bad response: "+JSON.stringify(e))),!0;if(e.h!=d.seqNum)return a.o.info(function(){return"Ignoring CAPABILITIES_RESPONSE with different seqNum: "+JSON.stringify(e)}),!1;mb(a.o,function(){return"Received CAPABILITIES_RESPONSE: "+JSON.stringify(e)});b(e.capabilities);return!0})})},Wz=function(a,b){az(a.u,2,function(c){var d=a.h.yb.We||"<UNKNOWN>";if(!d.startsWith("Chromecast")&&!d.startsWith("Eureka Dongle"))return a.o.L('HACK: Media Remoting disabled because the receiver model--"'+
(d+'" according to discovery--is not a Chromecast.')),ez(c),Promise.resolve();a.l=new wz(a.h,b,a.H,a.s,a.m,a.V);return zz(a.l,a.N.bind(a),a).catch(function(e){a.o.error("Media Remoting start failed: "+e.message,e)}).then(function(){return ez(c)})})};Sz.prototype.N=function(){var a=this;return az(this.u,2,function(b){return new Promise(function(c,d){Lz(a.C).then(function(){ez(b,3);a.G=!0;Jj(a);c(a.W.bind(a))}).catch(function(e){a.Nf("Failed to suspend MediaStreamer before starting remoting",e);d(e)})})})};
Sz.prototype.W=function(){var a=this;return az(this.u,3,function(b){return new Promise(function(c,d){a.C.resume().then(function(){ez(b,2);a.G=!1;Jj(a);c()}).catch(function(e){a.Nf("Failed resume MediaStreamer after ending remoting mode",e);d(e)})})})};var Xz=function(){Hj.call(this,"cast_streaming");this.m=this.F=this.K=this.H=this.l=null;this.ea=this.V="";this.ja=this.u=!1;this.sa=this.Ca.bind(this);this.N=this.W=this.Y=this.Ab=this.C=null};t(Xz,Hj);k=Xz.prototype;k.th=function(a){this.u=a||!1;this.ja=!0};k.getName=function(){return"cast_streaming"};
k.Al=function(a,b,c,d,e){var f=this;if(!this.u)return Hj.prototype.Al.call(this,a,b,c,d,e);this.M.info("Start mirroring on route "+a.id);if(!this.ja)return Vi(Error("Not initialized"));var g=new Promise(function(h,m){f.s().then(function(){if(Fj(b)&&c.shouldCaptureVideo)return mj(!1).then(function(q){f.ea=q})}).then(function(){return e?e(a).promise:a}).then(function(q){f.V=b;Yz(f,q);var r=f.H.createInterfacePtrAndBind(),z=f.K.createInterfacePtrAndBind(),D=Zz(q,c);$z(f,q,b,d);if(!f.l)throw new Zi("Error to get mirroring service host");
f.F=new mojo.MirroringCastMessageChannelPtr;f.Ab=ty();f.l.start(D,r,z,mojo.makeRequest(f.F));f.C=new Tj(a,f.j.N.bind(f.j));Jj(f.C);aA(f,q,b);f.W=function(){return h(q)};f.N=m}).catch(function(q){f.M.error("Mirroring launch error: "+q);f.Kg(void 0===q.reason?9:q.reason);m(q)})});return Wi(g)};k.Bi=function(a,b){return new Sz(a,b,20969472,null)};k.ai=function(){vy(0)};k.Xh=function(){vy(1)};k.wj=function(){vy(2)};k.Yh=function(){zb("MediaRouter.CastStreaming.Session.End")};
k.Kg=function(a){Ab("MediaRouter.CastStreaming.Start.Failure",a,Yi)};k.Zh=function(){zb("MediaRouter.CastStreaming.Stream.End")};
k.pk=function(a){var b=this;return this.u?Promise.resolve():(new Promise(function(c){return chrome.metricsPrivate.getIsCrashReportingEnabled(c)})).then(function(c){var d=c&&Cy(),e=[9351424];d&&e.push(20969472);return Uz(a,e).then(function(f){var g=f[f.length-1];f=Em(f[0].events).catch(function(h){b.M.error("Failed to persist events Blob.",h)});d&&0<g.events.size?yy(g.events,void 0,b.Mx.bind(b)):c&&xy("stats.json",g.Og,void 0,void 0);return f})})};
k.Mx=function(a){if(a){a=By();var b=Date.now();a.g=b}};k.zl=function(a){if(this.u)return bb();this.M.info("Received message to upload logs for "+a);return this.g?Uz(this.g,[20969472]).then(function(b){b=n(b).next().value;return 0==b.events.size?"":yy(b.events,a)}):Promise.resolve(bA(this,a))};
var bA=function(a,b){var c=window.localStorage.getItem("mr.temp.mirror.cast.Service.eventsBlob");if(null==c||1>c.length)c=null;else{for(var d=new Uint16Array(c.length),e=0;e<c.length;++e)d[e]=c.charCodeAt(e);c=d.buffer;d=(new Uint8Array(c,c.byteLength-1,1))[0];c=new Uint8Array(c,0,c.byteLength-(0==d?2:1));c=new Blob([c],{type:"application/gzip"})}if(null!=c&&0!=c.size)return Em(new Blob),a.M.info("Uploading saved logs for feedback."),yy(c,b)};k=Xz.prototype;
k.onError=function(a){this.N&&(this.N(a),this.W=this.N=null,this.Kg(9));this.M.info("Mirroring service error: "+a);this.s()};k.didStart=function(){this.W&&(this.W(),this.W=this.N=null);this.Ab&&(this.Ab.end(),this.Ab=null);this.Y=uy();Ej(this.V)?this.ai():Fj(this.V)?this.Xh():Cj(this.V)&&this.wj()};k.didStop=function(){this.s()};k.send=function(a){if(this.m){var b=JSON.parse(a.jsonFormatData);mb(this.M,function(){return"Sending message: "+JSON.stringify(b)});this.m.sendMessage(a.jsonFormatData,{namespace:a.messageNamespace})}};
k.Nx=function(a){if(a&&(a.namespace_===mojo.MirroringWebRtcNamespace||a.namespace_===mojo.MirroringRemotingNamespace)&&this.F){var b=new mojo.MirroringCastMessage;b.messageNamespace=a.namespace_;"string"!==typeof a.data?this.M.info("Received non-string as JSON"):(b.jsonFormatData=a.data,this.F.send(b))}};
var Yz=function(a,b){a.H=new mojo.Binding(mojo.MirroringSessionObserver,a,null);a.K=new mojo.Binding(mojo.MirroringCastMessageChannel,a,null);a.m=nx(b.id);a.m.onMessage=a.Nx.bind(a)},Zz=function(a,b){var c=new mojo.MirroringSessionParameters;c.receiverAddress=new mojo.IPAddress;c.receiverAddress.addressBytes=a.yb.gi.split(".").map(function(d){return parseInt(d,10)});c.receiverModelName=a.yb.We;a=cA(a.mediaSource);c.targetPlayoutDelay=dA(a);!b.shouldCaptureVideo||!b.shouldCaptureAudio||a&&"0"===a.searchParams.get("streamingCaptureAudio")?
c.type=b.shouldCaptureVideo?mojo.MirroringSessionType.VIDEO_ONLY:mojo.MirroringSessionType.AUDIO_ONLY:c.type=mojo.MirroringSessionType.AUDIO_AND_VIDEO;return c},dA=function(a){if(!a)return null;a=Number(a.searchParams.get("streamingTargetPlayoutDelayMillis"));return isNaN(a)||0>=a?null:new mojo.TimeDelta({microseconds:1E3*a})},cA=function(a){if(!a)return null;try{return new URL(a)}catch(b){return null}},$z=function(a,b,c,d){a.l=new mojo.MirroringServiceHostPtr;b=b.yb.tabId||-1;Ej(c)?a.j.getMirroringServiceHostForTab(b,
mojo.makeRequest(a.l)):Fj(c)?a.j.getMirroringServiceHostForDesktop(-1,a.ea,mojo.makeRequest(a.l)):Cj(c)?(b=new mojo.Url,b.url=c,a.j.getMirroringServiceHostForOffscreenTab(b,d||"",mojo.makeRequest(a.l))):a.l=null},aA=function(a,b,c){Ej(c)&&!chrome.tabs.onUpdated.hasListener(a.sa)&&chrome.tabs.onUpdated.addListener(a.sa);(Ej(c)||Cj(c))&&Mj(a.C,b.yb.tabId)};Xz.prototype.Ca=function(a,b,c){Bj(14);this.C&&Oj(this.C,a,b,c)};
Xz.prototype.s=function(){chrome.tabs.onUpdated.removeListener(this.sa);return this.u?this.ja?this.l?(this.l.ptr.reset(),this.F=this.l=null,this.m&&this.m.dispose(),this.m=null,this.H&&(this.H.close(),this.H=null),this.K&&(this.K.close(),this.K=null),Nj(this.j,this.C.h.id),this.C=null,this.ea=this.V="",this.Y&&(this.Y.end(),this.Y=null),this.Yh(),Promise.resolve(!0)):Promise.resolve(!1):Promise.reject("Not initialized"):Hj.prototype.s.call(this)};
Xz.prototype.oa=function(a,b,c,d,e,f){return this.u?Vi(Error("Mirroring service does not support updating stream")):Hj.prototype.oa.call(this,a,b,c,d,e,f)};Xz.prototype.send=Xz.prototype.send;Xz.prototype.didStop=Xz.prototype.didStop;Xz.prototype.didStart=Xz.prototype.didStart;Xz.prototype.onError=Xz.prototype.onError;var eA=new Xz;yj("mr.mirror.cast.Service",eA);
