'use strict';var Rba={TAB:0,wk:1,so:2},Sx=function(){return new sb("MediaRouter.CastStreaming.Session.Launch")},Tx=function(){return new yb("MediaRouter.CastStreaming.Session.Length")},Ux=function(a){Cb("MediaRouter.CastStreaming.Start.Success",a,Rba)};var Vx=hb("mr.mirror.cast.LogUploader"),Xx=function(a,c,b){Wx("raw_events.log.gz",a,c,b);return c?"https://crash.corp.google.com/samples?reportid=&q="+encodeURIComponent("UserComments='"+c+"'"):""},Wx=function(a,c,b,d){if(0==c.size)Vx.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,c);b&&e.append("comments",b);yw("https://clients2.google.com/cr/report",function(f){f=f.target;
var g=null;Gw(f)?(g=Hw(f),Vx.info("Upload to Crash succeeded: "+g)):Vx.info("Upload to Crash failed. HTTP status: "+f.Va());d&&d(g)},"POST",e,void 0,3E4)}};var Yx=function(){this.b=0;am(this)},$x=function(){Zx||(Zx=new Yx);return Zx},Sba=function(){var a=$x(),c={fraction:.01,autoSubmitTimeLimitMillis:6048E5},b=c.autoSubmitTimeLimitMillis,d=Date.now();return a.b&&b&&d-a.b<b?!1:Math.random()<c.fraction};Yx.prototype.Ea=function(){return"mirror.cast.LogUtils"};Yx.prototype.jb=function(){return[void 0,{lastAutoSubmitMillis:this.b}]};Yx.prototype.ib=function(){var a=Zl(this);this.b=a&&a.lastAutoSubmitMillis||0};var Zx=null;hb("mr.mirror.cast.LogUtils");var ay={Px:"OFFER",Nt:"ANSWER",sy:"PRESENTATION",Cv:"GET_STATUS",Ez:"STATUS_RESPONSE",Bv:"GET_CAPABILITIES",lu:"CAPABILITIES_RESPONSE",ez:"RPC"};var Tba=function(){this.capabilities=this.status=this.b=this.error=this.rpc=this.result=this.type=this.f=this.sessionId=null},Vba=function(a){try{if("string"!==typeof a)throw SyntaxError("Cannot parse non-string as JSON");var c;by(JSON.parse(a),function(d){c=Uba(d)},function(){throw Error("non-Object result from JSON parse");});return c}catch(d){var b=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(b+". Input was "+a);},Uba=function(a){var c=new Tba;null!=a.sessionId&&(c.sessionId=String(a.sessionId));cy(a.seqNum,function(f){c.f=f},function(){throw Error('"seqNum" must be a number');});if("type"in a){for(var b=String(a.type).toUpperCase(),d=l(Object.keys(ay)),e=d.next();!e.done;e=d.next())if(ay[e.value]==b){c.type=b;break}if(!c.type)throw Error('not a known message "type"');
}"result"in a&&(c.result=String(a.result));if("rpc"in a){if("string"!==typeof a.rpc)throw Error('"rpc" must be a String containing a base64 payload');c.rpc=new Uint8Array([].concat(n(atob(a.rpc))).map(function(f){return f.charCodeAt(0)}))}by(a.error,function(f){c.error=Wba(f)},function(){throw Error('"error" must be an Object');});by(a.answer,function(f){c.b=Xba(f)},function(){throw Error('"answer" must be an Object');});by(a.status,function(f){c.status=Yba(f)},function(){throw Error('"status" must be an Object');
});by(a.capabilities,function(f){c.capabilities=Zba(f)},function(){throw Error('"capabilities" must be an Object');});return c},by=function(a,c,b){void 0!==a&&(a instanceof Object?c(a):b())},cy=function(a,c,b){void 0!==a&&("number"!==typeof a?b():c(a))},dy=function(a,c,b){void 0!==a&&(a instanceof Array&&a.every(function(d){return"number"===typeof d})?c(a):b())},ey=function(a,c,b){void 0!==a&&(a instanceof Array?c(a.map(function(d){return String(d)})):b())},$ba=function(){this.j=null;this.b=[];this.f=
[];this.g=this.h=this.w=null},Xba=function(a){var c=new $ba;cy(a.udpPort,function(b){c.j=b},function(){throw Error('"answer.udpPort" must be a number');});dy(a.sendIndexes,function(b){c.b=b},function(){throw Error('"answer.sendIndexes" must be an array of numbers');});dy(a.ssrcs,function(b){c.f=b},function(){throw Error('"answer.ssrcs" must be an array of numbers');});"IV"in a&&(c.w=String(a.IV));"receiverGetStatus"in a&&(c.h="true"==String(a.receiverGetStatus).toLowerCase());"castMode"in a&&(c.g=
String(a.castMode));return c},aca=function(){this.details=this.description=this.code=null},Wba=function(a){var c=new aca;cy(a.code,function(b){c.code=b},function(){throw Error('"error.code" must be a number');});"description"in a&&(c.description=String(a.description));by(a.details,function(b){c.details=b},function(){throw Error('"error.details" must be an Object');});return c},bca=function(){this.f=this.b=null},Yba=function(a){var c=new bca;cy(a.wifiSnr,function(b){c.b=b},function(){throw Error('"status.wifiSnr" must be a number');
});dy(a.wifiSpeed,function(b){c.f=b},function(){throw Error('"status.wifiSpeed" must be an array of numbers');});return c},cca=function(){this.f=this.b=null},Zba=function(a){var c=new cca;ey(a.mediaCaps,function(b){c.b=b},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');c.f=a.map(function(b){var d;by(b,function(e){d=dca(e)},function(){throw Error('"capabilities.keySystems" entries must be *Objects');
});return d})}return c},eca=function(){this.g=this.m=this.w=this.j=this.s=this.b=this.o=this.f=this.initDataTypes=this.h=null},dca=function(a){var c=new eca;"keySystemName"in a&&(c.h=String(a.keySystemName));ey(a.initDataTypes,function(b){c.initDataTypes=b},function(){throw Error('"capabilities.initDataTypes" must be an array');});ey(a.codecs,function(b){c.f=b},function(){throw Error('"capabilities.codecs" must be an array');});ey(a.secureCodecs,function(b){c.o=b},function(){throw Error('"capabilities.secureCodecs" must be an array');
});ey(a.audioRobustness,function(b){c.b=b},function(){throw Error('"capabilities.audioRobustness" must be an array');});ey(a.videoRobustness,function(b){c.s=b},function(){throw Error('"capabilities.videoRobustness" must be an array');});"persistentLicenseSessionSupport"in a&&(c.j=String(a.persistentLicenseSessionSupport));"persistentReleaseMessageSessionSupport"in a&&(c.w=String(a.persistentReleaseMessageSessionSupport));"persistentStateSupport"in a&&(c.m=String(a.persistentStateSupport));"distinctiveIdentifierSupport"in
a&&(c.g=String(a.distinctiveIdentifierSupport));return c};var fy=function(a){this.l=hb("mr.mirror.cast.MessageDispatcher");this.h=a;this.b=null;this.f=new Map;this.g=0};fy.prototype.subscribe=function(a,c){if(this.f.has(a))throw Error("Attempt to multiple-subscribe to the same response type: "+a);this.f.set(a,c);this.g=0;ob(this.l,"Added subscriber for "+a+"-type messages.");this.b||(this.b=kx(this.h),this.b.onMessage=this.j.bind(this))};
var gy=function(a,c){a.f.delete(c)&&ob(a.l,function(){return"Removed subscriber of "+c+"-type messages."});0==a.f.size&&a.b&&(a.b.Za(),a.b=null)};fy.prototype.sendMessage=function(a){return this.b?"RPC"==a.type?this.b.sendMessage(a,{namespace:"urn:x-cast:com.google.cast.remoting"}):this.b.sendMessage(a,{namespace:"urn:x-cast:com.google.cast.webrtc"}):Promise.reject(Error("Require at least one subscriber before sending messages."))};
var hy=function(a,c,b,d,e){var f=null,g=function(){gy(a,b);null!=f&&(clearTimeout(f),f=null)};try{a.subscribe(b,function(k){e(k)&&g()})}catch(k){e(null,k);return}f=setTimeout(function(){g();e(null,Error("timeout"))},d);a.sendMessage(c).catch(function(k){g();e(null,k)})};
fy.prototype.j=function(a){if(a&&"string"===typeof a.namespace_&&a.namespace_.startsWith("urn:x-cast:com.google.cast.")){do{var c=void 0;try{c=Vba(a.data)}catch(d){c=d.message;break}if(c.type){var b=this.f.get(c.type);if(b)try{b(c);return}catch(d){c="Error thrown during delivery. Response was: "+(JSON.stringify(c)+". Error from subscriber callback ")+("was: "+d.message+".")}else c="Message was ignored: "+JSON.stringify(c)}else c="Message did not include response type: "+JSON.stringify(c)}while(0);
10>this.g?this.l.G(c):ob(this.l,c);++this.g}};var iy=function(){this.b=Promise.resolve(1)},ky=function(a,c,b){return jy(a,function(d){return d==c},b)},fca=function(a,c){var b=[3,4];return jy(a,function(d){return-1!=b.indexOf(d)},c)},ly=function(a,c){a.b=a.b.catch(function(){return 1});return jy(a,function(){return!0},c)},jy=function(a,c,b){var d,e,f=new Promise(function(g,k){d=g;e=k});a.b=a.b.then(function(g){if(!c(g))return e(Error("Operation requires a different starting checkpoint than "+g)),Promise.resolve(g);var k=new gca(g);try{var m=b(k)}catch(p){m=
Promise.reject(p)}return m.then(function(p){return d(p)},function(p){return e(p)}).then(function(){if(null===k.b)throw Error("A prior operation that started at "+(g+" did not complete."));return k.b})},function(g){e(g);throw g;});return f},gca=function(a){this.f=a;this.b=null},my=function(a,c){a.b="number"===typeof c?c:a.f};var ny=chrome.cast.streaming,py=function(a,c,b,d,e){this.J=a.sessionId;this.s=a.ag;this.O=a.ke;this.g=c;this.H=b;this.L=d;this.T=oy(e,"onAnswer",this.s);this.W=oy(e,"onSessionStop",this.s);this.l=hb("mr.mirror.cast.StreamingLaunchWorkflow");this.D=new iy;this.m=this.C=this.o=this.f=this.b=this.w=this.j=this.h=null};
py.prototype.start=function(a,c,b){var d=this;if(!a&&!c)return Promise.reject(Error("No tracks to stream"));var e=a instanceof qy,f=c instanceof qy;(e&&c&&!f||f&&a&&!e)&&Hb("Mixing remoting and non-remoting tracks");return ky(this.D,1,function(g){d.h=a;d.j=c;d.w=b;d.l.info(function(){return"Launching streaming for "+ry(d)+" "+("to a "+d.O+".")});return hca(d).then(d.F.bind(d)).then(function(k){return ica(d,k).then(function(m){d.T();var p=jca(d,m,k);d.b=sy(d,d.b,p);d.f=sy(d,d.f,p);if(!d.b&&!d.f)throw Error("Receiver did not select any offers from: "+
JSON.stringify(k));d.C=!!m.h;d.m=function(v,A){v==d.b?d.w.ef("Audio stream (id="+v+") error: "+A):v==d.f&&d.w.ef("Video stream (id="+v+") error: "+A)};ny.rtpStream.onError.addListener(d.m);return kca(d,m,p)})}).then(function(){d.l.info(function(){return"Launched streaming for "+ry(d)});d.w.yg(d);my(g,2);return{Jp:d.b,xt:d.f}})})};
py.prototype.stop=function(){var a=this;return ly(this.D,function(c){if(!a.h&&!a.j)return my(c,1),Promise.resolve();a.l.info(function(){return"Stopping streaming for "+ry(a)+"."});a.m&&(ny.rtpStream.onError.removeListener(a.m),a.m=null);if(a.w){var b=a.w.ih();a.w=null}else b=Promise.resolve();return b.then(function(){a.b&&(ny.rtpStream.stop(a.b),ny.rtpStream.destroy(a.b),a.b=null);a.f&&(ny.rtpStream.stop(a.f),ny.rtpStream.destroy(a.f),a.f=null);a.o&&(ny.udpTransport.destroy(a.o),a.o=null);a.W();a.l.info(function(){return"Stopped streaming for "+
ry(a)+"."});a.h=null;a.j=null;my(c,1)})})};
var lca=function(a,c){var b=JSON.stringify(c);return Promise.all([a.b&&new Promise(function(d){return ny.rtpStream.getRawEvents(a.b,b,d)}),a.f&&new Promise(function(d){return ny.rtpStream.getRawEvents(a.f,b,d)})]).catch(function(d){a.l.error("Unexpected error when calling getRawEvents()",d);return[]}).then(function(d){return new Blob(d.filter(function(e){return!!e}),{type:"application/gzip"})})},mca=function(a){return Promise.all([a.b&&new Promise(function(c){return ny.rtpStream.getStats(a.b,c)}),
a.f&&new Promise(function(c){return ny.rtpStream.getStats(a.f,c)})]).catch(function(c){a.l.error("Unexpected error when calling getStats()",c);return[]}).then(function(c){return Object.assign.apply(Object,[{}].concat(n(c.filter(function(b){return!!b}))))})},ry=function(a){if(a.h&&a.j)var c="audio+video ";else if(a.h)c="audio-only ";else if(a.j)c="video-only ";else return"stopped";return a.h instanceof qy||a.j instanceof qy?c+"remoting":c+"streaming"},hca=function(a){return new Promise(function(c){var b=
function(d,e,f){d&&!a.h&&(ny.rtpStream.destroy(d),d=null);e&&!a.j&&(ny.rtpStream.destroy(e),e=null);a.l.info(function(){return"Created Cast Streaming session: audioStreamId="+d+", videoStreamId="+e+"."});a.b=d;a.f=e;a.o=f;c()};a.h instanceof qy||a.j instanceof qy?ny.session.create(null,null,b):ny.session.create(a.h,a.j,b)})};
py.prototype.F=function(){for(var a=Nj(),c=Nj(),b=[],d=l([this.b,this.f]),e=d.next();!e.done;e=d.next())if(e=e.value)for(var f=e==this.b,g=f?127:96,k=f?Math.floor(499999*Math.random())+1:Math.floor(499999*Math.random())+500001,m=f?48E3:9E4,p=l(ny.rtpStream.getSupportedParams(e)),v=p.next();!v.done;v=p.next())v=v.value,v.payload.payloadType=g,v.payload.maxLatency=this.g.maxLatencyMillis,v.payload.minLatency=this.g.minLatencyMillis,v.payload.animatedLatency=this.g.animatedLatencyMillis,v.payload.ssrc=
k,v.payload.clockRate=m,v.payload.aesKey=a,v.payload.aesIvMask=c,f?(v.payload.channels=2,v.payload.maxBitrate=this.g.audioBitrate,v.payload.maxFrameRate=100):(v.payload.minBitrate=this.g.minVideoBitrate,v.payload.maxBitrate=this.g.maxVideoBitrate,v.payload.maxFrameRate=this.g.maxFrameRate),b.push(new nca(e,v));return b};
var sy=function(a,c,b){c&&!b.some(function(d){return d.dg==c})&&(a.l.G("Destroying RTP stream not selected by the receiver: id="+c),ny.rtpStream.destroy(c),c=null);return c},ica=function(a,c){return new Promise(function(b,d){for(var e=[],f=0;f<c.length;++f){var g=c[f].params,k={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.g.enableLogging,rtpExtensions:["adaptive_playout_delay"]};a.g.dscpEnabled&&(k.receiverRtcpDscp=46);127==g.payload.payloadType?Object.assign(k,{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(k,{type:"video_source",renderMode:"video",maxFrameRate:Math.round(1E3*g.payload.maxFrameRate)+"/1000",
maxBitRate:1E3*g.payload.maxBitrate,resolutions:[{width:a.g.maxWidth,height:a.g.maxHeight}]});e.push(k)}var m=a.h instanceof qy||a.j instanceof qy?"remoting":"mirroring",p={type:"OFFER",sessionId:a.J,seqNum:pn(a.H),offer:{castMode:m,receiverGetStatus:!0,supportedStreams:e}};a.l.info(function(){return"Sending OFFER message: "+JSON.stringify(p)});hy(a.L,p,"ANSWER",1E4,function(v,A){if(null==v)d(A);else if("ok"==v.result&&v.b){if(v.f!=p.seqNum)return a.l.G("Ignoring ANSWER for OFFER with different seqNum: "+
JSON.stringify(v)),!1;((A=v.b.g)&&A!=m||!A&&"mirroring"!=m)&&a.l.error("Expected receiver to ANSWER with castMode="+m+", but got: "+A);ob(a.l,function(){return"Received ANSWER: "+JSON.stringify(v)});b(v.b)}else d(Error("Non-OK ANSWER received: "+JSON.stringify(v)));return!0})})},jca=function(a,c,b){if(c.b.length!=c.f.length)return a.l.error("sendIndexes.length != ssrcs.length in ANSWER: "+JSON.stringify(c)),[];for(var d=[],e={},f=0;f<c.b.length;e={nf:e.nf},++f){var g=c.b[f];if(0>g||g>=b.length)return a.l.error("Receiver selected invalid index ("+
g+" < "+b.length+") in ANSWER: "+JSON.stringify(c)),[];e.nf=b[g];if(d.some(function(k){return function(m){return m.dg==k.nf.dg}}(e)))return a.l.error("Receiver selected same RTP stream twice in ANSWER: "+JSON.stringify(c)),[];e.nf.params.payload.feedbackSsrc=c.f[g];if(d.some(function(k){return function(m){return m.params.payload.feedbackSsrc==k.nf.params.payload.feedbackSsrc}}(e)))return a.l.error("Receiver provided same SSRC for two different RTP streams in ANSWER: "+JSON.stringify(c)),[];d.push(e.nf)}return d},
kca=function(a,c,b){var d=null,e=function(){d&&(ny.rtpStream.onStarted.removeListener(d),d=null)};return(new Promise(function(f,g){var k=c.j||2344;a.l.info(function(){return"Starting RTP streams to receiver at "+(a.s+":"+k)+(" for selected offers: "+JSON.stringify(b))});var m=a.o||-1;a.g.dscpEnabled&&(a.l.info("Enabled DSCP in sender."),ny.udpTransport.setOptions(m,{DSCP:!0}));ny.udpTransport.setDestination(m,{address:a.s,port:k});var p=new Set(b.map(function(A){return A.dg}));d=function(A){p.delete(A);
0==p.size&&f()};ny.rtpStream.onStarted.addListener(d);m=l(b);for(var v=m.next();!v.done;v=m.next())v=v.value,ny.rtpStream.toggleLogging(v.dg,a.g.enableLogging),ny.rtpStream.start(v.dg,v.params);setTimeout(function(){g(Error("Timeout: RTP streams failed to start."))},1E4)})).then(e).catch(function(f){e();throw f;})},oy=function(a,c,b){var d=this;return a&&c in a?function(){try{a[c](b)}catch(e){d.l.error("Error from testHooks."+c,e)}}:function(){}},nca=function(a,c){this.dg=a;this.params=c},qy=function(){};var ty=function(a,c,b,d,e,f){this.m=a;this.L=oca(c,this.m.mb);this.H=new py(this.m.mb,b,d,e,f);this.C=e;this.j=new iy;this.g=new pca;this.D=new mojo.Binding(mojo.MirrorServiceRemoter,this,null);this.l=hb("mr.mirror.cast.MediaRemoter");this.s=this.b=this.w=this.h=this.F=null;this.f=!0;this.o=this.J.bind(this)};
ty.prototype.initialize=function(a,c){var b=this;return ky(this.j,1,function(d){b.F=a;b.h=c;var e=b.D.createInterfacePtrAndBind();b.D.setConnectionErrorHandler(function(){b.l.info("Remoter mojo pipe connection error.");uy(b)});b.b=new mojo.MirrorServiceRemotingSourcePtr;var f=fj(b.m.mediaSource||"");if(!f)throw Error("Failed to parse tab ID from source:\n          "+b.m.mediaSource);b.l.info("Connecting remoter to browser: tabId="+f);(Oi.get("mr.ProviderManager")||null).onMediaRemoterCreated(f,e,
mojo.makeRequest(b.b));b.b.ptr.setConnectionErrorHandler(function(){b.l.info("RemotingSource mojo pipe connection error.");uy(b)});return qca(b).then(function(){if(b.f)b.b.onSinkAvailable(b.L);my(d,2)})})};
var uy=function(a){return ly(a.j,function(c){a.b&&(a.b.ptr.reset(),a.b=null);var b=a.w;a.w=null;a.h=null;a.F=null;a.D.close();chrome.settingsPrivate.onPrefsChanged.hasListener(a.o)&&chrome.settingsPrivate.onPrefsChanged.removeListener(a.o);return new Promise(function(d){window.setTimeout(function(){vy(a).then(function(){my(c,1);d();b&&b()})},250)})})};h=ty.prototype;h.Ps=function(a){wy(this.g,a)};h.yg=function(a){this.h&&this.h.yg(a)};h.ih=function(){return this.h?this.h.ih():Promise.resolve()};
h.ef=function(a,c){this.l.error("Error during streaming: "+a,c);if(this.b)this.b.onError();uy(this)};
h.start=function(){var a=this,c=!1;this.l.info(function(){c=!0;return"Starting next media remoting session."});c&&rca(this.g,function(b){return a.l.info(b)});sca(this.g);ky(this.j,2,function(b){return(0,a.F)().then(function(d){a.w=d;a.C.subscribe("RPC",function(e){if(e.rpc){var f=a.g;e=e.rpc;f.w&&(++f.m,f.f+=e.length,f.w(e))}});my(b,3)}).catch(function(d){return vy(a).then(function(){my(b);throw d;})})}).then(function(){a.l.info("Remoting started successfully.")}).catch(function(b){a.l.error("Failed to start remoting",
b);a.b.onError()})};h.nt=function(a,c){var b=this;return ky(this.j,3,function(d){return b.H.start(a?new qy:null,c?new qy:null,b).then(function(e){tca(b.g,function(f){return b.C.sendMessage(f)},function(f){b.b.onMessageFromSink(f)});my(d,4);return{audio_stream_id:e.Jp||-1,video_stream_id:e.xt||-1}}).catch(function(e){return vy(b).then(function(){my(d);throw e;})})}).catch(function(d){b.l.error("Failed to start remoting streams",d);uy(b);return{audio_stream_id:-1,video_stream_id:-1}})};
h.stop=function(a){var c=this;fca(this.j,function(b){c.b.onStopped(a);return vy(c).then(function(){c.l.info("Remoting stopped.");my(b,5);(0,c.w)().then(function(){return ky(c.j,5,function(d){if(c.b&&c.f)c.b.onSinkAvailable(c.L);my(d,2);return Promise.resolve()})}).catch(function(d){throw d;});c.w=null})}).catch(function(b){c.l.error("Failed to stop remoting: ",b);uy(c)})};
h.hq=function(){null===this.s&&(this.s=pf(this.m.mb.ag).then(function(a){return a.f||!1}));return this.s.then(function(a){return{rate:(a?1E7:5E6)/8}})};
var vy=function(a){return a.H.stop().then(function(){gy(a.C,"RPC");uca(a.g);xy(a.g)})},qca=function(a){return new Promise(function(c){chrome.settingsPrivate.getPref("media_router.media_remoting.enabled",function(b){chrome.runtime.lastError?a.l.error("Encountered error getting media remoting pref: "+JSON.stringify(chrome.runtime.lastError)):b.type!=chrome.settingsPrivate.PrefType.BOOLEAN?a.l.error("Pref value not a boolean: "+JSON.stringify(b)):(a.f=!!b.value,a.l.info("Initializing mediaRemotingEnabled_ with value read from pref: "+
a.f));chrome.settingsPrivate.onPrefsChanged.hasListener(a.o)||chrome.settingsPrivate.onPrefsChanged.addListener(a.o);c()})})};
ty.prototype.J=function(a){if(this.b){a=l(a);for(var c=a.next();!c.done;c=a.next())if(c=c.value,"media_router.media_remoting.enabled"==c.key){if(c.type!=chrome.settingsPrivate.PrefType.BOOLEAN){this.l.error("Pref value not a boolean: "+JSON.stringify(c));break}a=!!c.value;if(this.f==a)break;this.f=a;this.l.info("mediaRemotingEnabled_ changed to: "+this.f);if(this.f)this.b.onSinkAvailable(this.L);else this.b.onStopped(mojo.RemotingStopReason.USER_DISABLED);break}}};
var oca=function(a,c){var b=this,d=new mojo.RemotingSinkMetadata;d.features=[];d.friendly_name=c.jt||"";d.audio_capabilities=[];d.video_capabilities=[];var e=mojo.RemotingSinkAudioCapability,f=mojo.RemotingSinkVideoCapability,g=d.audio_capabilities,k=d.video_capabilities,m=c.ke||"";(a.b||[]).forEach(function(p){switch(p){case "audio":g.push(e.CODEC_BASELINE_SET);break;case "aac":g.push(e.CODEC_AAC);break;case "opus":g.push(e.CODEC_OPUS);break;case "video":k.push(f.CODEC_BASELINE_SET);break;case "4k":k.push(f.SUPPORT_4K);
break;case "h264":k.push(f.CODEC_H264);break;case "vp8":k.push(f.CODEC_VP8);break;case "vp9":m.startsWith("Chromecast Ultra")&&k.push(f.CODEC_VP9);break;case "hevc":m.startsWith("Chromecast Ultra")&&k.push(f.CODEC_HEVC);break;default:b.l.info("Unknown mediaCap name: "+p)}});c.ke&&"Chromecast Ultra"==c.ke&&k.push(f.SUPPORT_4K);return d};ty.prototype.estimateTransmissionCapacity=ty.prototype.hq;ty.prototype.stop=ty.prototype.stop;ty.prototype.startDataStreams=ty.prototype.nt;ty.prototype.start=ty.prototype.start;
ty.prototype.sendMessageToSink=ty.prototype.Ps;
var pca=function(){this.w=this.j=this.b=null;this.s=this.f=this.m=this.g=this.o=0;this.h=null},sca=function(a){a.b=[];yy(a,performance.now())},tca=function(a,c,b){a.j=c;a.w=b;a.b?(c=a.b,a.b=null,c.forEach(function(d){return wy(a,d.data).then(d.Rs,d.en)})):yy(a,performance.now())},uca=function(a){if(a.b){var c=Error("Stop before delivering pending message");a.b.forEach(function(b){return b.en(c)});a.b=null}a.j=null;a.w=null},wy=function(a,c){if(a.j){var b=btoa(String.fromCharCode.apply(null,c));++a.o;
a.g+=c.length;return a.j({type:"RPC",rpc:b})}return a.b?new Promise(function(d,e){a.b.push({data:c,Rs:d,en:e})}):Promise.reject(Error("RPC pipe not started"))},rca=function(a,c){xy(a);a.h=setInterval(function(){if(a.b)var b=a.b.length+" messages are waiting to send.";else{b=performance.now();var d=(b-a.s)/1E3;d="Over the past "+d.toFixed(1)+" seconds, sent "+(a.o+" messages ("+Math.round(a.g/d)+" bytes/sec) and ")+("received "+a.m+" messages ("+Math.round(a.f/d)+" ")+"bytes/sec).";yy(a,b);b=d}c(b)},
3E4)},xy=function(a){null!=a.h&&(clearInterval(a.h),a.h=null)},yy=function(a,c){a.o=0;a.g=0;a.m=0;a.f=0;a.s=c};var vca=function(a){return a&&a.getAudioTracks()&&0<a.getAudioTracks().length?a.getAudioTracks()[0]:null},wca=function(a){return a&&a.getVideoTracks()&&0<a.getVideoTracks().length?a.getVideoTracks()[0]:null};var zy=function(a,c,b,d,e){this.g=new py(a,c,b,d,void 0===e?null:e);this.l=hb("mr.mirror.cast.MediaStreamer");this.j=new iy;this.h=this.f=this.b=this.w=null};zy.prototype.start=function(a,c){var b=this;return ky(this.j,1,function(d){b.w=a;b.b=vca(a);b.b&&"ended"==b.b.readyState&&(b.b=null);b.f=wca(a);b.f&&"ended"==b.f.readyState&&(b.f=null);if(!b.b&&!b.f)return my(d),Promise.reject(Error("No MediaStream tracks to stream."));b.h=c;return b.g.start(b.b,b.f,b.h).then(function(){return my(d,2)})})};
zy.prototype.stop=function(){var a=this;return ly(this.j,function(c){return a.g.stop().then(function(){a.b=null;a.f=null;a.w=null;a.h=null;my(c,1)})})};var xca=function(a){return ky(a.j,2,function(c){a.l.info("Suspending media streaming...");return a.g.stop().then(function(){a.l.info("Suspended media streaming.");my(c,3)})})};
zy.prototype.resume=function(){var a=this;return ky(this.j,3,function(c){a.b&&"ended"==a.b.readyState&&(a.b=null);a.f&&"ended"==a.f.readyState&&(a.f=null);if(!a.b&&!a.f)return Promise.reject(Error("Cannot resume: All tracks have ended."));a.l.info("Resuming media streaming...");return a.g.start(a.b,a.f,a.h).then(function(){a.l.info("Resumed media streaming.");my(c,2)})})};var Ay=function(a,c,b){this.j=a;this.h=c;this.g=b;this.l=hb("mr.mirror.cast.WifiStatusMonitor");this.b=null;this.f=[]};Ay.prototype.start=function(){var a=this;null==this.b&&(ob(this.l,"Starting Wifi Status Monitoring."),this.f=[],this.g.subscribe("STATUS_RESPONSE",function(c){return yca(a,c)}),this.b=setInterval(function(){return By(a)},12E4),By(this))};Ay.prototype.stop=function(){null!=this.b&&(ob(this.l,"Stopping Wifi Status Monitoring."),clearInterval(this.b),this.b=null,gy(this.g,"STATUS_RESPONSE"))};
var yca=function(a,c){if(null!=a.b)if(c.status){var b={};null!=c.status.b&&(b.wifiSnr=c.status.b);null!=c.status.f&&(b.wifiSpeed=c.status.f[3]);0==Object.keys(b).length?a.l.G(function(){return"No status fields populated in response: "+JSON.stringify(c)}):(b.timestamp=Date.now(),30==a.f.length&&a.f.shift(),a.f.push(b),a.l.info(function(){return"Current Wifi status: "+JSON.stringify(b)}))}else a.l.G(function(){return"Ignoring response without status: "+JSON.stringify(c)})},By=function(a){a.g.sendMessage({type:"GET_STATUS",
sessionId:a.j,seqNum:pn(a.h),get_status:["wifiSnr","wifiSpeed"]})};var Cy=function(a,c,b,d){this.L=c.ag;this.m={extVersion:chrome.runtime.getManifest().version,extChannel:"public",mirrorSettings:uj(a),sender:navigator.userAgent||"UNKNOWN",receiverProductName:c.ke};this.F=b;this.C=d;this.h=this.f=this.o=this.w=this.j=this.s=this.g=null;this.b=[]};Cy.prototype.yg=function(a){null!=this.f&&clearInterval(this.f);this.g=a;this.s=Date.now();this.f=setInterval(this.D.bind(this,a),9E5)};
Cy.prototype.ih=function(){null!=this.f&&(clearInterval(this.f),this.f=null);if(null!=this.g){var a=this.D(this.g);this.g=null;return a}return Promise.resolve()};Cy.prototype.ef=function(a,c){null==this.j&&(this.j=Date.now(),"function"===typeof a?this.w=a():"string"===typeof a&&(this.w=a),c&&"string"===typeof c.stack&&(this.o=c.stack))};
var zca=function(a,c){return(null==a.g?Promise.resolve():a.D(a.g)).then(function(){var b=c.map(function(d){d=Dy(a,d);var e=d.map(function(g){return g.events}).filter(function(g){return null!=g}),f=["["];d.map(function(g){return g.cg}).forEach(function(g,k){0<k&&f.push(",");f.push(g)});f.push("]");return{events:new Blob(e,{type:"application/gzip"}),cg:new Blob(f,{type:"application/json"})}});a.b=[];return b})};
Cy.prototype.D=function(a){var c=this;if(null!=this.h)return this.h;var b=pf(this.L).then(function(d){d={receiverVersion:d.b,receiverConnected:d.h,receiverOnEthernet:d.f,receiverHasUpdatePending:d.g,receiverUptimeSeconds:d.j};Object.assign(d,c.m);var e=Date.now();Object.assign(d,{startTime:c.s,endTime:e,activity:ry(a),receiverWifiStatus:Array.from(c.C.f)});c.s=e;null!=c.j&&(Object.assign(d,{streamingErrorTime:c.j,streamingErrorMessage:c.w,streamingErrorCause:c.o}),c.j=null,c.w=null,c.o=null);return d});
return(this.h=Promise.all([b.then(function(d){return lca(a,d)}),b,mca(a)]).then(function(d){var e=l(d);d=e.next().value;var f=e.next().value;e=e.next().value;c.b.push({events:d,cg:new Blob([JSON.stringify(Object.assign({tags:f},e))],{type:"application/json"})});c.b=Dy(c,c.F);c.h=null}))||Promise.resolve()};
var Dy=function(a,c){c-=2;for(var b=[],d=a.b.length-1;0<=d;--d){c-=a.b[d].cg.size+1;if(0>c)break;b.push({events:null,cg:a.b[d].cg});if(null!=a.b[d].events){var e=a.b[d].events.size;c>=e&&(b[b.length-1].events=a.b[d].events,c-=e)}}return b.reverse()};var Ey=hb("mr.NetworkUtils"),Fy=function(a,c){return yi?new Promise(function(b,d){chrome.networkingPrivate.setWifiTDLSEnabledState(a,c,function(e){chrome.runtime.lastError?(Ey.G("Unable to set TDLS state: state = "+c+", error = "+chrome.runtime.lastError.message),d("Unable to set TDLS state to "+c+".")):(Ey.info("TDLS state changed: state = "+c+", status = "+e),b(e))})}):Promise.reject("TDLS feature not enabled.")};var Gy=function(a,c,b,d){d=void 0===d?null:d;rj.call(this,c);var e=c.mb;this.D=e.sessionId;this.J=e.ag;this.L=a;this.O=d;this.l=hb("mr.mirror.cast.Session");this.s=new iy;this.o=new on("mirror.cast.SeqNumGenerator");this.m=new fy(c.id);this.w=new zy(e,this.L,this.o,this.m,this.O);this.h=null;this.b=new Cy(a,e,b,new Ay(this.D,this.o,this.m));this.g=!1;this.C=null};q(Gy,rj);h=Gy.prototype;
h.start=function(a){var c=this;return ky(this.s,1,function(b){var d=Sx();return Aca(c).then(function(e){c.g=e;return c.w.start(a,c)}).then(function(){if(c.w.g.C){var e=c.b;e.m.tdlsIsOn=c.g;e.C.start();Bca(c)}else c.b.m.tdlsIsOn=c.g;d.end();c.C=Tx();my(b,2);return c})})};
h.stop=function(){var a=this;return ly(this.s,function(c){a.C&&(a.C.end(),a.C=null);a.b.C.stop();return a.w.stop().then(function(){return a.h?uy(a.h):Promise.resolve()}).then(function(){a.h=null;return a.g?Cca(a):Promise.resolve()}).then(function(){a.g=!1;my(c,4)})})};
h.cn=function(){var a=this,c={sessionId:this.D,seqNum:pn(this.o),type:"PRESENTATION",icons:[],title:pj(this.qc)};this.l.info("Sending session metadata update to receiver: "+this.D);this.m.sendMessage(c).catch(function(b){a.l.G("Failed to send activity to sink: "+b.message)})};h.yg=function(a){this.b.yg(a)};h.ih=function(){return this.b.ih()};h.ef=function(a,c){this.b.ef(a,c);this.l.error(a,c);this.stop()};
var Hy=function(a,c){return zca(a.b,c)},Aca=function(a){return a.L.useTdls?Fy(a.J,!0).then(function(c){if("Connected"==c)return a.l.info("Successfully enabled TDLS."),!0;a.l.G("Did not enable TDLS: result="+c);return!1}).catch(function(c){a.l.G("Error while calling enableTDLS()",c);return!1}):Promise.resolve(!1)},Cca=function(a){return Fy(a.J,!1).catch(function(c){return a.l.error("Error while turning TDLS back off",c)})},Bca=function(a){Dca(a).then(function(c){(c.b||[]).includes("video")?Eca(a,c):
a.l.G(function(){return"Receiver incapable of Media Remoting: "+JSON.stringify(c)})}).catch(function(c){a.l.G("None/Invalid capabilites response. Media Remoting disabled.",c)})},Dca=function(a){return new Promise(function(c,b){var d={type:"GET_CAPABILITIES",sessionId:a.D,seqNum:pn(a.o)};a.l.info(function(){return"Sending GET_CAPABILITIES message: "+JSON.stringify(d)});hy(a.m,d,"CAPABILITIES_RESPONSE",3E4,function(e,f){if(null==e)return b(f),!0;if("ok"!=e.result||!e.capabilities)return b(Error("Bad response: "+
JSON.stringify(e))),!0;if(e.f!=d.seqNum)return a.l.info(function(){return"Ignoring CAPABILITIES_RESPONSE with different seqNum: "+JSON.stringify(e)}),!1;ob(a.l,function(){return"Received CAPABILITIES_RESPONSE: "+JSON.stringify(e)});c(e.capabilities);return!0})})},Eca=function(a,c){ky(a.s,2,function(b){var d=a.f.mb.ke||"<UNKNOWN>";if(!d.startsWith("Chromecast")&&!d.startsWith("Eureka Dongle"))return a.l.G("HACK: Media Remoting disabled because the receiver model--"+('"'+d+'" according to discovery--is not a Chromecast.')),
my(b),Promise.resolve();a.h=new ty(a.f,c,a.L,a.o,a.m,a.O);return a.h.initialize(a.T.bind(a),a).catch(function(e){a.l.error("Media Remoting start failed: "+e.message,e)}).then(function(){return my(b)})})};Gy.prototype.T=function(){var a=this;return ky(this.s,2,function(c){return new Promise(function(b,d){xca(a.w).then(function(){my(c,3);a.F=!0;ij(a);b(a.W.bind(a))}).catch(function(e){a.ef("Failed to suspend MediaStreamer before starting remoting",e);d(e)})})})};
Gy.prototype.W=function(){var a=this;return ky(this.s,3,function(c){return new Promise(function(b,d){a.w.resume().then(function(){my(c,2);a.F=!1;ij(a);b()}).catch(function(e){a.ef("Failed resume MediaStreamer after ending remoting mode",e);d(e)})})})};var Iy=function(){gj.call(this,"cast_streaming");this.w=this.s=this.L=this.F=this.h=null;this.Ua=this.H="";this.da=this.o=!1;this.fa=this.qa.bind(this);this.J=this.O=this.T=this.W=this.j=null};q(Iy,gj);h=Iy.prototype;h.Ag=function(a){this.o=a||!1;this.da=!0};h.getName=function(){return"cast_streaming"};
h.Gj=function(a,c,b,d,e){var f=this;if(!this.o)return gj.prototype.Gj.call(this,a,c,b,d,e);this.R.info("Start mirroring on route "+a.id);if(!this.da)return ri(Error("Not initialized"));var g=new Promise(function(k,m){f.m().then(function(){if(bj(c)&&b.shouldCaptureVideo)return(new Promise(function(p){chrome.tabs.get(a.mb.tabId||-1,p)})).then(function(p){return Li(p).then(function(v){f.Ua=v})})}).then(function(){return e?e(a).b:a}).then(function(p){f.H=c;Fca(f,p);var v=f.F.createInterfacePtrAndBind(),
A=f.L.createInterfacePtrAndBind(),G=Gca(p,b);Hca(f,p,c,d);if(!f.h)throw new vi("Error to get mirroring service host");f.s=new mojo.MirroringCastMessageChannelPtr;f.W=Sx();f.h.start(G,v,A,mojo.makeRequest(f.s));f.j=new rj(a,f.g.Si.bind(f.g));ij(f.j);Ica(f,p,c);f.O=function(){return k(p)};f.J=m}).catch(function(p){f.R.info("Mirroring launch error: "+p);f.ah(p.reason);m(p)})});return si(g)};h.xh=function(a,c){return new Gy(a,c,20969472,null)};h.dh=function(){Ux(0)};h.Yg=function(){Ux(1)};h.Xh=function(){Ux(2)};
h.Zg=function(){Bb("MediaRouter.CastStreaming.Session.End")};h.ah=function(a){Cb("MediaRouter.CastStreaming.Start.Failure",a,ui)};h.bh=function(){Bb("MediaRouter.CastStreaming.Stream.End")};
h.vi=function(a){var c=this;return this.o?Promise.resolve():(new Promise(function(b){return chrome.metricsPrivate.getIsCrashReportingEnabled(b)})).then(function(b){var d=b&&Sba(),e=[9351424];d&&e.push(20969472);return Hy(a,e).then(function(f){var g=f[f.length-1];f=jm(f[0].events).catch(function(k){c.R.error("Failed to persist events Blob.",k)});d&&0<g.events.size?Xx(g.events,void 0,c.sr.bind(c)):b&&Wx("stats.json",g.cg,void 0,void 0);return f})})};h.sr=function(a){a&&($x().b=Date.now())};
h.Fj=function(a){if(this.o)return eb();this.R.info("Received message to upload logs for "+a);return this.b?Hy(this.b,[20969472]).then(function(c){c=l(c).next().value;return 0==c.events.size?"":Xx(c.events,a)}):Promise.resolve(Jca(this,a))};
var Jca=function(a,c){var b=window.localStorage.getItem("mr.temp.mirror.cast.Service.eventsBlob");if(null==b||1>b.length)b=null;else{for(var d=new Uint16Array(b.length),e=0;e<b.length;++e)d[e]=b.charCodeAt(e);b=d.buffer;d=(new Uint8Array(b,b.byteLength-1,1))[0];b=new Uint8Array(b,0,b.byteLength-(0==d?2:1));b=new Blob([b],{type:"application/gzip"})}if(null!=b&&0!=b.size)return jm(new Blob),a.R.info("Uploading saved logs for feedback."),Xx(b,c)};h=Iy.prototype;
h.onError=function(a){this.J&&(this.J(a),this.O=this.J=null);this.R.info("Mirroring service error: "+a);this.m()};h.didStart=function(){this.O&&(this.O(),this.O=this.J=null);this.W&&(this.W.end(),this.W=null);this.T=Tx();aj(this.H)?this.dh():bj(this.H)?this.Yg():dj(this.H)&&this.Xh()};h.didStop=function(){this.m()};h.send=function(a){if(this.w){var c=JSON.parse(a.jsonFormatData);ob(this.R,function(){return"Sending message: "+JSON.stringify(c)});this.w.sendMessage(a.jsonFormatData,{namespace:a.messageNamespace})}};
h.tr=function(a){if(a&&(a.namespace_===mojo.MirroringWebRtcNamespace||a.namespace_===mojo.MirroringRemotingNamespace)&&this.s){var c=new mojo.MirroringCastMessage;c.messageNamespace=a.namespace_;"string"!==typeof a.data?this.R.info("Received non-string as JSON"):(c.jsonFormatData=a.data,this.s.send(c))}};
var Fca=function(a,c){a.F=new mojo.Binding(mojo.MirroringSessionObserver,a,null);a.L=new mojo.Binding(mojo.MirroringCastMessageChannel,a,null);a.w=kx(c.id);a.w.onMessage=a.tr.bind(a)},Gca=function(a,c){var b=new mojo.MirroringSessionParameters;b.receiverAddress=new mojo.IPAddress;b.receiverAddress.addressBytes=a.mb.ag.split(".").map(function(d){return parseInt(d,10)});b.receiverModelName=a.mb.ke;b.type=c.shouldCaptureVideo&&c.shouldCaptureAudio?mojo.MirroringSessionType.AUDIO_AND_VIDEO:c.shouldCaptureVideo?
mojo.MirroringSessionType.VIDEO_ONLY:mojo.MirroringSessionType.AUDIO_ONLY;return b},Hca=function(a,c,b,d){a.h=new mojo.MirroringServiceHostPtr;c=c.mb.tabId||-1;aj(b)?a.g.getMirroringServiceHostForTab(c,mojo.makeRequest(a.h)):bj(b)?a.g.getMirroringServiceHostForDesktop(c,a.Ua,mojo.makeRequest(a.h)):dj(b)?(c=new mojo.Url,c.url=b,a.g.getMirroringServiceHostForOffscreenTab(c,d||"",mojo.makeRequest(a.h))):a.h=null},Ica=function(a,c,b){aj(b)&&!chrome.tabs.onUpdated.hasListener(a.fa)&&chrome.tabs.onUpdated.addListener(a.fa);
(aj(b)||dj(b))&&lj(a.j,c.mb.tabId)};Iy.prototype.qa=function(a,c,b){$i(14);this.j&&mj(this.j,a,c,b)};
Iy.prototype.m=function(){chrome.tabs.onUpdated.removeListener(this.fa);return this.o?this.da?this.h?(this.h.ptr.reset(),this.s=this.h=null,this.w&&this.w.Za(),this.w=null,this.F&&(this.F.close(),this.F=null),this.L&&(this.L.close(),this.L=null),this.g.Th(this.j.f.id),this.j=null,this.Ua=this.H="",this.T&&(this.T.end(),this.T=null),this.Zg(),Promise.resolve(!0)):Promise.resolve(!1):Promise.reject("Not initialized"):gj.prototype.m.call(this)};
Iy.prototype.Hj=function(a,c,b,d,e,f){return this.o?ri(Error("Mirroring service does not support updating stream")):gj.prototype.Hj.call(this,a,c,b,d,e,f)};Iy.prototype.send=Iy.prototype.send;Iy.prototype.didStop=Iy.prototype.didStop;Iy.prototype.didStart=Iy.prototype.didStart;Iy.prototype.onError=Iy.prototype.onError;var Kca=new Iy;Xi("mr.mirror.cast.Service",Kca);
